PeterXie666 commited on
Commit
c7e4258
·
verified ·
1 Parent(s): 9e0914b

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/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/claude_batch.py +309 -0
  2. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/trace_html.py +148 -0
  3. leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/__init__.py +1 -0
  4. leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/bddl.py +66 -0
  5. leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/envs.py +325 -0
  6. leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/skills.py +156 -0
  7. leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/task_base.py +129 -0
  8. leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/vla.py +293 -0
  9. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/client/pyproject.toml +13 -0
  10. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/__init__.py +1 -0
  11. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/envs.py +325 -0
  12. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/__init__.py +63 -0
  13. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/base.py +364 -0
  14. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/claude_code.py +514 -0
  15. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/dsh.py +403 -0
  16. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.267_0399c793ff571d59_claude-opus-5-5_high.json +15 -0
  17. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-2_high.json +15 -0
  18. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full_2.1.267_0399c793ff571d59_deepseek-flash_high.json +15 -0
  19. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-chatgpt-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +14 -0
  20. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +14 -0
  21. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +27 -0
  22. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/rpent.py +530 -0
  23. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/trajectory.py +86 -0
  24. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/skills.py +156 -0
  25. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/task_base.py +129 -0
  26. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l2_knock.py +457 -0
  27. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l2_restore_layout.py +502 -0
  28. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_card_shelf.py +587 -0
  29. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py +598 -0
  30. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py +392 -0
  31. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l6_count.py +562 -0
  32. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_bystander.py +830 -0
  33. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py +715 -0
  34. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py +468 -0
  35. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/vla.py +299 -0
  36. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/qwen_vl_server.sh +17 -0
  37. leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/redteam_report.py +124 -0
  38. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json +26 -0
  39. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/plan.json +95 -0
  40. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/summary.json +979 -0
  41. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/workspace_exposure_audit.json +329 -0
  42. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/workspace_isolation_patch.json +41 -0
  43. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/client/lffbench_client/__init__.py +139 -0
  44. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/__init__.py +21 -0
  45. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/__init__.py +53 -0
  46. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py +73 -0
  47. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l3_under_table_tool.py +50 -0
  48. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py +61 -0
  49. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l7_key_turn.py +34 -0
  50. leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py +18 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/claude_batch.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch bookkeeping for Claude-subagent policy runs.
2
+
3
+ start python scripts/claude_batch.py start --batch exp1 --model sonnet --tasks t1:s1,s2 t2:s1 --k 3 --port0 9000
4
+ -> starts one server per (task, seed, condition) run and writes runs/claude/<batch>/manifest.json
5
+ conditions: harness = memory full + feedback (default F1) + k attempts in one agent;
6
+ noharness = k independent single-attempt agents (memory none, k=1)
7
+ usage python scripts/claude_batch.py usage --batch exp1 --run <run> --agent <agentId> --tokens N --ms N --tools N
8
+ audit python scripts/claude_batch.py audit --batch exp1 (runs audit_subagent on every recorded agent)
9
+ table python scripts/claude_batch.py table --batch exp1 [--batch exp2 ...]
10
+ stop python scripts/claude_batch.py stop --batch exp1
11
+ """
12
+ import argparse
13
+ import glob
14
+ import json
15
+ import os
16
+ import subprocess
17
+ import sys
18
+
19
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
20
+ RUNS = os.path.join(ROOT, "runs", "claude")
21
+ RUNS_DIR_DEFAULT = RUNS
22
+ TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (<agentId>.output files)
23
+
24
+ PLAYER_PROMPT = """You are controlling a simulated robot arm. Everything you need is in the directory {sb}
25
+
26
+ Rules (strict):
27
+ - First read {sb}/README.md — it explains the robot, the coordinate frames, the cameras, the commands and your task.
28
+ - Control the robot only by running shell commands of the form:
29
+ cd {sb} && ./robot <command> key=value ...
30
+ Run one robot command per shell call.
31
+ - Look at camera images only with your file-reading tool on the image paths the robot prints (they are inside that directory's obs/ folder).
32
+ - Do not read, list, search or execute anything else on this machine: no other files or directories, no other programs, no scripts of your own, no web access. Only README.md, the obs/ images and ./robot.
33
+ - Keep going until a robot command tells you to stop or that the episode is over.
34
+
35
+ When you are told to stop, reply with a short report: what you did (key commands and parameter values), what you observed, any feedback you got, and how you changed your approach."""
36
+
37
+
38
+ PLAYER_PROMPT_LA = """You are controlling a simulated robot arm. Your workspace is the directory {sb}
39
+
40
+ Rules (strict):
41
+ - First read {sb}/README.md: it explains the robot, the commands, the observation files and your task.
42
+ - Every shell call must be exactly one of these forms, with nothing chained before or after it:
43
+ cd {sb} && ./robot <command> key=value ...
44
+ cd {sb} && ./shell '<bash command>'
45
+ cd {sb} && ./shell <<'EOF'
46
+ <multi-line bash command, e.g. a python3 heredoc>
47
+ EOF
48
+ ./robot runs one robot command. ./shell runs your command inside the workspace (ls, python3 with numpy / scipy /
49
+ Pillow / OpenCV, writing your own notes or scripts, ...); it has no network and cannot control the robot.
50
+ - Use your file-reading tool to look at images and other files, and your file-writing tools if you want, but only on
51
+ files inside {sb}.
52
+ - Do not read, list, search or execute anything else on this machine, do not use any other tool, no web access.
53
+ - Keep going until a robot command tells you to stop or that the episode is over.
54
+
55
+ When you are told to stop, reply with a short report: what you did (key commands and parameter values), what you
56
+ observed, any feedback you got, and how you changed your approach."""
57
+
58
+
59
+ THINK_ALOUD = """
60
+
61
+ Think aloud (for the experiment log): before every ./robot command, first write one to three plain sentences as
62
+ normal text (not inside a tool call): what you currently see or know, what you conclude from it, and what the next
63
+ command is meant to achieve. After each attempt ends, also write what you think went wrong (or right) and what you
64
+ will change. Keep these notes short and factual."""
65
+
66
+
67
+ def manifest_path(batch):
68
+ return os.path.join(RUNS, batch, "manifest.json")
69
+
70
+
71
+ def load(batch):
72
+ with open(manifest_path(batch)) as f:
73
+ return json.load(f)
74
+
75
+
76
+ def save(batch, m):
77
+ os.makedirs(os.path.dirname(manifest_path(batch)), exist_ok=True)
78
+ with open(manifest_path(batch), "w") as f:
79
+ json.dump(m, f, indent=1)
80
+
81
+
82
+ def port_free(port):
83
+ import socket
84
+ with socket.socket() as so:
85
+ try:
86
+ so.bind(("127.0.0.1", port))
87
+ return True
88
+ except OSError:
89
+ return False
90
+
91
+
92
+ def start_one(task, seed, mem, k, port, tag, perception="depth", video=False, style="v1", extra="", feedback="F1"):
93
+ env = dict(os.environ, LFF_RUNS_DIR=os.environ.get("LFF_RUNS_DIR", RUNS_DIR_DEFAULT), LFF_STYLE=style, LFF_EXTRA_ARGS=extra)
94
+ out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, str(seed), mem, feedback,
95
+ str(port), "direct", str(k), tag, perception, "1" if video else "0"], capture_output=True, text=True,
96
+ env=env)
97
+ kv = dict(line.split("=", 1) for line in out.stdout.strip().splitlines() if "=" in line and line.split("=")[0] in ("SANDBOX", "LOG"))
98
+ if "SANDBOX" not in kv:
99
+ raise RuntimeError(out.stdout + out.stderr)
100
+ return kv["SANDBOX"], kv["LOG"]
101
+
102
+
103
+ def cmd_start(a):
104
+ m = load(a.batch) if os.path.exists(manifest_path(a.batch)) else dict(batch=a.batch, runs=[])
105
+ port = a.port0
106
+ used = {r["port"] for r in m["runs"]}
107
+ for spec in a.tasks:
108
+ task, seeds = spec.split(":")
109
+ for seed in seeds.split(","):
110
+ conds = [("harness", "full", a.k, 0)] + [("noharness", "none", 1, i) for i in range(a.k)]
111
+ for cond, mem, k, rep in conds:
112
+ if a.only and cond != a.only:
113
+ continue
114
+ while port in used or not port_free(port):
115
+ port += 1
116
+ hide_k = bool(a.hide_k and cond == "harness")
117
+ tag = (f"{a.batch}-{a.model}-{cond}{rep if cond == 'noharness' else ''}" + ("-nominal" if a.nominal else "")
118
+ + ("-hidek" if hide_k else "") + (f"-arm{a.arm}" if a.arm != "none" else "")
119
+ + ("-dossier" if a.dossier else ""))
120
+ extra = (("--agent-iface cli" if a.style == "la" else "") + (" --nominal" if a.nominal else "")
121
+ + (" --hide-k" if hide_k else "") + (f" --arm {a.arm}" if a.arm != "none" else "")
122
+ + (f" --dossier {os.path.abspath(a.dossier)}" if a.dossier else ""))
123
+ os.environ["LFF_RUNS_DIR"] = os.path.join(RUNS, a.batch)
124
+ sb, log = start_one(task, int(seed), mem, k, port, tag, a.perception, a.video, a.style, extra.strip(), a.feedback)
125
+ used.add(port)
126
+ r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, cond=cond, rep=rep, k=k,
127
+ port=port, sandbox=sb, log=log, perception=a.perception, video=a.video, style=a.style,
128
+ nominal=a.nominal, feedback=a.feedback, think_aloud=a.think_aloud, hide_k=hide_k,
129
+ arm=a.arm, dossier=os.path.abspath(a.dossier) if a.dossier else "",
130
+ prompt=(PLAYER_PROMPT_LA if a.style == "la" else PLAYER_PROMPT).format(sb=sb)
131
+ + (THINK_ALOUD if a.think_aloud else ""))
132
+ m["runs"].append(r)
133
+ print(json.dumps({k_: r[k_] for k_ in ("run", "sandbox")}), flush=True)
134
+ save(a.batch, m)
135
+
136
+
137
+ def cmd_usage(a):
138
+ m = load(a.batch)
139
+ for r in m["runs"]:
140
+ if r["run"] == a.run or r["sandbox"] == a.run:
141
+ r.update(agent=a.agent, tokens=a.tokens, ms=a.ms, tool_uses=a.tools)
142
+ save(a.batch, m)
143
+
144
+
145
+ def cmd_audit(a):
146
+ m = load(a.batch)
147
+ for r in m["runs"]:
148
+ if not r.get("agent"):
149
+ continue
150
+ tr = os.path.join(TRANSCRIPTS, f"{r['agent']}.output")
151
+ if not os.path.exists(tr):
152
+ r["audit"] = "transcript missing"
153
+ continue
154
+ out = subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "audit_subagent.py"), tr, r["sandbox"],
155
+ "--out", os.path.join(r["log"], "audit.json")] + (["--la"] if r.get("style") == "la" else []),
156
+ capture_output=True, text=True)
157
+ res = json.loads(out.stdout)
158
+ r["audit"] = dict(n_calls=res["n_calls"], n_violations=res["n_violations"])
159
+ if res["n_violations"]:
160
+ print(r["run"], res["violations"][:3])
161
+ save(a.batch, m)
162
+ print("audited", sum(1 for r in m["runs"] if r.get("audit")))
163
+
164
+
165
+ def run_stats(r):
166
+ ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
167
+ if r.get("only_attempt"): # one attempt of a run (api_batch --memfree followup: attempt 1 of a history run)
168
+ ev = [e for e in ev if e.get("attempt") == r["only_attempt"]]
169
+ dones = [e for e in ev if e["ev"] == "done"]
170
+ http = [e for e in ev if e["ev"] == "http"]
171
+ calls = [e for e in ev if e["ev"] == "call"]
172
+ first = next((d["attempt"] for d in dones if d["success"]), None)
173
+ think = [h["think_s"] for h in http if h.get("think_s") is not None]
174
+ srv = [h["server_s"] for h in http]
175
+ t0 = http[0]["t_recv"] if http else None
176
+ t1 = http[-1]["t_send"] if http else None
177
+ return dict(attempts=len(dones), first_success=first, n_calls=len(calls), n_http=len(http),
178
+ think_s=sum(think), server_s=sum(srv), wall_s=(t1 - t0) if t0 else None,
179
+ think_per_cmd=(sum(think) / len(think)) if think else None,
180
+ outcomes=[(d["attempt"], d["success"], d.get("feedback", "")) for d in dones])
181
+
182
+
183
+ def cmd_table(a):
184
+ rows = []
185
+ for b in a.batch:
186
+ for r in load(b)["runs"]:
187
+ try:
188
+ st = run_stats(r)
189
+ except FileNotFoundError:
190
+ continue
191
+ rows.append(dict(r, **st))
192
+ import collections
193
+ # group: (task, model) -> harness runs / noharness groups by seed
194
+ g = collections.defaultdict(lambda: dict(h=[], n=collections.defaultdict(list)))
195
+ for x in rows:
196
+ key = (x["task"], x["model"])
197
+ if x["cond"] == "harness":
198
+ g[key]["h"].append(x)
199
+ else:
200
+ g[key]["n"][x["seed"]].append(x)
201
+ lines = ["| task | model | n | harness @1 | harness @k | no-harness @1 | no-harness @k (k indep.) | think s/cmd | cmds/attempt | wall min/run (harness) |",
202
+ "|---|---|---|---|---|---|---|---|---|---|"]
203
+ tot = collections.defaultdict(lambda: [0, 0, 0, 0, 0])
204
+ for (task, model), d in sorted(g.items()):
205
+ H = [x for x in d["h"] if x["attempts"] > 0]
206
+ K = max([x["k"] for x in H] or [3])
207
+ h1 = sum(1 for x in H if x["first_success"] == 1)
208
+ hk = sum(1 for x in H if x["first_success"] is not None)
209
+ seeds = [s for s, xs in d["n"].items() if all(x["attempts"] > 0 for x in xs)]
210
+ n1 = sum(1 for s in seeds if sorted(d["n"][s], key=lambda x: x["rep"])[0]["first_success"])
211
+ nk = sum(1 for s in seeds if any(x["first_success"] for x in d["n"][s]))
212
+ allx = H + [x for s in seeds for x in d["n"][s] if not x.get("only_attempt")] # attempt 1 counted in H
213
+ th = [x["think_per_cmd"] for x in allx if x["think_per_cmd"]]
214
+ cpa = [x["n_calls"] / max(x["attempts"], 1) for x in allx]
215
+ wall = [x["wall_s"] / 60 for x in H if x["wall_s"]]
216
+ f = lambda v: f"{sum(v) / len(v):.1f}" if v else "—"
217
+ lines.append(f"| {task} | {model} | {len(H)}/{len(seeds)} | {h1}/{len(H)} | {hk}/{len(H)} | {n1}/{len(seeds)} | "
218
+ f"{nk}/{len(seeds)} | {f(th)} | {f(cpa)} | {f(wall)} |")
219
+ t = tot[model]
220
+ t[0] += h1; t[1] += hk; t[2] += len(H); t[3] += nk; t[4] += len(seeds)
221
+ for model, t in tot.items():
222
+ lines.append(f"| **all** | {model} | | {t[0]}/{t[2]} | {t[1]}/{t[2]} | | {t[3]}/{t[4]} | | | |")
223
+ print("\n".join(lines))
224
+
225
+
226
+ def cmd_restart(a):
227
+ """Re-run interrupted runs from scratch: stop the old server, start a fresh one (new sandbox, new port),
228
+ keep the old entry under 'superseded'."""
229
+ m = load(a.batch)
230
+ used = {r["port"] for r in m["runs"]}
231
+ port = a.port0
232
+ for i, r in enumerate(list(m["runs"])):
233
+ if r["run"] not in a.runs:
234
+ continue
235
+ try:
236
+ os.kill(int(open(os.path.join(r["log"], "server.pid")).read()), 15)
237
+ except (ProcessLookupError, FileNotFoundError):
238
+ pass
239
+ while port in used or not port_free(port):
240
+ port += 1
241
+ mem = "full" if r["cond"] == "harness" else "none"
242
+ tag = f"{a.batch}-{r['model']}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
243
+ if r.get("style") == "la":
244
+ os.environ["LFF_RUNS_DIR"] = os.path.dirname(r["log"])
245
+ extra = (("--agent-iface cli" if r.get("style") == "la" else "") + (" --nominal" if r.get("nominal") else "")
246
+ + (" --hide-k" if r.get("hide_k") else "")
247
+ + (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "")
248
+ + (f" --dossier {r['dossier']}" if r.get("dossier") else ""))
249
+ tag += ("-hidek" if r.get("hide_k") else "") + (f"-arm{r['arm']}" if r.get("arm", "none") != "none" else "") \
250
+ + ("-dossier" if r.get("dossier") else "")
251
+ sb, log = start_one(r["task"], r["seed"], mem, r["k"], port, tag, r.get("perception", "depth"), r.get("video", False),
252
+ r.get("style", "v1"), extra.strip(), r.get("feedback", "F2"))
253
+ used.add(port)
254
+ new = {k: v for k, v in r.items() if k not in ("agent", "tokens", "ms", "tool_uses", "audit")}
255
+ new.update(run=os.path.basename(log), port=port, sandbox=sb, log=log,
256
+ prompt=(PLAYER_PROMPT_LA if r.get("style") == "la" else PLAYER_PROMPT).format(sb=sb))
257
+ m.setdefault("superseded", []).append(dict(r, reason=a.reason))
258
+ m["runs"][i] = new
259
+ print(json.dumps(dict(run=new["run"], sandbox=sb)))
260
+ save(a.batch, m)
261
+
262
+
263
+ def cmd_stop(a):
264
+ for r in load(a.batch)["runs"]:
265
+ pid = os.path.join(r["log"], "server.pid")
266
+ if os.path.exists(pid):
267
+ try:
268
+ os.kill(int(open(pid).read()), 15)
269
+ except ProcessLookupError:
270
+ pass
271
+
272
+
273
+ def main():
274
+ ap = argparse.ArgumentParser()
275
+ sub = ap.add_subparsers(dest="cmd")
276
+ s = sub.add_parser("start"); s.add_argument("--batch", required=True); s.add_argument("--model", required=True)
277
+ s.add_argument("--tasks", nargs="+", required=True); s.add_argument("--k", type=int, default=3)
278
+ s.add_argument("--port0", type=int, default=9000); s.add_argument("--only", choices=["harness", "noharness"])
279
+ s.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"]); s.add_argument("--video", action="store_true")
280
+ s.add_argument("--style", default="v1", choices=["v1", "v2", "la"])
281
+ s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
282
+ s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
283
+ help="full5 controlled arm (lffbench/arm_specs/<task>.py), passed to every run of this call")
284
+ s.add_argument("--dossier", default="",
285
+ help="la, single task:seed per call: earlier-attempt record (scripts/make_dossier.py) copied to history/")
286
+ s.add_argument("--hide-k", action="store_true",
287
+ help="harness runs: README says 1 attempt (same as the independent run); the other k-1 attempts are "
288
+ "announced only after a failure")
289
+ s.add_argument("--think-aloud", action="store_true",
290
+ help="append a request to write 1-3 plain sentences before every robot command (the transcript keeps no "
291
+ "thinking text, so this is the only way to record the agent's reasoning); changes the prompt")
292
+ s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"],
293
+ help="after a failed attempt: F1 = success/failure only (default since 2026-10-08); F2 = measured error "
294
+ "(privileged; neither LIBERO-Agent nor RoboDojo gives it), ablation only")
295
+ u = sub.add_parser("usage"); u.add_argument("--batch", required=True); u.add_argument("--run", required=True)
296
+ u.add_argument("--agent", required=True); u.add_argument("--tokens", type=int); u.add_argument("--ms", type=int)
297
+ u.add_argument("--tools", type=int)
298
+ au = sub.add_parser("audit"); au.add_argument("--batch", required=True)
299
+ t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True)
300
+ st = sub.add_parser("stop"); st.add_argument("--batch", required=True)
301
+ rs = sub.add_parser("restart"); rs.add_argument("--batch", required=True); rs.add_argument("--runs", nargs="+", required=True)
302
+ rs.add_argument("--port0", type=int, default=9300)
303
+ rs.add_argument("--reason", default="interrupted (rate limit)")
304
+ a = ap.parse_args()
305
+ dict(start=cmd_start, usage=cmd_usage, audit=cmd_audit, table=cmd_table, stop=cmd_stop, restart=cmd_restart)[a.cmd](a)
306
+
307
+
308
+ if __name__ == "__main__":
309
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_sonnet/lff/source_closure/scripts/trace_html.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render one player-subagent run as a self-contained HTML trace: everything the agent received,
2
+ every command it ran, every result and image it saw, its own text, plus the server-side ground truth.
3
+
4
+ python scripts/trace_html.py --batch exp1 --sandbox <hex> --out traces/<name>.html
5
+ """
6
+ import argparse
7
+ import base64
8
+ import html
9
+ import json
10
+ import os
11
+ from datetime import datetime
12
+
13
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
14
+ TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (<agentId>.output files)
15
+
16
+ CSS = """
17
+ :root{--bg:#fafaf9;--fg:#1c1917;--mut:#57534e;--card:#fff;--bd:#e7e5e4;--acc:#2563eb;--tool:#f5f5f4;--ok:#15803d;--bad:#b91c1c;--th:#7c3aed}
18
+ @media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#1c1917;--fg:#e7e5e4;--mut:#a8a29e;--card:#292524;--bd:#44403c;--acc:#60a5fa;--tool:#231f1d;--ok:#4ade80;--bad:#f87171;--th:#c4b5fd}}
19
+ body{background:var(--bg);color:var(--fg);font:14px/1.55 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;margin:0;padding:16px;max-width:1100px;margin:auto}
20
+ h1{font-size:20px}h2{font-size:17px;margin-top:28px;border-bottom:1px solid var(--bd);padding-bottom:4px}
21
+ .card{background:var(--card);border:1px solid var(--bd);border-radius:8px;padding:10px 12px;margin:8px 0}
22
+ pre{white-space:pre-wrap;word-break:break-word;background:var(--tool);border:1px solid var(--bd);border-radius:6px;padding:8px;font:12px/1.45 ui-monospace,Menlo,monospace;margin:4px 0;max-height:420px;overflow:auto}
23
+ .lbl{font-size:12px;color:var(--mut);font-weight:600;text-transform:uppercase;letter-spacing:.03em}
24
+ .cmd{color:var(--acc)}.think{color:var(--th)}.ok{color:var(--ok);font-weight:600}.bad{color:var(--bad);font-weight:600}
25
+ img{max-width:256px;border-radius:4px;border:1px solid var(--bd);margin:2px}
26
+ details>summary{cursor:pointer;color:var(--mut)}
27
+ table{border-collapse:collapse}td,th{border:1px solid var(--bd);padding:3px 8px;text-align:left;font-size:13px}
28
+ .step{display:flex;gap:8px}.n{color:var(--mut);min-width:34px;font-variant-numeric:tabular-nums}
29
+ """
30
+
31
+
32
+ def esc(s):
33
+ return html.escape(str(s))
34
+
35
+
36
+ def ts(x):
37
+ return datetime.fromisoformat(x.replace("Z", "+00:00")).timestamp()
38
+
39
+
40
+ def main():
41
+ ap = argparse.ArgumentParser()
42
+ ap.add_argument("--batch", default="exp1")
43
+ ap.add_argument("--sandbox", required=True, help="sandbox hex id")
44
+ ap.add_argument("--out", required=True)
45
+ ap.add_argument("--title", default="")
46
+ a = ap.parse_args()
47
+ m = json.load(open(os.path.join(ROOT, "runs", "claude", a.batch, "manifest.json")))
48
+ run = next(r for r in m["runs"] if r["sandbox"].endswith(a.sandbox))
49
+ tr = [json.loads(l) for l in open(os.path.join(TRANSCRIPTS, f"{run['agent']}.output"))]
50
+ ev = [json.loads(l) for l in open(os.path.join(run["log"], "events.jsonl"))]
51
+ start = next(e for e in ev if e["ev"] == "session_start")
52
+ dones = [e for e in ev if e["ev"] == "done"]
53
+ http = [e for e in ev if e["ev"] == "http"]
54
+ think = [h["think_s"] for h in http if h.get("think_s")]
55
+ srv = [h["server_s"] for h in http]
56
+
57
+ out = [f"<!doctype html><html lang='zh'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>{esc(a.title or 'Agent trace')}</title><style>{CSS}</style></head><body>"]
58
+ out.append(f"<h1>{esc(a.title or run['run'])}</h1>")
59
+ out.append("<div class='card'><table>")
60
+ rows = [("任务", run["task"]), ("种子", run["seed"]), ("模型", run["model"]), ("条件", run["cond"] + f"(k={run['k']})"),
61
+ ("沙箱", run["sandbox"]), ("服务端 run 名", run["run"]),
62
+ ("结果", ";".join(f"第{d['attempt']}次 {'成功' if d['success'] else '失败'}" for d in dones)),
63
+ ("命令数 / 模型思考总时长 / 仿真执行总时长", f"{sum(1 for e in ev if e['ev']=='call')} / {sum(think):.0f} s / {sum(srv):.0f} s"),
64
+ ("子代理墙钟", f"{(ts(tr[-1]['timestamp']) - ts(tr[0]['timestamp'])) / 60:.1f} min")]
65
+ for k, v in rows:
66
+ out.append(f"<tr><th>{esc(k)}</th><td>{esc(v)}</td></tr>")
67
+ out.append("</table></div>")
68
+ inst = {k: v for k, v in start["inst"].items()}
69
+ out.append("<div class='card'><div class='lbl'>服务端真值(agent 从未看到)</div><pre>" + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "</pre></div>")
70
+
71
+ # ---------------------------------------------------------------- what the agent received
72
+ out.append("<h2>1. agent 收到的上下文</h2>")
73
+ out.append("<div class='card'>Claude Code 内置的系统提示和工具定义不在对话记录里(由 Claude Code 注入,这里看不到原文)。下面是记录里能看到的全部注入内容和我的提示。</div>")
74
+ for d in tr:
75
+ if d["type"] != "attachment":
76
+ continue
77
+ at = d["attachment"]
78
+ t = at.get("type")
79
+ if t == "instructions":
80
+ for f in at.get("files", []):
81
+ out.append(f"<details class='card'><summary>注入附���:{esc(f.get('type'))} — {esc(f.get('path'))}({len(f.get('content',''))} 字符)</summary><pre>{esc(f.get('content',''))}</pre></details>")
82
+ elif t in ("environment", "model", "date", "session_context", "skill_listing", "deferred_tools_delta", "credential_org"):
83
+ body = json.dumps({k: v for k, v in at.items() if k != "type"}, ensure_ascii=False, indent=1)
84
+ out.append(f"<details class='card'><summary>注入附件:{esc(t)}({len(body)} 字符)</summary><pre>{esc(body[:6000])}</pre></details>")
85
+ first_user = next(d for d in tr if d["type"] == "user")
86
+ out.append("<div class='card'><div class='lbl'>我给 agent 的提示(原文)</div><pre>" + esc(first_user["message"]["content"]) + "</pre></div>")
87
+
88
+ # ---------------------------------------------------------------- timeline
89
+ out.append("<h2>2. 逐步过程(agent 的文字、执行的命令、收到的结果和图像)</h2>")
90
+ n = 0
91
+ results = {}
92
+ for d in tr:
93
+ if d["type"] == "user" and isinstance(d["message"].get("content"), list):
94
+ for c in d["message"]["content"]:
95
+ if c.get("type") == "tool_result":
96
+ results[c["tool_use_id"]] = c
97
+ t0 = ts(tr[0]["timestamp"])
98
+ for d in tr:
99
+ if d["type"] != "assistant":
100
+ continue
101
+ for c in d["message"].get("content", []):
102
+ ct = c.get("type")
103
+ tt = f"+{ts(d['timestamp']) - t0:6.0f}s"
104
+ if ct == "thinking" and c.get("thinking"):
105
+ out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl think'>思考</span><pre class='think'>{esc(c['thinking'])}</pre></div>")
106
+ elif ct == "text" and c.get("text", "").strip():
107
+ out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>agent 文字</span><pre>{esc(c['text'])}</pre></div>")
108
+ elif ct == "tool_use":
109
+ n += 1
110
+ inp = c.get("input", {})
111
+ if c["name"] == "Bash":
112
+ head = f"Bash: <span class='cmd'>{esc(inp.get('command',''))}</span>"
113
+ elif c["name"] == "Read":
114
+ head = f"Read: <span class='cmd'>{esc(inp.get('file_path',''))}</span>"
115
+ elif c["name"] == "SubagentHandback":
116
+ head = "最终报告(SubagentHandback)"
117
+ else:
118
+ head = f"{esc(c['name'])}: {esc(json.dumps(inp, ensure_ascii=False)[:300])}"
119
+ block = [f"<div class='card'><span class='n'>{tt} #{n}</span> <span class='lbl'>工具调用</span> {head}"]
120
+ if c["name"] == "SubagentHandback":
121
+ block.append(f"<pre>{esc(inp.get('message',''))}</pre>")
122
+ r = results.get(c["id"])
123
+ if r is not None:
124
+ rc = r.get("content")
125
+ if isinstance(rc, str):
126
+ rc = [{"type": "text", "text": rc}]
127
+ for part in rc or []:
128
+ if part.get("type") == "text":
129
+ txt = part["text"]
130
+ block.append(f"<details {'open' if len(txt) < 1500 else ''}><summary>返回({len(txt)} 字符)</summary><pre>{esc(txt)}</pre></details>")
131
+ elif part.get("type") == "image":
132
+ src = part.get("source", {})
133
+ if src.get("type") == "base64":
134
+ block.append(f"<img src='data:{src.get('media_type','image/jpeg')};base64,{src['data']}'>")
135
+ block.append("</div>")
136
+ out.extend(block)
137
+ out.append("<h2>3. 服务端每次 done 的判定</h2>")
138
+ for e in dones:
139
+ out.append(f"<div class='card'>第 {e['attempt']} 次:<span class='{'ok' if e['success'] else 'bad'}'>{'成功' if e['success'] else '失败'}</span><pre>{esc(e.get('feedback',''))}</pre></div>")
140
+ out.append("</body></html>")
141
+ os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
142
+ with open(a.out, "w") as f:
143
+ f.write("\n".join(out))
144
+ print(a.out, os.path.getsize(a.out), "bytes; tool calls", n)
145
+
146
+
147
+ if __name__ == "__main__":
148
+ main()
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench: a learn-from-failure benchmark for robot agents on LIBERO."""
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/bddl.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tiny BDDL writer for tabletop problems. Layout is overridden at reset by the task, so the
2
+ regions here only need to be valid placement areas."""
3
+ import os
4
+
5
+ from .objects import GEN_DIR
6
+
7
+
8
+ def region(name, x0, y0, x1, y1, yaw=None):
9
+ s = f""" ({name}
10
+ (:target main_table)
11
+ (:ranges (
12
+ ({x0} {y0} {x1} {y1})
13
+ )
14
+ )"""
15
+ if yaw is not None:
16
+ s += f"""
17
+ (:yaw_rotation (
18
+ ({yaw} {yaw})
19
+ )
20
+ )"""
21
+ return s + "\n )\n"
22
+
23
+
24
+ def write_bddl(task_name, language, objects, fixtures=(), extra_regions="", goal="(And)"):
25
+ """objects / fixtures: list of (instance_name, category, region_name, (x0,y0,x1,y1))."""
26
+ regs = ""
27
+ for inst, cat, rname, box in list(objects) + list(fixtures):
28
+ regs += region(rname, *box)
29
+ regs += extra_regions
30
+ fx = "\n".join(f" {i} - {c}" for i, c, _, _ in fixtures)
31
+ ob = "\n".join(f" {i} - {c}" for i, c, _, _ in objects)
32
+ init = "\n".join(f" (On {i} main_table_{r})" for i, _, r, _ in list(objects) + list(fixtures))
33
+ text = f"""(define (problem LIBERO_Tabletop_Manipulation)
34
+ (:domain robosuite)
35
+ (:language {language})
36
+ (:regions
37
+ {regs} )
38
+
39
+ (:fixtures
40
+ main_table - table
41
+ {fx}
42
+ )
43
+
44
+ (:objects
45
+ {ob}
46
+ )
47
+
48
+ (:obj_of_interest
49
+ )
50
+
51
+ (:init
52
+ {init}
53
+ )
54
+
55
+ (:goal
56
+ {goal}
57
+ )
58
+
59
+ )
60
+ """
61
+ path = os.path.join(GEN_DIR, f"{task_name}.bddl")
62
+ tmp = f"{path}.{os.getpid()}.tmp" # atomic: concurrent builders must never read a half-written file
63
+ with open(tmp, "w") as f:
64
+ f.write(text)
65
+ os.replace(tmp, path)
66
+ return path
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/envs.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Environment construction and low-level sim helpers on top of LIBERO / robosuite."""
2
+ import os
3
+
4
+ os.environ.setdefault("MUJOCO_GL", "osmesa")
5
+ os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
6
+ # LIBERO reads its paths from <LIBERO_CONFIG_PATH>/config.yaml (written by setup/install.sh into <repo>/.libero)
7
+ os.environ.setdefault("LIBERO_CONFIG_PATH", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".libero"))
8
+
9
+ import numpy as np
10
+
11
+ TABLE_Z = 0.90 # LIBERO main_table top surface (table_offset z)
12
+ # Upper limit of the Panda elbow (robot0_joint4; stock -0.0698). The arm is fully stretched at about -0.47 rad; a fast
13
+ # move out of a far pose could carry the elbow past that into (-0.47, -0.07], where the OSC's only way to shorten the
14
+ # arm runs into the stock limit and every later move stops 4-17 cm short for the rest of the attempt (measured
15
+ # 2026-10-19: 50 of 160 targets of the workspace box; 44 of 714 logged LA attempts). Capping the joint keeps the elbow
16
+ # on the normal side: reach is unchanged, and no scripted oracle / naive run of the main set goes above -0.73.
17
+ ELBOW_Q4_MAX = -0.55
18
+
19
+
20
+ def make_env(bddl_path, cam_res=256, cams=("agentview", "robot0_eye_in_hand"), depth=False, controller=None):
21
+ """Build a LIBERO env from a BDDL file without camera rendering on every step.
22
+
23
+ Images are rendered on demand with `render(env, cam)`.
24
+ """
25
+ import robosuite as suite
26
+ import libero.libero.envs.bddl_utils as BDDLUtils
27
+ from libero.libero.envs import TASK_MAPPING
28
+
29
+ cfg = suite.load_controller_config(default_controller="OSC_POSE")
30
+ if controller is None:
31
+ from .skills import CONTROLLER
32
+ controller = CONTROLLER
33
+ if controller:
34
+ cfg.update(controller)
35
+ info = BDDLUtils.get_problem_info(bddl_path)
36
+ env = TASK_MAPPING[info["problem_name"]](
37
+ bddl_path,
38
+ robots=["Panda"],
39
+ controller_configs=cfg,
40
+ gripper_types="default",
41
+ initialization_noise=None,
42
+ use_camera_obs=False,
43
+ has_renderer=False,
44
+ has_offscreen_renderer=True,
45
+ render_camera="frontview",
46
+ render_collision_mesh=False,
47
+ render_visual_mesh=True,
48
+ render_gpu_device_id=-1,
49
+ control_freq=20,
50
+ horizon=10 ** 7,
51
+ ignore_done=True,
52
+ hard_reset=False,
53
+ camera_names=list(cams),
54
+ camera_heights=cam_res,
55
+ camera_widths=cam_res,
56
+ camera_depths=depth,
57
+ camera_segmentations=None,
58
+ renderer="mujoco",
59
+ renderer_config=None,
60
+ )
61
+ env.lff_language = info["language_instruction"]
62
+ m = env.sim.model # hard_reset=False: the model (and this limit) survives env.reset()
63
+ m.jnt_range[m.joint_name2id("robot0_joint4"), 1] = ELBOW_Q4_MAX
64
+ return env
65
+
66
+
67
+ def render(env, cam="agentview", res=256, depth=False):
68
+ """Render an RGB image (H, W, 3, uint8), upright."""
69
+ out = env.sim.render(camera_name=cam, width=res, height=res, depth=depth)
70
+ if depth:
71
+ rgb, d = out
72
+ return rgb[::-1].copy(), d[::-1].copy()
73
+ return out[::-1].copy()
74
+
75
+
76
+ # ---------------------------------------------------------------- object state helpers
77
+
78
+ def body_id(env, obj_name):
79
+ return env.sim.model.body_name2id(env.objects_dict[obj_name].root_body)
80
+
81
+
82
+ def obj_pos(env, obj_name):
83
+ return env.sim.data.body_xpos[body_id(env, obj_name)].copy()
84
+
85
+
86
+ def obj_quat(env, obj_name):
87
+ """wxyz"""
88
+ return env.sim.data.body_xquat[body_id(env, obj_name)].copy()
89
+
90
+
91
+ def obj_upright_cos(env, obj_name):
92
+ """cos of the angle between the object's z axis and world z."""
93
+ xmat = env.sim.data.body_xmat[body_id(env, obj_name)].reshape(3, 3)
94
+ return float(xmat[2, 2])
95
+
96
+
97
+ def free_joint_addr(env, obj_name):
98
+ jname = env.objects_dict[obj_name].joints[0]
99
+ jid = env.sim.model.joint_name2id(jname)
100
+ return env.sim.model.jnt_qposadr[jid], env.sim.model.jnt_dofadr[jid]
101
+
102
+
103
+ def set_obj_pose(env, obj_name, pos, yaw=0.0, quat_wxyz=None):
104
+ """Teleport a free-joint object (used only at reset / by the protocol, never by agents)."""
105
+ qa, da = free_joint_addr(env, obj_name)
106
+ if quat_wxyz is None:
107
+ quat_wxyz = np.array([np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)])
108
+ env.sim.data.qpos[qa:qa + 3] = pos
109
+ env.sim.data.qpos[qa + 3:qa + 7] = quat_wxyz
110
+ env.sim.data.qvel[da:da + 6] = 0.0
111
+
112
+
113
+ def obj_geom_ids(env, obj_name):
114
+ return [env.sim.model.geom_name2id(g) for g in env.objects_dict[obj_name].contact_geoms]
115
+
116
+
117
+ def set_friction(env, obj_name, mu, priority=2):
118
+ """Set sliding friction of an object's collision geoms and give them priority so their
119
+ friction is used in contacts (MuJoCo otherwise takes the max of the two geoms)."""
120
+ for g in obj_geom_ids(env, obj_name):
121
+ env.sim.model.geom_friction[g, 0] = mu
122
+ env.sim.model.geom_priority[g] = priority
123
+
124
+
125
+ def scale_mass(env, obj_name, mass):
126
+ bid = body_id(env, obj_name)
127
+ m0 = env.sim.model.body_mass[bid]
128
+ env.sim.model.body_mass[bid] = mass
129
+ env.sim.model.body_inertia[bid] *= mass / max(m0, 1e-9)
130
+
131
+
132
+ def settle(env, steps=20):
133
+ """Let physics settle while holding the arm still."""
134
+ for _ in range(steps):
135
+ env.step(np.zeros(env.action_dim))
136
+
137
+
138
+ def contacts_between(env, geoms_a, geoms_b):
139
+ a, b = set(geoms_a), set(geoms_b)
140
+ d = env.sim.data
141
+ for i in range(d.ncon):
142
+ c = d.contact[i]
143
+ if (c.geom1 in a and c.geom2 in b) or (c.geom1 in b and c.geom2 in a):
144
+ return True
145
+ return False
146
+
147
+
148
+ def robot_geom_ids(env):
149
+ m = env.sim.model
150
+ ids = []
151
+ for g in range(m.ngeom):
152
+ n = m.geom_id2name(g) or ""
153
+ if n.startswith("robot0_") or n.startswith("gripper0_"):
154
+ ids.append(g)
155
+ return ids
156
+
157
+
158
+ # ---------------------------------------------------------------- upright placement (added 2026-10-06)
159
+
160
+ def _quat_mul(a, b):
161
+ """wxyz quaternion product a*b"""
162
+ w1, x1, y1, z1 = a
163
+ w2, x2, y2, z2 = b
164
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
165
+ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
166
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
167
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
168
+
169
+
170
+ def canonical_quat(env, obj_name):
171
+ """The orientation LIBERO's own placement gives an object, with any random yaw set to 0 (wxyz).
172
+
173
+ Reproduces LIBERO exactly, including its convention bug: TableRegionSampler._sample_quat builds an
174
+ xyzw quaternion, multiplies it with obj.init_quat (xyzw), and bddl_base_domain writes that array
175
+ straight into the wxyz qpos slot. E.g. scanned objects (plate, bowls, basket; rotation (pi/2, pi/2)
176
+ about x) therefore end up yawed by 90 deg, not rolled; HOPE groceries (dict rotation) come out
177
+ as (0.5, 0.5, 0.5, 0.5), which is the same under both readings. (Fixed 2026-10-06 after the L3
178
+ developer found plates being stood on edge.)"""
179
+ from robosuite.utils.transform_utils import quat_multiply
180
+
181
+ o = env.objects_dict[obj_name]
182
+ rot = getattr(o, "rotation", None)
183
+ ax = getattr(o, "rotation_axis", None) or "z"
184
+
185
+ def xyzw(axis, a):
186
+ h = a / 2
187
+ return {"x": np.array([np.sin(h), 0.0, 0.0, np.cos(h)]),
188
+ "y": np.array([0.0, np.sin(h), 0.0, np.cos(h)]),
189
+ "z": np.array([0.0, 0.0, np.sin(h), np.cos(h)])}[axis]
190
+
191
+ def fixed(r): # a random range means a free angle -> use 0 (only yaw ranges occur in practice)
192
+ return float(r[0]) if float(min(r)) == float(max(r)) else 0.0
193
+
194
+ if isinstance(rot, dict):
195
+ q = np.array([0.0, 0.0, 0.0, 1.0])
196
+ for axis, r in rot.items():
197
+ q = quat_multiply(xyzw(axis, fixed(r)), q)
198
+ else:
199
+ if rot is None:
200
+ a = 0.0
201
+ elif isinstance(rot, (tuple, list)):
202
+ a = fixed(rot)
203
+ else:
204
+ a = float(rot)
205
+ q = xyzw(ax, a)
206
+ init = np.array(getattr(o, "init_quat", [0.0, 0.0, 0.0, 1.0]), dtype=float)
207
+ q = quat_multiply(q, init)
208
+ return np.array(q, dtype=float) # used directly as wxyz, like LIBERO does
209
+
210
+
211
+ def obj_min_z(env, obj_name):
212
+ """Lowest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
213
+ m, d = env.sim.model, env.sim.data
214
+ zmin = np.inf
215
+ for g in obj_geom_ids(env, obj_name):
216
+ R = d.geom_xmat[g].reshape(3, 3)
217
+ c_local = m.geom_aabb[g, :3]
218
+ half = m.geom_aabb[g, 3:]
219
+ cz = d.geom_xpos[g][2] + R[2] @ c_local
220
+ zmin = min(zmin, cz - np.abs(R[2]) @ half)
221
+ return float(zmin)
222
+
223
+
224
+ def obj_max_z(env, obj_name):
225
+ """Highest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
226
+ m, d = env.sim.model, env.sim.data
227
+ zmax = -np.inf
228
+ for g in obj_geom_ids(env, obj_name):
229
+ R = d.geom_xmat[g].reshape(3, 3)
230
+ cz = d.geom_xpos[g][2] + R[2] @ m.geom_aabb[g, :3]
231
+ zmax = max(zmax, cz + np.abs(R[2]) @ m.geom_aabb[g, 3:])
232
+ return float(zmax)
233
+
234
+
235
+ FINGERTIP_BELOW_SITE = 0.0095 # lowest point of the Panda finger collision meshes below the grasp site (measured)
236
+
237
+
238
+ def place_upright(env, obj_name, xy, yaw=0.0, surface_z=TABLE_Z, clearance=0.002):
239
+ """Teleport an object upright (LIBERO canonical orientation, then `yaw` about world z) so that its
240
+ lowest collision point sits `clearance` above `surface_z`. Call env.sim.forward() / settle after."""
241
+ q = _quat_mul(np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]), canonical_quat(env, obj_name))
242
+ set_obj_pose(env, obj_name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
243
+ env.sim.forward()
244
+ dz = obj_min_z(env, obj_name) - (surface_z + clearance)
245
+ qa, _ = free_joint_addr(env, obj_name)
246
+ env.sim.data.qpos[qa + 2] -= dz
247
+ env.sim.forward()
248
+
249
+
250
+ # ---------------------------------------------------------------- collision bounds after runtime edits (2026-10-12)
251
+
252
+ def _quat2mat(q):
253
+ w, x, y, z = q
254
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
255
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
256
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
257
+
258
+
259
+ def _prim_bounds(m, g):
260
+ """(half extents in the geom frame, bounding-sphere radius) of a primitive geom from geom_size; None otherwise"""
261
+ t, s = int(m.geom_type[g]), m.geom_size[g]
262
+ if t == 6: # box
263
+ return np.array(s[:3], float), float(np.linalg.norm(s[:3]))
264
+ if t == 4: # ellipsoid
265
+ return np.array(s[:3], float), float(max(s[:3]))
266
+ if t == 2: # sphere
267
+ return np.full(3, float(s[0])), float(s[0])
268
+ if t == 5: # cylinder
269
+ return np.array([s[0], s[0], s[1]], float), float(np.hypot(s[0], s[1]))
270
+ if t == 3: # capsule
271
+ return np.array([s[0], s[0], s[0] + s[1]], float), float(s[0] + s[1])
272
+ return None
273
+
274
+
275
+ def refit_bounds(model, bodies, margin=0.0, geoms=True):
276
+ """Make the collision bounds of `bodies` (body id or ids) consistent again after runtime edits of their geoms
277
+ (geom_size / geom_pos / geom_quat) or of their inertial frame (body_ipos / body_iquat). `model`: an env, a
278
+ robosuite MjModel wrapper or a raw mujoco.MjModel.
279
+
280
+ MuJoCo (3.2.3) computes these bounds at compile time and never updates them: geom_aabb / geom_rbound (geom
281
+ frame; broad phase and geom-pair filters) and the per-body bounding-volume hierarchy bvh_aabb, stored in the
282
+ body's INERTIAL frame and used by the mid-phase whenever one of the two bodies of a pair has >= 2 collision
283
+ geoms. Stale boxes make MuJoCo silently skip contacts (lh_fence v1: a post whose centre of mass was raised sank
284
+ 2.2 cm into the table; measured 2026-10-12: a body with a single collision geom whose COM moved 6 cm missed every
285
+ contact with a 2-geom body beyond the shifted box). With geoms=True the primitive geoms' geom_aabb / geom_rbound
286
+ are recomputed from geom_size (meshes keep theirs); then every BVH node becomes the union of its leaf geoms'
287
+ boxes (+ margin) in the runtime inertial frame, following body_sameframe / geom_sameframe like mj_kinematics
288
+ (on a pristine model this reproduces the compiled bvh_aabb exactly).
289
+ Also note: a runtime body_ipos is ignored by MuJoCo if the compiled inertial pos is the body origin
290
+ (body_sameframe = 1); bodies whose centre of mass is moved at runtime need a non-zero compiled inertial pos."""
291
+ if hasattr(model, "sim"):
292
+ model = model.sim.model
293
+ m = getattr(model, "_model", model)
294
+ for b in np.atleast_1d(bodies):
295
+ b = int(b)
296
+ if geoms:
297
+ for g in range(int(m.body_geomadr[b]), int(m.body_geomadr[b] + m.body_geomnum[b])):
298
+ pb = _prim_bounds(m, g)
299
+ if pb is not None:
300
+ m.geom_aabb[g] = [0.0, 0.0, 0.0, *pb[0]]
301
+ m.geom_rbound[g] = pb[1]
302
+ a, n = int(m.body_bvhadr[b]), int(m.body_bvhnum[b])
303
+ if a < 0 or n < 1:
304
+ continue
305
+ sf = int(m.body_sameframe[b]) # 1: inertial frame = body frame, 3: same orientation as the body
306
+ ip = np.zeros(3) if sf == 1 else np.array(m.body_ipos[b], float)
307
+ iR = np.eye(3) if sf in (1, 3) else _quat2mat(m.body_iquat[b])
308
+
309
+ def rec(i):
310
+ g = int(m.bvh_nodeid[i])
311
+ if g >= 0:
312
+ gsf = int(m.geom_sameframe[g]) # 1: body frame, 2: inertial frame, 3/4: their orientation
313
+ gp = np.zeros(3) if gsf == 1 else ip if gsf == 2 else np.array(m.geom_pos[g], float)
314
+ gR = np.eye(3) if gsf in (1, 3) else iR if gsf in (2, 4) else _quat2mat(m.geom_quat[g])
315
+ R = iR.T @ gR
316
+ c = iR.T @ (gp - ip) + R @ np.asarray(m.geom_aabb[g, :3])
317
+ h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:])
318
+ lo, hi = c - h, c + h
319
+ else:
320
+ l1, h1 = rec(a + int(m.bvh_child[i][0]))
321
+ l2, h2 = rec(a + int(m.bvh_child[i][1]))
322
+ lo, hi = np.minimum(l1, l2), np.maximum(h1, h2)
323
+ m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin])
324
+ return lo, hi
325
+ rec(a)
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/skills.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Motion primitives executed with robosuite's OSC_POSE controller.
2
+
3
+ All positions are world-frame metres (LIBERO table top is z = TABLE_Z = 0.90).
4
+ `bias` is a hidden calibration error added to every commanded position (used by L1 tasks);
5
+ agents never see it.
6
+ """
7
+ import numpy as np
8
+ import robosuite.utils.transform_utils as T
9
+
10
+ from .envs import TABLE_Z
11
+
12
+ DT = 0.05 # control period (20 Hz)
13
+ ROT_SCALE = 0.5
14
+ # Faster OSC than LIBERO's default (default caps the end effector at ~0.25 m/s; this reaches ~0.6 m/s).
15
+ CONTROLLER = dict(kp=300, output_max=[0.1, 0.1, 0.1, 0.5, 0.5, 0.5], output_min=[-0.1, -0.1, -0.1, -0.5, -0.5, -0.5])
16
+
17
+
18
+ def _rotz(a):
19
+ c, s = np.cos(a), np.sin(a)
20
+ return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
21
+
22
+
23
+ def _rot_err(R_target, R_cur):
24
+ """axis-angle (world frame) rotating R_cur to R_target"""
25
+ R = R_target @ R_cur.T
26
+ q = T.mat2quat(R) # xyzw
27
+ return T.quat2axisangle(q)
28
+
29
+
30
+ class Skills:
31
+ def __init__(self, env, bias=None, recorder=None):
32
+ self.env = env
33
+ self.pos_scale = float(env.robots[0].controller.output_max[0])
34
+ self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
35
+ self.grip = -1.0 # -1 open, +1 closed
36
+ self.R0 = self.eef_mat().copy() # top-down orientation at reset == yaw 0
37
+ self.yaw = 0.0
38
+ self.recorder = recorder # callable(env) invoked every `record_every` control steps
39
+ self.record_every = 4
40
+ self.n_steps = 0
41
+ self.log = []
42
+
43
+ # ------------------------------------------------------------------ state
44
+ def eef_pos(self):
45
+ return self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id].copy()
46
+
47
+ def eef_mat(self):
48
+ return self.env.sim.data.site_xmat[self.env.robots[0].eef_site_id].reshape(3, 3).copy()
49
+
50
+ def gripper_width(self):
51
+ g = self.env.robots[0].gripper
52
+ q = [self.env.sim.data.qpos[self.env.sim.model.joint_name2id(j)] for j in g.joints]
53
+ return float(abs(q[0] - q[1]))
54
+
55
+ def holding(self, obj_name):
56
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
57
+ object_geoms=self.env.objects_dict[obj_name]))
58
+
59
+ # ------------------------------------------------------------------ low level
60
+ def _act(self, dpos, drot, grip):
61
+ a = np.zeros(7)
62
+ a[:3] = np.clip(dpos / self.pos_scale, -1, 1)
63
+ a[3:6] = np.clip(drot / ROT_SCALE, -1, 1)
64
+ a[6] = grip
65
+ self.env.step(a)
66
+ self.n_steps += 1
67
+ if self.recorder is not None and self.n_steps % self.record_every == 0:
68
+ self.recorder(self.env)
69
+
70
+ def hold(self, steps=10):
71
+ p, R = self.eef_pos(), self._R()
72
+ for _ in range(steps):
73
+ self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
74
+
75
+ def _R(self, yaw=None):
76
+ return _rotz(self.yaw if yaw is None else yaw) @ self.R0
77
+
78
+ # ------------------------------------------------------------------ primitives
79
+ YAW_LIMIT = np.pi / 2 + 0.4
80
+
81
+ def wrap_yaw(self, yaw):
82
+ """A parallel-jaw gripper is symmetric under a rotation by pi, so pick the equivalent yaw closest
83
+ to the current one inside |yaw| <= pi/2 + 0.4. Without this, asking for ~180 deg of wrist rotation
84
+ makes the OSC (whose axis-angle error is ambiguous at pi) wind the arm into its joint limits and
85
+ it never recovers (found by the L3 developer: push towards -y -> 0/6 success, 2026-10-06)."""
86
+ cands = [yaw + k * np.pi for k in range(-3, 4)]
87
+ ok = [c for c in cands if abs(c) <= self.YAW_LIMIT] or cands
88
+ return float(min(ok, key=lambda c: abs(c - self.yaw)))
89
+
90
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
91
+ """Move the gripper site to `target` (world xyz). If `speed` (m/s) is given the reference
92
+ moves along a straight line at that speed; otherwise go as fast as the controller allows.
93
+ `yaw` is wrapped to the closest gripper-symmetric equivalent unless wrap_yaw=False.
94
+ Returns a report dict."""
95
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
96
+ if yaw is not None:
97
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
98
+ R = self._R()
99
+ p0 = self.eef_pos()
100
+ dist = np.linalg.norm(tgt - p0)
101
+ direction = (tgt - p0) / max(dist, 1e-9)
102
+ s = 0.0
103
+ for k in range(max_steps):
104
+ if speed is not None:
105
+ s = min(dist, s + speed * DT)
106
+ ref = p0 + direction * s
107
+ # lead the reference a little so the OSC lag does not throttle the speed
108
+ ref = ref + direction * min(dist - s, speed * DT * 1.5)
109
+ else:
110
+ ref = tgt
111
+ cur = self.eef_pos()
112
+ self._act(ref - cur, _rot_err(R, self.eef_mat()), self.grip)
113
+ err = np.linalg.norm(tgt - self.eef_pos())
114
+ if err < tol and (speed is None or s >= dist):
115
+ break
116
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
117
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1)
118
+ self.log.append(rep)
119
+ return rep
120
+
121
+ def set_gripper(self, close, steps=15):
122
+ self.grip = 1.0 if close else -1.0
123
+ self.hold(steps)
124
+ rep = dict(prim="close" if close else "open", width=round(self.gripper_width(), 4))
125
+ self.log.append(rep)
126
+ return rep
127
+
128
+ def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
129
+ """Composite: above -> descend -> close -> lift. For scripted policies."""
130
+ self.set_gripper(False, steps=5)
131
+ self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
132
+ self.move_to([xy[0], xy[1], z_grasp], tol=0.003)
133
+ self.set_gripper(True, steps=15)
134
+ self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
135
+
136
+ def place_at(self, xy, z_release, approach=0.10):
137
+ self.move_to([xy[0], xy[1], z_release + approach])
138
+ self.move_to([xy[0], xy[1], z_release], tol=0.004)
139
+ self.set_gripper(False, steps=12)
140
+ self.move_to([xy[0], xy[1], z_release + approach])
141
+
142
+ def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
143
+ """Straight-line push: go to `pre` m behind the start point at height z with the gripper closed,
144
+ then sweep `pre + distance` along direction at `speed`, stop, and lift away."""
145
+ d = np.asarray(direction_xy, float)
146
+ d = d / np.linalg.norm(d)
147
+ z = TABLE_Z + 0.02 if z is None else z
148
+ s = np.asarray(start_xy, float) - d * pre
149
+ self.set_gripper(True, steps=5)
150
+ self.move_to([s[0], s[1], z + 0.12], yaw=np.arctan2(d[1], d[0]) - np.pi / 2)
151
+ self.move_to([s[0], s[1], z], tol=0.003)
152
+ e = s + d * (pre + distance)
153
+ rep = self.move_to([e[0], e[1], z], speed=speed, tol=0.01, max_steps=400)
154
+ self.hold(2)
155
+ self.move_to([e[0], e[1], z + 0.12], speed=0.3)
156
+ return rep
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/task_base.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task interface shared by all LFF-Bench tasks.
2
+
3
+ A task = a LIBERO scene + an instance sampler (layout and hidden variables) + a success / outcome
4
+ measurement + scripted reference policies used to validate that the task really requires learning
5
+ from failure:
6
+
7
+ oracle knows the hidden variables; should succeed on attempt 1
8
+ naive acts on the prior (what an agent would do without the failure information)
9
+ adaptive scripted learner that updates its parameters from structured (F2) feedback
10
+ blind repeats the naive behaviour with small random variation, no history
11
+
12
+ Tasks whose policies can be expressed as "execute(params)" get the cross-attempt protocol for free.
13
+ Tasks that need within-episode recovery override `run_scripted`.
14
+ """
15
+ import numpy as np
16
+
17
+ from . import envs
18
+ from .skills import Skills
19
+
20
+ TASKS = {}
21
+
22
+
23
+ def register_task(cls):
24
+ TASKS[cls.name] = cls
25
+ return cls
26
+
27
+
28
+ class LFFTask:
29
+ name = "base"
30
+ level = "L?"
31
+ # the user's 7 categories (2026-10-06): hidden information -> required capability -> adapted action
32
+ category = "" # system_identification | dynamics_adaptation | failed_interaction_inference |
33
+ # state_restoration | procedural_memory | strategy_switching | geometry_inference
34
+ capabilities = ()
35
+ max_attempts = 5
36
+ protocol = "cross" # "cross": reset between attempts; "within": one episode, recover in place
37
+ instruction = "" # direct reference
38
+ instruction_indirect = "" # descriptive reference (perception / semantic reasoning variant)
39
+ cam_res = 256
40
+
41
+ def __init__(self, cam_res=None):
42
+ if cam_res:
43
+ self.cam_res = cam_res
44
+ self.bddl_path = self.make_bddl()
45
+ self.env = envs.make_env(self.bddl_path, cam_res=self.cam_res)
46
+ self.env.reset()
47
+ self.sk = None
48
+
49
+ # ------------------------------------------------------------ to implement
50
+ def make_bddl(self):
51
+ raise NotImplementedError
52
+
53
+ def sample_instance(self, seed):
54
+ """Return a JSON-serialisable dict with layout + hidden variables."""
55
+ raise NotImplementedError
56
+
57
+ def apply_instance(self, inst):
58
+ """Place objects / set hidden physics after env.reset()."""
59
+ raise NotImplementedError
60
+
61
+ def outcome(self, inst):
62
+ """dict with at least {'success': bool}; may contain structured measurements."""
63
+ raise NotImplementedError
64
+
65
+ def feedback(self, inst, out, level="F2"):
66
+ """Text the agent receives after an attempt. F0: nothing, F1: success flag, F2: measurement."""
67
+ if level == "F0":
68
+ return ""
69
+ s = "Attempt succeeded." if out["success"] else "Attempt failed."
70
+ if level == "F1":
71
+ return s
72
+ return s + (" " + out["detail"] if out.get("detail") else "")
73
+
74
+ def skill_bias(self, inst):
75
+ return None
76
+
77
+ # scripted references (cross protocol) ----------------------------------
78
+ def default_params(self, inst):
79
+ raise NotImplementedError
80
+
81
+ def oracle_params(self, inst):
82
+ raise NotImplementedError
83
+
84
+ def adapt_params(self, inst, history):
85
+ raise NotImplementedError
86
+
87
+ def blind_params(self, inst, attempt, rng):
88
+ return self.default_params(inst)
89
+
90
+ def execute(self, inst, params):
91
+ raise NotImplementedError
92
+
93
+ # ------------------------------------------------------------ shared
94
+ def reset_instance(self, inst, recorder=None):
95
+ self.env.reset()
96
+ self.apply_instance(inst)
97
+ self.env.sim.forward()
98
+ envs.settle(self.env, 10)
99
+ self.sk = Skills(self.env, bias=self.skill_bias(inst), recorder=recorder)
100
+ return self.sk
101
+
102
+ def snapshot(self, cam="agentview", res=None):
103
+ return envs.render(self.env, cam, res or self.cam_res)
104
+
105
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
106
+ """Cross-attempt protocol with a scripted policy. Returns the per-attempt history."""
107
+ k = k or self.max_attempts
108
+ rng = np.random.default_rng(seed)
109
+ history = []
110
+ for a in range(k):
111
+ self.reset_instance(inst)
112
+ if kind == "oracle":
113
+ params = self.oracle_params(inst)
114
+ elif kind == "naive":
115
+ params = self.default_params(inst)
116
+ elif kind == "adaptive":
117
+ params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
118
+ elif kind == "blind":
119
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
120
+ else:
121
+ raise ValueError(kind)
122
+ self.execute(inst, params)
123
+ out = self.outcome(inst)
124
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
125
+ if on_attempt:
126
+ on_attempt(a, params, out)
127
+ if out["success"] or kind in ("oracle", "naive"):
128
+ break
129
+ return history
leaf/release/source_packages/models-20261115-g56sol_breakfast1_20261114/lff/source_closure/lffbench/vla.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate a visuomotor policy (VLA, e.g. pi0.5) on LFF-Bench instances.
2
+
3
+ A VLA sends 7-D OSC actions at 20 Hz instead of the agents' robot commands. Everything else is the benchmark's own:
4
+ task scenes and instances, per-attempt budgets, attempt transitions (cross = reset, within = continue in place) and
5
+ task.outcome(). The observation has the layout of the LeRobot replay dataset (scripts/lerobot_replay.py, Recorder.state),
6
+ so a policy trained on that dataset needs no adapter. Driver: scripts/vla_eval.py.
7
+
8
+ What differs from the agents' interface, and why:
9
+ - Actions go through sk._act, not env.step: the tasks' per-step monitors and failure injections live there.
10
+ - sk.grip and sk.yaw are kept in step with the policy, because outcome() and go_home() use them (Skills.hold holds
11
+ sk.yaw, not the current orientation) and set_gripper hooks run with steps=0 once the fingers have settled.
12
+ - The hidden offset of L1 tasks is applied in Skills.move_to / YawSkills.R0, which direct actions bypass. The policy still
13
+ reads its proprioception in the robot's believed frame (frame="believed"), as the agents do, but an L1 result does not
14
+ measure the same trap as for an agent: report those tasks separately.
15
+ - There is no `finish`: an attempt ends when its simulated-time budget runs out or the arm has been idle for idle_s.
16
+ """
17
+ import os
18
+ import select
19
+ import time
20
+
21
+ import msgpack
22
+ import numpy as np
23
+
24
+ from . import envs
25
+ from .agent import camera as C
26
+ from .skills import ROT_SCALE
27
+
28
+ CONTROL_HZ = 20
29
+ GRIP_SETTLE = 15 # control steps the fingers get before the set_gripper hooks fire (Skills.set_gripper's default)
30
+ IDLE_EEF_M = 0.001 # the grasp point moved less than this over idle_s, with the gripper command unchanged
31
+
32
+
33
+ def _rotz(a):
34
+ c, s = np.cos(a), np.sin(a)
35
+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
36
+
37
+
38
+ def read_state(env, sk, frame="believed"):
39
+ """8-D state: eef position (world, m), eef orientation (axis-angle), two finger joints -- the dataset's layout.
40
+ frame="believed" applies the hidden calibration errors the way everything shown to an agent does (Skills.bias,
41
+ YawSkills.yaw_bias; robot_server._believed_pose); without such an error it equals frame="true"."""
42
+ import robosuite.utils.transform_utils as T
43
+ d, rob = env.sim.data, env.robots[0]
44
+ pos = np.array(d.site_xpos[rob.eef_site_id], np.float64)
45
+ quat = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
46
+ if frame == "believed":
47
+ pos = pos - np.asarray(sk.bias, np.float64)
48
+ beta = float(getattr(sk, "yaw_bias", 0.0))
49
+ if beta:
50
+ quat = T.mat2quat(_rotz(-beta) @ T.quat2mat(quat))
51
+ elif frame != "true":
52
+ raise ValueError(f"unknown proprioception frame {frame!r}")
53
+ grip = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
54
+ return np.concatenate([pos, np.asarray(T.quat2axisangle(quat), np.float64), grip]).astype(np.float32)
55
+
56
+
57
+ def task_prompt(task, inst):
58
+ """The instruction an agent gets for this instance (robot_server.instruction): some tasks build it per instance."""
59
+ hook = getattr(task, "agent_instruction", None)
60
+ return hook(inst, "direct") if hook is not None else task.instruction
61
+
62
+
63
+ def read_obs(task, inst, res=256, frame="believed"):
64
+ """The observation a policy receives, in the openpi request format. Images are uint8 HWC, upright."""
65
+ env = task.env
66
+ return {"observation/image": envs.render(env, C.mj_cam("agentview"), res),
67
+ "observation/wrist_image": envs.render(env, C.mj_cam("wrist"), res),
68
+ "observation/state": read_state(env, task.sk, frame),
69
+ "prompt": task_prompt(task, inst)}
70
+
71
+
72
+ class PolicyActuator:
73
+ """Applies one policy action to the task's Skills. a = (dpos, drot, gripper) in [-1, 1], scaled like Skills._act;
74
+ gripper > 0 closes (dataset convention: -1 open, +1 close)."""
75
+
76
+ def __init__(self, task):
77
+ self.task = task
78
+ self.sk = task.sk
79
+ self.close = self.sk.grip > 0
80
+ self.wait = 0
81
+
82
+ def _sync_yaw(self):
83
+ sk = self.sk
84
+ R = sk.eef_mat() @ sk.R0.T
85
+ sk.yaw = float(np.arctan2(R[1, 0], R[0, 0]))
86
+
87
+ def step(self, action):
88
+ sk = self.sk
89
+ a = np.clip(np.asarray(action, np.float64), -1.0, 1.0)
90
+ close = bool(a[6] > 0)
91
+ if (sk.grip > 0) != self.close: # the task moved the jaws itself (l6_sequence_resume's emergency stop)
92
+ self.close, self.wait = sk.grip > 0, 0
93
+ if getattr(self.task, "_latch", None) is not None:
94
+ # The task is driving the arm (env.step ignores the action) until "the current primitive has returned" and
95
+ # the arm is home. A policy has no primitives, so only the arm reaching home ends the routine.
96
+ sk.log.append(dict(prim="vla_step"))
97
+ elif close != self.close:
98
+ self.close, self.wait = close, GRIP_SETTLE
99
+ sk.grip = 1.0 if close else -1.0
100
+ sk._act(a[:3] * sk.pos_scale, a[3:6] * ROT_SCALE, sk.grip)
101
+ self._sync_yaw()
102
+ if self.wait:
103
+ self.wait -= 1
104
+ if not self.wait:
105
+ sk.set_gripper(self.close, steps=0)
106
+
107
+
108
+ def probe_success(task, inst, timeout=120.0):
109
+ """Would outcome() call this a success right now? outcome() steps the simulator and changes the task's monitors, so
110
+ it runs in a forked copy of this process; the attempt in the parent is untouched."""
111
+ r, w = os.pipe()
112
+ pid = os.fork()
113
+ if pid == 0:
114
+ code = 1
115
+ try:
116
+ os.close(r)
117
+ os.write(w, b"1" if task.outcome(inst)["success"] else b"0")
118
+ code = 0
119
+ finally:
120
+ os._exit(code)
121
+ os.close(w)
122
+ ready = select.select([r], [], [], timeout)[0]
123
+ got = os.read(r, 1) if ready else b""
124
+ os.close(r)
125
+ if not ready:
126
+ os.kill(pid, 9)
127
+ os.waitpid(pid, 0)
128
+ return got == b"1"
129
+
130
+
131
+ # ---------------------------------------------------------------- policies
132
+ class PolicyEnded(Exception):
133
+ """The policy has no more actions (a replayed recording ran out)."""
134
+
135
+
136
+ class ZeroPolicy:
137
+ """Holds still with the gripper open. Smoke tests only."""
138
+ metadata = dict(policy="zero")
139
+
140
+ def reset(self):
141
+ pass
142
+
143
+ def infer(self, obs):
144
+ a = np.zeros((10, 7), np.float32)
145
+ a[:, 6] = -1.0
146
+ return a
147
+
148
+
149
+ class ReplayPolicy:
150
+ """Replays recorded actions open loop, ignoring the observation. Used to test the evaluator against the recorded
151
+ verdicts (scripts/vla_acceptance.py)."""
152
+ metadata = dict(policy="replay")
153
+
154
+ def __init__(self, actions, chunk=5, on_obs=None):
155
+ self.actions, self.chunk, self.on_obs = actions, int(chunk), on_obs
156
+ self.t = 0
157
+
158
+ def reset(self):
159
+ pass
160
+
161
+ def infer(self, obs):
162
+ if self.t >= len(self.actions):
163
+ raise PolicyEnded()
164
+ if self.on_obs is not None:
165
+ self.on_obs(self.t, obs)
166
+ chunk = self.actions[self.t:self.t + self.chunk]
167
+ self.t += len(chunk)
168
+ return chunk
169
+
170
+
171
+ def _pack(o):
172
+ if isinstance(o, np.ndarray):
173
+ return {b"__ndarray__": True, b"data": o.tobytes(), b"dtype": o.dtype.str, b"shape": o.shape}
174
+ if isinstance(o, np.generic):
175
+ return {b"__npgeneric__": True, b"data": o.item(), b"dtype": o.dtype.str}
176
+ return o
177
+
178
+
179
+ def _unpack(o):
180
+ if b"__ndarray__" in o:
181
+ return np.ndarray(buffer=o[b"data"], dtype=np.dtype(o[b"dtype"]), shape=o[b"shape"])
182
+ if b"__npgeneric__" in o:
183
+ return np.dtype(o[b"dtype"]).type(o[b"data"])
184
+ return o
185
+
186
+
187
+ class WebsocketPolicy:
188
+ """Client of a policy server speaking the openpi websocket protocol (openpi scripts/serve_policy.py; StarVLA's
189
+ WebsocketPolicyServer, which wraps the reply in {"status", "data"})."""
190
+
191
+ def __init__(self, url, open_timeout=300):
192
+ from websockets.sync.client import connect
193
+ # No keepalive pings: the server cannot answer them while it runs a request, and the first one compiles the model
194
+ # for minutes on PPU.
195
+ self.ws = connect(url, compression=None, max_size=None, open_timeout=open_timeout, ping_interval=None)
196
+ self.metadata = msgpack.unpackb(self.ws.recv(), object_hook=_unpack)
197
+
198
+ def reset(self):
199
+ pass
200
+
201
+ def infer(self, obs):
202
+ self.ws.send(msgpack.packb(obs, default=_pack))
203
+ out = self.ws.recv()
204
+ if isinstance(out, str): # openpi sends the server's traceback as text
205
+ raise RuntimeError(f"policy server error: {out}")
206
+ out = msgpack.unpackb(out, object_hook=_unpack)
207
+ if out.get("status") == "error":
208
+ raise RuntimeError(f"policy server error: {out.get('error')}")
209
+ return np.asarray(out.get("data", out)["actions"])
210
+
211
+ def close(self):
212
+ self.ws.close()
213
+
214
+
215
+ # ---------------------------------------------------------------- attempts
216
+ def budget_steps(task):
217
+ """Control steps per attempt: the agents' simulated-time budget (robot_server._sim_budget) at 20 Hz."""
218
+ return int(round(3.0 * int(getattr(task, "agent_max_steps", 40)) * CONTROL_HZ))
219
+
220
+
221
+ def run_attempt(task, inst, policy, max_steps, replan=5, res=256, frame="believed", idle_s=5.0, probe_every_s=5.0,
222
+ on_frame=None):
223
+ """Drive the policy until the budget or an idle arm ends the attempt. Returns timing and the first time a forked
224
+ outcome() check saw success (what an evaluator stopping at first success would have counted)."""
225
+ sk = task.sk
226
+ act = PolicyActuator(task)
227
+ step0 = sk.n_steps
228
+ idle_steps = int(idle_s * CONTROL_HZ) if idle_s else 0
229
+ probe_steps = int(probe_every_s * CONTROL_HZ) if probe_every_s else 0
230
+ infer_s, render_s = [], 0.0
231
+ first_ok = None
232
+ end = "budget"
233
+ ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, 0
234
+ t = 0
235
+ done = False
236
+ while t < max_steps and not done:
237
+ t0 = time.time()
238
+ obs = read_obs(task, inst, res, frame)
239
+ t1 = time.time()
240
+ try:
241
+ chunk = np.asarray(policy.infer(obs), np.float64)
242
+ except PolicyEnded:
243
+ end = "policy_ended"
244
+ break
245
+ t2 = time.time()
246
+ render_s += t1 - t0
247
+ infer_s.append(t2 - t1)
248
+ if chunk.ndim != 2 or chunk.shape[1] < 7 or not np.isfinite(chunk[:, :7]).all():
249
+ raise ValueError(f"bad action chunk from the policy: shape {chunk.shape}")
250
+ if on_frame is not None:
251
+ on_frame(t, obs)
252
+ for a in chunk[:replan]:
253
+ if t >= max_steps:
254
+ break
255
+ act.step(a[:7])
256
+ t += 1
257
+ if probe_steps and first_ok is None and t % probe_steps == 0 and probe_success(task, inst):
258
+ first_ok = t
259
+ if idle_steps:
260
+ if np.linalg.norm(sk.eef_pos() - ref_pos) > IDLE_EEF_M or act.close != ref_close:
261
+ ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, t
262
+ elif t - ref_t >= idle_steps:
263
+ end, done = "idle", True
264
+ break
265
+ return dict(end=end, n_steps=int(sk.n_steps - step0), first_success_step=first_ok,
266
+ n_infer=len(infer_s), infer_s_mean=float(np.mean(infer_s)) if infer_s else None,
267
+ infer_s_p95=float(np.percentile(infer_s, 95)) if infer_s else None, render_s=round(render_s, 2))
268
+
269
+
270
+ def run_session(task, inst, policy, k=3, max_steps=None, on_attempt=None, **kw):
271
+ """Up to k attempts on one instance with the benchmark's attempt transitions; stops at the first success or a
272
+ terminal failure. The policy gets no feedback and no history: a retry only differs by its sampling noise."""
273
+ max_steps = budget_steps(task) if max_steps is None else int(max_steps)
274
+ protocol = getattr(task, "protocol", "cross")
275
+ attempts = []
276
+ for attempt in range(1, k + 1):
277
+ if attempt == 1 or protocol == "cross":
278
+ task.reset_instance(inst)
279
+ policy.reset()
280
+ t0 = time.time()
281
+ rec = run_attempt(task, inst, policy, max_steps, **kw)
282
+ n0 = task.sk.n_steps
283
+ out = task.outcome(inst)
284
+ rec.update(attempt=attempt, success=bool(out["success"]), failure=out.get("failure"), detail=out.get("detail"),
285
+ terminal=bool(out.get("terminal")), judge_steps=int(task.sk.n_steps - n0),
286
+ wall_s=round(time.time() - t0, 2))
287
+ rec["outcome"] = {key: v for key, v in out.items() if key not in ("feedback", "detail")}
288
+ attempts.append(rec)
289
+ if on_attempt is not None:
290
+ on_attempt(rec)
291
+ if rec["success"] or rec["terminal"]:
292
+ break
293
+ return attempts
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/client/pyproject.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lffbench-client"
7
+ version = "0.1.0"
8
+ description = "LFF-Bench agent tools (robot / shell / view_images) for robot harness frameworks, via the episode's tool gateway"
9
+ requires-python = ">=3.8"
10
+ dependencies = []
11
+
12
+ [tool.setuptools]
13
+ packages = ["lffbench_client"]
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """LFF-Bench: a learn-from-failure benchmark for robot agents on LIBERO."""
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/envs.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Environment construction and low-level sim helpers on top of LIBERO / robosuite."""
2
+ import os
3
+
4
+ os.environ.setdefault("MUJOCO_GL", "osmesa")
5
+ os.environ.setdefault("PYOPENGL_PLATFORM", "osmesa")
6
+ # LIBERO reads its paths from <LIBERO_CONFIG_PATH>/config.yaml (written by setup/install.sh into <repo>/.libero)
7
+ os.environ.setdefault("LIBERO_CONFIG_PATH", os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".libero"))
8
+
9
+ import numpy as np
10
+
11
+ TABLE_Z = 0.90 # LIBERO main_table top surface (table_offset z)
12
+ # Upper limit of the Panda elbow (robot0_joint4; stock -0.0698). The arm is fully stretched at about -0.47 rad; a fast
13
+ # move out of a far pose could carry the elbow past that into (-0.47, -0.07], where the OSC's only way to shorten the
14
+ # arm runs into the stock limit and every later move stops 4-17 cm short for the rest of the attempt (measured
15
+ # 2026-10-19: 50 of 160 targets of the workspace box; 44 of 714 logged LA attempts). Capping the joint keeps the elbow
16
+ # on the normal side: reach is unchanged, and no scripted oracle / naive run of the main set goes above -0.73.
17
+ ELBOW_Q4_MAX = -0.55
18
+
19
+
20
+ def make_env(bddl_path, cam_res=256, cams=("agentview", "robot0_eye_in_hand"), depth=False, controller=None):
21
+ """Build a LIBERO env from a BDDL file without camera rendering on every step.
22
+
23
+ Images are rendered on demand with `render(env, cam)`.
24
+ """
25
+ import robosuite as suite
26
+ import libero.libero.envs.bddl_utils as BDDLUtils
27
+ from libero.libero.envs import TASK_MAPPING
28
+
29
+ cfg = suite.load_controller_config(default_controller="OSC_POSE")
30
+ if controller is None:
31
+ from .skills import CONTROLLER
32
+ controller = CONTROLLER
33
+ if controller:
34
+ cfg.update(controller)
35
+ info = BDDLUtils.get_problem_info(bddl_path)
36
+ env = TASK_MAPPING[info["problem_name"]](
37
+ bddl_path,
38
+ robots=["Panda"],
39
+ controller_configs=cfg,
40
+ gripper_types="default",
41
+ initialization_noise=None,
42
+ use_camera_obs=False,
43
+ has_renderer=False,
44
+ has_offscreen_renderer=True,
45
+ render_camera="frontview",
46
+ render_collision_mesh=False,
47
+ render_visual_mesh=True,
48
+ render_gpu_device_id=-1,
49
+ control_freq=20,
50
+ horizon=10 ** 7,
51
+ ignore_done=True,
52
+ hard_reset=False,
53
+ camera_names=list(cams),
54
+ camera_heights=cam_res,
55
+ camera_widths=cam_res,
56
+ camera_depths=depth,
57
+ camera_segmentations=None,
58
+ renderer="mujoco",
59
+ renderer_config=None,
60
+ )
61
+ env.lff_language = info["language_instruction"]
62
+ m = env.sim.model # hard_reset=False: the model (and this limit) survives env.reset()
63
+ m.jnt_range[m.joint_name2id("robot0_joint4"), 1] = ELBOW_Q4_MAX
64
+ return env
65
+
66
+
67
+ def render(env, cam="agentview", res=256, depth=False):
68
+ """Render an RGB image (H, W, 3, uint8), upright."""
69
+ out = env.sim.render(camera_name=cam, width=res, height=res, depth=depth)
70
+ if depth:
71
+ rgb, d = out
72
+ return rgb[::-1].copy(), d[::-1].copy()
73
+ return out[::-1].copy()
74
+
75
+
76
+ # ---------------------------------------------------------------- object state helpers
77
+
78
+ def body_id(env, obj_name):
79
+ return env.sim.model.body_name2id(env.objects_dict[obj_name].root_body)
80
+
81
+
82
+ def obj_pos(env, obj_name):
83
+ return env.sim.data.body_xpos[body_id(env, obj_name)].copy()
84
+
85
+
86
+ def obj_quat(env, obj_name):
87
+ """wxyz"""
88
+ return env.sim.data.body_xquat[body_id(env, obj_name)].copy()
89
+
90
+
91
+ def obj_upright_cos(env, obj_name):
92
+ """cos of the angle between the object's z axis and world z."""
93
+ xmat = env.sim.data.body_xmat[body_id(env, obj_name)].reshape(3, 3)
94
+ return float(xmat[2, 2])
95
+
96
+
97
+ def free_joint_addr(env, obj_name):
98
+ jname = env.objects_dict[obj_name].joints[0]
99
+ jid = env.sim.model.joint_name2id(jname)
100
+ return env.sim.model.jnt_qposadr[jid], env.sim.model.jnt_dofadr[jid]
101
+
102
+
103
+ def set_obj_pose(env, obj_name, pos, yaw=0.0, quat_wxyz=None):
104
+ """Teleport a free-joint object (used only at reset / by the protocol, never by agents)."""
105
+ qa, da = free_joint_addr(env, obj_name)
106
+ if quat_wxyz is None:
107
+ quat_wxyz = np.array([np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)])
108
+ env.sim.data.qpos[qa:qa + 3] = pos
109
+ env.sim.data.qpos[qa + 3:qa + 7] = quat_wxyz
110
+ env.sim.data.qvel[da:da + 6] = 0.0
111
+
112
+
113
+ def obj_geom_ids(env, obj_name):
114
+ return [env.sim.model.geom_name2id(g) for g in env.objects_dict[obj_name].contact_geoms]
115
+
116
+
117
+ def set_friction(env, obj_name, mu, priority=2):
118
+ """Set sliding friction of an object's collision geoms and give them priority so their
119
+ friction is used in contacts (MuJoCo otherwise takes the max of the two geoms)."""
120
+ for g in obj_geom_ids(env, obj_name):
121
+ env.sim.model.geom_friction[g, 0] = mu
122
+ env.sim.model.geom_priority[g] = priority
123
+
124
+
125
+ def scale_mass(env, obj_name, mass):
126
+ bid = body_id(env, obj_name)
127
+ m0 = env.sim.model.body_mass[bid]
128
+ env.sim.model.body_mass[bid] = mass
129
+ env.sim.model.body_inertia[bid] *= mass / max(m0, 1e-9)
130
+
131
+
132
+ def settle(env, steps=20):
133
+ """Let physics settle while holding the arm still."""
134
+ for _ in range(steps):
135
+ env.step(np.zeros(env.action_dim))
136
+
137
+
138
+ def contacts_between(env, geoms_a, geoms_b):
139
+ a, b = set(geoms_a), set(geoms_b)
140
+ d = env.sim.data
141
+ for i in range(d.ncon):
142
+ c = d.contact[i]
143
+ if (c.geom1 in a and c.geom2 in b) or (c.geom1 in b and c.geom2 in a):
144
+ return True
145
+ return False
146
+
147
+
148
+ def robot_geom_ids(env):
149
+ m = env.sim.model
150
+ ids = []
151
+ for g in range(m.ngeom):
152
+ n = m.geom_id2name(g) or ""
153
+ if n.startswith("robot0_") or n.startswith("gripper0_"):
154
+ ids.append(g)
155
+ return ids
156
+
157
+
158
+ # ---------------------------------------------------------------- upright placement (added 2026-10-06)
159
+
160
+ def _quat_mul(a, b):
161
+ """wxyz quaternion product a*b"""
162
+ w1, x1, y1, z1 = a
163
+ w2, x2, y2, z2 = b
164
+ return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
165
+ w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
166
+ w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
167
+ w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
168
+
169
+
170
+ def canonical_quat(env, obj_name):
171
+ """The orientation LIBERO's own placement gives an object, with any random yaw set to 0 (wxyz).
172
+
173
+ Reproduces LIBERO exactly, including its convention bug: TableRegionSampler._sample_quat builds an
174
+ xyzw quaternion, multiplies it with obj.init_quat (xyzw), and bddl_base_domain writes that array
175
+ straight into the wxyz qpos slot. E.g. scanned objects (plate, bowls, basket; rotation (pi/2, pi/2)
176
+ about x) therefore end up yawed by 90 deg, not rolled; HOPE groceries (dict rotation) come out
177
+ as (0.5, 0.5, 0.5, 0.5), which is the same under both readings. (Fixed 2026-10-06 after the L3
178
+ developer found plates being stood on edge.)"""
179
+ from robosuite.utils.transform_utils import quat_multiply
180
+
181
+ o = env.objects_dict[obj_name]
182
+ rot = getattr(o, "rotation", None)
183
+ ax = getattr(o, "rotation_axis", None) or "z"
184
+
185
+ def xyzw(axis, a):
186
+ h = a / 2
187
+ return {"x": np.array([np.sin(h), 0.0, 0.0, np.cos(h)]),
188
+ "y": np.array([0.0, np.sin(h), 0.0, np.cos(h)]),
189
+ "z": np.array([0.0, 0.0, np.sin(h), np.cos(h)])}[axis]
190
+
191
+ def fixed(r): # a random range means a free angle -> use 0 (only yaw ranges occur in practice)
192
+ return float(r[0]) if float(min(r)) == float(max(r)) else 0.0
193
+
194
+ if isinstance(rot, dict):
195
+ q = np.array([0.0, 0.0, 0.0, 1.0])
196
+ for axis, r in rot.items():
197
+ q = quat_multiply(xyzw(axis, fixed(r)), q)
198
+ else:
199
+ if rot is None:
200
+ a = 0.0
201
+ elif isinstance(rot, (tuple, list)):
202
+ a = fixed(rot)
203
+ else:
204
+ a = float(rot)
205
+ q = xyzw(ax, a)
206
+ init = np.array(getattr(o, "init_quat", [0.0, 0.0, 0.0, 1.0]), dtype=float)
207
+ q = quat_multiply(q, init)
208
+ return np.array(q, dtype=float) # used directly as wxyz, like LIBERO does
209
+
210
+
211
+ def obj_min_z(env, obj_name):
212
+ """Lowest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
213
+ m, d = env.sim.model, env.sim.data
214
+ zmin = np.inf
215
+ for g in obj_geom_ids(env, obj_name):
216
+ R = d.geom_xmat[g].reshape(3, 3)
217
+ c_local = m.geom_aabb[g, :3]
218
+ half = m.geom_aabb[g, 3:]
219
+ cz = d.geom_xpos[g][2] + R[2] @ c_local
220
+ zmin = min(zmin, cz - np.abs(R[2]) @ half)
221
+ return float(zmin)
222
+
223
+
224
+ def obj_max_z(env, obj_name):
225
+ """Highest world z of the object's collision geoms (exact for boxes, AABB bound for meshes)."""
226
+ m, d = env.sim.model, env.sim.data
227
+ zmax = -np.inf
228
+ for g in obj_geom_ids(env, obj_name):
229
+ R = d.geom_xmat[g].reshape(3, 3)
230
+ cz = d.geom_xpos[g][2] + R[2] @ m.geom_aabb[g, :3]
231
+ zmax = max(zmax, cz + np.abs(R[2]) @ m.geom_aabb[g, 3:])
232
+ return float(zmax)
233
+
234
+
235
+ FINGERTIP_BELOW_SITE = 0.0095 # lowest point of the Panda finger collision meshes below the grasp site (measured)
236
+
237
+
238
+ def place_upright(env, obj_name, xy, yaw=0.0, surface_z=TABLE_Z, clearance=0.002):
239
+ """Teleport an object upright (LIBERO canonical orientation, then `yaw` about world z) so that its
240
+ lowest collision point sits `clearance` above `surface_z`. Call env.sim.forward() / settle after."""
241
+ q = _quat_mul(np.array([np.cos(yaw / 2), 0.0, 0.0, np.sin(yaw / 2)]), canonical_quat(env, obj_name))
242
+ set_obj_pose(env, obj_name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
243
+ env.sim.forward()
244
+ dz = obj_min_z(env, obj_name) - (surface_z + clearance)
245
+ qa, _ = free_joint_addr(env, obj_name)
246
+ env.sim.data.qpos[qa + 2] -= dz
247
+ env.sim.forward()
248
+
249
+
250
+ # ---------------------------------------------------------------- collision bounds after runtime edits (2026-10-12)
251
+
252
+ def _quat2mat(q):
253
+ w, x, y, z = q
254
+ return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
255
+ [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
256
+ [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
257
+
258
+
259
+ def _prim_bounds(m, g):
260
+ """(half extents in the geom frame, bounding-sphere radius) of a primitive geom from geom_size; None otherwise"""
261
+ t, s = int(m.geom_type[g]), m.geom_size[g]
262
+ if t == 6: # box
263
+ return np.array(s[:3], float), float(np.linalg.norm(s[:3]))
264
+ if t == 4: # ellipsoid
265
+ return np.array(s[:3], float), float(max(s[:3]))
266
+ if t == 2: # sphere
267
+ return np.full(3, float(s[0])), float(s[0])
268
+ if t == 5: # cylinder
269
+ return np.array([s[0], s[0], s[1]], float), float(np.hypot(s[0], s[1]))
270
+ if t == 3: # capsule
271
+ return np.array([s[0], s[0], s[0] + s[1]], float), float(s[0] + s[1])
272
+ return None
273
+
274
+
275
+ def refit_bounds(model, bodies, margin=0.0, geoms=True):
276
+ """Make the collision bounds of `bodies` (body id or ids) consistent again after runtime edits of their geoms
277
+ (geom_size / geom_pos / geom_quat) or of their inertial frame (body_ipos / body_iquat). `model`: an env, a
278
+ robosuite MjModel wrapper or a raw mujoco.MjModel.
279
+
280
+ MuJoCo (3.2.3) computes these bounds at compile time and never updates them: geom_aabb / geom_rbound (geom
281
+ frame; broad phase and geom-pair filters) and the per-body bounding-volume hierarchy bvh_aabb, stored in the
282
+ body's INERTIAL frame and used by the mid-phase whenever one of the two bodies of a pair has >= 2 collision
283
+ geoms. Stale boxes make MuJoCo silently skip contacts (lh_fence v1: a post whose centre of mass was raised sank
284
+ 2.2 cm into the table; measured 2026-10-12: a body with a single collision geom whose COM moved 6 cm missed every
285
+ contact with a 2-geom body beyond the shifted box). With geoms=True the primitive geoms' geom_aabb / geom_rbound
286
+ are recomputed from geom_size (meshes keep theirs); then every BVH node becomes the union of its leaf geoms'
287
+ boxes (+ margin) in the runtime inertial frame, following body_sameframe / geom_sameframe like mj_kinematics
288
+ (on a pristine model this reproduces the compiled bvh_aabb exactly).
289
+ Also note: a runtime body_ipos is ignored by MuJoCo if the compiled inertial pos is the body origin
290
+ (body_sameframe = 1); bodies whose centre of mass is moved at runtime need a non-zero compiled inertial pos."""
291
+ if hasattr(model, "sim"):
292
+ model = model.sim.model
293
+ m = getattr(model, "_model", model)
294
+ for b in np.atleast_1d(bodies):
295
+ b = int(b)
296
+ if geoms:
297
+ for g in range(int(m.body_geomadr[b]), int(m.body_geomadr[b] + m.body_geomnum[b])):
298
+ pb = _prim_bounds(m, g)
299
+ if pb is not None:
300
+ m.geom_aabb[g] = [0.0, 0.0, 0.0, *pb[0]]
301
+ m.geom_rbound[g] = pb[1]
302
+ a, n = int(m.body_bvhadr[b]), int(m.body_bvhnum[b])
303
+ if a < 0 or n < 1:
304
+ continue
305
+ sf = int(m.body_sameframe[b]) # 1: inertial frame = body frame, 3: same orientation as the body
306
+ ip = np.zeros(3) if sf == 1 else np.array(m.body_ipos[b], float)
307
+ iR = np.eye(3) if sf in (1, 3) else _quat2mat(m.body_iquat[b])
308
+
309
+ def rec(i):
310
+ g = int(m.bvh_nodeid[i])
311
+ if g >= 0:
312
+ gsf = int(m.geom_sameframe[g]) # 1: body frame, 2: inertial frame, 3/4: their orientation
313
+ gp = np.zeros(3) if gsf == 1 else ip if gsf == 2 else np.array(m.geom_pos[g], float)
314
+ gR = np.eye(3) if gsf in (1, 3) else iR if gsf in (2, 4) else _quat2mat(m.geom_quat[g])
315
+ R = iR.T @ gR
316
+ c = iR.T @ (gp - ip) + R @ np.asarray(m.geom_aabb[g, :3])
317
+ h = np.abs(R) @ np.asarray(m.geom_aabb[g, 3:])
318
+ lo, hi = c - h, c + h
319
+ else:
320
+ l1, h1 = rec(a + int(m.bvh_child[i][0]))
321
+ l2, h2 = rec(a + int(m.bvh_child[i][1]))
322
+ lo, hi = np.minimum(l1, l2), np.maximum(h1, h2)
323
+ m.bvh_aabb[i] = np.concatenate([(lo + hi) / 2, (hi - lo) / 2 + margin])
324
+ return lo, hi
325
+ rec(a)
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/__init__.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness adapters (docs/15): one way to plug any agent harness into a robot_server session.
2
+
3
+ ours reference driver scripts/api_player.py (main table)
4
+ claude_code Claude Code CLI, --bare, only our MCP tools (arm B)
5
+ claude_code_full Claude Code CLI without --bare: full system prompt, still one-time dirs and only MCP (arm B')
6
+ codex Codex CLI exec (+ exec resume on early exit), one-time CODEX_HOME, only our MCP tools (arm F)
7
+ rpent_codex RPent (robot harness framework) on Codex: RPent's loop and prompt, the main table's Codex config,
8
+ tools through the episode's tool gateway (docs/18, lffbench/harnesses/rpent.py)
9
+ dsh DeepSeek Harness (`dsh --profile headless`), only our MCP tools, one-time dirs
10
+
11
+ Use scripts/harness_run.py (one session) or scripts/api_batch.py start --harness ... (batches).
12
+ """
13
+ import json
14
+ import importlib
15
+ import os
16
+ import sys
17
+
18
+ from .base import EpisodeSpec, HarnessAdapter, HarnessRefused, first_message_text # noqa: F401
19
+
20
+ # A new Codex-based Robot Harness registers here; both single-run and batch CLIs
21
+ # derive their choices, provider and common options from this registry.
22
+ ROBOT_HARNESSES = {
23
+ "rpent_codex": ("rpent", "RPentCodex"),
24
+ "sensenova_codex": ("sensenova", "SenseNovaCodex"),
25
+ "embodied_evo_codex": ("embodied_evo", "EmbodiedEvoCodex"),
26
+ }
27
+ NAMES = ("ours", "claude_code", "claude_code_full", "codex", "dsh", *ROBOT_HARNESSES)
28
+ PROVIDER = dict(claude_code="anthropic", claude_code_full="anthropic", codex="openai", dsh="deepseek",
29
+ **{name: "openai" for name in ROBOT_HARNESSES})
30
+
31
+
32
+ def get_adapter(name, **kw):
33
+ if name == "ours":
34
+ from .reference import Reference
35
+ return Reference(**kw)
36
+ if name == "claude_code":
37
+ from .claude_code import ClaudeCode
38
+ return ClaudeCode(**kw)
39
+ if name == "claude_code_full":
40
+ from .claude_code import ClaudeCodeFull
41
+ return ClaudeCodeFull(**kw)
42
+ if name == "codex":
43
+ from .codex import Codex
44
+ return Codex(**kw)
45
+ if name == "dsh":
46
+ from .dsh import DeepSeekHarness
47
+ return DeepSeekHarness(**kw)
48
+ if name in ROBOT_HARNESSES:
49
+ module, cls = ROBOT_HARNESSES[name]
50
+ return getattr(importlib.import_module("." + module, __name__), cls)(**kw)
51
+ raise ValueError(f"unknown harness {name!r}; one of {NAMES}")
52
+
53
+
54
+ def render_first_message(ep):
55
+ """Call `status` once over HTTP (exactly as the reference driver does before its first turn) and build the first
56
+ user message for a native harness. Returns (text, status_json)."""
57
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
58
+ "scripts"))
59
+ from api_player import call_server # noqa: E402
60
+ st = json.loads(call_server(ep.port, ep.token, "status", {}))
61
+ readme = open(os.path.join(ep.sandbox, "README.md")).read()
62
+ status_json = json.dumps(st)
63
+ return first_message_text(readme, status_json), status_json
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/base.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Harness adapter interface (docs/15 §3).
2
+
3
+ An adapter runs one episode (one robot_server session) with one agent harness and leaves behind, in the run's log
4
+ dir: harness.json (what was launched), trajectory.jsonl (unified trajectory), harness_audit.json (checks + violations).
5
+ Budgets, automatic finish and attempt switching are NOT the adapter's business: robot_server and the MCP server /
6
+ reference driver enforce them identically for every harness.
7
+
8
+ name stable harness name (the "harness" column of a table)
9
+ capabilities CapabilityDecl: every item of REQUIRED and FORBIDDEN must be declared, with its evidence source;
10
+ a missing item makes the class definition fail (so the import fails)
11
+ version() the actual installed version (probed before launch)
12
+ prepare(ep, first_message) -> LaunchSpec: one-time dirs, configs, argv / env
13
+ launch(spec) fail-closed preflight, then start the process (env exactly the whitelist) -> RunHandle
14
+ collect(h) native event stream -> trajectory.jsonl (ATIF-like), usage, exit reason
15
+ audit(h) tool list, preset prompt, memory, state left behind, violations
16
+ """
17
+ import dataclasses
18
+ import json
19
+ import os
20
+ import secrets
21
+ import shutil
22
+ import signal
23
+ import subprocess
24
+ import time
25
+
26
+ from . import contract as C
27
+
28
+ EVIDENCE = ("launch", "stream", "server", "probe", "preflight")
29
+
30
+ REQUIRED = {
31
+ "only_benchmark_tools": "the model can call exactly robot / shell / view_images (ours) and nothing else of use",
32
+ "images_reach_model": "view_images returns the image bytes to the model unchanged",
33
+ "non_persistent_session": "nothing of the session is written to disk for later runs",
34
+ "pinned_version": "the harness version (and binary hash) is recorded and pinned",
35
+ "machine_readable_events": "a machine-readable event stream of the whole run",
36
+ "tool_calls_logged": "every tool call is logged (harness stream + MCP / driver transcript + events.jsonl)",
37
+ "model_and_effort": "model and reasoning effort can be set and are visible in the request",
38
+ }
39
+ FORBIDDEN = {
40
+ "persistent_memory": "harness memory across runs (C4: auto-memory, CLAUDE.md / AGENTS.md, memories db)",
41
+ "instruction_file_injection": "instruction files picked up from the work / config / home dir",
42
+ "web_access": "web search / fetch",
43
+ "host_file_read": "reading host files outside the episode workspace",
44
+ "builtin_shell": "a shell of the harness itself (outside our jailed shell tool)",
45
+ "subagent_delegation": "spawning sub-agents",
46
+ "background_execution": "background tasks that outlive a tool call",
47
+ }
48
+
49
+
50
+ @dataclasses.dataclass(frozen=True)
51
+ class Cap:
52
+ status: str # REQUIRED items: "yes" | "partial" | "no"; FORBIDDEN items: "absent" | "present" | "partial"
53
+ evidence: str # one of EVIDENCE
54
+ note: str = ""
55
+
56
+
57
+ PROXY_KEYS = ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy")
58
+ NO_PROXY_KEYS = ("NO_PROXY", "no_proxy")
59
+ NO_PROXY_LOCAL = "127.0.0.1,localhost,::1"
60
+
61
+
62
+ def proxy_env(environ=None):
63
+ """The calling environment's HTTP(S) proxy, passed to a native harness so it can reach the model API on machines
64
+ that only get out through a proxy. NO_PROXY is loopback only (the preflight's fake API), never the host's list.
65
+ Not part of config_sha256 (machine plumbing, not harness configuration)."""
66
+ environ = os.environ if environ is None else environ
67
+ e = {k: environ[k] for k in PROXY_KEYS if environ.get(k)}
68
+ if e:
69
+ e.update({k: NO_PROXY_LOCAL for k in NO_PROXY_KEYS})
70
+ return e
71
+
72
+
73
+ class CapabilityError(TypeError):
74
+ pass
75
+
76
+
77
+ def check_capabilities(name, caps):
78
+ if not isinstance(caps, dict):
79
+ raise CapabilityError(f"{name}: capabilities must be a dict")
80
+ missing = [k for k in list(REQUIRED) + list(FORBIDDEN) if k not in caps]
81
+ extra = [k for k in caps if k not in REQUIRED and k not in FORBIDDEN]
82
+ if missing or extra:
83
+ raise CapabilityError(f"{name}: capability declaration incomplete: missing {missing}, unknown {extra}")
84
+ for k, c in caps.items():
85
+ if not isinstance(c, Cap) or c.evidence not in EVIDENCE:
86
+ raise CapabilityError(f"{name}: capability {k!r} needs a Cap(status, evidence in {EVIDENCE})")
87
+ ok = ("yes", "partial", "no") if k in REQUIRED else ("absent", "present", "partial")
88
+ if c.status not in ok:
89
+ raise CapabilityError(f"{name}: capability {k!r} status must be one of {ok}")
90
+
91
+
92
+ class HarnessRefused(RuntimeError):
93
+ """Fail-closed: the launch preflight found a tool list / preset prompt that is not the pinned one."""
94
+
95
+
96
+ @dataclasses.dataclass
97
+ class EpisodeSpec:
98
+ session_path: str
99
+ log_dir: str
100
+ sandbox: str
101
+ port: int
102
+ token: str
103
+ max_tool_calls: int
104
+ model: str
105
+ effort: str
106
+ provider: str = ""
107
+ task: str = ""
108
+ seed: int = 0
109
+ extra: dict = dataclasses.field(default_factory=dict)
110
+
111
+ @classmethod
112
+ def from_session(cls, session_path, model, effort, provider="", **extra):
113
+ session_path = os.path.abspath(session_path)
114
+ log_dir = os.path.dirname(session_path)
115
+ sess = json.load(open(session_path))
116
+ iface = json.load(open(os.path.join(log_dir, "agent_iface.json")))
117
+ st = C.session_start(log_dir)
118
+ return cls(session_path=session_path, log_dir=log_dir, sandbox=sess["sandbox"], port=int(sess["port"]),
119
+ token=iface["token"], max_tool_calls=int(iface["max_tool_calls"]), model=model, effort=effort,
120
+ provider=provider, task=st["task"], seed=int(st["seed"]), extra=extra)
121
+
122
+
123
+ @dataclasses.dataclass
124
+ class LaunchSpec:
125
+ argv: list # full argv (the first message may be one element)
126
+ env: dict # the complete environment of the harness process (nothing else is inherited)
127
+ cwd: str
128
+ run_dir: str = "" # one-time dir tree, removed after audit
129
+ state_dirs: dict = dataclasses.field(default_factory=dict) # name -> path (home, config, ...)
130
+ first_message: str = ""
131
+ config_files: dict = dataclasses.field(default_factory=dict) # name -> path of files the adapter wrote
132
+ stdout_path: str = ""
133
+ stderr_path: str = ""
134
+ redact_argv: dict = dataclasses.field(default_factory=dict) # argv index -> replacement for the log
135
+ preflight: dict = dataclasses.field(default_factory=dict)
136
+ timeout_s: float = 10800
137
+
138
+
139
+ @dataclasses.dataclass
140
+ class RunHandle:
141
+ spec: LaunchSpec
142
+ ep: EpisodeSpec
143
+ proc: object = None
144
+ pid: int = 0
145
+ t_start: float = 0.0
146
+ t_end: float = 0.0
147
+ exit_code: int = None
148
+ exit_reason: str = ""
149
+ env_observed_keys: list = None # read from /proc/<pid>/environ right after the start
150
+ info: dict = dataclasses.field(default_factory=dict)
151
+
152
+
153
+ def env_keys_of(pid):
154
+ try:
155
+ raw = open(f"/proc/{pid}/environ", "rb").read()
156
+ except OSError:
157
+ return None
158
+ return sorted({kv.split(b"=", 1)[0].decode("utf-8", "replace") for kv in raw.split(b"\0") if kv})
159
+
160
+
161
+ def new_run_dir(root="/tmp/lffrun"):
162
+ """/tmp/lffrun/<12 hex>: the opaque work dir (its path is shown to the model by some harnesses)."""
163
+ os.makedirs(root, exist_ok=True)
164
+ while True:
165
+ d = os.path.join(root, secrets.token_hex(6))
166
+ try:
167
+ os.mkdir(d, 0o700)
168
+ return d
169
+ except FileExistsError:
170
+ continue
171
+
172
+
173
+ def binary_info(path):
174
+ real = os.path.realpath(path)
175
+ return dict(path=path, realpath=real, sha256=C.sha256_file(real) if os.path.exists(real) else None)
176
+
177
+
178
+ class HarnessAdapter:
179
+ name = None
180
+ capabilities = None
181
+ uses_mcp = False
182
+ uses_gateway = False # harness_run starts the episode's tool gateway (scripts/tool_gateway.py) for
183
+ # this adapter: MCP adapters through the MCP server, framework adapters
184
+ # (RPent, ...) through lffbench_client with LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN
185
+ clean_dirs = () # keys of spec.state_dirs that must be empty at launch
186
+ clean_allowed = {} # key of spec.state_dirs -> file names the adapter itself put there (e.g. auth.json)
187
+ ancestor_files = () # instruction files that must not exist in the work dir or any ancestor
188
+ unsafe_skip_clean_check = False # tests/harness_selfcheck only (probing what the harness would read)
189
+ jail = None # lffbench/harnesses/jail.HarnessJail when the adapter runs jailed (docs/15 §3.4)
190
+ can_resume = False # resume(): the CLI can continue its session with one more user message
191
+
192
+ def clean_state_problems(self, spec):
193
+ """Fail-closed: the work dir and the one-time dirs must be empty, and no instruction file may sit in an
194
+ ancestor of the work dir (harnesses walk up the tree looking for CLAUDE.md / AGENTS.md)."""
195
+ p = []
196
+ if spec.cwd and os.path.isdir(spec.cwd) and os.listdir(spec.cwd):
197
+ p.append(f"work dir not empty: {sorted(os.listdir(spec.cwd))[:5]}")
198
+ for k in self.clean_dirs:
199
+ d = spec.state_dirs.get(k)
200
+ left = [n for n in os.listdir(d) if n not in self.clean_allowed.get(k, ())] if d and os.path.isdir(d) else []
201
+ if left:
202
+ p.append(f"{k} dir not empty: {sorted(left)[:5]}")
203
+ d = spec.cwd
204
+ while d and d != "/":
205
+ d = os.path.dirname(d)
206
+ for f in self.ancestor_files:
207
+ if os.path.exists(os.path.join(d, f)):
208
+ p.append(f"instruction file in an ancestor of the work dir: {os.path.join(d, f)}")
209
+ return p
210
+
211
+ def __init_subclass__(cls, **kw):
212
+ super().__init_subclass__(**kw)
213
+ if cls.name is None:
214
+ raise CapabilityError(f"{cls.__name__}: no name")
215
+ check_capabilities(cls.name, cls.capabilities)
216
+
217
+ # -------------------------------------------------------------------------------------------- interface
218
+ def version(self):
219
+ raise NotImplementedError
220
+
221
+ def prepare(self, ep, first_message):
222
+ raise NotImplementedError
223
+
224
+ def preflight(self, spec, ep):
225
+ """Fail-closed launch check; returns a dict for harness.json, raises HarnessRefused."""
226
+ return dict(skipped=True)
227
+
228
+ def collect(self, h):
229
+ raise NotImplementedError
230
+
231
+ def audit(self, h):
232
+ raise NotImplementedError
233
+
234
+ # -------------------------------------------------------------------------------------------- shared
235
+ def mcp_server_command(self, python, script, args):
236
+ """(command, args) of the MCP server entry in the harness config: our server, or, jailed, the relay to it."""
237
+ if self.jail is not None:
238
+ return self.jail.mcp_command([python, script] + list(args), env={"PATH": "/usr/bin:/bin"})
239
+ return python, [script] + list(args)
240
+
241
+ def jailed_argv(self, argv, env, cwd, dirs):
242
+ """argv as started: unchanged, or wrapped into the jail with `dirs` (one-time dirs) mounted back."""
243
+ return self.jail.wrap(argv, env, cwd, dirs) if self.jail is not None else list(argv)
244
+
245
+ def jail_info(self):
246
+ return self.jail.info() if self.jail is not None else dict(enabled=False)
247
+
248
+ def auth_info(self):
249
+ """How the harness authenticates to the model API (for harness.json; never a secret)."""
250
+ return dict(mode="api_env", keys=sorted(getattr(self, "api_env", {}) or {}))
251
+
252
+ def launch(self, spec, ep, skip_preflight=False):
253
+ if not self.unsafe_skip_clean_check:
254
+ probs = self.clean_state_problems(spec)
255
+ if probs:
256
+ spec.preflight = dict(problems=probs)
257
+ raise HarnessRefused("clean-state check: " + "; ".join(probs))
258
+ spec.preflight = dict(skipped=True, reason="skip_preflight") if skip_preflight else self.preflight(spec, ep)
259
+ out = open(spec.stdout_path, "wb")
260
+ err = open(spec.stderr_path, "wb")
261
+ h = RunHandle(spec=spec, ep=ep, t_start=time.time())
262
+ argv = self.jailed_argv(spec.argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
263
+ h.proc = subprocess.Popen(argv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
264
+ stderr=err, start_new_session=True)
265
+ h.pid = h.proc.pid
266
+ for _ in range(20): # the exec has happened once /proc/<pid>/environ differs from ours
267
+ keys = env_keys_of(h.pid)
268
+ if keys is not None and set(keys) == set(spec.env):
269
+ break
270
+ time.sleep(0.05)
271
+ h.env_observed_keys = keys # retain the observed sample; a second read can race setpriv/exec
272
+ return h
273
+
274
+ def resume_argv(self, h, message):
275
+ """argv that continues the run's session with one more user message (adapters with can_resume)."""
276
+ raise NotImplementedError
277
+
278
+ def resume(self, h, message):
279
+ """Continue the run's session with one more user message, after the CLI exited before the episode was over
280
+ (scripts/harness_run.py sends the reference driver's nudge). Same env, work dir and one-time dirs; the output
281
+ is appended to the same stdout / stderr files."""
282
+ spec = h.spec
283
+ argv = self.resume_argv(h, message)
284
+ out, err = open(spec.stdout_path, "ab"), open(spec.stderr_path, "ab")
285
+ jargv = self.jailed_argv(argv, spec.env, spec.cwd, list(spec.state_dirs.values()) + [spec.run_dir])
286
+ h.proc = subprocess.Popen(jargv, env=spec.env, cwd=spec.cwd, stdin=subprocess.DEVNULL, stdout=out,
287
+ stderr=err, start_new_session=True)
288
+ h.pid, h.exit_code, h.exit_reason = h.proc.pid, None, ""
289
+ keys = None
290
+ for _ in range(20):
291
+ keys = env_keys_of(h.pid)
292
+ if keys is not None and set(keys) == set(spec.env):
293
+ break
294
+ time.sleep(0.05)
295
+ h.info.setdefault("resumes", []).append(dict(t=time.time(), pid=h.pid, message=message,
296
+ argv=[("<message>" if x == message else x) for x in argv],
297
+ env_observed_keys=keys))
298
+ return h
299
+
300
+ def wait(self, h, timeout=None):
301
+ try:
302
+ h.exit_code = h.proc.wait(timeout=timeout or h.spec.timeout_s)
303
+ h.exit_reason = "exited" if h.exit_code == 0 else f"exit code {h.exit_code}"
304
+ except subprocess.TimeoutExpired:
305
+ self.kill(h)
306
+ h.exit_reason = "timeout"
307
+ h.t_end = time.time()
308
+ return h
309
+
310
+ @staticmethod
311
+ def kill(h):
312
+ try:
313
+ os.killpg(h.proc.pid, signal.SIGTERM)
314
+ h.exit_code = h.proc.wait(timeout=20)
315
+ except ProcessLookupError:
316
+ pass
317
+ except subprocess.TimeoutExpired:
318
+ os.killpg(h.proc.pid, signal.SIGKILL)
319
+ h.exit_code = h.proc.wait()
320
+
321
+ def logged_argv(self, spec):
322
+ return [spec.redact_argv.get(i, a) for i, a in enumerate(spec.argv)]
323
+
324
+ def cleanup(self, spec):
325
+ if spec.run_dir and spec.run_dir.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(spec.run_dir):
326
+ shutil.rmtree(spec.run_dir, ignore_errors=True)
327
+ for d in spec.state_dirs.values():
328
+ if d.startswith(("/tmp/lffrun/", "/tmp/lffstate/")) and os.path.isdir(d):
329
+ shutil.rmtree(d, ignore_errors=True)
330
+ if self.jail is not None:
331
+ self.jail.close()
332
+
333
+
334
+ def gateway_env(log_dir):
335
+ """{LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN} of the episode's tool gateway, for a framework adapter (uses_gateway) whose
336
+ process talks to it through lffbench_client (Session.from_env). harness_run.py starts the gateway right before
337
+ launch, so call this in the adapter's launch() and add it to spec.env before the process starts. The token is the
338
+ gateway's, never robot_server's."""
339
+ d = json.load(open(os.path.join(log_dir, "gateway.json")))
340
+ return {"LFF_GATEWAY_URL": d["url"], "LFF_GATEWAY_TOKEN": d["token"]}
341
+
342
+
343
+ def snapshot_tree(root):
344
+ """Relative paths of all files under root (to list what a harness left behind)."""
345
+ out = []
346
+ for dp, dn, fn in os.walk(root):
347
+ for f in fn:
348
+ out.append(os.path.relpath(os.path.join(dp, f), root))
349
+ return sorted(out)
350
+
351
+
352
+ def first_message_text(readme, status_json):
353
+ """What a native harness gets as its first user message: the reference driver's instructions (preamble + README,
354
+ byte-identical) followed by its first user turn (the status report). The reference driver sends the same two
355
+ strings as system prompt and first user message; native harnesses keep their own system prompt."""
356
+ from .contract import tool_schemas
357
+ _, preamble = tool_schemas()
358
+ return preamble + readme + "\n\n" + "Begin. Current status (robot command `status`):\n" + status_json
359
+
360
+
361
+ def reference_instructions(readme):
362
+ from .contract import tool_schemas
363
+ _, preamble = tool_schemas()
364
+ return preamble + readme
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/claude_code.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Claude Code CLI as a native harness (docs/15 §3.3; flags measured in research_notes/harness接入调研/02 §2.1).
2
+
3
+ Two variants:
4
+ claude_code arm B : -p --bare (system prompt ~400 chars, no CLAUDE.md / auto-memory / hooks / plugins)
5
+ claude_code_full arm B': same but without --bare: Claude Code's full system prompt; still a one-time config dir and
6
+ HOME, an empty opaque work dir, --tools "" and only our MCP server
7
+ Both: process env is exactly the whitelist (env -i equivalent; plus the calling HTTP(S) proxy, base.proxy_env),
8
+ HOME / CLAUDE_CONFIG_DIR / TMPDIR are one-time dirs
9
+ under /tmp/lffstate/<hex>, the work dir is /tmp/lffrun/<12 hex> (its path is written into the system prompt), the MCP
10
+ server is scripts/mcp_robot_server.py on the run's session.
11
+
12
+ Two ways to authenticate (auth=):
13
+ apikey ANTHROPIC_API_KEY (api_env)
14
+ oauth a Claude subscription: the long-lived token of `claude setup-token`, passed as CLAUDE_CODE_OAUTH_TOKEN
15
+ (api_env; never taken from the calling environment). claude_code_full only: --bare reads nothing but
16
+ ANTHROPIC_API_KEY / apiKeyHelper (2.1.267 --help).
17
+ Measured with 2.1.267 against the fake server (2026-10-20): the same single request in both modes, identical system
18
+ prompt, tools, messages and parameters; oauth sends Authorization: Bearer instead of x-api-key, two more beta flags
19
+ (oauth-2025-04-20, extended-cache-ttl-2025-04-11) and cache_control ttl=1h. Pins are per auth mode (pin name
20
+ claude_code_full-oauth).
21
+
22
+ Early exit: `claude -p` ends when the model replies without a tool call, also mid-episode. scripts/harness_run.py then
23
+ sends the reference driver's nudge with `claude -p <nudge> --resume <session>` (resume_argv), as for Codex. Hence no
24
+ --no-session-persistence: the session transcript is kept in the one-time CLAUDE_CONFIG_DIR (removed after the run);
25
+ the audit allows only this run's session. Measured against the fake server: the resumed request has the same system
26
+ prompt, tools, parameters and headers, then the earlier turns and the nudge as a user message.
27
+
28
+ Fail-closed launch: before the real run the same argv / env is started once against a local fake Anthropic server
29
+ (free) with a schema-only MCP server; the first request's tool list, system prompt, harness-added message prefix and
30
+ request parameters are normalised and hashed, and the launch is refused unless the hash equals the pinned one
31
+ (pins/claude_code*.json, written by tests/harness_selfcheck after the self-check passed). During the real run the
32
+ stream's init event is checked again (tool list); on a mismatch the process is killed.
33
+ """
34
+ import copy
35
+ import json
36
+ import os
37
+ import re
38
+ import shutil
39
+ import subprocess
40
+ import sys
41
+ import time
42
+
43
+ from . import contract as C
44
+ from . import pins
45
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
46
+ new_run_dir, proxy_env, snapshot_tree)
47
+ from .fakeapi import FakeAnthropic
48
+ from .trajectory import TrajWriter, strip_mcp
49
+
50
+ ROOT = C.ROOT
51
+ MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
52
+ MCP_TOOLS = ["mcp__lff__robot", "mcp__lff__shell", "mcp__lff__view_images"]
53
+ BASE_PATH = "/usr/bin:/bin"
54
+ OAUTH_KEY = "CLAUDE_CODE_OAUTH_TOKEN"
55
+ PREFLIGHT_CREDENTIAL = dict(apikey=("ANTHROPIC_API_KEY", "sk-preflight-not-a-key"),
56
+ oauth=(OAUTH_KEY, "sk-ant-oat01-" + "x" * 95 + "AA")) # dummies, only for the fake server
57
+
58
+
59
+ def claude_bin():
60
+ return os.environ.get("LFF_CLAUDE_BIN") or shutil.which("claude") or "claude"
61
+
62
+
63
+ def _norm(s, spec):
64
+ """Remove what legitimately differs between runs from preset prompt text: paths of the one-time dirs, dates."""
65
+ for k, v in sorted(dict(spec.state_dirs, cwd=spec.cwd).items(), key=lambda kv: -len(kv[1])):
66
+ s = s.replace(v, f"<{k.upper()}>")
67
+ s = re.sub(r"/tmp/lffrun/[0-9a-f]{12}", "<RUNDIR>", s)
68
+ s = re.sub(r"-tmp-lffrun-[0-9a-f]{12}", "<RUNDIR_SLUG>", s) # auto-memory dir name derived from the cwd
69
+ s = re.sub(r"(cc_version=\d+\.\d+\.\d+)\.[0-9a-f]+", r"\1.<X>", s) # billing header suffix varies per request
70
+ s = re.sub(r"/tmp/lffstate/[0-9a-f]{12}", "<STATEDIR>", s)
71
+ s = re.sub(r"\b20\d\d-\d\d-\d\d\b", "<DATE>", s)
72
+ s = re.sub(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", "<UUID>", s)
73
+ return s
74
+
75
+
76
+ def request_fingerprint(body, headers, spec, first_message):
77
+ """Normalised preset part of the first request + the checks that do not need a pin."""
78
+ problems = []
79
+ system = body.get("system")
80
+ if isinstance(system, str):
81
+ system = [dict(type="text", text=system)]
82
+ sys_blocks = [dict(text=_norm(b.get("text", ""), spec), cache=bool(b.get("cache_control"))) for b in system or []]
83
+ tools = [dict(name=t.get("name"), description=t.get("description"), input_schema=t.get("input_schema"))
84
+ for t in body.get("tools") or []]
85
+ if [t["name"] for t in tools] != MCP_TOOLS:
86
+ problems.append(f"tool list is {[t['name'] for t in tools]}, expected {MCP_TOOLS}")
87
+ msgs = body.get("messages") or []
88
+ first = msgs[0] if msgs else {}
89
+ content = first.get("content")
90
+ if isinstance(content, str):
91
+ content = [dict(type="text", text=content)]
92
+ prefix, found = [], False
93
+ for b in content or []:
94
+ if b.get("type") == "text" and b.get("text") == first_message:
95
+ found = True
96
+ break
97
+ prefix.append(_norm(b.get("text", "") if b.get("type") == "text" else json.dumps(b, sort_keys=True), spec))
98
+ if not found:
99
+ problems.append("the first user message does not contain our first message byte-for-byte as one block")
100
+ params = {k: body.get(k) for k in ("model", "max_tokens", "thinking", "output_config", "context_management",
101
+ "temperature", "top_p", "top_k", "tool_choice")}
102
+ fp = dict(system=sys_blocks, tools=tools, user_prefix=prefix, params=params,
103
+ anthropic_beta=sorted((headers.get("anthropic-beta") or headers.get("Anthropic-Beta") or "").split(",")),
104
+ system_chars=sum(len(b.get("text", "")) for b in system or []))
105
+ return fp, problems
106
+
107
+
108
+ class ClaudeCode(HarnessAdapter):
109
+ name = "claude_code"
110
+ bare = True
111
+ uses_mcp = True
112
+ clean_dirs = ("home", "config", "tmp")
113
+ ancestor_files = ("CLAUDE.md", "CLAUDE.local.md", ".claude", "AGENTS.md")
114
+ can_resume = True
115
+ capabilities = dict(
116
+ only_benchmark_tools=Cap("yes", "preflight", '--tools "" + --strict-mcp-config: request tools = 3 MCP tools'),
117
+ images_reach_model=Cap("yes", "probe", "MCP image content forwarded as image blocks, md5 equal"),
118
+ non_persistent_session=Cap("yes", "probe", "only this run's session (kept for -p --resume) in the one-time "
119
+ "config dir, removed after the run"),
120
+ pinned_version=Cap("yes", "launch", "claude --version + binary sha256 in harness.json; pin per version"),
121
+ machine_readable_events=Cap("yes", "stream", "--output-format stream-json --verbose"),
122
+ tool_calls_logged=Cap("yes", "stream", "tool_use / tool_result in stream + mcp_transcript + events.jsonl"),
123
+ model_and_effort=Cap("yes", "preflight", "--model / --effort; request output_config.effort checked"),
124
+ persistent_memory=Cap("absent", "probe", "--bare: no auto-memory; canaries never reach the request"),
125
+ instruction_file_injection=Cap("absent", "probe", "--bare: CLAUDE.md discovery off; canaries absent"),
126
+ web_access=Cap("absent", "preflight", "no WebFetch / WebSearch tool in the request"),
127
+ host_file_read=Cap("absent", "probe", "no Read tool; MCP shell is jailed; view_images confined"),
128
+ builtin_shell=Cap("absent", "preflight", "no Bash tool in the request"),
129
+ subagent_delegation=Cap("absent", "preflight", "no Agent / Task tool in the request"),
130
+ background_execution=Cap("absent", "preflight", "no Bash / Monitor tool in the request"),
131
+ )
132
+
133
+ def __init__(self, api_env=None, max_budget_usd=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
134
+ python=None, extra_args=None, jail=False, auth="apikey"):
135
+ """api_env: the only API variables passed to the harness: {"ANTHROPIC_API_KEY": ...} (auth="apikey") or
136
+ {"CLAUDE_CODE_OAUTH_TOKEN": ...} (auth="oauth", a subscription token of `claude setup-token`), optional
137
+ "ANTHROPIC_BASE_URL". Never inherited from the calling environment. jail: run the CLI in the
138
+ native-harness jail (lffbench/harnesses/jail.py; /proc stays the host's: Bun needs it)."""
139
+ if auth not in PREFLIGHT_CREDENTIAL:
140
+ raise ValueError(f"auth must be one of {sorted(PREFLIGHT_CREDENTIAL)}, not {auth!r}")
141
+ if auth == "oauth" and self.bare:
142
+ raise ValueError("claude_code (--bare) authenticates only with ANTHROPIC_API_KEY / apiKeyHelper; "
143
+ "use claude_code_full for a subscription token")
144
+ other = PREFLIGHT_CREDENTIAL["oauth" if auth == "apikey" else "apikey"][0]
145
+ if other in (api_env or {}):
146
+ raise ValueError(f"auth={auth}: api_env must not hold {other} (the CLI would use it instead)")
147
+ self.auth = auth
148
+ if jail:
149
+ from .jail import HarnessJail
150
+ self.jail = HarnessJail(claude_bin(), proc="host")
151
+ self.api_env = dict(api_env or {})
152
+ self.proxy = proxy_env()
153
+ self.max_budget_usd = max_budget_usd
154
+ self.timeout_s = timeout_s
155
+ self.pins_dir = pins_dir
156
+ self.allow_unpinned = allow_unpinned
157
+ self.python = python or sys.executable
158
+ self.extra_args = list(extra_args or [])
159
+ self._version = None
160
+
161
+ # ------------------------------------------------------------------------------------------------ version
162
+ def version(self):
163
+ if self._version is None:
164
+ b = claude_bin()
165
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent"), capture_output=True,
166
+ text=True, timeout=60)
167
+ v = (out.stdout.strip().split() or ["?"])[0]
168
+ self._version = dict(version=v, binary=binary_info(b))
169
+ return self._version
170
+
171
+ def pin_key(self, ep):
172
+ v = self.version()
173
+ name = self.name if self.auth == "apikey" else f"{self.name}-{self.auth}"
174
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
175
+
176
+ def auth_info(self):
177
+ key = PREFLIGHT_CREDENTIAL[self.auth][0]
178
+ return dict(mode=self.auth, credential_var=key, credential_set=bool(self.api_env.get(key)),
179
+ keys=sorted(self.api_env))
180
+
181
+ # ------------------------------------------------------------------------------------------------ prepare
182
+ def mcp_config(self, session_path=None, describe=False):
183
+ """describe: for config_sha256 only (jailed, no relay is set up for it)."""
184
+ args = ["--session", session_path] if session_path else ["--schema-only"]
185
+ if describe or self.jail is None:
186
+ cmd, a = ("<jail relay>" if self.jail is not None else self.python), [MCP_SCRIPT] + args
187
+ else:
188
+ cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args)
189
+ return {"mcpServers": {"lff": {"type": "stdio", "command": cmd, "args": a, "env": {"PATH": BASE_PATH}}}}
190
+
191
+ def argv(self, spec_paths, ep, first_message):
192
+ a = [claude_bin(), "-p", first_message]
193
+ if self.bare:
194
+ a.append("--bare")
195
+ a += ["--tools", "", "--strict-mcp-config", "--mcp-config", spec_paths["mcp_config"],
196
+ "--allowedTools", ",".join(MCP_TOOLS), "--permission-mode", "dontAsk", "--disable-slash-commands",
197
+ "--output-format", "stream-json", "--verbose", "--model", ep.model, "--effort", ep.effort]
198
+ if self.max_budget_usd:
199
+ a += ["--max-budget-usd", str(self.max_budget_usd)]
200
+ return a + self.extra_args
201
+
202
+ @staticmethod
203
+ def session_ids(stdout_path):
204
+ """Session ids of the init events in the stream, in order (one per launch / resume)."""
205
+ out = []
206
+ try:
207
+ for line in open(stdout_path, encoding="utf-8", errors="replace"):
208
+ if line.startswith("{") and '"init"' in line:
209
+ d = json.loads(line)
210
+ if d.get("type") == "system" and d.get("subtype") == "init" and d.get("session_id"):
211
+ out.append(d["session_id"])
212
+ except (OSError, ValueError):
213
+ pass
214
+ return out
215
+
216
+ def resume_argv(self, h, message):
217
+ """`claude -p <message> ... --resume <session>`: the launch's flags unchanged, the message in the place of the
218
+ first message (right after -p, before the variadic --allowedTools)."""
219
+ sids = self.session_ids(h.spec.stdout_path)
220
+ if not sids:
221
+ raise HarnessRefused("resume: no session id in the stream")
222
+ a = list(h.spec.argv)
223
+ return a[:2] + [message] + a[3:] + ["--resume", sids[0]]
224
+
225
+ def env(self, state):
226
+ # CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: measured 2026-10-21 with 2.1.299 and claude-fable-5-1: when the model's
227
+ # safeguards flag a request, the CLI otherwise answers it, and the rest of the session, with another model
228
+ # (claude-opus-4-8) under the requested model's name; with it, a flagged request ends as a refusal
229
+ # (system event model_refusal_no_fallback) and the run stays on the model under test
230
+ e = dict(PATH=BASE_PATH, HOME=state["home"], CLAUDE_CONFIG_DIR=state["config"], TMPDIR=state["tmp"],
231
+ LANG="C.UTF-8", CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC="1", DISABLE_AUTOUPDATER="1",
232
+ DISABLE_TELEMETRY="1", DISABLE_ERROR_REPORTING="1", MCP_TIMEOUT="60000", MCP_TOOL_TIMEOUT="900000",
233
+ CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK="1")
234
+ e.update(self.proxy)
235
+ e.update(self.api_env)
236
+ return e
237
+
238
+ def _state_dirs(self, hexname=None):
239
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
240
+ os.makedirs(root, exist_ok=True)
241
+ state = dict(state=root, home=os.path.join(root, "home"), config=os.path.join(root, "config"),
242
+ tmp=os.path.join(root, "tmp"))
243
+ for k in ("home", "config", "tmp"):
244
+ os.makedirs(state[k], exist_ok=True)
245
+ return state
246
+
247
+ def prepare(self, ep, first_message, reuse_state=None):
248
+ work = new_run_dir("/tmp/lffrun")
249
+ state = reuse_state or self._state_dirs(os.path.basename(work))
250
+ if self.jail is not None:
251
+ self.jail.stderr_dir = ep.log_dir
252
+ mcp_path = os.path.join(state["state"], "mcp.json")
253
+ with open(mcp_path, "w") as f:
254
+ json.dump(self.mcp_config(ep.session_path), f)
255
+ argv = self.argv(dict(mcp_config=mcp_path), ep, first_message)
256
+ spec = LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
257
+ first_message=first_message, config_files=dict(mcp_config=mcp_path),
258
+ stdout_path=os.path.join(ep.log_dir, "claude_stream.jsonl"),
259
+ stderr_path=os.path.join(ep.log_dir, "claude_stderr.txt"),
260
+ redact_argv={2: f"<first message: sha256={C.sha256_text(first_message)}>"},
261
+ timeout_s=self.timeout_s)
262
+ return spec
263
+
264
+ def config_sha256(self, spec, ep):
265
+ """Hash of everything configurable (argv without the first message, MCP config, env values except keys /
266
+ one-time dirs)."""
267
+ argv = [("<MCP_CONFIG>" if a == spec.config_files["mcp_config"] else a) for a in self.logged_argv(spec)[3:]]
268
+ env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
269
+ if k not in ("HOME", "CLAUDE_CONFIG_DIR", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
270
+ return C.sha256_json(dict(argv=argv, mcp=self.mcp_config("<SESSION>", describe=True), env=env))
271
+
272
+ # ------------------------------------------------------------------------------------------------ preflight
273
+ def preflight(self, spec, ep, record_dir=None):
274
+ """Run the identical command against a fake API (free); refuse on any mismatch with the pin."""
275
+ t0 = time.time()
276
+ fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start()
277
+ pre_state = self._state_dirs()
278
+ try:
279
+ mcp_path = os.path.join(pre_state["state"], "mcp.json")
280
+ with open(mcp_path, "w") as f:
281
+ json.dump(self.mcp_config(None), f)
282
+ argv = self.argv(dict(mcp_config=mcp_path), ep, spec.first_message)
283
+ env = {k: v for k, v in self.env(pre_state).items() if k not in self.api_env} # no real credential
284
+ cred_key, cred_dummy = PREFLIGHT_CREDENTIAL[self.auth]
285
+ env.update({"ANTHROPIC_BASE_URL": fake.base_url, cred_key: cred_dummy})
286
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre_state.values())), env=env, cwd=spec.cwd,
287
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=180)
288
+ reqs = fake.message_requests()
289
+ if not reqs:
290
+ raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): "
291
+ f"{r.stderr.decode('utf-8', 'replace')[-500:]}")
292
+ n, body = reqs[0]
293
+ headers = {}
294
+ if record_dir:
295
+ headers = json.load(open(os.path.join(record_dir, f"req_{n:03d}.json"))).get("headers", {})
296
+ fp, problems = request_fingerprint(body, headers, spec, spec.first_message)
297
+ init = next((json.loads(x) for x in r.stdout.decode("utf-8", "replace").splitlines()
298
+ if x.startswith('{"type":"system"') and '"init"' in x), {})
299
+ if init.get("tools") != MCP_TOOLS:
300
+ problems.append(f"init event tools {init.get('tools')}")
301
+ want_src = "ANTHROPIC_API_KEY" if self.auth == "apikey" else "none" # none = no API key: the OAuth token
302
+ if init.get("apiKeySource") != want_src:
303
+ problems.append(f"init apiKeySource {init.get('apiKeySource')!r}, expected {want_src!r} for "
304
+ f"auth={self.auth}")
305
+ if self.bare and "memory_paths" in init:
306
+ problems.append("init event has memory_paths under --bare")
307
+ if [s.get("status") for s in init.get("mcp_servers", [])] != ["connected"]:
308
+ problems.append(f"MCP servers {init.get('mcp_servers')}")
309
+ if os.listdir(spec.cwd):
310
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
311
+ fp_sha = C.sha256_json(fp)
312
+ out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs),
313
+ tools=[t["name"] for t in fp["tools"]], effort_in_request=(fp["params"].get("output_config")
314
+ or {}).get("effort"),
315
+ model_in_request=fp["params"].get("model"), init_tools=init.get("tools"),
316
+ memory_paths=init.get("memory_paths"), dt_s=round(time.time() - t0, 1), problems=problems)
317
+ if out["effort_in_request"] != ep.effort:
318
+ problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}")
319
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
320
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
321
+ out["fingerprint"] = fp
322
+ if problems:
323
+ raise HarnessRefused("preflight: " + "; ".join(problems))
324
+ if pin is None:
325
+ if not self.allow_unpinned:
326
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
327
+ f"with --write-pins after the self-check passes)")
328
+ out["pin_status"] = "unpinned (allowed)"
329
+ elif pin["fingerprint_sha256"] != fp_sha:
330
+ raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
331
+ f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
332
+ else:
333
+ out["pin_status"] = "match"
334
+ return out
335
+ finally:
336
+ fake.stop()
337
+ shutil.rmtree(pre_state["state"], ignore_errors=True)
338
+
339
+ def launch(self, spec, ep, skip_preflight=False):
340
+ try:
341
+ h = super().launch(spec, ep, skip_preflight)
342
+ except HarnessRefused:
343
+ raise
344
+ # second line of defence: the init event of the real run
345
+ deadline = time.time() + 120
346
+ while time.time() < deadline and h.proc.poll() is None:
347
+ init = self._init_event(spec)
348
+ if init is not None:
349
+ h.info["init"] = {k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version",
350
+ "permissionMode", "memory_paths", "apiKeySource")}
351
+ if init.get("tools") != MCP_TOOLS:
352
+ self.kill(h)
353
+ h.exit_reason = "refused: init tools " + json.dumps(init.get("tools"))
354
+ raise HarnessRefused(h.exit_reason)
355
+ break
356
+ time.sleep(0.2)
357
+ return h
358
+
359
+ @staticmethod
360
+ def _init_event(spec):
361
+ try:
362
+ with open(spec.stdout_path) as f:
363
+ for line in f:
364
+ if line.startswith("{"):
365
+ d = json.loads(line)
366
+ if d.get("type") == "system" and d.get("subtype") == "init":
367
+ return d
368
+ except (OSError, ValueError):
369
+ return None
370
+ return None
371
+
372
+ # ------------------------------------------------------------------------------------------------ collect
373
+ def collect(self, h):
374
+ spec, ep = h.spec, h.ep
375
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
376
+ init, result, by_id, compactions, other = None, None, {}, 0, []
377
+ inits, results = [], [] # one init / result per launch or resume
378
+ lines = open(spec.stdout_path, encoding="utf-8", errors="replace").read().splitlines()
379
+ for line in lines:
380
+ if not line.startswith("{"):
381
+ continue
382
+ d = json.loads(line)
383
+ t = d.get("type")
384
+ if t == "system" and d.get("subtype") == "init":
385
+ init = init or d
386
+ inits.append(d)
387
+ elif t == "system":
388
+ if "compact" in str(d.get("subtype", "")):
389
+ compactions += 1
390
+ other.append(d.get("subtype"))
391
+ elif t == "assistant":
392
+ m = d.get("message") or {}
393
+ mid = m.get("id") or d.get("uuid")
394
+ st = by_id.get(mid)
395
+ if st is None:
396
+ u = m.get("usage") or {}
397
+ st = tw.add_step("agent", timestamp=d.get("timestamp"), model_name=m.get("model"),
398
+ metrics=dict(prompt_tokens=u.get("input_tokens"),
399
+ completion_tokens=u.get("output_tokens"),
400
+ cached_tokens=u.get("cache_read_input_tokens")))
401
+ by_id[mid] = st
402
+ for b in m.get("content") or []:
403
+ if b.get("type") == "text":
404
+ st["message"] += b.get("text", "")
405
+ elif b.get("type") == "thinking":
406
+ st["reasoning_content"] += b.get("thinking", "")
407
+ elif b.get("type") == "tool_use":
408
+ st["tool_calls"].append(dict(tool_call_id=b.get("id"), function_name=strip_mcp(b.get("name")),
409
+ native_name=b.get("name"), arguments=b.get("input")))
410
+ elif t == "user":
411
+ for b in (d.get("message") or {}).get("content") or []:
412
+ if isinstance(b, dict) and b.get("type") == "tool_result":
413
+ c = b.get("content")
414
+ texts, imgs = [], 0
415
+ for x in (c if isinstance(c, list) else [dict(type="text", text=c)]):
416
+ if x.get("type") == "text":
417
+ texts.append(x.get("text") or "")
418
+ elif x.get("type") == "image":
419
+ imgs += 1
420
+ tw.add_result(b.get("tool_use_id"), "\n".join(texts), bool(b.get("is_error")), imgs)
421
+ elif t == "result":
422
+ result = d
423
+ results.append(d)
424
+ v = self.version()
425
+ tw.set_header(session_id=(init or {}).get("session_id"), source=os.path.basename(spec.stdout_path),
426
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
427
+ tools=(init or {}).get("tools"))
428
+
429
+ def tot(key, sub=None): # summed over the segments (each resume reports its own usage)
430
+ vals = [((r.get("usage") or {}).get(key) if sub is None else r.get(key)) for r in results]
431
+ vals = [x for x in vals if isinstance(x, (int, float))]
432
+ return sum(vals) if vals else None
433
+ cost = tot("total_cost_usd", sub=True)
434
+ tw.set_final(h.exit_reason, native_result={k: (result or {}).get(k) for k in
435
+ ("subtype", "is_error", "num_turns", "duration_ms",
436
+ "duration_api_ms", "total_cost_usd", "usage", "modelUsage")},
437
+ total_prompt_tokens=(tot("input_tokens") or 0) + (tot("cache_read_input_tokens") or 0)
438
+ + (tot("cache_creation_input_tokens") or 0),
439
+ total_completion_tokens=tot("output_tokens"), total_cached_tokens=tot("cache_read_input_tokens"),
440
+ total_cost_usd=cost, compactions=compactions, segments=len(results))
441
+ tw.write()
442
+ h.info.update(init_full=init, inits=inits, result=result, results=results, compactions=compactions,
443
+ other_system=other, traj=tw)
444
+ return tw
445
+
446
+ # ------------------------------------------------------------------------------------------------ audit
447
+ def audit(self, h):
448
+ spec, ep = h.spec, h.ep
449
+ init = h.info.get("init_full") or {}
450
+ tw = h.info.get("traj")
451
+ v, problems, notes = [], [], []
452
+ inits = h.info.get("inits") or [init]
453
+ for i, x in enumerate(inits): # every launch / resume
454
+ if x.get("tools") != MCP_TOOLS:
455
+ v.append(f"init {i} tools {x.get('tools')}")
456
+ sids = sorted({x.get("session_id") for x in inits if x.get("session_id")})
457
+ if len(sids) > 1:
458
+ v.append(f"several sessions in one run: {sids}")
459
+ if h.info.get("resumes"):
460
+ notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
461
+ f"episode was over)")
462
+ if self.bare and init.get("memory_paths"):
463
+ v.append(f"memory_paths {init.get('memory_paths')}")
464
+ if not self.bare and init.get("memory_paths"):
465
+ mp = json.dumps(init.get("memory_paths"))
466
+ if spec.state_dirs["state"] not in mp and spec.cwd not in mp:
467
+ v.append(f"memory_paths outside the one-time dirs: {mp}")
468
+ notes.append("full variant: memory_paths point into the one-time dirs (empty at start)")
469
+ names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]]
470
+ bad = sorted({n for n in names if n not in MCP_TOOLS})
471
+ if bad:
472
+ notes.append(f"model asked for unavailable tools (all rejected by the harness): {bad}")
473
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
474
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
475
+ left = dict(config=snapshot_tree(spec.state_dirs["config"]), home=snapshot_tree(spec.state_dirs["home"]),
476
+ work=snapshot_tree(spec.cwd))
477
+ mcp_logs = [p for p in left["home"] if "/mcp-logs-" in p]
478
+ own = [p for p in left["config"] if sids and p.startswith("projects/")
479
+ and (p.endswith(f"/{sids[0]}.jsonl") or f"/{sids[0]}/" in p)] # this run's session (for --resume)
480
+ transcripts = [p for p in left["config"] + left["home"] if p.endswith(".jsonl") and p not in mcp_logs
481
+ and p not in own]
482
+ if transcripts:
483
+ v.append(f"session transcripts other than this run's session: {transcripts}")
484
+ if own:
485
+ notes.append(f"this run's own session kept in the one-time config dir (for --resume): {own}")
486
+ if mcp_logs: # MCP connection log of the CLI in the one-time HOME (removed after the run, never read back)
487
+ notes.append(f"Claude Code wrote its MCP log into the one-time HOME: {mcp_logs}")
488
+ if left["work"]:
489
+ v.append(f"files in the work dir: {left['work']}")
490
+ mcp_env = None
491
+ mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
492
+ if os.path.exists(mt):
493
+ for line in open(mt):
494
+ d = json.loads(line)
495
+ if d.get("ev") == "start" and "env_keys" in d:
496
+ mcp_env = d["env_keys"]
497
+ out = dict(harness=self.name, violations=v, problems=problems, notes=notes, files_left=left,
498
+ mcp_server_env_keys=mcp_env, compactions=h.info.get("compactions"),
499
+ init={k: init.get(k) for k in ("tools", "mcp_servers", "model", "claude_code_version",
500
+ "permissionMode", "memory_paths", "apiKeySource")},
501
+ tool_calls=len(names), unavailable_tool_requests=bad, ok=not v)
502
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
503
+ json.dump(out, f, indent=1)
504
+ return out
505
+
506
+
507
+ class ClaudeCodeFull(ClaudeCode):
508
+ name = "claude_code_full"
509
+ bare = False
510
+ capabilities = dict(ClaudeCode.capabilities,
511
+ persistent_memory=Cap("partial", "probe", "auto-memory is on in the harness, but its dirs are "
512
+ "one-time and empty; canaries outside them never reach the request"),
513
+ instruction_file_injection=Cap("partial", "probe", "CLAUDE.md discovery is on, but work / "
514
+ "config / home are empty one-time dirs; canaries outside absent"))
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/dsh.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DeepSeek Harness (`dsh`, deepseek-ai/deepseek-harness, developer preview) as a native harness.
2
+
3
+ Launch: `node <dsh>/lib/bin.js --profile headless --patch <one-time patch> --json <first message>`, process env exactly
4
+ the whitelist, a brand-new empty DSH_HOME and HOME under /tmp/lffstate/<hex>, work dir /tmp/lffrun/<12 hex>. The patch
5
+ is a Cordis overlay on the shipped headless profile: it switches off every built-in tool plugin and what serves only
6
+ them (memory-like instructions, skills, goals, web, sub-agents, plan mode, code-mode tool calls) and adds our MCP
7
+ server. What stays as shipped is the harness under test: its system prompt, agent loop, retry policy, compaction,
8
+ tool-result pruning and image offload.
9
+
10
+ Two more plugins are off because they are provider telemetry, not agent behaviour (model-hidden top-level request
11
+ fields, docs/deepseek-llm-api-wire-extensions.md): session-log-deepseek (`dsh_session_log`: the session log on every
12
+ request) and plugin-package-inventory-deepseek (`dsh_plugin_packages`). session-title-llm is off: an extra model call
13
+ that only names the session.
14
+
15
+ The model API is the direct DeepSeek adapter (Anthropic Messages, default root https://api.deepseek.com/anthropic, or
16
+ OpenCode Go's https://opencode.ai/inference/go; model id passed through, `output_config.effort`). DeepSeek's adapter uploads each request image through /v1/files and
17
+ sends file ids, falling back to inline base64; the model gateway allows the Files path for this harness
18
+ (scripts/model_gateway.py --allow-files), otherwise each image would first fail an upload.
19
+
20
+ Release layout (LFF_DSH_HOME, default /mnt/cpfs/workspace/env/dsh-<version>): bin/node (official Node.js build, no
21
+ dependency on /etc/dsw, so it runs in the jail) + node_modules/ from `npm install @deepseek-ai/dsh@<version>`. The pin
22
+ key's hash covers bin/node and package-lock.json.
23
+
24
+ Early exit: as for the other CLIs, the process ends when the model replies without a tool call, also mid-episode;
25
+ scripts/harness_run.py then sends the reference driver's nudge with `--session-id <id> <nudge>` (resume_argv).
26
+
27
+ The --json stream caps strings at 8 KiB and is not lossless, so the durable session log (session.v4.jsonl.zstd) is
28
+ copied into the run's log dir in audit(), before the one-time dirs are removed.
29
+
30
+ Fail-closed launch: as Claude Code (claude_code.py): the same argv / env against a local fake Anthropic server with a
31
+ schema-only MCP server; tools, system prompt, harness-added message prefix and parameters are hashed against the pin.
32
+ """
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import subprocess
38
+ import sys
39
+ import time
40
+
41
+ from . import contract as C
42
+ from . import pins
43
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
44
+ new_run_dir, proxy_env, snapshot_tree)
45
+ from .claude_code import MCP_TOOLS, request_fingerprint
46
+ from .fakeapi import FakeAnthropic
47
+ from .trajectory import TrajWriter, strip_mcp
48
+
49
+ ROOT = C.ROOT
50
+ MCP_SCRIPT = os.path.join(ROOT, "scripts", "mcp_robot_server.py")
51
+ BASE_PATH = "/usr/bin:/bin"
52
+ DEFAULT_RELEASE = "/mnt/cpfs/workspace/env/dsh-0.2.1-rc.5"
53
+ DEEPSEEK_ANTHROPIC_URL = "https://api.deepseek.com/anthropic"
54
+ BIN_JS = os.path.join("node_modules", "@deepseek-ai", "dsh", "lib", "bin.js")
55
+ PACKAGE_JSON = os.path.join("node_modules", "@deepseek-ai", "dsh", "package.json")
56
+ CONTEXT_WINDOW = 1048576 # GET https://api.deepseek.com/models, DeepSeek-V4.1-Flash, 2026-10-30
57
+ SESSION_LOG = "session.v4.jsonl.zstd"
58
+ OK_EVENTS = ("session", "status", "text", "thinking", "tool_call", "tool_result", "final", "error")
59
+ # request fields of the provider telemetry plugins switched off in the patch: their return is a launch refusal
60
+ TELEMETRY_FIELDS = ("dsh_session_log", "dsh_plugin_packages")
61
+ DISABLE = ["tool-bash", "tool-pwsh", "tool-jobs", "tool-fs", "tool-fs-search", "tool-skill", "tool-todo", "tool-goal",
62
+ "tool-web", "tool-subagent", "tool-subagent-fork", "tool-subagent-control", "tool-workflow",
63
+ "tool-working-directory", "mcp-resources", "agent-instructions", "skill-filesystem", "skill",
64
+ "goal-round-driver", "command-goal", "goal", "plan-mode", "subagent-fork-in-process",
65
+ "subagent-spawn-in-process", "subagent", "workflow-ptc", "tool-executor-ptc", "ptc-runtime",
66
+ "web-fetch-http", "web-deepseek-api", "web-search-deepseek", "web", "session-title-llm",
67
+ "session-log-deepseek", "plugin-package-inventory-deepseek", "llm-deepseek-account"]
68
+
69
+
70
+ def release_dir():
71
+ return os.environ.get("LFF_DSH_HOME") or DEFAULT_RELEASE
72
+
73
+
74
+ def node_bin():
75
+ return os.path.join(release_dir(), "bin", "node")
76
+
77
+
78
+ def _yaml_str(s):
79
+ return json.dumps(s) # a JSON string is a valid YAML flow scalar
80
+
81
+
82
+ def patch_yaml(mcp_cmd, mcp_args, cwd, effort, base_url, model):
83
+ """The Cordis overlay of a run. A config override replaces the whole entry config, hence the full llm-deepseek row.
84
+ The model is declared in `models` because dsh treats a model id outside its built-in catalog as text-only
85
+ (docs/user/guide/providers.md), and the OpenCode Go id is one; capacity and image input from DeepSeek's /models."""
86
+ out = [f"- id: {name}\n disabled: true\n" for name in DISABLE]
87
+ out.append("- id: llm-deepseek\n config:\n"
88
+ f" baseURL: {_yaml_str(base_url)}\n apiKeyEnv: DEEPSEEK_API_KEY\n"
89
+ f" reasoningEffort: {_yaml_str(effort)}\n"
90
+ f" models:\n - id: {_yaml_str(model)}\n contextWindow: {CONTEXT_WINDOW}\n"
91
+ " inputModalities: [text, image]\n")
92
+ out.append("- insert:\n - id: mcp-lff\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n"
93
+ " serverName: lff\n transport: stdio\n"
94
+ f" command: {_yaml_str(mcp_cmd)}\n"
95
+ f" args: {json.dumps(list(mcp_args))}\n"
96
+ f" env: {{PATH: {_yaml_str(BASE_PATH)}}}\n"
97
+ f" cwd: {_yaml_str(cwd)}\n"
98
+ " toolCallTimeoutMs: 900000\n failOnStartupError: true\n")
99
+ return "".join(out)
100
+
101
+
102
+ class DeepSeekHarness(HarnessAdapter):
103
+ name = "dsh"
104
+ uses_mcp = True
105
+ can_resume = True
106
+ clean_dirs = ("home", "dsh_home", "tmp")
107
+ ancestor_files = ("AGENTS.md", "CLAUDE.md", ".dsh", ".agents")
108
+ capabilities = dict(
109
+ only_benchmark_tools=Cap("yes", "preflight", "built-in tool plugins off in the patch: request tools = 3 MCP "
110
+ "tools"),
111
+ images_reach_model=Cap("partial", "probe", "MCP images reach the model through dsh's request-image pipeline, "
112
+ "which resizes to DeepSeek's vision grid (at most 1024 tokens an image) and may offload "
113
+ "the oldest images of a long run; not byte-identical above that size"),
114
+ non_persistent_session=Cap("yes", "probe", "only this run's session (for --session-id) in the one-time "
115
+ "DSH_HOME, removed after the run"),
116
+ pinned_version=Cap("yes", "launch", "package version + hash of bin/node and package-lock.json in harness.json"),
117
+ machine_readable_events=Cap("partial", "stream", "--json NDJSON, strings capped at 8 KiB; the lossless session "
118
+ "log is copied into the log dir"),
119
+ tool_calls_logged=Cap("yes", "stream", "tool_call / tool_result in stream + mcp_transcript + events.jsonl"),
120
+ model_and_effort=Cap("yes", "preflight", "agent default model / llm-deepseek reasoningEffort; request "
121
+ "output_config.effort checked"),
122
+ persistent_memory=Cap("absent", "probe", "no memory plugin in the profile; empty one-time DSH_HOME"),
123
+ instruction_file_injection=Cap("absent", "preflight", "agent-instructions and skills plugins off; empty dirs"),
124
+ web_access=Cap("absent", "preflight", "web plugins off; no web tool in the request"),
125
+ host_file_read=Cap("absent", "preflight", "tool-fs / tool-fs-search off; MCP shell is jailed"),
126
+ builtin_shell=Cap("absent", "preflight", "tool-bash / tool-pwsh off; not in the request"),
127
+ subagent_delegation=Cap("absent", "preflight", "subagent plugins off; not in the request"),
128
+ background_execution=Cap("absent", "preflight", "tool-jobs off; not in the request"),
129
+ )
130
+
131
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False, python=None,
132
+ extra_args=None, jail=False):
133
+ """api_env: {"DEEPSEEK_API_KEY": ...}; base_url: Messages root (default the official one; never read from the
134
+ calling environment)."""
135
+ self.release = release_dir()
136
+ self.node = node_bin()
137
+ if not os.access(self.node, os.X_OK):
138
+ raise HarnessRefused(f"dsh: no {self.node} (see lffbench/harnesses/dsh.py, release layout)")
139
+ if jail:
140
+ from .jail import HarnessJail
141
+ self.jail = HarnessJail(self.node, proc="host") # /proc: Node reads the host's cgroup / cpu files
142
+ self.api_env = dict(api_env or {})
143
+ self.base_url = base_url or DEEPSEEK_ANTHROPIC_URL
144
+ self.proxy = proxy_env()
145
+ self.timeout_s = timeout_s
146
+ self.pins_dir = pins_dir
147
+ self.allow_unpinned = allow_unpinned
148
+ self.python = python or sys.executable
149
+ self.extra_args = list(extra_args or [])
150
+ self._version = None
151
+
152
+ # ------------------------------------------------------------------------------------------------ version
153
+ def version(self):
154
+ if self._version is None:
155
+ pkg = json.load(open(os.path.join(self.release, PACKAGE_JSON)))
156
+ lock = C.sha256_file(os.path.join(self.release, "package-lock.json"))
157
+ node = binary_info(self.node)
158
+ self._version = dict(version=pkg["version"], binary=node, package_lock_sha256=lock,
159
+ pin_sha256=C.sha256_text(node["sha256"] + lock))
160
+ return self._version
161
+
162
+ def pin_key(self, ep):
163
+ v = self.version()
164
+ return pins.key(self.name, v["version"], v["pin_sha256"], ep.model, ep.effort)
165
+
166
+ def auth_info(self):
167
+ return dict(mode="apikey", keys=sorted(self.api_env))
168
+
169
+ # ------------------------------------------------------------------------------------------------ prepare
170
+ def bin_js(self):
171
+ """lib/bin.js as the process sees it: in the jail, inside the verified copy of the release dir."""
172
+ if self.jail is not None:
173
+ root = os.path.dirname(os.path.dirname(self.jail.binary_jailed))
174
+ return os.path.join(root, BIN_JS)
175
+ return os.path.join(self.release, BIN_JS)
176
+
177
+ def argv(self, patch_path, first_message):
178
+ return [self.node, self.bin_js(), "--profile", "headless", "--patch", patch_path, "--json"] + self.extra_args + [
179
+ first_message]
180
+
181
+ def write_patch(self, state, session_path, cwd, ep, base_url):
182
+ args = ["--session", session_path] if session_path else ["--schema-only"]
183
+ cmd, a = self.mcp_server_command(self.python, MCP_SCRIPT, args)
184
+ path = os.path.join(state["state"], "patch.yml")
185
+ with open(path, "w") as f:
186
+ f.write(patch_yaml(cmd, a, cwd, ep.effort, base_url, ep.model))
187
+ return path
188
+
189
+ def env(self, state, base_url_unused=None):
190
+ e = dict(PATH=BASE_PATH, HOME=state["home"], DSH_HOME=state["dsh_home"], TMPDIR=state["tmp"], LANG="C.UTF-8",
191
+ NO_UPDATE_NOTIFIER="1")
192
+ e.update(self.proxy)
193
+ e.update(self.api_env)
194
+ return e
195
+
196
+ def _state_dirs(self, hexname=None):
197
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
198
+ os.makedirs(root, exist_ok=True)
199
+ state = dict(state=root, home=os.path.join(root, "home"), dsh_home=os.path.join(root, "dsh_home"),
200
+ tmp=os.path.join(root, "tmp"))
201
+ for k in ("home", "dsh_home", "tmp"):
202
+ os.makedirs(state[k], exist_ok=True)
203
+ return state
204
+
205
+ def _write_profile_default(self, state, ep):
206
+ """The run's model as the profile's default (a config override of agent-default-model) goes into the patch of
207
+ the same directory: dsh has no --model flag in headless mode."""
208
+ path = os.path.join(state["state"], "patch.yml")
209
+ with open(path, "a") as f:
210
+ f.write("- id: agent-default-model\n config:\n provider: deepseek-official\n"
211
+ f" model: {_yaml_str(ep.model)}\n")
212
+
213
+ def prepare(self, ep, first_message, reuse_state=None):
214
+ work = new_run_dir("/tmp/lffrun")
215
+ state = reuse_state or self._state_dirs(os.path.basename(work))
216
+ if self.jail is not None:
217
+ self.jail.stderr_dir = ep.log_dir
218
+ patch = self.write_patch(state, ep.session_path, work, ep, self.base_url)
219
+ self._write_profile_default(state, ep)
220
+ argv = self.argv(patch, first_message)
221
+ return LaunchSpec(argv=argv, env=self.env(state), cwd=work, run_dir=work, state_dirs=state,
222
+ first_message=first_message, config_files=dict(patch=patch),
223
+ stdout_path=os.path.join(ep.log_dir, "dsh_events.jsonl"),
224
+ stderr_path=os.path.join(ep.log_dir, "dsh_stderr.txt"),
225
+ redact_argv={len(argv) - 1: f"<first message: sha256={C.sha256_text(first_message)}>"},
226
+ timeout_s=self.timeout_s)
227
+
228
+ def config_sha256(self, spec, ep):
229
+ """Hash of everything configurable: argv without the first message, the patch with the run's paths normalised,
230
+ env values except keys / one-time dirs."""
231
+ def norm(s):
232
+ s = s.replace(spec.state_dirs["state"], "<STATE>").replace(spec.cwd, "<CWD>").replace(ep.session_path,
233
+ "<SESSION>")
234
+ s = re.sub(r"/tmp/lffsock/[0-9a-f]{12}/[^\"\],]+", "<JAIL_SOCKET>", s)
235
+ return re.sub(r"http://127\.0\.0\.1:\d+[^\"\s]*", "<MODEL_ENDPOINT>", s)
236
+ argv = [norm(a) for a in self.logged_argv(spec)[1:-1]]
237
+ patch = norm(open(spec.config_files["patch"]).read())
238
+ env = {k: (v if k not in self.api_env else "<api>") for k, v in spec.env.items()
239
+ if k not in ("HOME", "DSH_HOME", "TMPDIR") + PROXY_KEYS + NO_PROXY_KEYS}
240
+ return C.sha256_json(dict(argv=argv, patch=patch, env=env))
241
+
242
+ # ------------------------------------------------------------------------------------------------ preflight
243
+ def preflight(self, spec, ep, record_dir=None):
244
+ t0 = time.time()
245
+ fake = FakeAnthropic([[("text", "preflight ok")]], record_dir=record_dir).start()
246
+ pre = self._state_dirs()
247
+ try:
248
+ patch = self.write_patch(pre, None, spec.cwd, ep, fake.base_url)
249
+ self._write_profile_default(pre, ep)
250
+ argv = self.argv(patch, spec.first_message)
251
+ env = {k: v for k, v in self.env(pre).items() if k not in self.api_env}
252
+ env["DEEPSEEK_API_KEY"] = "sk-preflight-not-a-key"
253
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
254
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
255
+ reqs = fake.message_requests()
256
+ if not reqs:
257
+ raise HarnessRefused(f"preflight: harness sent no request (rc={r.returncode}): "
258
+ f"{r.stderr.decode('utf-8', 'replace')[-800:]}"
259
+ f"{r.stdout.decode('utf-8', 'replace')[-400:]}")
260
+ n, body = reqs[0]
261
+ fp, problems = request_fingerprint(body, {}, spec, spec.first_message)
262
+ fp.pop("anthropic_beta", None)
263
+ fp["body_keys"] = sorted(body)
264
+ for f in TELEMETRY_FIELDS:
265
+ if f in body:
266
+ problems.append(f"request carries the telemetry field {f}")
267
+ if os.listdir(spec.cwd):
268
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
269
+ fp_sha = C.sha256_json(fp)
270
+ out = dict(fingerprint_sha256=fp_sha, system_chars=fp["system_chars"], n_requests=len(reqs),
271
+ tools=[t["name"] for t in fp["tools"]],
272
+ effort_in_request=(fp["params"].get("output_config") or {}).get("effort"),
273
+ model_in_request=fp["params"].get("model"), dt_s=round(time.time() - t0, 1), problems=problems)
274
+ if out["effort_in_request"] != ep.effort:
275
+ problems.append(f"effort in request {out['effort_in_request']!r} != {ep.effort!r}")
276
+ if out["model_in_request"] != ep.model:
277
+ problems.append(f"model in request {out['model_in_request']!r} != {ep.model!r}")
278
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
279
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
280
+ out["fingerprint"] = fp
281
+ if problems:
282
+ raise HarnessRefused("preflight: " + "; ".join(problems))
283
+ if pin is None:
284
+ if not self.allow_unpinned:
285
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
286
+ f"with --write-pins after the self-check passes)")
287
+ out["pin_status"] = "unpinned (allowed)"
288
+ elif pin["fingerprint_sha256"] != fp_sha:
289
+ raise HarnessRefused(f"preflight: preset prompt / tools fingerprint {fp_sha[:12]} != pinned "
290
+ f"{pin['fingerprint_sha256'][:12]} ({pin['key']})")
291
+ else:
292
+ out["pin_status"] = "match"
293
+ return out
294
+ finally:
295
+ fake.stop()
296
+ shutil.rmtree(pre["state"], ignore_errors=True)
297
+
298
+ # ------------------------------------------------------------------------------------------------ resume
299
+ @staticmethod
300
+ def session_ids(stdout_path):
301
+ out = []
302
+ try:
303
+ for line in open(stdout_path, encoding="utf-8", errors="replace"):
304
+ if line.startswith('{"type":"session"'):
305
+ out.append(json.loads(line)["sessionId"])
306
+ except (OSError, ValueError, KeyError):
307
+ pass
308
+ return out
309
+
310
+ def resume_argv(self, h, message):
311
+ sids = self.session_ids(h.spec.stdout_path)
312
+ if not sids:
313
+ raise HarnessRefused("resume: no session id in the stream")
314
+ return list(h.spec.argv[:-1]) + ["--session-id", sids[0], message]
315
+
316
+ # ------------------------------------------------------------------------------------------------ collect
317
+ def collect(self, h):
318
+ spec, ep = h.spec, h.ep
319
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
320
+ usage, sid, kinds, errors, turn_ends, truncated = dict(input=0, cached=0, output=0, cache_write=0), None, [], [], [], 0
321
+ cur = None
322
+ for line in open(spec.stdout_path, encoding="utf-8", errors="replace"):
323
+ if not line.startswith("{"):
324
+ continue
325
+ d = json.loads(line)
326
+ t = d.get("type")
327
+ kinds.append(t)
328
+ truncated += bool(d.get("truncated"))
329
+ if t == "session":
330
+ sid = sid or d.get("sessionId")
331
+ elif t == "text":
332
+ cur = tw.add_step("agent", message=d.get("text", ""))
333
+ elif t == "thinking":
334
+ cur = tw.add_step("agent", reasoning=d.get("text", ""))
335
+ elif t == "tool_call":
336
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=d.get("callId"), function_name=strip_mcp(d.get("tool")),
337
+ native_name=d.get("tool"), arguments=d.get("input"))])
338
+ elif t == "tool_result":
339
+ tw.add_result(d.get("callId"), d.get("result", ""), d.get("status") == "error", 0)
340
+ elif t == "status" and d.get("phase") == "step_end":
341
+ u = d.get("usage") or {}
342
+ usage["input"] += u.get("inputTokens") or 0
343
+ usage["output"] += u.get("outputTokens") or 0
344
+ usage["cached"] += u.get("cacheReadTokens") or 0
345
+ usage["cache_write"] += u.get("cacheWriteTokens") or 0
346
+ elif t == "status" and d.get("phase") == "turn_end":
347
+ turn_ends.append(d.get("reason"))
348
+ elif t == "error":
349
+ errors.append(d)
350
+ del cur
351
+ v = self.version()
352
+ tw.set_header(session_id=sid, source=os.path.basename(spec.stdout_path),
353
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort),
354
+ tools=MCP_TOOLS)
355
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], turn_ends=turn_ends[-5:]),
356
+ total_prompt_tokens=usage["input"] + usage["cached"] + usage["cache_write"],
357
+ total_completion_tokens=usage["output"], total_cached_tokens=usage["cached"],
358
+ total_cost_usd=None, segments=len(turn_ends), truncated_events=truncated)
359
+ tw.write()
360
+ h.info.update(kinds=kinds, traj=tw, session=sid, errors=errors, turn_ends=turn_ends)
361
+ return tw
362
+
363
+ # ------------------------------------------------------------------------------------------------ audit
364
+ def audit(self, h):
365
+ spec, ep = h.spec, h.ep
366
+ v, notes = [], []
367
+ bad = sorted({k for k in h.info.get("kinds") or [] if k not in OK_EVENTS})
368
+ if bad:
369
+ notes.append(f"unknown event types in the stream: {bad}")
370
+ tw = h.info.get("traj")
371
+ names = [tc.get("native_name") for st in (tw.steps if tw else []) for tc in st["tool_calls"]]
372
+ badt = sorted({n for n in names if n not in MCP_TOOLS})
373
+ if badt:
374
+ notes.append(f"model asked for unavailable tools: {badt}")
375
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
376
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
377
+ left = dict(dsh_home=snapshot_tree(spec.state_dirs["dsh_home"]), home=snapshot_tree(spec.state_dirs["home"]),
378
+ work=snapshot_tree(spec.cwd))
379
+ sid = h.info.get("session")
380
+ logs = [p for p in left["dsh_home"] if p.endswith(SESSION_LOG)]
381
+ foreign = [p for p in logs if not (sid and f"/{sid}/" in p)]
382
+ if foreign:
383
+ v.append(f"session logs other than this run's: {foreign}")
384
+ for p in logs:
385
+ shutil.copy(os.path.join(spec.state_dirs["dsh_home"], p), os.path.join(ep.log_dir, SESSION_LOG))
386
+ if h.info.get("resumes"):
387
+ notes.append(f"resumed {len(h.info['resumes'])}x with the reference driver's nudge (CLI exited before the "
388
+ f"episode was over)")
389
+ if left["work"]:
390
+ v.append(f"files in the work dir: {left['work']}")
391
+ mcp_env = None
392
+ mt = os.path.join(ep.log_dir, "mcp_transcript.jsonl")
393
+ if os.path.exists(mt):
394
+ for line in open(mt):
395
+ d = json.loads(line)
396
+ if d.get("ev") == "start" and "env_keys" in d:
397
+ mcp_env = d["env_keys"]
398
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, mcp_server_env_keys=mcp_env,
399
+ errors=h.info.get("errors"), turn_ends=h.info.get("turn_ends"), tool_calls=len(names),
400
+ unavailable_tool_requests=badt, ok=not v)
401
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
402
+ json.dump(out, f, indent=1)
403
+ return out
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/claude_code_full-oauth_2.1.299_2d894a4b1bfaaa9a_claude-fable-5-2_high.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "claude_code_full-oauth|2.1.299|2d894a4b1bfaaa9a|claude-fable-5-2|high",
3
+ "fingerprint_sha256": "da76da3889b0e8258550e2d7b199dcdcdedd5a2aa0dbe59018695a7aa7773f26",
4
+ "written": "2026-11-10 15:40:33",
5
+ "summary": {
6
+ "system_chars": 6207,
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-fable-5-2"
14
+ }
15
+ }
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-chatgpt-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "embodied_evo_codex-chatgpt-generic-646620c9aa77|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
4
+ "written": "2026-10-26 07:09:40",
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": "470278c478bdb5e4b6f17dde1ea0393761f230f0",
10
+ "tree_sha256": "1aeeee06baa254fce963c153f883e3605180d0f39e06e5f8fd6ac15f3c10e0c1",
11
+ "workflow_sha256": "95bcf2e05ad493f808aa03aa6a17fc7c7c470a1c5a25075247b864c008132ba2"
12
+ }
13
+ }
14
+ }
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/embodied_evo_codex-generic-646620c9aa77_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "embodied_evo_codex-generic-646620c9aa77|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "3dc06d7d7d7c5fb03c550905ba2d16faecefde695afc17f1f9f77da16c376e8c",
4
+ "written": "2026-10-25 04:39:36",
5
+ "summary": {
6
+ "report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json",
7
+ "checks": 10,
8
+ "framework": {
9
+ "commit": "470278c478bdb5e4b6f17dde1ea0393761f230f0",
10
+ "tree_sha256": "1aeeee06baa254fce963c153f883e3605180d0f39e06e5f8fd6ac15f3c10e0c1",
11
+ "workflow_sha256": "95bcf2e05ad493f808aa03aa6a17fc7c7c470a1c5a25075247b864c008132ba2"
12
+ }
13
+ }
14
+ }
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/pins/rpent_codex-generic-9f0e3aafc10c_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "key": "rpent_codex-generic-9f0e3aafc10c|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
3
+ "fingerprint_sha256": "6e63c24ad13895ebfbb0bc76a17ebbdc9765414a3f4351fe442480afa50b5ce9",
4
+ "written": "2026-10-24 07:27: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": "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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/rpent.py ADDED
@@ -0,0 +1,530 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """RPent (a robot harness framework, RLinf/RPent v0.1) on Codex as an upper-layer harness (docs/18; research note
2
+ harness接入调研/04 §13.7-13.9).
3
+
4
+ rpent_codex RPent's session loop, prompt and archive / handoff rules (robots/lffbench in an RPent checkout with our
5
+ patch), driving Codex through RPent's own Codex planner (openai_codex SDK -> `codex app-server`)
6
+
7
+ What the run is made of:
8
+ - the RPent runtime (LFF_RPENT_HOME, default /mnt/cpfs/workspace/env/rpent-v0.1): src/ = RPent at a pinned commit
9
+ plus our patch (integrations/rpent-v0.1), venv/ = its locked dependencies on /usr/bin/python3.12, no simulator;
10
+ hashed into rpent_tree_sha256 (recorded, and part of the pin);
11
+ - the framework process `python -m robots.lffbench.run` (one per episode), whose only way to the robot is the
12
+ episode's tool gateway (uses_gateway: LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN, lffbench_client, face "rpent");
13
+ - Codex: the same pinned binary and the same configuration as the main table's `codex` adapter (generic model
14
+ catalog in a one-time CODEX_HOME, the same disabled features and instruction switches, read-only sandbox, MCP
15
+ tools approved), passed to RPent's planner as RPENT_CODEX_CONFIG_OVERRIDES; RPent's in-process MCP server is named
16
+ "lff", so the model sees mcp__lff.robot / .shell / .view_images exactly as with `codex exec`.
17
+ Measured 2026-10-21 (fake API, Codex 0.163.0, gpt-6.1-sol / high): the first request of this path has the same
18
+ normalised fingerprint (tools, developer message, parameters, sandbox) as the `codex` adapter's preflight request;
19
+ the only difference is RPent's system prompt in front of the first user message (RPent puts system prompt and first
20
+ message into one user turn). The preflight checks both: the middle-layer fingerprint against the main table's codex
21
+ pin for the same model / effort (when it exists) and the whole fingerprint (incl. RPent's prefix) against this
22
+ adapter's own pin.
23
+
24
+ The framework owns its loop (sessions, handoff, archive): harness_run's resume / nudge does not apply (can_resume
25
+ False). Episode budgets and attempt switching stay with robot_server and the gateway. Only an API key is supported
26
+ (auth="apikey"; the side table runs gpt-6.1-sol on an OpenAI key, user 2026-10-21).
27
+ """
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ import time
34
+
35
+ from . import contract as C
36
+ from . import pins
37
+ from .base import (NO_PROXY_KEYS, PROXY_KEYS, Cap, HarnessAdapter, HarnessRefused, LaunchSpec, binary_info,
38
+ gateway_env, new_run_dir, proxy_env, snapshot_tree)
39
+ from .codex import (CATALOG_FILE, CATALOGS, DISABLE, EXPECTED_TOP_GENERIC, OFFICIAL_API, codex_bin, model_catalog,
40
+ request_fingerprint, toml_str)
41
+ from .fakeapi import FakeResponses
42
+ from .trajectory import TrajWriter
43
+
44
+ ROOT = C.ROOT
45
+ RPENT_HOME = "/mnt/cpfs/workspace/env/rpent-v0.1"
46
+ JAIL_RPENT_DIR = "/opt/lffjail/hjail/rpent"
47
+ BASE_PATH = "/usr/bin:/bin"
48
+ MCP_SERVER = "lff"
49
+ MCP_TOOLS = ["robot", "shell", "view_images"]
50
+ TREE_SKIP = {".git", "__pycache__", "docs", "tests", ".github"}
51
+
52
+
53
+ def rpent_home():
54
+ return os.environ.get("LFF_RPENT_HOME") or RPENT_HOME
55
+
56
+
57
+ def tree_sha256(root, skip=TREE_SKIP):
58
+ """sha256 over (relative path, file sha256 / symlink target) of every file under root, skipping `skip` dirs."""
59
+ h = hashlib.sha256()
60
+ for dp, dn, fn in os.walk(root):
61
+ dn[:] = sorted(d for d in dn if d not in skip)
62
+ for f in sorted(fn):
63
+ if f.endswith(".pyc"):
64
+ continue
65
+ p = os.path.join(dp, f)
66
+ rel = os.path.relpath(p, root)
67
+ if os.path.islink(p):
68
+ h.update(f"L {rel} {os.readlink(p)}\n".encode())
69
+ else:
70
+ h.update(f"F {rel} {C.sha256_file(p)}\n".encode())
71
+ return h.hexdigest()
72
+
73
+
74
+ def runtime_info(home):
75
+ """The RPent runtime: upstream commit, our patch on top, and the tree hash of src + venv."""
76
+ src, venv = os.path.join(home, "src"), os.path.join(home, "venv")
77
+ for d in (src, venv):
78
+ if not os.path.isdir(d):
79
+ raise HarnessRefused(f"RPent runtime incomplete: {d} missing (integrations/rpent-v0.1/setup.sh)")
80
+
81
+ def git(*a):
82
+ r = subprocess.run(["git", "-C", src] + list(a), capture_output=True, text=True, timeout=60)
83
+ return r.stdout.strip() if r.returncode == 0 else None
84
+ commit = git("rev-parse", "HEAD")
85
+ patch = subprocess.run(["git", "-C", src, "diff", "HEAD"], capture_output=True, timeout=60).stdout
86
+ untracked = (git("ls-files", "--others", "--exclude-standard") or "").split()
87
+ return dict(home=home, commit=commit, patch_sha256=hashlib.sha256(patch).hexdigest(),
88
+ untracked=sorted(u for u in untracked if "__pycache__" not in u),
89
+ tree_sha256=hashlib.sha256((tree_sha256(src) + tree_sha256(venv)).encode()).hexdigest())
90
+
91
+
92
+ def jail_runtime_copy(home, tree):
93
+ """A verified read-only copy of the runtime under /opt/lffjail/hjail/rpent (visible in the jail; /mnt is not)."""
94
+ dst = os.path.join(JAIL_RPENT_DIR, f"rpent-{tree[:12]}")
95
+ stamp = os.path.join(dst, ".tree_sha256")
96
+ if os.path.exists(stamp) and open(stamp).read().strip() == tree:
97
+ return dst
98
+ os.makedirs(JAIL_RPENT_DIR, mode=0o755, exist_ok=True)
99
+ tmp = dst + ".tmp-" + os.urandom(3).hex()
100
+ shutil.copytree(os.path.join(home, "src"), os.path.join(tmp, "src"), symlinks=True,
101
+ ignore=shutil.ignore_patterns(".git", "__pycache__", "*.pyc"))
102
+ shutil.copytree(os.path.join(home, "venv"), os.path.join(tmp, "venv"), symlinks=True,
103
+ ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))
104
+ got = hashlib.sha256((tree_sha256(os.path.join(tmp, "src")) + tree_sha256(os.path.join(tmp, "venv"))).encode()
105
+ ).hexdigest()
106
+ if got != tree:
107
+ shutil.rmtree(tmp, ignore_errors=True)
108
+ raise HarnessRefused(f"copy of the RPent runtime does not match its tree hash ({got[:12]} != {tree[:12]})")
109
+ for dp, dn, fn in os.walk(tmp):
110
+ os.chmod(dp, 0o755)
111
+ for f in fn:
112
+ p = os.path.join(dp, f)
113
+ if not os.path.islink(p):
114
+ os.chmod(p, os.stat(p).st_mode | 0o444)
115
+ with open(os.path.join(tmp, ".tree_sha256"), "w") as f:
116
+ f.write(tree)
117
+ if os.path.exists(dst):
118
+ shutil.rmtree(dst)
119
+ os.rename(tmp, dst)
120
+ return dst
121
+
122
+
123
+ def codex_overrides(effort, catalog_path):
124
+ """The main table's Codex configuration (lffbench/harnesses/codex.py Codex.config_args / --disable), as -c
125
+ overrides for RPent's planner; the provider and the MCP server URL are RPent's own (CODEX_BASE_URL, in-process)."""
126
+ return (["model_reasoning_effort=" + toml_str(effort),
127
+ "include_permissions_instructions=false", "include_environment_context=false",
128
+ "include_collaboration_mode_instructions=false", "skills.include_instructions=false",
129
+ "skills.bundled.enabled=false", 'web_search="disabled"',
130
+ f"mcp_servers.{MCP_SERVER}.enabled_tools=" + json.dumps(MCP_TOOLS),
131
+ f'mcp_servers.{MCP_SERVER}.default_tools_approval_mode="approve"',
132
+ f"mcp_servers.{MCP_SERVER}.required=true", f"mcp_servers.{MCP_SERVER}.startup_timeout_sec=60",
133
+ f"mcp_servers.{MCP_SERVER}.tool_timeout_sec=900",
134
+ "model_catalog_json=" + toml_str(catalog_path)]
135
+ + [f"features.{f}=false" for f in DISABLE])
136
+
137
+
138
+ def _items(stream_path):
139
+ """Codex app-server notifications of one RPent session (RPent writes them as JSONL)."""
140
+ out = []
141
+ if not os.path.exists(stream_path):
142
+ return out
143
+ for line in open(stream_path, encoding="utf-8", errors="replace"):
144
+ try:
145
+ out.append(json.loads(line))
146
+ except ValueError:
147
+ continue
148
+ return out
149
+
150
+
151
+ def _item_of(ev):
152
+ it = (ev.get("payload") or {}).get("item") or {}
153
+ return it.get("root", it) if isinstance(it, dict) else {}
154
+
155
+
156
+ class RPentCodex(HarnessAdapter):
157
+ name = "rpent_codex"
158
+ uses_mcp = False
159
+ uses_gateway = True
160
+ can_resume = False
161
+ clean_dirs = ("home", "codex_home", "tmp", "out")
162
+ clean_allowed = {"codex_home": (CATALOG_FILE,)}
163
+ ancestor_files = ("AGENTS.md", "AGENTS.override.md", ".codex")
164
+ capabilities = dict(
165
+ only_benchmark_tools=Cap("partial", "preflight", "Codex generic catalog (as the main table): our 3 tools as "
166
+ "mcp__lff functions + residual resource×3 / request_user_input; RPent registers "
167
+ "no tool of its own (no file tools, no finish)"),
168
+ images_reach_model=Cap("yes", "probe", "gateway content blocks passed through verbatim (ToolResult.content), "
169
+ "JPEG with its own MIME type"),
170
+ non_persistent_session=Cap("yes", "probe", "RPent's threads only in the one-time CODEX_HOME, removed after the "
171
+ "run; no RPent memory (no MemoryManager, no HF memory)"),
172
+ pinned_version=Cap("yes", "launch", "codex binary sha256 + RPent commit / patch / tree hash (src + venv) in "
173
+ "harness.json; pin per version and tree"),
174
+ machine_readable_events=Cap("yes", "stream", "Codex app-server notifications per RPent session "
175
+ "(codex.out.stream.jsonl) + RPent run.json"),
176
+ tool_calls_logged=Cap("yes", "stream", "mcpToolCall items + gateway_transcript (face rpent) + events.jsonl"),
177
+ model_and_effort=Cap("yes", "preflight", "model and effort in the request checked"),
178
+ persistent_memory=Cap("absent", "probe", "memories feature off; empty one-time CODEX_HOME; RPent memory not "
179
+ "constructed"),
180
+ instruction_file_injection=Cap("absent", "probe", "project_doc_max_bytes=0, empty CODEX_HOME, no skills"),
181
+ web_access=Cap("absent", "preflight", "web_search disabled (not in the tool list)"),
182
+ host_file_read=Cap("absent", "preflight", "no file tools; the only shell is the gateway's jailed shell"),
183
+ builtin_shell=Cap("absent", "preflight", "shell_tool and unified_exec disabled (not in the tool list)"),
184
+ subagent_delegation=Cap("absent", "preflight", "multi_agent disabled; no collaboration tools in the request"),
185
+ background_execution=Cap("absent", "preflight", "no background tool in the request"),
186
+ )
187
+
188
+ def __init__(self, api_env=None, base_url=None, timeout_s=10800, pins_dir=None, allow_unpinned=False,
189
+ jail=False, auth="apikey", catalog="generic", sessions=5, attempts_per_session=1, max_turns=100,
190
+ home=None, provider=None):
191
+ """api_env: {"OPENAI_API_KEY": ...}; base_url: Responses endpoint (default: the official API). sessions /
192
+ attempts_per_session / max_turns: RPent's --explore-sessions / --explore-attempts-per-session / --max-turns.
193
+ Defaults = the side table's setting (user 2026-10-21): variant H (one attempt per session, then a fresh session
194
+ with RPent's handoff), up to 5 sessions (k=3 + 2 spare), 100 model responses per session; within a session the
195
+ reference driver's continue rule (robots/lffbench/toolkit.py)."""
196
+ if auth != "apikey":
197
+ raise ValueError("rpent_codex supports auth=apikey only")
198
+ if catalog not in CATALOGS:
199
+ raise ValueError(f"catalog must be one of {CATALOGS}")
200
+ self.auth, self.catalog = auth, catalog
201
+ self.api_env = dict(api_env or {})
202
+ self.base_url = base_url or OFFICIAL_API
203
+ self.timeout_s, self.pins_dir, self.allow_unpinned = timeout_s, pins_dir, allow_unpinned
204
+ self.sessions, self.attempts_per_session, self.max_turns = int(sessions), int(attempts_per_session), \
205
+ int(max_turns)
206
+ self.home = home or rpent_home()
207
+ self.proxy = proxy_env()
208
+ self._version = None
209
+ self._runtime = None
210
+ self.runtime_dir = self.home
211
+ if jail:
212
+ from .jail import HarnessJail
213
+ self.jail = HarnessJail(codex_bin(), proc="static")
214
+
215
+ # ------------------------------------------------------------------------------------------------ identity
216
+ def runtime(self):
217
+ if self._runtime is None:
218
+ self._runtime = runtime_info(self.home)
219
+ if self.jail is not None:
220
+ self.runtime_dir = jail_runtime_copy(self.home, self._runtime["tree_sha256"])
221
+ return self._runtime
222
+
223
+ def version(self):
224
+ if self._version is None:
225
+ b = codex_bin()
226
+ out = subprocess.run([b, "--version"], env=dict(PATH=BASE_PATH, HOME="/nonexistent",
227
+ CODEX_HOME="/nonexistent"),
228
+ capture_output=True, text=True, timeout=60)
229
+ v = (out.stdout.strip().split() or ["?"])[-1]
230
+ rt = self.runtime()
231
+ self._version = dict(version=v, binary=binary_info(b),
232
+ rpent=dict(commit=rt["commit"], patch_sha256=rt["patch_sha256"],
233
+ tree_sha256=rt["tree_sha256"], untracked=rt["untracked"]))
234
+ return self._version
235
+
236
+ def pin_key(self, ep):
237
+ v = self.version()
238
+ name = f"{self.name}-{self.catalog}-{v['rpent']['tree_sha256'][:12]}"
239
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
240
+
241
+ def anchor_pin_key(self, ep):
242
+ """The main table's codex pin for the same model / effort (apikey, same catalog)."""
243
+ v = self.version()
244
+ name = "codex" + ("" if self.catalog == "native" else f"-{self.catalog}")
245
+ return pins.key(name, v["version"], v["binary"]["sha256"], ep.model, ep.effort)
246
+
247
+ def auth_info(self):
248
+ return dict(mode="apikey", credential_var="CODEX_API_KEY", credential_set=bool(self.api_env.get(
249
+ "OPENAI_API_KEY")), keys=["CODEX_API_KEY"])
250
+
251
+ def config_info(self):
252
+ return dict(catalog=self.catalog, sessions=self.sessions, attempts_per_session=self.attempts_per_session,
253
+ max_turns=self.max_turns, rpent=self.version()["rpent"])
254
+
255
+ # ------------------------------------------------------------------------------------------------ prepare
256
+ def _state_dirs(self, hexname=None):
257
+ root = os.path.join("/tmp/lffstate", hexname) if hexname else new_run_dir("/tmp/lffstate")
258
+ os.makedirs(root, exist_ok=True)
259
+ state = dict(state=root, **{k: os.path.join(root, k) for k in ("home", "codex_home", "tmp", "out")})
260
+ for k in ("home", "codex_home", "tmp", "out"):
261
+ os.makedirs(state[k], exist_ok=True)
262
+ return state
263
+
264
+ def _install_catalog(self, codex_home, ep):
265
+ cat, src = model_catalog(self.catalog, self.version()["version"], ep.model, None, ep.effort)
266
+ path = os.path.join(codex_home, CATALOG_FILE)
267
+ with open(path, "w") as f:
268
+ json.dump(cat, f)
269
+ return path, C.sha256_file(path), os.path.relpath(src, ROOT)
270
+
271
+ def argv(self, ep, out_dir, sessions=None, preflight=False):
272
+ py = os.path.join(self.runtime_dir, "venv", "bin", "python")
273
+ return [py, "-m", "robots.lffbench.run", "--model", ep.model, "--effort", ep.effort, "--out", out_dir,
274
+ "--sessions", str(sessions or self.sessions), "--attempts-per-session", str(self.attempts_per_session),
275
+ "--max-turns", str(self.max_turns), "--timeout-s", str(int(self.timeout_s) - 60)] \
276
+ + (["--no-continue"] if preflight else [])
277
+
278
+ def env(self, state, ep, base_url, work):
279
+ e = dict(PATH=BASE_PATH, HOME=state["home"], TMPDIR=state["tmp"], CODEX_HOME=state["codex_home"],
280
+ CODEX_BIN=(self.jail.binary_jailed if self.jail is not None else codex_bin()),
281
+ CODEX_BASE_URL=base_url, RPENT_CODEX_SANDBOX="read_only", RPENT_MCP_SERVER_NAME=MCP_SERVER,
282
+ RPENT_CODEX_CONFIG_OVERRIDES=json.dumps(codex_overrides(
283
+ ep.effort, os.path.join(state["codex_home"], CATALOG_FILE))),
284
+ RPENT_REPO_ROOT=work, PYTHONPATH=os.path.join(self.runtime_dir, "src"),
285
+ PYTHONDONTWRITEBYTECODE="1", PYTHONUNBUFFERED="1", LANG="C.UTF-8")
286
+ e.update(self.proxy)
287
+ if self.api_env.get("OPENAI_API_KEY"):
288
+ e["CODEX_API_KEY"] = self.api_env["OPENAI_API_KEY"]
289
+ return e
290
+
291
+ def prepare(self, ep, first_message, reuse_state=None):
292
+ self.version()
293
+ work = new_run_dir("/tmp/lffrun")
294
+ state = reuse_state or self._state_dirs(os.path.basename(work))
295
+ if self.jail is not None:
296
+ self.jail.stderr_dir = ep.log_dir
297
+ if not reuse_state and os.listdir(state["codex_home"]):
298
+ raise HarnessRefused("CODEX_HOME is not empty")
299
+ cat_path, cat_sha, cat_src = self._install_catalog(state["codex_home"], ep)
300
+ return LaunchSpec(argv=self.argv(ep, state["out"]), env=self.env(state, ep, self.base_url, work), cwd=work,
301
+ run_dir=work, state_dirs=state, first_message=first_message,
302
+ stdout_path=os.path.join(ep.log_dir, "rpent_stdout.txt"),
303
+ stderr_path=os.path.join(ep.log_dir, "rpent_stderr.txt"),
304
+ config_files=dict(model_catalog_json=dict(path=cat_path, sha256=cat_sha, source=cat_src,
305
+ catalog=self.catalog, code_mode=False)),
306
+ timeout_s=self.timeout_s)
307
+
308
+ def config_sha256(self, spec, ep):
309
+ argv = [a.replace(spec.state_dirs["out"], "<OUT>").replace(self.runtime_dir, "<RPENT>")
310
+ for a in spec.argv]
311
+ hidden = ("HOME", "TMPDIR", "CODEX_HOME", "CODEX_BIN", "CODEX_API_KEY", "RPENT_REPO_ROOT", "PYTHONPATH",
312
+ "LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") + PROXY_KEYS + NO_PROXY_KEYS
313
+ env = {k: v for k, v in spec.env.items() if k not in hidden}
314
+ env["RPENT_CODEX_CONFIG_OVERRIDES"] = env.get("RPENT_CODEX_CONFIG_OVERRIDES", "").replace(
315
+ spec.state_dirs["codex_home"], "<CODEX_HOME>")
316
+ cat = (spec.config_files.get("model_catalog_json") or {}).get("sha256")
317
+ return C.sha256_json(dict(argv=argv, env=env, model_catalog_sha256=cat,
318
+ rpent_tree_sha256=self.version()["rpent"]["tree_sha256"]))
319
+
320
+ # ------------------------------------------------------------------------------------------------ launch
321
+ def launch(self, spec, ep, skip_preflight=False):
322
+ """harness_run starts the gateway after prepare(), right before launch: hand its address to the process."""
323
+ spec.env.update(gateway_env(ep.log_dir))
324
+ return super().launch(spec, ep, skip_preflight=skip_preflight)
325
+
326
+ def preflight(self, spec, ep, record_dir=None):
327
+ """The same framework process, one session, against a local fake Responses server that answers with text
328
+ only: no tool call reaches the gateway. Checks the first request (tools, developer message, parameters,
329
+ sandbox, RPent's prefix + our first message) against the pins."""
330
+ t0 = time.time()
331
+ fake = FakeResponses([[("text", "preflight ok")]], record_dir=record_dir).start()
332
+ pre = self._state_dirs()
333
+ try:
334
+ self._install_catalog(pre["codex_home"], ep)
335
+ env = self.env(pre, ep, fake.base_url, spec.cwd)
336
+ env["CODEX_API_KEY"] = "sk-preflight-not-a-key"
337
+ env.update({k: spec.env[k] for k in ("LFF_GATEWAY_URL", "LFF_GATEWAY_TOKEN") if k in spec.env})
338
+ argv = self.argv(ep, pre["out"], sessions=1, preflight=True) # no status call on the episode
339
+ r = subprocess.run(self.jailed_argv(argv, env, spec.cwd, list(pre.values())), env=env, cwd=spec.cwd,
340
+ stdin=subprocess.DEVNULL, capture_output=True, timeout=300)
341
+ reqs = fake.model_requests()
342
+ if not reqs:
343
+ raise HarnessRefused(f"preflight: no model request (rc={r.returncode}): "
344
+ f"{(r.stdout + r.stderr).decode('utf-8', 'replace')[-1200:]}")
345
+ body = reqs[0][1]
346
+ fp, problems = request_fingerprint(body, spec.cwd, spec.first_message, EXPECTED_TOP_GENERIC)
347
+ problems = [p for p in problems if not p.startswith("user input is not exactly our first message")]
348
+ users = [c.get("text") for it in body.get("input") or [] if it.get("type") == "message"
349
+ and it.get("role") == "user" for c in it.get("content") or []]
350
+ prefix = None
351
+ if len(users) != 1 or not users[0].endswith(spec.first_message):
352
+ problems.append(f"the first user message does not end with our first message ({len(users)} blocks)")
353
+ else:
354
+ prefix = users[0][:-len(spec.first_message)]
355
+ effort = (fp["params"].get("reasoning") or {}).get("effort")
356
+ if effort != ep.effort:
357
+ problems.append(f"reasoning.effort in request {effort!r} != {ep.effort!r}")
358
+ if fp["params"].get("model") != ep.model:
359
+ problems.append(f"model in request {fp['params'].get('model')!r} != {ep.model!r}")
360
+ if os.listdir(spec.cwd):
361
+ problems.append(f"work dir not empty after preflight: {os.listdir(spec.cwd)}")
362
+ mid_sha = C.sha256_json(fp)
363
+ full = dict(middle=fp, rpent_prefix=prefix)
364
+ fp_sha = C.sha256_json(full)
365
+ anchor = pins.load(self.anchor_pin_key(ep), self.pins_dir)
366
+ out = dict(fingerprint_sha256=fp_sha, middle_fingerprint_sha256=mid_sha,
367
+ rpent_prefix_sha256=C.sha256_text(prefix) if prefix is not None else None,
368
+ rpent_prefix_chars=len(prefix) if prefix is not None else None,
369
+ developer_chars=fp["developer_chars"], n_requests=len(reqs),
370
+ top_tools=[t["name"] for t in fp["tools"]], catalog=self.catalog, effort_in_request=effort,
371
+ model_in_request=fp["params"].get("model"), sandbox=fp["sandbox"],
372
+ dt_s=round(time.time() - t0, 1), problems=problems,
373
+ anchor_pin=anchor and dict(key=anchor["key"], fingerprint_sha256=anchor["fingerprint_sha256"]))
374
+ if anchor is None:
375
+ out["anchor_status"] = "no main-table pin for this model / effort"
376
+ elif anchor["fingerprint_sha256"] != mid_sha:
377
+ problems.append(f"Codex request {mid_sha[:12]} != main-table pin {anchor['fingerprint_sha256'][:12]} "
378
+ f"({anchor['key']}): the middle layer is not the main table's")
379
+ else:
380
+ out["anchor_status"] = "match"
381
+ pin = pins.load(self.pin_key(ep), self.pins_dir)
382
+ out["pin"] = pin and dict(key=pin["key"], fingerprint_sha256=pin["fingerprint_sha256"])
383
+ out["fingerprint"] = full
384
+ if problems:
385
+ raise HarnessRefused("preflight: " + "; ".join(problems))
386
+ if pin is None:
387
+ if not self.allow_unpinned:
388
+ raise HarnessRefused(f"preflight: no pin for {self.pin_key(ep)} (run tests/harness_selfcheck "
389
+ f"with --write-pins after the self-check passes)")
390
+ out["pin_status"] = "unpinned (allowed)"
391
+ elif pin["fingerprint_sha256"] != fp_sha:
392
+ raise HarnessRefused(f"preflight: fingerprint {fp_sha[:12]} != pinned {pin['fingerprint_sha256'][:12]} "
393
+ f"({pin['key']})")
394
+ else:
395
+ out["pin_status"] = "match"
396
+ return out
397
+ finally:
398
+ fake.stop()
399
+ shutil.rmtree(pre["state"], ignore_errors=True)
400
+
401
+ # ------------------------------------------------------------------------------------------------ collect
402
+ def collect(self, h):
403
+ spec, ep = h.spec, h.ep
404
+ dst = os.path.join(ep.log_dir, "rpent")
405
+ if os.path.isdir(spec.state_dirs["out"]):
406
+ shutil.copytree(spec.state_dirs["out"], dst, dirs_exist_ok=True)
407
+ run = {}
408
+ if os.path.exists(os.path.join(dst, "run.json")):
409
+ run = json.load(open(os.path.join(dst, "run.json")))
410
+ tw = TrajWriter(os.path.join(ep.log_dir, "trajectory.jsonl"))
411
+ usage = dict(input=0, cached=0, output=0, reasoning=0)
412
+ items, threads, errors = [], [], []
413
+ for sdir in sorted(os.listdir(os.path.join(dst, "sessions"))) if os.path.isdir(os.path.join(dst, "sessions")) \
414
+ else []:
415
+ last = None
416
+ for ev in _items(os.path.join(dst, "sessions", sdir, "codex.out.stream.jsonl")):
417
+ m = ev.get("method") or ev.get("type")
418
+ p = ev.get("payload") or {}
419
+ if m == "thread/tokenUsage/updated":
420
+ last = (p.get("token_usage") or {}).get("total") or last
421
+ if p.get("thread_id") and p["thread_id"] not in threads:
422
+ threads.append(p["thread_id"])
423
+ elif m in ("error", "fatal", "timeout"):
424
+ errors.append(ev)
425
+ elif m == "item/completed":
426
+ it = _item_of(ev)
427
+ t = it.get("type")
428
+ items.append(t)
429
+ if t == "agentMessage":
430
+ tw.add_step("agent", message=it.get("text", ""))
431
+ elif t == "reasoning":
432
+ tw.add_step("agent", reasoning=json.dumps(it.get("summary") or it.get("content") or ""))
433
+ elif t in ("mcpToolCall", "dynamicToolCall", "commandExecution", "fileChange"):
434
+ name = it.get("tool") or t
435
+ tw.add_step("agent", tool_calls=[dict(tool_call_id=it.get("id"), function_name=name,
436
+ native_name=f"{it.get('server', '')}.{name}",
437
+ item_type=t, arguments=it.get("arguments"),
438
+ session=sdir)])
439
+ res = it.get("result") or {}
440
+ texts = [c.get("text", "") for c in res.get("content") or [] if c.get("type") == "text"]
441
+ imgs = sum(1 for c in res.get("content") or [] if c.get("type") == "image")
442
+ tw.add_result(it.get("id"), "\n".join(texts) if texts else json.dumps(it.get("error")),
443
+ bool(it.get("error")) or it.get("status") == "failed", imgs)
444
+ if last:
445
+ usage["input"] += last.get("input_tokens") or 0
446
+ usage["cached"] += last.get("cached_input_tokens") or 0
447
+ usage["output"] += last.get("output_tokens") or 0
448
+ usage["reasoning"] += last.get("reasoning_output_tokens") or 0
449
+ # Framework close-out uses the same counted gateway shell, outside
450
+ # the model stream. Keep it visible in trajectories and tool totals.
451
+ session_record = next((s for s in run.get("sessions", [])
452
+ if sdir == f"session_{s['number']:03d}"), {})
453
+ handoff = session_record.get("handoff") or {}
454
+ if handoff:
455
+ call_id = f"framework-handoff-{sdir}"
456
+ tw.add_step("framework", tool_calls=[dict(
457
+ tool_call_id=call_id, function_name="shell", native_name=f"{MCP_SERVER}.shell",
458
+ item_type="frameworkToolCall", arguments=handoff["arguments"], session=sdir)])
459
+ tw.add_result(call_id, "\n".join(c.get("text", "") for c in handoff["content"]
460
+ if c.get("type") == "text"))
461
+ v = self.version()
462
+ tw.set_header(session_id=",".join(threads), source="rpent/sessions/*/codex.out.stream.jsonl",
463
+ agent=dict(name=self.name, version=v["version"], model_name=ep.model, effort=ep.effort,
464
+ rpent=v["rpent"]), tools=EXPECTED_TOP_GENERIC)
465
+ tw.set_final(h.exit_reason, native_result=dict(errors=errors[-5:], item_types=sorted(set(items)),
466
+ run={k: run.get(k) for k in ("stop", "finished",
467
+ "attempts_failed", "tool_calls")},
468
+ sessions=len(run.get("sessions") or [])),
469
+ total_prompt_tokens=usage["input"], total_completion_tokens=usage["output"],
470
+ total_cached_tokens=usage["cached"], total_cost_usd=None, reasoning_tokens=usage["reasoning"])
471
+ tw.write()
472
+ h.info.update(items=items, traj=tw, threads=threads, errors=errors, run=run)
473
+ return tw
474
+
475
+ # ------------------------------------------------------------------------------------------------ audit
476
+ def audit(self, h):
477
+ spec, ep = h.spec, h.ep
478
+ v, notes = [], []
479
+ items = h.info.get("items") or []
480
+ bad = sorted({i for i in items if i not in ("userMessage", "agentMessage", "reasoning", "mcpToolCall",
481
+ "plan", "hookPrompt")})
482
+ if bad:
483
+ v.append(f"items other than messages / reasoning / MCP calls: {bad}")
484
+ residual = []
485
+ tw = h.info.get("traj")
486
+ for st in (tw.steps if tw else []):
487
+ for tc in st["tool_calls"]:
488
+ if tc["native_name"] == f"{MCP_SERVER}.{tc['function_name']}" and tc["function_name"] in MCP_TOOLS:
489
+ continue
490
+ if tc["function_name"] in ("list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource"):
491
+ residual.append(tc["function_name"])
492
+ else:
493
+ v.append(f"unexpected tool call {tc['native_name']}")
494
+ if residual:
495
+ notes.append(f"residual MCP-resource tool calls (empty): {residual}")
496
+ if h.env_observed_keys is not None and set(h.env_observed_keys) != set(spec.env):
497
+ v.append(f"process env keys {h.env_observed_keys} != whitelist {sorted(spec.env)}")
498
+ run = h.info.get("run") or {}
499
+ nsess = len(run.get("sessions") or [])
500
+ if len(h.info.get("threads") or []) > max(1, nsess):
501
+ v.append(f"{len(h.info['threads'])} Codex threads for {nsess} RPent sessions")
502
+ if nsess > 1:
503
+ notes.append(f"{nsess} RPent sessions (handoff after a session ended before the episode was over)")
504
+ if run.get("stop") not in (None, "episode over"):
505
+ notes.append(f"RPent stopped: {run.get('stop')}")
506
+ left = dict(codex_home=snapshot_tree(spec.state_dirs["codex_home"]), home=snapshot_tree(spec.state_dirs["home"]),
507
+ work=snapshot_tree(spec.cwd))
508
+ if left["work"]:
509
+ v.append(f"files in the work dir: {left['work']}")
510
+ foreign = [f for f in left["codex_home"] if f.startswith(("sessions/", "archived_sessions/"))
511
+ and not any(t in f for t in (h.info.get("threads") or []))]
512
+ if foreign:
513
+ v.append(f"session files other than this run's threads: {foreign}")
514
+ gt = os.path.join(ep.log_dir, "gateway_transcript.jsonl")
515
+ faces = set()
516
+ if os.path.exists(gt):
517
+ for line in open(gt):
518
+ try:
519
+ d = json.loads(line)
520
+ except ValueError:
521
+ continue
522
+ if d.get("ev") == "tool" and d.get("face"):
523
+ faces.add(d["face"])
524
+ if faces - {"rpent"}:
525
+ v.append(f"gateway calls from other access paths: {sorted(faces)}")
526
+ out = dict(harness=self.name, violations=v, notes=notes, files_left=left, gateway_faces=sorted(faces),
527
+ item_types=sorted(set(items)), errors=h.info.get("errors"), run_stop=run.get("stop"), ok=not v)
528
+ with open(os.path.join(ep.log_dir, "harness_audit.json"), "w") as f:
529
+ json.dump(out, f, indent=1)
530
+ return out
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/harnesses/trajectory.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unified trajectory (minimal, field names follow Harbor's ATIF where there is one).
2
+
3
+ <log_dir>/trajectory.jsonl, one JSON object per line:
4
+ line 1 {"kind": "header", "schema": "lff-traj-0", "atif_like": "ATIF v1.x field names", "session_id",
5
+ "agent": {"name", "version", "model_name", "effort"}, "tools": [...], "source": "<native log file>"}
6
+ steps {"kind": "step", "step_id", "timestamp", "source": "user"|"agent"|"system", "message",
7
+ "reasoning_content", "tool_calls": [{"tool_call_id", "function_name", "arguments"}],
8
+ "observation": {"results": [{"source_call_id", "content", "is_error", "images"}]},
9
+ "metrics": {"prompt_tokens", "completion_tokens", "cached_tokens", "cost_usd"}}
10
+ last {"kind": "final", "final_metrics": {"total_prompt_tokens", "total_completion_tokens",
11
+ "total_cached_tokens", "total_cost_usd", "total_steps"}, "exit_reason", "native_result"}
12
+ Not full ATIF: no per-step model name, no subagent trajectories, images only counted (bytes stay in the workspace).
13
+ Tool names are reported without the MCP prefix (robot / shell / view_images), so all harnesses line up.
14
+ """
15
+ import json
16
+ import os
17
+
18
+ SCHEMA = "lff-traj-0"
19
+
20
+
21
+ def strip_mcp(name):
22
+ for p in ("mcp__lff__", "lff."):
23
+ if name and name.startswith(p):
24
+ return name[len(p):]
25
+ return name
26
+
27
+
28
+ class TrajWriter:
29
+ def __init__(self, path):
30
+ self.path = path
31
+ self.steps = []
32
+ self.header = None
33
+ self.final = None
34
+
35
+ def set_header(self, **kw):
36
+ self.header = dict(kind="header", schema=SCHEMA, atif_like="field names follow Harbor ATIF", **kw)
37
+
38
+ def add_step(self, source, message="", reasoning="", tool_calls=None, timestamp=None, metrics=None, **extra):
39
+ st = dict(kind="step", step_id=len(self.steps) + 1, timestamp=timestamp, source=source, message=message or "",
40
+ reasoning_content=reasoning or "", tool_calls=tool_calls or [],
41
+ observation=dict(results=[]), metrics=metrics or {})
42
+ st.update(extra)
43
+ self.steps.append(st)
44
+ return st
45
+
46
+ def add_result(self, call_id, content, is_error=False, images=0):
47
+ for st in reversed(self.steps):
48
+ if any(tc["tool_call_id"] == call_id for tc in st["tool_calls"]):
49
+ st["observation"]["results"].append(dict(source_call_id=call_id, content=content, is_error=is_error,
50
+ images=images))
51
+ return True
52
+ return False
53
+
54
+ def set_final(self, exit_reason, native_result=None, **metrics):
55
+ fm = dict(total_prompt_tokens=0, total_completion_tokens=0, total_cached_tokens=0, total_cost_usd=None,
56
+ total_steps=len(self.steps))
57
+ fm.update({k: v for k, v in metrics.items() if v is not None})
58
+ self.final = dict(kind="final", final_metrics=fm, exit_reason=exit_reason, native_result=native_result)
59
+
60
+ def write(self):
61
+ with open(self.path, "w") as f:
62
+ for d in [self.header] + self.steps + [self.final]:
63
+ if d is not None:
64
+ f.write(json.dumps(d, ensure_ascii=False) + "\n")
65
+ return self.path
66
+
67
+ def tool_call_names(self):
68
+ return [tc["function_name"] for st in self.steps for tc in st["tool_calls"]]
69
+
70
+
71
+ def read(path):
72
+ with open(path) as f:
73
+ return [json.loads(line) for line in f if line.strip()]
74
+
75
+
76
+ def usage_summary(log_dir):
77
+ """Token / cost totals from trajectory.jsonl (None if missing)."""
78
+ p = os.path.join(log_dir or "", "trajectory.jsonl")
79
+ if not os.path.exists(p):
80
+ return None
81
+ rows = read(p)
82
+ fin = next((r for r in rows if r.get("kind") == "final"), None)
83
+ steps = [r for r in rows if r.get("kind") == "step" and r.get("source") == "agent"]
84
+ out = dict(calls=len(steps), exit_reason=(fin or {}).get("exit_reason"))
85
+ out.update((fin or {}).get("final_metrics") or {})
86
+ return out
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/skills.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Motion primitives executed with robosuite's OSC_POSE controller.
2
+
3
+ All positions are world-frame metres (LIBERO table top is z = TABLE_Z = 0.90).
4
+ `bias` is a hidden calibration error added to every commanded position (used by L1 tasks);
5
+ agents never see it.
6
+ """
7
+ import numpy as np
8
+ import robosuite.utils.transform_utils as T
9
+
10
+ from .envs import TABLE_Z
11
+
12
+ DT = 0.05 # control period (20 Hz)
13
+ ROT_SCALE = 0.5
14
+ # Faster OSC than LIBERO's default (default caps the end effector at ~0.25 m/s; this reaches ~0.6 m/s).
15
+ CONTROLLER = dict(kp=300, output_max=[0.1, 0.1, 0.1, 0.5, 0.5, 0.5], output_min=[-0.1, -0.1, -0.1, -0.5, -0.5, -0.5])
16
+
17
+
18
+ def _rotz(a):
19
+ c, s = np.cos(a), np.sin(a)
20
+ return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
21
+
22
+
23
+ def _rot_err(R_target, R_cur):
24
+ """axis-angle (world frame) rotating R_cur to R_target"""
25
+ R = R_target @ R_cur.T
26
+ q = T.mat2quat(R) # xyzw
27
+ return T.quat2axisangle(q)
28
+
29
+
30
+ class Skills:
31
+ def __init__(self, env, bias=None, recorder=None):
32
+ self.env = env
33
+ self.pos_scale = float(env.robots[0].controller.output_max[0])
34
+ self.bias = np.zeros(3) if bias is None else np.asarray(bias, float)
35
+ self.grip = -1.0 # -1 open, +1 closed
36
+ self.R0 = self.eef_mat().copy() # top-down orientation at reset == yaw 0
37
+ self.yaw = 0.0
38
+ self.recorder = recorder # callable(env) invoked every `record_every` control steps
39
+ self.record_every = 4
40
+ self.n_steps = 0
41
+ self.log = []
42
+
43
+ # ------------------------------------------------------------------ state
44
+ def eef_pos(self):
45
+ return self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id].copy()
46
+
47
+ def eef_mat(self):
48
+ return self.env.sim.data.site_xmat[self.env.robots[0].eef_site_id].reshape(3, 3).copy()
49
+
50
+ def gripper_width(self):
51
+ g = self.env.robots[0].gripper
52
+ q = [self.env.sim.data.qpos[self.env.sim.model.joint_name2id(j)] for j in g.joints]
53
+ return float(abs(q[0] - q[1]))
54
+
55
+ def holding(self, obj_name):
56
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper,
57
+ object_geoms=self.env.objects_dict[obj_name]))
58
+
59
+ # ------------------------------------------------------------------ low level
60
+ def _act(self, dpos, drot, grip):
61
+ a = np.zeros(7)
62
+ a[:3] = np.clip(dpos / self.pos_scale, -1, 1)
63
+ a[3:6] = np.clip(drot / ROT_SCALE, -1, 1)
64
+ a[6] = grip
65
+ self.env.step(a)
66
+ self.n_steps += 1
67
+ if self.recorder is not None and self.n_steps % self.record_every == 0:
68
+ self.recorder(self.env)
69
+
70
+ def hold(self, steps=10):
71
+ p, R = self.eef_pos(), self._R()
72
+ for _ in range(steps):
73
+ self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
74
+
75
+ def _R(self, yaw=None):
76
+ return _rotz(self.yaw if yaw is None else yaw) @ self.R0
77
+
78
+ # ------------------------------------------------------------------ primitives
79
+ YAW_LIMIT = np.pi / 2 + 0.4
80
+
81
+ def wrap_yaw(self, yaw):
82
+ """A parallel-jaw gripper is symmetric under a rotation by pi, so pick the equivalent yaw closest
83
+ to the current one inside |yaw| <= pi/2 + 0.4. Without this, asking for ~180 deg of wrist rotation
84
+ makes the OSC (whose axis-angle error is ambiguous at pi) wind the arm into its joint limits and
85
+ it never recovers (found by the L3 developer: push towards -y -> 0/6 success, 2026-10-06)."""
86
+ cands = [yaw + k * np.pi for k in range(-3, 4)]
87
+ ok = [c for c in cands if abs(c) <= self.YAW_LIMIT] or cands
88
+ return float(min(ok, key=lambda c: abs(c - self.yaw)))
89
+
90
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
91
+ """Move the gripper site to `target` (world xyz). If `speed` (m/s) is given the reference
92
+ moves along a straight line at that speed; otherwise go as fast as the controller allows.
93
+ `yaw` is wrapped to the closest gripper-symmetric equivalent unless wrap_yaw=False.
94
+ Returns a report dict."""
95
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
96
+ if yaw is not None:
97
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
98
+ R = self._R()
99
+ p0 = self.eef_pos()
100
+ dist = np.linalg.norm(tgt - p0)
101
+ direction = (tgt - p0) / max(dist, 1e-9)
102
+ s = 0.0
103
+ for k in range(max_steps):
104
+ if speed is not None:
105
+ s = min(dist, s + speed * DT)
106
+ ref = p0 + direction * s
107
+ # lead the reference a little so the OSC lag does not throttle the speed
108
+ ref = ref + direction * min(dist - s, speed * DT * 1.5)
109
+ else:
110
+ ref = tgt
111
+ cur = self.eef_pos()
112
+ self._act(ref - cur, _rot_err(R, self.eef_mat()), self.grip)
113
+ err = np.linalg.norm(tgt - self.eef_pos())
114
+ if err < tol and (speed is None or s >= dist):
115
+ break
116
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
117
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1)
118
+ self.log.append(rep)
119
+ return rep
120
+
121
+ def set_gripper(self, close, steps=15):
122
+ self.grip = 1.0 if close else -1.0
123
+ self.hold(steps)
124
+ rep = dict(prim="close" if close else "open", width=round(self.gripper_width(), 4))
125
+ self.log.append(rep)
126
+ return rep
127
+
128
+ def grasp_at(self, xy, z_grasp, yaw=0.0, approach=0.10, lift=0.15):
129
+ """Composite: above -> descend -> close -> lift. For scripted policies."""
130
+ self.set_gripper(False, steps=5)
131
+ self.move_to([xy[0], xy[1], z_grasp + approach], yaw=yaw)
132
+ self.move_to([xy[0], xy[1], z_grasp], tol=0.003)
133
+ self.set_gripper(True, steps=15)
134
+ self.move_to([xy[0], xy[1], z_grasp + lift], speed=0.25)
135
+
136
+ def place_at(self, xy, z_release, approach=0.10):
137
+ self.move_to([xy[0], xy[1], z_release + approach])
138
+ self.move_to([xy[0], xy[1], z_release], tol=0.004)
139
+ self.set_gripper(False, steps=12)
140
+ self.move_to([xy[0], xy[1], z_release + approach])
141
+
142
+ def push(self, start_xy, direction_xy, distance, speed, z=None, pre=0.06):
143
+ """Straight-line push: go to `pre` m behind the start point at height z with the gripper closed,
144
+ then sweep `pre + distance` along direction at `speed`, stop, and lift away."""
145
+ d = np.asarray(direction_xy, float)
146
+ d = d / np.linalg.norm(d)
147
+ z = TABLE_Z + 0.02 if z is None else z
148
+ s = np.asarray(start_xy, float) - d * pre
149
+ self.set_gripper(True, steps=5)
150
+ self.move_to([s[0], s[1], z + 0.12], yaw=np.arctan2(d[1], d[0]) - np.pi / 2)
151
+ self.move_to([s[0], s[1], z], tol=0.003)
152
+ e = s + d * (pre + distance)
153
+ rep = self.move_to([e[0], e[1], z], speed=speed, tol=0.01, max_steps=400)
154
+ self.hold(2)
155
+ self.move_to([e[0], e[1], z + 0.12], speed=0.3)
156
+ return rep
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/task_base.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task interface shared by all LFF-Bench tasks.
2
+
3
+ A task = a LIBERO scene + an instance sampler (layout and hidden variables) + a success / outcome
4
+ measurement + scripted reference policies used to validate that the task really requires learning
5
+ from failure:
6
+
7
+ oracle knows the hidden variables; should succeed on attempt 1
8
+ naive acts on the prior (what an agent would do without the failure information)
9
+ adaptive scripted learner that updates its parameters from structured (F2) feedback
10
+ blind repeats the naive behaviour with small random variation, no history
11
+
12
+ Tasks whose policies can be expressed as "execute(params)" get the cross-attempt protocol for free.
13
+ Tasks that need within-episode recovery override `run_scripted`.
14
+ """
15
+ import numpy as np
16
+
17
+ from . import envs
18
+ from .skills import Skills
19
+
20
+ TASKS = {}
21
+
22
+
23
+ def register_task(cls):
24
+ TASKS[cls.name] = cls
25
+ return cls
26
+
27
+
28
+ class LFFTask:
29
+ name = "base"
30
+ level = "L?"
31
+ # the user's 7 categories (2026-10-06): hidden information -> required capability -> adapted action
32
+ category = "" # system_identification | dynamics_adaptation | failed_interaction_inference |
33
+ # state_restoration | procedural_memory | strategy_switching | geometry_inference
34
+ capabilities = ()
35
+ max_attempts = 5
36
+ protocol = "cross" # "cross": reset between attempts; "within": one episode, recover in place
37
+ instruction = "" # direct reference
38
+ instruction_indirect = "" # descriptive reference (perception / semantic reasoning variant)
39
+ cam_res = 256
40
+
41
+ def __init__(self, cam_res=None):
42
+ if cam_res:
43
+ self.cam_res = cam_res
44
+ self.bddl_path = self.make_bddl()
45
+ self.env = envs.make_env(self.bddl_path, cam_res=self.cam_res)
46
+ self.env.reset()
47
+ self.sk = None
48
+
49
+ # ------------------------------------------------------------ to implement
50
+ def make_bddl(self):
51
+ raise NotImplementedError
52
+
53
+ def sample_instance(self, seed):
54
+ """Return a JSON-serialisable dict with layout + hidden variables."""
55
+ raise NotImplementedError
56
+
57
+ def apply_instance(self, inst):
58
+ """Place objects / set hidden physics after env.reset()."""
59
+ raise NotImplementedError
60
+
61
+ def outcome(self, inst):
62
+ """dict with at least {'success': bool}; may contain structured measurements."""
63
+ raise NotImplementedError
64
+
65
+ def feedback(self, inst, out, level="F2"):
66
+ """Text the agent receives after an attempt. F0: nothing, F1: success flag, F2: measurement."""
67
+ if level == "F0":
68
+ return ""
69
+ s = "Attempt succeeded." if out["success"] else "Attempt failed."
70
+ if level == "F1":
71
+ return s
72
+ return s + (" " + out["detail"] if out.get("detail") else "")
73
+
74
+ def skill_bias(self, inst):
75
+ return None
76
+
77
+ # scripted references (cross protocol) ----------------------------------
78
+ def default_params(self, inst):
79
+ raise NotImplementedError
80
+
81
+ def oracle_params(self, inst):
82
+ raise NotImplementedError
83
+
84
+ def adapt_params(self, inst, history):
85
+ raise NotImplementedError
86
+
87
+ def blind_params(self, inst, attempt, rng):
88
+ return self.default_params(inst)
89
+
90
+ def execute(self, inst, params):
91
+ raise NotImplementedError
92
+
93
+ # ------------------------------------------------------------ shared
94
+ def reset_instance(self, inst, recorder=None):
95
+ self.env.reset()
96
+ self.apply_instance(inst)
97
+ self.env.sim.forward()
98
+ envs.settle(self.env, 10)
99
+ self.sk = Skills(self.env, bias=self.skill_bias(inst), recorder=recorder)
100
+ return self.sk
101
+
102
+ def snapshot(self, cam="agentview", res=None):
103
+ return envs.render(self.env, cam, res or self.cam_res)
104
+
105
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
106
+ """Cross-attempt protocol with a scripted policy. Returns the per-attempt history."""
107
+ k = k or self.max_attempts
108
+ rng = np.random.default_rng(seed)
109
+ history = []
110
+ for a in range(k):
111
+ self.reset_instance(inst)
112
+ if kind == "oracle":
113
+ params = self.oracle_params(inst)
114
+ elif kind == "naive":
115
+ params = self.default_params(inst)
116
+ elif kind == "adaptive":
117
+ params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
118
+ elif kind == "blind":
119
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
120
+ else:
121
+ raise ValueError(kind)
122
+ self.execute(inst, params)
123
+ out = self.outcome(inst)
124
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
125
+ if on_attempt:
126
+ on_attempt(a, params, out)
127
+ if out["success"] or kind in ("oracle", "naive"):
128
+ break
129
+ return history
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l2_knock.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray.
2
+
3
+ Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of
4
+ its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which
5
+ neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance
6
+ variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after
7
+ the main task fails; it has to notice the side effect and put the item back (within-episode recovery).
8
+
9
+ Protocols
10
+ within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one
11
+ corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round.
12
+ cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again
13
+ on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item
14
+ right after the main task. The rule also allows prevention (the knock only hits a neighbour that is
15
+ still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked
16
+ by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card).
17
+ """
18
+ import numpy as np
19
+
20
+ from .. import envs
21
+ from ..bddl import write_bddl
22
+ from ..skills import Skills
23
+ from ..task_base import LFFTask, register_task
24
+
25
+ TARGET = "ketchup_1"
26
+ NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
27
+ TRAY, BASKET = "wooden_tray_1", "basket_1"
28
+ PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)}
29
+
30
+ # wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x)
31
+ TRAY_IN_X = (-0.128, 0.143)
32
+ TRAY_IN_Y = (-0.081, 0.072)
33
+ TRAY_OUT_X = (-0.142, 0.156)
34
+ TRAY_OUT_Y = (-0.088, 0.080)
35
+ TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor
36
+ TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point
37
+ BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin)
38
+ BASKET_RIM = 0.150 # rim height above the basket's lowest point
39
+ BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
40
+
41
+ NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
42
+ "chocolate_pudding_1": "chocolate pudding"}
43
+ DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
44
+ "chocolate_pudding_1": "brown box"}
45
+ SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y
46
+
47
+
48
+ def _qz(a):
49
+ return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
50
+
51
+
52
+ def _wrap_half(a):
53
+ """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
54
+ return (a + np.pi / 2) % np.pi - np.pi / 2
55
+
56
+
57
+ class KnockSkills(Skills):
58
+ """Skills with a hook called after every control step (used for the failure injection)."""
59
+
60
+ def __init__(self, env, bias=None, recorder=None, hook=None):
61
+ super().__init__(env, bias=bias, recorder=recorder)
62
+ self.hook = hook
63
+
64
+ def _act(self, dpos, drot, grip):
65
+ super()._act(dpos, drot, grip)
66
+ if self.hook is not None:
67
+ self.hook()
68
+
69
+
70
+ @register_task
71
+ class KnockRestore(LFFTask):
72
+ name = "l2_knock_restore"
73
+ level = "L2"
74
+ category = "state_restoration"
75
+ capabilities = ("Perceive", "Plan")
76
+ protocol = "within"
77
+ instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray."
78
+ instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. "
79
+ "Everything else must stay on the tray.")
80
+ knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
81
+ knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked
82
+
83
+ def __init__(self, cam_res=None):
84
+ super().__init__(cam_res)
85
+ # upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention:
86
+ # the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame
87
+ # (identity => tray long axis along world x, as the TRAY_* constants assume).
88
+ self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
89
+ self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
90
+ self._inj = None
91
+ self.start = {}
92
+
93
+ # ------------------------------------------------------------ scene
94
+ def make_bddl(self):
95
+ names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET]
96
+ objs = []
97
+ for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
98
+ x0 = -0.30 + 0.13 * (i % 3)
99
+ y0 = -0.25 + 0.25 * (i // 3)
100
+ objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
101
+ return write_bddl(self.name, self.instruction, objs)
102
+
103
+ def sample_instance(self, seed):
104
+ rng = np.random.default_rng(seed)
105
+ nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side]
106
+ victim = int(rng.integers(2))
107
+ side = str(rng.choice(SIDES))
108
+ return dict(seed=int(seed),
109
+ tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))],
110
+ tray_yaw=float(rng.uniform(-0.10, 0.10)),
111
+ basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))],
112
+ target_dx=float(rng.uniform(-0.01, 0.01)),
113
+ target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)),
114
+ neighbors=nb,
115
+ nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)],
116
+ nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)],
117
+ nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)],
118
+ # hidden variables of the injected failure
119
+ victim=nb[victim], side=side,
120
+ land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object
121
+ land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot
122
+ land_dyaw=float(rng.uniform(-0.35, 0.35)))
123
+
124
+ def _tray_frame(self):
125
+ p = envs.obj_pos(self.env, TRAY)
126
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3)
127
+ return p, R
128
+
129
+ def tray_yaw(self):
130
+ _, R = self._tray_frame()
131
+ return float(np.arctan2(R[1, 0], R[0, 0]))
132
+
133
+ def tray_to_world(self, lx, ly):
134
+ p, R = self._tray_frame()
135
+ return p[:2] + R[:2, :2] @ np.array([lx, ly])
136
+
137
+ def world_to_tray(self, xy):
138
+ p, R = self._tray_frame()
139
+ return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2])
140
+
141
+ def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
142
+ """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z."""
143
+ q = envs._quat_mul(_qz(yaw), self.q_up[name])
144
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
145
+ self.env.sim.forward()
146
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
147
+ qa, _ = envs.free_joint_addr(self.env, name)
148
+ self.env.sim.data.qpos[qa + 2] -= dz
149
+ self.env.sim.forward()
150
+
151
+ def apply_instance(self, inst):
152
+ env = self.env
153
+ envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper
154
+ envs.scale_mass(env, BASKET, 2.0)
155
+ for n in NEIGHBOR_POOL:
156
+ if n not in inst["neighbors"]:
157
+ self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view
158
+ self.place(TRAY, inst["tray_xy"], inst["tray_yaw"])
159
+ self.place(BASKET, inst["basket_xy"], 0.0)
160
+ floor = envs.TABLE_Z + TRAY_FLOOR
161
+ ty = inst["tray_yaw"]
162
+ cx = TRAY_CX + inst["target_dx"]
163
+ self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor)
164
+ for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side]
165
+ lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i]
166
+ self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor)
167
+ env.sim.forward()
168
+
169
+ def reset_instance(self, inst, recorder=None):
170
+ self.env.reset()
171
+ self.apply_instance(inst)
172
+ self.env.sim.forward()
173
+ envs.settle(self.env, 10)
174
+ self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]}
175
+ self._inj = dict(inst=inst, done=False, knocked=False, step=None)
176
+ self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook)
177
+ return self.sk
178
+
179
+ # ------------------------------------------------------------ measurements
180
+ def footprint(self, name):
181
+ """Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range.
182
+ Scripted policies use it as a stand-in for perception."""
183
+ m, d = self.env.sim.model, self.env.sim.data
184
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
185
+ best = None
186
+ for g in envs.obj_geom_ids(self.env, name):
187
+ R = d.geom_xmat[g].reshape(3, 3)
188
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
189
+ e = np.abs(R) @ m.geom_aabb[g, 3:]
190
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
191
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
192
+ if best is None or vol > best[0]:
193
+ best = (vol, R, m.geom_aabb[g, 3:])
194
+ _, R, half = best
195
+ horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
196
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
197
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
198
+ half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
199
+
200
+ def _corners_tray(self, name):
201
+ """All collision-box corners of `name` in tray coordinates."""
202
+ m, d = self.env.sim.model, self.env.sim.data
203
+ pts = []
204
+ for g in envs.obj_geom_ids(self.env, name):
205
+ Rg = d.geom_xmat[g].reshape(3, 3)
206
+ c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
207
+ h = m.geom_aabb[g, 3:]
208
+ for sx in (-1, 1):
209
+ for sy in (-1, 1):
210
+ for sz in (-1, 1):
211
+ pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz]))))
212
+ return np.array(pts)
213
+
214
+ # ------------------------------------------------------------ failure injection
215
+ def _knock_hook(self):
216
+ st = self._inj
217
+ if st is None or st["done"] or self.sk is None:
218
+ return
219
+ if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
220
+ return
221
+ if not self.sk.holding(TARGET):
222
+ return
223
+ st["done"] = True
224
+ inst = st["inst"]
225
+ vxy = np.array(self.footprint(inst["victim"])["center"][:2])
226
+ if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius:
227
+ return # the victim was moved out of the way beforehand: nothing happens
228
+ self.knock(inst)
229
+ st["knocked"] = True
230
+ st["step"] = self.sk.n_steps
231
+
232
+ def knock(self, inst):
233
+ """Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis
234
+ roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point
235
+ `land_gap` from the wall's outer face, `land_off` along the wall from where it stood.
236
+ (The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)"""
237
+ v, side = inst["victim"], inst["side"]
238
+ loc = self.world_to_tray(self.footprint(v)["center"])
239
+ axis, sgn = 1, (1 if side == "right" else -1)
240
+ wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0]
241
+ self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08),
242
+ self.tray_yaw() + np.pi / 2 + inst["land_dyaw"])
243
+ pts = self._corners_tray(v)
244
+ near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max()
245
+ shift = (wall + sgn * inst["land_gap"]) - near
246
+ _, R = self._tray_frame()
247
+ qa, _ = envs.free_joint_addr(self.env, v)
248
+ self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift
249
+ self.env.sim.forward()
250
+
251
+ # ------------------------------------------------------------ outcome
252
+ def where(self, name):
253
+ """Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'."""
254
+ f = self.footprint(name)
255
+ c = np.array(f["center"])
256
+ lt = self.world_to_tray(c)
257
+ if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02:
258
+ return "gripper", f
259
+ if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005
260
+ and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002):
261
+ return "tray", f
262
+ bp = envs.obj_pos(self.env, BASKET)
263
+ 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:
264
+ return "basket", f
265
+ if f["zmin"] < envs.TABLE_Z + 0.01:
266
+ return "table", f
267
+ return "other", f
268
+
269
+ def rel_to_tray(self, c):
270
+ """Where a point on the table is relative to the tray, in robot-centric words (never image left/right).
271
+ Distances are from the tray's outer edge to the object's centre."""
272
+ lt = self.world_to_tray(c)
273
+ dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0)
274
+ dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0)
275
+ # robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left,
276
+ # +x = forward (away from the robot)
277
+ parts = []
278
+ if dy:
279
+ parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray")
280
+ if dx:
281
+ parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} "
282
+ f"of the tray")
283
+ return " and ".join(parts) if parts else "right next to the tray"
284
+
285
+ def _describe(self, inst, loc, names):
286
+ t_loc = loc[TARGET][0]
287
+ tn = names[TARGET]
288
+ msgs = []
289
+ if t_loc != "basket":
290
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
291
+ "tray": f"The {tn} is still on the tray, not in the basket.",
292
+ "table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), "
293
+ "not in the basket."}.get(t_loc, f"The {tn} is not in the basket."))
294
+ for n in inst["neighbors"]:
295
+ l, f = loc[n]
296
+ if l == "tray":
297
+ continue
298
+ msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table "
299
+ f"{self.rel_to_tray(f['center'])}.",
300
+ "basket": f"The {names[n]} is no longer on the tray: it is in the basket.",
301
+ "gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."}
302
+ .get(l, f"The {names[n]} is no longer on the tray."))
303
+ if not msgs:
304
+ msgs.append(f"The {tn} is in the basket and everything else is on the tray.")
305
+ return " ".join(msgs)
306
+
307
+ def outcome(self, inst):
308
+ envs.settle(self.env, 30)
309
+ loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]}
310
+ off = [n for n in inst["neighbors"] if loc[n][0] != "tray"]
311
+ success = bool(loc[TARGET][0] == "basket" and not off)
312
+ return dict(success=success,
313
+ target_loc=loc[TARGET][0],
314
+ locations={n: l for n, (l, _) in loc.items()},
315
+ off_tray=off,
316
+ footprints={n: f for n, (_, f) in loc.items()},
317
+ knocked=bool(self._inj and self._inj["knocked"]),
318
+ detail=self._describe(inst, loc, NAMES),
319
+ detail_indirect=self._describe(inst, loc, DESCR))
320
+
321
+ def feedback(self, inst, out, level="F2", indirect=False):
322
+ """F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names."""
323
+ if indirect and level == "F2":
324
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
325
+ return super().feedback(inst, out, level)
326
+
327
+ # ------------------------------------------------------------ scripted motions
328
+ def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None,
329
+ travel_z=1.15):
330
+ """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
331
+ object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the
332
+ basket rim) so the arm does not sweep through the scene."""
333
+ sk = self.sk
334
+ f = fp or self.footprint(name)
335
+ c = np.array(f["center"])
336
+ h = f["zmax"] - f["zmin"]
337
+ gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
338
+ if name == TARGET:
339
+ zg = f["zmax"] - 0.035
340
+ else:
341
+ zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site
342
+ sk.set_gripper(False, steps=6)
343
+ p = sk.eef_pos()
344
+ if p[2] < travel_z - 0.02:
345
+ sk.move_to([p[0], p[1], travel_z])
346
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
347
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
348
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
349
+ sk.set_gripper(True, steps=12)
350
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
351
+ gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
352
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
353
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25,
354
+ max_steps=120)
355
+ sk.set_gripper(False, steps=10)
356
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
357
+
358
+ def main_task(self, fp=None):
359
+ """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
360
+ b = envs.obj_pos(self.env, BASKET)
361
+ floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
362
+ self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
363
+
364
+ def restore_spot(self, name, inst):
365
+ """A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever
366
+ is further from everything else currently on the tray."""
367
+ others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"]
368
+ best, best_d = None, -1.0
369
+ for cand in (TARGET, name):
370
+ xy = np.array(self.start[cand]["center"][:2])
371
+ dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0])
372
+ if dmin > best_d + 0.01:
373
+ best, best_d = xy, dmin
374
+ return best
375
+
376
+ def restore(self, name, inst):
377
+ """Put `name` back onto the tray (long axis across the tray, fingers closing along the tray)."""
378
+ xy = self.restore_spot(name, inst)
379
+ self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08,
380
+ clearance=0.013)
381
+
382
+ def do(self, actions, inst):
383
+ for act in actions:
384
+ if act[0] == "ketchup_to_basket":
385
+ self.main_task(fp=act[1] if len(act) > 1 else None)
386
+ elif act[0] == "restore":
387
+ self.restore(act[1], inst)
388
+ else:
389
+ raise ValueError(act)
390
+
391
+ # ------------------------------------------------------------ scripted reference policies
392
+ def _plan(self, kind, inst, a, history, rng):
393
+ """Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name]."""
394
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")):
395
+ return [["ketchup_to_basket"]]
396
+ if kind == "oracle": # knows the victim: restores it right after the main task, without feedback
397
+ return [["ketchup_to_basket"], ["restore", inst["victim"]]]
398
+ if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is
399
+ last = history[-1]["outcome"]
400
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
401
+ return acts + [["restore", n] for n in last["off_tray"]]
402
+ if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
403
+ fp = self.footprint(TARGET)
404
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
405
+ return [["ketchup_to_basket", fp]]
406
+ raise ValueError(kind)
407
+
408
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
409
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.
410
+ After every attempt the outcome (success + F2 detail) is measured; stops at success
411
+ (oracle / naive stop after attempt 1)."""
412
+ k = k or self.max_attempts
413
+ rng = np.random.default_rng(seed)
414
+ history = []
415
+ self.reset_instance(inst)
416
+ for a in range(k):
417
+ actions = self._plan(kind, inst, a, history, rng)
418
+ self.do(actions, inst)
419
+ out = self.outcome(inst)
420
+ params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
421
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
422
+ if on_attempt:
423
+ on_attempt(a, params, out)
424
+ if out["success"] or kind in ("oracle", "naive"):
425
+ break
426
+ return history
427
+
428
+
429
+ @register_task
430
+ class KnockRestoreCross(KnockRestore):
431
+ """Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each
432
+ time. Learned behaviour: anticipate it (restore the reported item right after the main task)."""
433
+ name = "l2_knock_restore_cross"
434
+ protocol = "cross"
435
+
436
+ def _plan(self, kind, inst, a, history, rng):
437
+ if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking
438
+ fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]})
439
+ return [["ketchup_to_basket"]] + [["restore", n] for n in fallen]
440
+ return super()._plan(kind, inst, a, history, rng)
441
+
442
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
443
+ k = k or self.max_attempts
444
+ rng = np.random.default_rng(seed)
445
+ history = []
446
+ for a in range(k):
447
+ self.reset_instance(inst)
448
+ actions = self._plan(kind, inst, a, history, rng)
449
+ self.do(actions, inst)
450
+ out = self.outcome(inst)
451
+ params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
452
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
453
+ if on_attempt:
454
+ on_attempt(a, params, out)
455
+ if out["success"] or kind in ("oracle", "naive"):
456
+ break
457
+ return history
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l2_restore_layout.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was.
2
+
3
+ Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare
4
+ table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the
5
+ robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the
6
+ first frame.
7
+
8
+ Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the
9
+ neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the
10
+ ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is
11
+ real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still
12
+ succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim
13
+ back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in
14
+ its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was).
15
+
16
+ Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
17
+ round chosen by the policy; the outcome (success + F2 text) is computed after each round.
18
+
19
+ Scripted references
20
+ oracle knows the victim: right after the main task it puts the victim back at its saved start pose.
21
+ naive main task, then done.
22
+ adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are
23
+ out of place (Retrieve their saved poses) and puts them back (Utilize).
24
+ blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the
25
+ basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind.
26
+ nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows
27
+ which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw).
28
+ """
29
+ import numpy as np
30
+
31
+ from .. import envs
32
+ from ..bddl import write_bddl
33
+ from ..task_base import LFFTask, register_task
34
+
35
+ TARGET = "ketchup_1"
36
+ BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
37
+ BASKET = "basket_1"
38
+ ITEMS = (TARGET,) + BOXES
39
+
40
+ # LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer
41
+ BASKET_IN = 0.060 # half size of the inner floor
42
+ BASKET_RIM = 0.150 # rim height above the basket's lowest point
43
+ BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
44
+ BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout)
45
+
46
+ POS_TOL = 0.03 # success: box centre within 3 cm of its start
47
+ YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180)
48
+ STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start
49
+
50
+ REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres
51
+ KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest
52
+ MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base
53
+ BASE_X = -0.66
54
+ R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm)
55
+ GAP = 0.03 # free space between footprints (finger room)
56
+ SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table
57
+ SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached
58
+
59
+ NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
60
+ "chocolate_pudding_1": "chocolate pudding", BASKET: "basket"}
61
+ DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
62
+ "chocolate_pudding_1": "brown box", BASKET: "wicker basket"}
63
+
64
+
65
+ def _qz(a):
66
+ return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
67
+
68
+
69
+ def _wrap_half(a):
70
+ """wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
71
+ return float((a + np.pi / 2) % np.pi - np.pi / 2)
72
+
73
+
74
+ def _seg_dist(p, a, b):
75
+ """distance from point p to segment a-b (2D)"""
76
+ p, a, b = (np.asarray(v, float) for v in (p, a, b))
77
+ ab = b - a
78
+ t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0)
79
+ return float(np.linalg.norm(p - (a + t * ab)))
80
+
81
+
82
+ def _in_rect(xy, r):
83
+ return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3]
84
+
85
+
86
+ def _reach_ok(xy):
87
+ return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH
88
+
89
+
90
+ @register_task
91
+ class RestoreLayout(LFFTask):
92
+ name = "l2_restore_layout"
93
+ level = "L2"
94
+ category = "state_restoration"
95
+ capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
96
+ protocol = "within"
97
+ max_attempts = 5
98
+ instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it "
99
+ "is now, in the same position and orientation.")
100
+ instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay "
101
+ "exactly where it is now, in the same position and orientation.")
102
+ knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
103
+
104
+ def __init__(self, cam_res=None):
105
+ super().__init__(cam_res)
106
+ # upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down;
107
+ # basket and boxes are upright in their mesh frame
108
+ self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
109
+ self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
110
+ self._inj = None
111
+ self.start = {}
112
+ self._home = None
113
+ # per-control-step monitor on env.step: also sees attempts driven by the agent harness
114
+ orig_step = self.env.step
115
+
116
+ def step(action):
117
+ ret = orig_step(action)
118
+ if self._inj is not None:
119
+ self._knock_step()
120
+ return ret
121
+
122
+ self.env.step = step
123
+
124
+ # ------------------------------------------------------------ scene
125
+ def make_bddl(self):
126
+ names = [*ITEMS, BASKET]
127
+ objs = []
128
+ for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
129
+ x0 = -0.30 + 0.13 * (i % 3)
130
+ y0 = -0.25 + 0.25 * (i // 3)
131
+ objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
132
+ return write_bddl(self.name, self.instruction, objs)
133
+
134
+ def sample_instance(self, seed):
135
+ rng = np.random.default_rng(seed)
136
+ for _ in range(5000):
137
+ basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)])
138
+ k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)])
139
+ victim = str(rng.choice(BOXES))
140
+ others = [b for b in BOXES if b != victim]
141
+ a_v = rng.uniform(0, 2 * np.pi)
142
+ r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02)
143
+ pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])}
144
+ ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim])
145
+ for o in others:
146
+ if not ok:
147
+ break
148
+ for _ in range(200):
149
+ p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
150
+ if not _reach_ok(p):
151
+ continue
152
+ if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP:
153
+ continue
154
+ if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET):
155
+ continue
156
+ pos[o] = p
157
+ break
158
+ else:
159
+ ok = False
160
+ if not ok:
161
+ continue
162
+ if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS):
163
+ continue
164
+ # the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign)
165
+ ang = a_v + rng.uniform(-np.radians(35), np.radians(35))
166
+ dist = rng.uniform(0.09, 0.14)
167
+ u = np.array([np.cos(ang), np.sin(ang)])
168
+ end = pos[victim] + dist * u
169
+ if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)):
170
+ continue
171
+ if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03:
172
+ continue
173
+ # the path and the resting spot keep clear of the other boxes (finger room around the victim too)
174
+ if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others):
175
+ continue
176
+ if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others):
177
+ continue
178
+ if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP:
179
+ continue
180
+ turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80)))
181
+ return dict(seed=int(seed),
182
+ basket_xy=basket.round(4).tolist(),
183
+ xy={n: pos[n].round(4).tolist() for n in ITEMS},
184
+ yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES},
185
+ TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))},
186
+ # hidden variables of the injected failure
187
+ victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn,
188
+ knock_end=end.round(4).tolist())
189
+ raise RuntimeError("could not sample a layout")
190
+
191
+ def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
192
+ """Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only)."""
193
+ q = envs._quat_mul(_qz(yaw), self.q_up[name])
194
+ envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
195
+ self.env.sim.forward()
196
+ dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
197
+ qa, _ = envs.free_joint_addr(self.env, name)
198
+ self.env.sim.data.qpos[qa + 2] -= dz
199
+ self.env.sim.forward()
200
+
201
+ def apply_instance(self, inst):
202
+ envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock)
203
+ self.place(BASKET, inst["basket_xy"], 0.0)
204
+ for n in ITEMS:
205
+ self.place(n, inst["xy"][n], inst["yaw"][n])
206
+ self.env.sim.forward()
207
+
208
+ def reset_instance(self, inst, recorder=None):
209
+ self._inj = None
210
+ sk = super().reset_instance(inst, recorder)
211
+ self.start = {n: self.footprint(n) for n in ITEMS}
212
+ self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0)
213
+ self._home = sk.eef_pos()
214
+ return sk
215
+
216
+ # ------------------------------------------------------------ measurements
217
+ def footprint(self, name):
218
+ """Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range.
219
+ Scripted policies use it as a stand-in for perception."""
220
+ m, d = self.env.sim.model, self.env.sim.data
221
+ lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
222
+ best = None
223
+ for g in envs.obj_geom_ids(self.env, name):
224
+ R = d.geom_xmat[g].reshape(3, 3)
225
+ c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
226
+ e = np.abs(R) @ m.geom_aabb[g, 3:]
227
+ lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
228
+ vol = float(np.prod(m.geom_aabb[g, 3:]))
229
+ if best is None or vol > best[0]:
230
+ best = (vol, R, m.geom_aabb[g, 3:])
231
+ _, R, half = best
232
+ horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
233
+ ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
234
+ return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
235
+ half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
236
+
237
+ def body_yaw(self, name):
238
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
239
+ return float(np.arctan2(R[1, 0], R[0, 0]))
240
+
241
+ # ------------------------------------------------------------ failure injection (physical knock)
242
+ def _knock_step(self):
243
+ st = self._inj
244
+ if st["done"]:
245
+ if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps)
246
+ self._spin(st)
247
+ return
248
+ if self.sk is None:
249
+ return
250
+ if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
251
+ return
252
+ if not self.sk.holding(TARGET):
253
+ return
254
+ st["done"] = True
255
+ inst = st["inst"]
256
+ v = inst["victim"]
257
+ if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL:
258
+ return # the victim was moved beforehand: nothing happens
259
+ qa, da = envs.free_joint_addr(self.env, v)
260
+ v0 = np.sqrt(inst["knock_dist"] / SLIDE_K)
261
+ dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])])
262
+ d = self.env.sim.data
263
+ d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0]
264
+ st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"],
265
+ spin_steps=6)
266
+ self._spin(st)
267
+
268
+ def _spin(self, st):
269
+ v = st["inst"]["victim"]
270
+ _, da = envs.free_joint_addr(self.env, v)
271
+ turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0
272
+ rest = st["spin_left"] - turned
273
+ st["spin_steps"] -= 1
274
+ if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]):
275
+ st["spin_steps"] = 0
276
+ return
277
+ # measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short
278
+ w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W))
279
+ self.env.sim.data.qvel[da + 5] = np.sign(rest) * w
280
+
281
+ # ------------------------------------------------------------ outcome
282
+ def where_target(self):
283
+ """'basket', 'gripper', 'table' or 'other' for the ketchup."""
284
+ f = self.footprint(TARGET)
285
+ c = np.array(f["center"])
286
+ if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02:
287
+ return "gripper", f
288
+ bp = envs.obj_pos(self.env, BASKET)
289
+ 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:
290
+ return "basket", f
291
+ if f["zmin"] < envs.TABLE_Z + 0.01:
292
+ return "table", f
293
+ return "other", f
294
+
295
+ def box_state(self, name):
296
+ """Pose error of a box w.r.t. its start pose and where it is."""
297
+ f = self.footprint(name)
298
+ s = self.start[name]
299
+ c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2])
300
+ dpos = float(np.linalg.norm(c - c0))
301
+ dyaw = _wrap_half(f["yaw"] - s["yaw"])
302
+ held = bool(self.sk is not None and self.sk.holding(name))
303
+ upright = envs.obj_upright_cos(self.env, name) > 0.9
304
+ on_table = f["zmin"] < envs.TABLE_Z + 0.01
305
+ bp = envs.obj_pos(self.env, BASKET)
306
+ loc = ("gripper" if held else
307
+ "basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else
308
+ "table" if on_table and upright else
309
+ "table_tipped" if on_table else "other")
310
+ ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL)
311
+ return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"],
312
+ offset=(c - c0).tolist())
313
+
314
+ @staticmethod
315
+ def _offset_words(off, dyaw):
316
+ """robot-centric words for a displacement (current - start) and turn (for the offset tier only)"""
317
+ parts = []
318
+ if abs(off[0]) >= 0.005:
319
+ parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}")
320
+ if abs(off[1]) >= 0.005:
321
+ parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}")
322
+ s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot"
323
+ if abs(dyaw) >= np.radians(3):
324
+ s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)"
325
+ return s
326
+
327
+ def _describe(self, tloc, boxes, names, offset=False):
328
+ tn = names[TARGET]
329
+ msgs = []
330
+ if tloc != "basket":
331
+ msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
332
+ "table": f"The {tn} is on the table, not in the basket."}
333
+ .get(tloc, f"The {tn} is not in the basket."))
334
+ for n in BOXES:
335
+ b = boxes[n]
336
+ if b["ok"]:
337
+ continue
338
+ if b["loc"] == "gripper":
339
+ msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.")
340
+ continue
341
+ if b["loc"] == "basket":
342
+ msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.")
343
+ continue
344
+ if b["loc"] == "table_tipped":
345
+ msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.")
346
+ continue
347
+ if b["loc"] != "table":
348
+ msgs.append(f"The {names[n]} is not where it was at the start.")
349
+ continue
350
+ what = []
351
+ if b["dpos"] > POS_TOL:
352
+ what.append("position")
353
+ if abs(b["dyaw"]) > YAW_TOL:
354
+ what.append("orientation")
355
+ m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)."
356
+ if offset:
357
+ m += f" It is {self._offset_words(b['offset'], b['dyaw'])}."
358
+ msgs.append(m)
359
+ if not msgs:
360
+ msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.")
361
+ return " ".join(msgs)
362
+
363
+ def outcome(self, inst):
364
+ envs.settle(self.env, 30)
365
+ tloc, tf = self.where_target()
366
+ boxes = {n: self.box_state(n) for n in BOXES}
367
+ moved = [n for n in BOXES if not boxes[n]["ok"]]
368
+ success = bool(tloc == "basket" and not moved)
369
+ return dict(success=success, target_loc=tloc, moved=moved,
370
+ boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4),
371
+ dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()},
372
+ knocked=bool(self._inj and self._inj["knocked"]),
373
+ detail=self._describe(tloc, boxes, NAMES),
374
+ detail_indirect=self._describe(tloc, boxes, DESCR),
375
+ detail_offset=self._describe(tloc, boxes, NAMES, offset=True))
376
+
377
+ def feedback(self, inst, out, level="F2", indirect=False, offset=False):
378
+ """F0: nothing, F1: success flag, F2: which item is out of place (never where it was).
379
+ offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric
380
+ words -- this externalises the memory and is not the default."""
381
+ if level == "F2":
382
+ key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
383
+ out = dict(out, detail=out.get(key, out["detail"]))
384
+ return super().feedback(inst, out, level)
385
+
386
+ # ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only)
387
+ def go_home(self):
388
+ """End of an attempt: lift the arm out of the camera's way."""
389
+ sk = self.sk
390
+ p = sk.eef_pos()
391
+ sk.move_to([p[0], p[1], max(p[2], self._home[2])])
392
+ sk.move_to(self._home)
393
+
394
+ def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None,
395
+ travel_z=1.15):
396
+ """Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
397
+ object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis."""
398
+ sk = self.sk
399
+ f = fp or self.footprint(name)
400
+ c = np.array(f["center"])
401
+ h = f["zmax"] - f["zmin"]
402
+ gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
403
+ if name == TARGET:
404
+ zg = f["zmax"] - 0.035
405
+ else:
406
+ zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site
407
+ sk.set_gripper(False, steps=6)
408
+ p = sk.eef_pos()
409
+ if p[2] < travel_z - 0.02:
410
+ sk.move_to([p[0], p[1], travel_z])
411
+ sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
412
+ sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
413
+ sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
414
+ sk.set_gripper(True, steps=12)
415
+ sk.move_to([c[0], c[1], carry_z], speed=0.3)
416
+ gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
417
+ sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
418
+ sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2,
419
+ max_steps=150)
420
+ sk.hold(4)
421
+ sk.set_gripper(False, steps=10)
422
+ sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
423
+
424
+ def main_task(self, fp=None):
425
+ """Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
426
+ b = envs.obj_pos(self.env, BASKET)
427
+ floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
428
+ self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
429
+
430
+ def restore(self, name, pose):
431
+ """Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw)."""
432
+ self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05,
433
+ clearance=0.004)
434
+
435
+ def do(self, actions, inst):
436
+ for act in actions:
437
+ if act[0] == "ketchup_to_basket":
438
+ self.main_task(fp=act[1] if len(act) > 1 else None)
439
+ elif act[0] == "restore": # ["restore", name, pose]
440
+ self.restore(act[1], act[2])
441
+ else:
442
+ raise ValueError(act)
443
+
444
+ # ------------------------------------------------------------ scripted reference policies
445
+ def _guess_pose(self, name, rng):
446
+ """nomem control: a random free spot within 15 cm of where the box is now, random yaw."""
447
+ cur = np.array(self.footprint(name)["center"][:2])
448
+ others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name]
449
+ for _ in range(200):
450
+ r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi)
451
+ p = cur + r * np.array([np.cos(a), np.sin(a)])
452
+ if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others):
453
+ return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
454
+ return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
455
+
456
+ def _plan(self, kind, inst, a, history, rng, memory):
457
+ """Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose]."""
458
+ if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
459
+ return [["ketchup_to_basket"]]
460
+ if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory)
461
+ return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]]
462
+ last = history[-1]["outcome"]
463
+ if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were
464
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
465
+ return acts + [["restore", n, memory[n]] for n in last["moved"]]
466
+ if kind == "nomem": # F2 but no start frame: guesses
467
+ acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
468
+ return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]]
469
+ if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
470
+ fp = self.footprint(TARGET)
471
+ fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
472
+ return [["ketchup_to_basket", fp]]
473
+ raise ValueError(kind)
474
+
475
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
476
+ """Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
477
+ k = k or self.max_attempts
478
+ rng = np.random.default_rng(seed)
479
+ history = []
480
+ self.reset_instance(inst)
481
+ memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save
482
+ for a in range(k):
483
+ actions = self._plan(kind, inst, a, history, rng, memory)
484
+ self.do(actions, inst)
485
+ self.go_home()
486
+ out = self.outcome(inst)
487
+ params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else
488
+ [x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)]
489
+ for x in actions])
490
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
491
+ if on_attempt:
492
+ on_attempt(a, params, out)
493
+ if out["success"] or kind in ("oracle", "naive"):
494
+ break
495
+ return history
496
+
497
+ # cross-protocol hooks are not used by this task
498
+ def default_params(self, inst):
499
+ return dict(policy="naive")
500
+
501
+ def oracle_params(self, inst):
502
+ return dict(policy="oracle")
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_loaded_beam.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L5 loaded_beam (2026-10-12): a deepened l5_slippery_lift -- lift a loaded bar level without spilling its load.
2
+
3
+ Why (../research_notes/P1P2_加深与常识任务设计.md sec. 1, 2, 3.1): l5_slippery_lift saturated. Sonnet 5.5 (cla4)
4
+ grasped the bar's middle, lifted, saw the 45-60 deg tilt, put the bar down and regrasped near the centre of mass,
5
+ all inside attempt 1 (both runs succeeded on attempt 1): the tilting lift cost nothing. Rule R3: the first
6
+ common-sense interaction must cost something. Here the tilting lift spills the load.
7
+
8
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, "left" = +y): the l5_slippery_lift bar (steel grey,
9
+ 4 x 28 x 4 cm, long axis along the robot's left-right axis, same layout and hidden weight per seed) with two small red
10
+ blocks (2.5 cm cubes, 30 g, smooth: friction 0.2, they slide on the steel beyond ~11 deg of tilt) resting on its top
11
+ near the ends, 12.5 cm left and right of its middle.
12
+
13
+ Hidden variable (same in every attempt, invisible): a slug inside the bar puts its centre of mass e = 2.5-7 cm from
14
+ the middle, towards the left or right end (bar 0.8-1.2 kg, finger friction 0.40-0.60; l5_slippery_lift). The blocks
15
+ are symmetric, so the centre of mass of bar + blocks sits at M e / (M + 2 m) (2.3-6.7 cm).
16
+
17
+ Mechanism (physics, nothing teleported): grasped at its middle and lifted, the bar rotates in the slippery finger
18
+ pads and hangs tilted; the block on the low (heavy) end slides off, drops onto the table and, once the bar is set down
19
+ again, lies 2-5 cm beyond the bar's end; the other block slides along the bar to the fingers. Measured (20 seeds,
20
+ middle grasp): lift 15 cm at 0.1 m/s -> tilt 29-54 deg, spill 20/20; 15 cm at 0.03 m/s -> spill 20/20 (block friction =
21
+ the bar's, task card); a 5.5 cm "half lift" -> 20-22 deg, spill 20/20; 3 cm -> 10-11 deg, spill 2/20; 1 / 1.5 cm test
22
+ lifts -> 0.6-2.5 / 2.5-4.5 deg, spill 0/20 each (the low end stays on the table). Putting it right is a real repair:
23
+ set the bar down, release, pick the fallen block from the table, put it back on the end, move the other block back to
24
+ its end, regrasp nearer the heavy end, lift again: 20 commands for the scripted policy (5 for the whole oracle; the
25
+ same repair costs 7 commands in l5_slippery_lift, where nothing spills). What helps: a ~1 cm test lift shows the tilt
26
+ direction without spilling, or, after the first failure, grasping on the side of the end that sank (the heavy end),
27
+ ideally at the combined centre of mass (+-5 mm: 80/80 level lifts, nothing spilled).
28
+
29
+ Success: the bar is held (after a 1.5 s hold), tilted <= 8 deg, its lowest point >= 10 cm above the table (the
30
+ l5_slippery_lift condition), and both blocks rest on the bar, one within 3 cm of each end position (+-12.5 cm from the
31
+ middle; either block may sit on either end). Protocol: cross (reset before every attempt), k = 3.
32
+
33
+ Outcome (server log only; the agent gets F1): success / failure code, the bar's tilt and height, final block states,
34
+ per-step events (bar_lifted, bar_tilted, load_fell = the trap fired, load_displaced, load_removed, load_restored with
35
+ by_robot, bar_set_down), the lifts with their grasp points and maximum tilt, trap_fired, recovered_in_attempt,
36
+ first_interaction_ok and an F2-style `detail` in robot-centric words.
37
+ """
38
+ import numpy as np
39
+
40
+ from .. import envs
41
+ from ..bddl import write_bddl
42
+ from ..objects import box_xml, register_generated
43
+ from ..task_base import register_task
44
+ from .l5_slippery_lift import (BAR, HALF, LIFT_MIN, TILT_MAX, YAW_ACROSS, Z_GRASP, BarSkills, SlipperyLift,
45
+ bar_tilt_deg, weighted_box_xml)
46
+
47
+ TZ = envs.TABLE_Z
48
+ LOADS = ("block_1", "block_2") # block_1 starts on the left (+y) end, block_2 on the right (-y) end
49
+ LOAD_SIGN = {"block_1": 1.0, "block_2": -1.0}
50
+ LOAD_H = 0.0125 # 2.5 cm cubes
51
+ LOAD_MASS = 0.030
52
+ LOAD_RGBA = (0.85, 0.20, 0.12, 1.0)
53
+ LOAD_MU = 0.20 # block sliding friction (geom priority 3: used against the bar, the table and the fingers): the blocks
54
+ # slide on the steel bar beyond ~11 deg of tilt. With the bar's own mu (0.4-0.6, slide beyond 22-31 deg)
55
+ # a 5.5 cm "half lift" (20 deg) spilled nothing (0/10) and was a free probe; with 0.2 it spills.
56
+ SLOT = 0.125 # block centre this far from the bar's middle (along the bar)
57
+ SLOT_TOL = 0.03 # success: within 3 cm of an end position
58
+ BAR_TOP = TZ + 2 * HALF[2]
59
+ LIFTED = 0.02 # the bar's centre this much higher than at rest (while held) -> "lifted" (a ~1 cm test lift is not)
60
+ DOWN = 0.008 # ... and back below this -> "set down"
61
+ DEBOUNCE = 5 # control steps a new block state must persist before it counts
62
+ SAFE_ALONG = 0.09 # scripted grasps stay within +-9 cm of the middle (the hand must not touch the blocks)
63
+
64
+
65
+ class _Budget(Exception):
66
+ """the scripted policy used up the agent command budget of the attempt"""
67
+
68
+
69
+ def bar_frame(env):
70
+ """(centre, along, side, up): `along` = the bar's long axis oriented towards the robot's left (+y); `up` = the
71
+ bar's cross-section axis closest to world up (the face the blocks rest on); `side` completes the frame."""
72
+ bid = envs.body_id(env, BAR)
73
+ d = env.sim.data
74
+ c = d.body_xpos[bid].copy()
75
+ R = d.body_xmat[bid].reshape(3, 3)
76
+ al = R[:, 1].copy()
77
+ if al[1] < 0:
78
+ al = -al
79
+ up = max((R[:, 0].copy(), R[:, 2].copy()), key=lambda v: abs(v[2]))
80
+ if up[2] < 0:
81
+ up = -up
82
+ side = np.cross(up, al)
83
+ return c, al, side, up
84
+
85
+
86
+ def _end_word(s):
87
+ return "left" if s > 0 else "right"
88
+
89
+
90
+ class BeamSkills(BarSkills):
91
+ """BarSkills (records where along the bar the jaws closed) + the task's per-step monitor."""
92
+
93
+ def __init__(self, env, task, recorder=None):
94
+ super().__init__(env, recorder=recorder)
95
+ self.task = task
96
+
97
+ def _act(self, dpos, drot, grip):
98
+ super()._act(dpos, drot, grip)
99
+ self.task.monitor_step()
100
+
101
+
102
+ @register_task
103
+ class LoadedBeam(SlipperyLift):
104
+ name = "l5_loaded_beam"
105
+ level = "L5"
106
+ category = "dynamics_adaptation"
107
+ capabilities = ("Perceive", "Reason", "Plan", "Utilize")
108
+ protocol = "cross"
109
+ max_attempts = 3
110
+ agent_max_steps = 40
111
+ instruction = ("Lift the metal bar together with the two small red blocks resting near its ends, and hold it level "
112
+ "(tilted less than 8 degrees) with its lowest point at least 10 cm above the table. Both blocks must "
113
+ "stay on the bar near its ends. Keep holding the bar when you finish.")
114
+ instruction_indirect = ("Raise the long grey rod with the two little red cubes sitting near its ends and hold it "
115
+ "horizontal (tilted less than 8 degrees), its lowest point at least 10 cm above the table. "
116
+ "Both cubes must stay on the rod near its ends. Keep holding the rod when you finish.")
117
+
118
+ # ------------------------------------------------------------ scene
119
+ def make_bddl(self):
120
+ bar = register_generated("LffBeamBar", weighted_box_xml("lff_beam_bar", HALF, (0.52, 0.55, 0.58, 1.0)))
121
+ dens = LOAD_MASS / (2 * LOAD_H) ** 3
122
+ la = register_generated("LffBeamBlockA", box_xml("lff_beam_block_a", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
123
+ lb = register_generated("LffBeamBlockB", box_xml("lff_beam_block_b", (LOAD_H,) * 3, LOAD_RGBA, density=dens))
124
+ # LIBERO's sampler puts the bar anywhere within +-13 cm of its region's centre (it "keeps the bar's 14 cm
125
+ # radius inside" a 2 cm region) and rejects block placements closer than 14 + 1.8 cm to it: the block regions
126
+ # are >= 19 cm from every possible bar position (the first layout, 2 cm beside the bar's range, failed with
127
+ # "Cannot place all objects" in 13 of 400 resets, this one 0 of 400). apply_instance moves everything anyway.
128
+ objs = [(BAR, bar, "bar_region", (-0.11, -0.01, -0.09, 0.01)),
129
+ ("block_1", la, "block1_region", (-0.11, 0.32, -0.09, 0.34)),
130
+ ("block_2", lb, "block2_region", (-0.11, -0.34, -0.09, -0.32))]
131
+ return write_bddl(self.name, "lift the loaded bar and hold it level", objs)
132
+
133
+ def __init__(self, cam_res=None):
134
+ self.mon = None
135
+ self.budget = None # scripted policies only: command budget of the current attempt
136
+ self.ncmd = 0
137
+ super().__init__(cam_res)
138
+
139
+ def sample_instance(self, seed):
140
+ inst = super().sample_instance(seed) # same bar layout and hidden weight as l5_slippery_lift for this seed
141
+ m = inst["mass"]
142
+ inst.update(load_mass=LOAD_MASS, slot=SLOT,
143
+ com_total=float(m * inst["com_offset"] / (m + 2 * LOAD_MASS))) # bar + both blocks on their ends
144
+ return inst
145
+
146
+ def apply_instance(self, inst):
147
+ super().apply_instance(inst) # bar pose, friction, hidden weight (+ envs.refit_bounds)
148
+ x, y = inst["bar_xy"]
149
+ for nm in LOADS:
150
+ envs.set_obj_pose(self.env, nm, [x, y + LOAD_SIGN[nm] * SLOT, BAR_TOP + LOAD_H + 0.0005])
151
+ if LOAD_MU is not None:
152
+ envs.set_friction(self.env, nm, LOAD_MU, priority=3)
153
+
154
+ def reset_instance(self, inst, recorder=None):
155
+ self.env.reset()
156
+ self.apply_instance(inst)
157
+ self.env.sim.forward()
158
+ envs.settle(self.env, 10)
159
+ self.mon = None
160
+ self.sk = BeamSkills(self.env, self, recorder=recorder)
161
+ self._init_monitor()
162
+ return self.sk
163
+
164
+ # ------------------------------------------------------------ state
165
+ def bar_bottom(self):
166
+ return envs.obj_min_z(self.env, BAR) - TZ
167
+
168
+ def load_rel(self, nm):
169
+ """block centre in the bar frame: (along (+ = towards the bar's left end), side, height above the bar's centre)"""
170
+ c, al, side, up = bar_frame(self.env)
171
+ r = envs.obj_pos(self.env, nm) - c
172
+ return float(r @ al), float(r @ side), float(r @ up)
173
+
174
+ def _block_held(self, nm):
175
+ sk = self.sk
176
+ if sk is None or sk.grip < 0:
177
+ return False
178
+ if np.linalg.norm(envs.obj_pos(self.env, nm) - sk.eef_pos()) > 0.06:
179
+ return False
180
+ return sk.holding(nm)
181
+
182
+ def load_state(self, nm, tol=SLOT_TOL):
183
+ """'slot+' / 'slot-' (on the bar within `tol` of its left / right end position), 'bar' (on the bar
184
+ elsewhere), 'held', 'table', 'air' (anything else: falling, resting on the gripper ...)"""
185
+ if self._block_held(nm):
186
+ return "held"
187
+ a, s, u = self.load_rel(nm)
188
+ if abs(u - (HALF[2] + LOAD_H)) <= 0.008 and abs(s) <= HALF[0] + 0.003 and abs(a) <= HALF[1] + 0.003:
189
+ if abs(a - SLOT) <= tol:
190
+ return "slot+"
191
+ if abs(a + SLOT) <= tol:
192
+ return "slot-"
193
+ return "bar"
194
+ if envs.obj_pos(self.env, nm)[2] < TZ + 0.027:
195
+ return "table"
196
+ return "air"
197
+
198
+ # ------------------------------------------------------------ monitor
199
+ def _init_monitor(self):
200
+ st = {nm: self.load_state(nm) for nm in LOADS}
201
+ self.mon = dict(stable=dict(st), cand={nm: None for nm in LOADS}, cnt={nm: 0 for nm in LOADS},
202
+ last_on_bar={nm: self.load_rel(nm)[0] for nm in LOADS}, lost=set(), carried=set(), events=[],
203
+ lifts=[],
204
+ lifted=False, tilted=False, max_tilt=0.0)
205
+
206
+ def _event(self, ev, step=None, **kw):
207
+ self.mon["events"].append(dict(step=int(self.sk.n_steps if step is None else step), ev=ev, **kw))
208
+
209
+ def _last_grasp(self):
210
+ return next((c for c in reversed(self.sk.closes) if c["holding"]), None)
211
+
212
+ def monitor_step(self):
213
+ mon, sk = self.mon, self.sk
214
+ if mon is None or sk is None:
215
+ return
216
+ n = sk.n_steps
217
+ # --- the bar: lifts and tilt
218
+ rise = float(envs.obj_pos(self.env, BAR)[2]) - (TZ + HALF[2])
219
+ held = sk.grip > 0 and sk.holding(BAR)
220
+ if not mon["lifted"] and held and rise > LIFTED:
221
+ g = self._last_grasp()
222
+ mon["lifted"], mon["tilted"], mon["max_tilt"] = True, False, 0.0
223
+ mon["lifts"].append(dict(step_up=n, step_down=None, grasp_along=None if g is None else round(g["along"], 4),
224
+ max_tilt_deg=0.0, falls=[]))
225
+ self._event("bar_lifted", grasp_along=mon["lifts"][-1]["grasp_along"])
226
+ if mon["lifted"]:
227
+ t = bar_tilt_deg(self.env)
228
+ lift = mon["lifts"][-1]
229
+ if abs(t) > abs(lift["max_tilt_deg"]):
230
+ lift["max_tilt_deg"] = round(t, 1)
231
+ if not mon["tilted"] and abs(t) > TILT_MAX and held:
232
+ mon["tilted"] = True
233
+ self._event("bar_tilted", tilt_deg=round(t, 1), low_end=_end_word(t))
234
+ if rise < DOWN:
235
+ mon["lifted"] = False
236
+ lift["step_down"] = n
237
+ self._event("bar_set_down", max_tilt_deg=lift["max_tilt_deg"])
238
+ # --- the blocks (debounced state machine)
239
+ for nm in LOADS:
240
+ # hysteresis: a block that has left its end position must come back within 2 cm of an end to count as
241
+ # restored (a block sliding along the tilted bar hovered around the 3 cm limit and flickered)
242
+ s = self.load_state(nm, SLOT_TOL - 0.01 if nm in mon["lost"] else SLOT_TOL)
243
+ if s in ("slot+", "slot-", "bar"):
244
+ mon["last_on_bar"][nm] = self.load_rel(nm)[0]
245
+ old = mon["stable"][nm]
246
+ if s == old:
247
+ mon["cand"][nm], mon["cnt"][nm] = None, 0
248
+ continue
249
+ if s != mon["cand"][nm]:
250
+ mon["cand"][nm], mon["cnt"][nm] = s, 0
251
+ mon["cnt"][nm] += 1
252
+ if mon["cnt"][nm] < DEBOUNCE:
253
+ continue
254
+ step = n - DEBOUNCE + 1
255
+ mon["stable"][nm], mon["cand"][nm], mon["cnt"][nm] = s, None, 0
256
+ start = _end_word(LOAD_SIGN[nm])
257
+ if s == "held":
258
+ mon["carried"].add(nm)
259
+ if s in ("slot+", "slot-"):
260
+ if nm in mon["lost"]:
261
+ # by_robot: the gripper carried it back (else physics did, e.g. the high-end block sliding back out
262
+ # while the bar swings after the other block fell: 3-4 of 59 blind attempts)
263
+ mon["lost"].discard(nm)
264
+ self._event("load_restored", step, load=nm, start_end=start, end=_end_word(1 if s == "slot+" else -1),
265
+ by_robot=nm in mon["carried"])
266
+ mon["carried"].discard(nm)
267
+ elif old in ("slot+", "slot-") and s == "bar":
268
+ mon["lost"].add(nm)
269
+ self._event("load_displaced", step, load=nm, start_end=start, along_cm=round(100 * self.load_rel(nm)[0], 1))
270
+ elif old in ("slot+", "slot-", "bar", "air") and s == "table":
271
+ mon["lost"].add(nm)
272
+ end = _end_word(mon["last_on_bar"][nm])
273
+ self._event("load_fell", step, load=nm, start_end=start, off_end=end)
274
+ if mon["lifted"]:
275
+ mon["lifts"][-1]["falls"].append(nm)
276
+ elif old == "held" and s == "table":
277
+ mon["lost"].add(nm)
278
+ self._event("load_removed", step, load=nm, start_end=start)
279
+ elif old in ("slot+", "slot-") and s == "held":
280
+ mon["lost"].add(nm) # picked up by the agent: counts as lost until it is back on an end
281
+
282
+ # ------------------------------------------------------------ outcome / F2
283
+ def _where(self, nm):
284
+ """robot-centric description of a block that is not on an end position"""
285
+ st = self.load_state(nm)
286
+ a, s, u = self.load_rel(nm)
287
+ if st == "held":
288
+ return "is held in the gripper"
289
+ if st == "bar":
290
+ e = 1.0 if a >= 0 else -1.0
291
+ return (f"is still on the bar but {100 * (SLOT - abs(a)):.0f} cm in from its {_end_word(e)} end position "
292
+ f"({100 * abs(a):.0f} cm {_end_word(e)} of the bar's middle)")
293
+ c, al, side, up = bar_frame(self.env)
294
+ e = 1.0 if a >= 0 else -1.0
295
+ u = al[:2] / max(np.linalg.norm(al[:2]), 1e-6) # the bar's direction seen from above
296
+ end = c[:2] + al[:2] * e * HALF[1] # the end's position seen from above (also while the bar hangs tilted)
297
+ r = envs.obj_pos(self.env, nm)[:2] - end
298
+ beyond = float(r @ u) * e
299
+ lateral = float(r @ np.array([-u[1], u[0]]))
300
+ where = "on the table" if st == "table" else "off the bar"
301
+ if beyond > 0 and abs(lateral) < 0.04:
302
+ return f"lies {where}, {100 * beyond:.0f} cm beyond the bar's {_end_word(e)} end"
303
+ fx = f"{100 * abs(r[0]):.0f} cm {'forward' if r[0] > 0 else 'back'}"
304
+ fy = f"{100 * abs(r[1]):.0f} cm {'left' if r[1] > 0 else 'right'}"
305
+ return f"lies {where}, {fx} and {fy} of the bar's {_end_word(e)} end"
306
+
307
+ def outcome(self, inst):
308
+ sk, mon = self.sk, self.mon
309
+ sk.hold(30) # 1.5 s with the gripper as the agent left it (envs.settle would open the jaws)
310
+ held = bool(sk.holding(BAR))
311
+ tilt = bar_tilt_deg(self.env)
312
+ bottom = self.bar_bottom()
313
+ states = {nm: self.load_state(nm) for nm in LOADS}
314
+ on_plus = [nm for nm in LOADS if states[nm] == "slot+"]
315
+ on_minus = [nm for nm in LOADS if states[nm] == "slot-"]
316
+ loads_ok = len(on_plus) == 1 and len(on_minus) == 1
317
+ level_ok = held and abs(tilt) <= TILT_MAX and bottom >= LIFT_MIN
318
+ success = bool(level_ok and loads_ok)
319
+ lifted_ever = bool(mon["lifts"]) or (sk.zmax - sk.z0) > 0.03
320
+ g = self._last_grasp()
321
+ evs = mon["events"]
322
+ falls = [e for e in evs if e["ev"] == "load_fell"]
323
+ restored = [e for e in evs if e["ev"] == "load_restored"]
324
+ lifts = mon["lifts"]
325
+ first_ok = None if not lifts else bool(not lifts[0]["falls"]) # the first lift spilled nothing
326
+ # --- text
327
+ gtxt = ""
328
+ if g is not None:
329
+ a = g["along"]
330
+ gtxt = (f" You last grasped the bar {100 * abs(a):.1f} cm to the {_end_word(a)} of its middle."
331
+ if abs(a) >= 0.0005 else " You last grasped the bar at its middle.")
332
+ tilt_txt = (f"hangs tilted by {abs(tilt):.0f} degrees, its {_end_word(tilt)} end lower than its "
333
+ f"{_end_word(-tilt)} end")
334
+ if success:
335
+ failure = None
336
+ bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
337
+ "with a block on each end.")
338
+ elif held and abs(tilt) > TILT_MAX:
339
+ failure = "tilted"
340
+ bar_txt = f"The bar did not stay level: it rotated in the gripper and now {tilt_txt}."
341
+ if bottom < LIFT_MIN:
342
+ bar_txt += f" Its lowest point is {100 * bottom:.0f} cm above the table."
343
+ elif held and bottom < LIFT_MIN:
344
+ failure = "too_low"
345
+ bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees) but its lowest point is only "
346
+ f"{100 * bottom:.0f} cm above the table.")
347
+ elif held:
348
+ failure = "load_off"
349
+ bar_txt = (f"The bar is held level (tilt {abs(tilt):.0f} degrees), {100 * bottom:.0f} cm above the table, "
350
+ "but the blocks are not both on its ends.")
351
+ elif lifted_ever:
352
+ failure = "dropped"
353
+ bar_txt = "The bar was lifted but is no longer in the gripper; it lies on the table."
354
+ else:
355
+ failure = "no_grasp"
356
+ bar_txt = ("The gripper never closed on the bar; it is still lying on the table." if not sk.closes else
357
+ "The gripper did not catch the bar; it is still lying on the table.")
358
+ parts = [bar_txt]
359
+ if falls:
360
+ f0 = falls[0]
361
+ lift = next((l for l in lifts if f0["load"] in l["falls"]), None)
362
+ how = (f" while the bar hung tilted by up to {abs(lift['max_tilt_deg']):.0f} degrees with its "
363
+ f"{_end_word(lift['max_tilt_deg'])} end lower") if lift and abs(lift["max_tilt_deg"]) > 1 else ""
364
+ parts.append(f"The {f0['start_end']} block slid off the bar's {f0['off_end']} end{how}."
365
+ + (f" Blocks fell off {len(falls)} times in this attempt." if len(falls) > 1 else ""))
366
+ if not loads_ok:
367
+ for nm in LOADS:
368
+ if states[nm] in ("slot+", "slot-") and (len(on_plus) == 1 or states[nm] != "slot+") and \
369
+ (len(on_minus) == 1 or states[nm] != "slot-"):
370
+ continue
371
+ parts.append(f"The {_end_word(LOAD_SIGN[nm])} block {self._where(nm)}.")
372
+ detail = " ".join(parts) + gtxt
373
+ loads = {}
374
+ for nm in LOADS:
375
+ a, s, u = self.load_rel(nm)
376
+ loads[nm] = dict(state=states[nm], along_cm=round(100 * a, 1), side_cm=round(100 * s, 1),
377
+ above_bar_centre_cm=round(100 * u, 1))
378
+ out = dict(success=success, failure=failure, held=held, tilt_deg=round(tilt, 1), bottom_cm=round(100 * bottom, 1),
379
+ grasp_along=None if g is None else round(g["along"], 4),
380
+ stages=dict(bar_held_level_high=bool(level_ok), loads_on_ends=bool(loads_ok)),
381
+ loads=loads, loads_on_ends=len(on_plus) + len(on_minus) if loads_ok else
382
+ int(len(on_plus) >= 1) + int(len(on_minus) >= 1),
383
+ trap_fired=bool(falls), n_load_falls=len(falls), n_restored=len(restored),
384
+ n_restored_by_robot=len([e for e in restored if e.get("by_robot")]),
385
+ n_regressions=len([e for e in evs if e["ev"] in ("load_fell", "load_displaced")]),
386
+ recovered_in_attempt=bool(falls and success), first_interaction_ok=first_ok,
387
+ n_lifts=len(lifts), lifts=lifts, events=list(evs), closes=sk.closes, detail=detail)
388
+ out["detail_indirect"] = detail.replace("bar", "rod").replace("block", "cube")
389
+ return out
390
+
391
+ # ------------------------------------------------------------ scripted primitives (agent-command counted)
392
+ def _cmd(self, target=None, yaw=None, speed=None, grip=None, tol=0.004, max_steps=250):
393
+ """one agent command (move_eef with an optional gripper action, or observe when nothing is given)"""
394
+ self.ncmd += 1
395
+ if self.budget is not None and self.ncmd > self.budget:
396
+ raise _Budget()
397
+ sk = self.sk
398
+ if target is not None:
399
+ t = np.asarray(target, float).copy()
400
+ t[2] = max(t[2], TZ + 0.006) # the agent interface does not go below 0.5 cm above the table
401
+ sk.move_to(t, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
402
+ if grip is not None:
403
+ sk.set_gripper(bool(grip))
404
+
405
+ def grasp_lift(self, along, lift=0.15, speed=0.10, dx=0.0):
406
+ """open, above the grasp point (jaws across the bar), descend, close, lift, look: 5 commands"""
407
+ c, al, side, up = bar_frame(self.env)
408
+ g = c + al * float(along) + np.array([dx, 0.0, 0.0])
409
+ z = max(float(c[2]), Z_GRASP)
410
+ self._cmd([g[0], g[1], z + 0.10], yaw=YAW_ACROSS, grip=False)
411
+ self._cmd([g[0], g[1], z], tol=0.003)
412
+ self._cmd(grip=True)
413
+ self._cmd([g[0], g[1], z + lift], speed=speed, max_steps=600)
414
+ self._cmd()
415
+
416
+ def put_down(self):
417
+ """lower the held bar onto the table, release, back up: 2 commands"""
418
+ e = self.sk.eef_pos()
419
+ self._cmd([e[0], e[1], Z_GRASP + 0.003], speed=0.05, grip=False, max_steps=600)
420
+ self._cmd([e[0], e[1], Z_GRASP + 0.12])
421
+
422
+ def _block_yaw(self, nm):
423
+ """gripper yaw whose jaws close on two faces of the block, preferring jaws that do not reach towards the bar"""
424
+ q = envs.obj_quat(self.env, nm)
425
+ w, x, y, z = q
426
+ psi = float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
427
+ c, al, side, up = bar_frame(self.env)
428
+ p = envs.obj_pos(self.env, nm)
429
+ a = float(np.clip((p - c) @ al, -HALF[1], HALF[1]))
430
+ v = (p - (c + al * a))[:2]
431
+ v = v / max(np.linalg.norm(v), 1e-6)
432
+ best = None
433
+ for k in range(2):
434
+ ang = psi + k * np.pi / 2 # closing direction candidate (a face normal)
435
+ n = np.array([np.cos(ang), np.sin(ang)])
436
+ score = abs(n @ v)
437
+ if best is None or score < best[0]:
438
+ best = (score, ang)
439
+ yaw = best[1] + np.pi / 2 # yaw = closing direction + 90 deg (YAW_ACROSS closes along world x)
440
+ return float((yaw + np.pi / 2) % np.pi - np.pi / 2)
441
+
442
+ def move_block_to_slot(self, nm, sign, tries=2):
443
+ """pick a block (from the table or the bar) and set it on the end position `sign`: 6 commands per try"""
444
+ sk = self.sk
445
+ for _ in range(tries):
446
+ p = envs.obj_pos(self.env, nm)
447
+ yaw = self._block_yaw(nm)
448
+ zg = max(float(p[2]), TZ + 0.008)
449
+ self._cmd([p[0], p[1], zg + 0.08], yaw=yaw, grip=False)
450
+ self._cmd([p[0], p[1], zg], tol=0.003, grip=True)
451
+ self._cmd([p[0], p[1], BAR_TOP + LOAD_H + 0.07])
452
+ if not sk.holding(nm):
453
+ continue
454
+ c, al, side, up = bar_frame(self.env)
455
+ t = c + al * sign * SLOT
456
+ ztop = envs.obj_max_z(self.env, BAR)
457
+ self._cmd([t[0], t[1], ztop + LOAD_H + 0.06])
458
+ self._cmd([t[0], t[1], ztop + LOAD_H + 0.004], speed=0.05, grip=False)
459
+ self._cmd([t[0], t[1], ztop + LOAD_H + 0.08])
460
+ if self.load_state(nm) == ("slot+" if sign > 0 else "slot-"):
461
+ return True
462
+ return False
463
+
464
+ def restore_loads(self):
465
+ """put every block that is not on an end position back onto a free end; True if both ends are taken"""
466
+ for _ in range(2):
467
+ st = {nm: self.load_state(nm) for nm in LOADS}
468
+ free = [s for s in (1.0, -1.0) if not any(v == ("slot+" if s > 0 else "slot-") for v in st.values())]
469
+ if not free:
470
+ return True
471
+ loose = [nm for nm in LOADS if st[nm] not in ("slot+", "slot-")]
472
+ for sgn in free:
473
+ if not loose:
474
+ break
475
+ c, al, side, up = bar_frame(self.env)
476
+ slot = c + al * sgn * SLOT
477
+ nm = min(loose, key=lambda b: np.linalg.norm(envs.obj_pos(self.env, b)[:2] - slot[:2]))
478
+ loose.remove(nm)
479
+ self.move_block_to_slot(nm, sgn)
480
+ self._cmd() # look
481
+ st = {nm: self.load_state(nm) for nm in LOADS}
482
+ return sorted(st.values()) == ["slot+", "slot-"]
483
+
484
+ def judge(self):
485
+ """what an agent sees after a lift (perfect perception): (all good, tilt, blocks on their ends)"""
486
+ tilt = bar_tilt_deg(self.env)
487
+ st = sorted(self.load_state(nm) for nm in LOADS)
488
+ ok_loads = st == ["slot+", "slot-"]
489
+ good = self.sk.holding(BAR) and abs(tilt) <= TILT_MAX - 2 and self.bar_bottom() >= LIFT_MIN + 0.01 and ok_loads
490
+ return bool(good), float(tilt), ok_loads
491
+
492
+ # ------------------------------------------------------------ scripted policies
493
+ def execute(self, inst, params):
494
+ self.grasp_lift(params["along"], params.get("lift", 0.15), params.get("speed", 0.10), params.get("dx", 0.0))
495
+
496
+ def default_params(self, inst):
497
+ return dict(along=0.0, lift=0.15, speed=0.10) # Sonnet 5.5 (cla4): middle, up to ~15-18 cm at 0.1 m/s
498
+
499
+ def oracle_params(self, inst):
500
+ return dict(along=float(inst["com_total"]), lift=0.15, speed=0.10)
501
+
502
+ def blind_params(self, inst, attempt, rng):
503
+ return dict(along=float(rng.normal(0.0, 0.01)), lift=float(rng.uniform(0.12, 0.18)),
504
+ speed=float(rng.uniform(0.05, 0.20)))
505
+
506
+ MARGIN = 0.008 # a lift that sank towards +y at grasp g says COM > g + MARGIN
507
+ STEP = 0.030 # first move towards the end that sank when only one side is bounded
508
+
509
+ def bracket(self, obs):
510
+ """grasp point from (grasp_along, tilt) observations: the end that sank is the heavy side of that grasp"""
511
+ lo, hi = -SAFE_ALONG, SAFE_ALONG
512
+ lo_set = hi_set = False
513
+ for g, t in obs:
514
+ if t > 0:
515
+ lo, lo_set = max(lo, g + self.MARGIN), True
516
+ else:
517
+ hi, hi_set = min(hi, g - self.MARGIN), True
518
+ if lo_set and hi_set:
519
+ a = 0.5 * (lo + hi)
520
+ elif lo_set:
521
+ a = lo + self.STEP - self.MARGIN
522
+ elif hi_set:
523
+ a = hi - self.STEP + self.MARGIN
524
+ else:
525
+ a = 0.0
526
+ return float(np.clip(a, -SAFE_ALONG, SAFE_ALONG))
527
+
528
+ def adapt_params(self, inst, history):
529
+ obs = [o for h in history for o in h["params"].get("obs", [])]
530
+ return dict(along=self.bracket(obs))
531
+
532
+ def adaptive_attempt(self, obs):
533
+ """lift at the current estimate; if the bar tilts or a block falls: set the bar down, put the blocks back,
534
+ regrasp on the side of the end that sank (bracketing), lift again -- while the command budget allows"""
535
+ tried = []
536
+ along = self.bracket(obs)
537
+ while True:
538
+ tried.append(round(along, 4))
539
+ self.grasp_lift(along)
540
+ good, tilt, ok_loads = self.judge()
541
+ if good:
542
+ return tried
543
+ g = self._last_grasp()
544
+ if abs(tilt) > 3.0 or not ok_loads:
545
+ lift = self.mon["lifts"][-1] if self.mon["lifts"] else None
546
+ t = tilt if abs(tilt) > 3.0 else (lift["max_tilt_deg"] if lift else 0.0)
547
+ if abs(t) > 1.0:
548
+ obs.append((g["along"] if g is not None else along, t))
549
+ # a repair = set down (2) + both blocks back (2 x 6: the fallen one and the one that slid to the fingers)
550
+ # + look (1) + regrasp, lift, look (5) = 20 commands; without enough budget keep holding the bar as it is
551
+ if self.budget is not None and self.ncmd + 20 > self.budget:
552
+ return tried
553
+ self.put_down()
554
+ if not self.restore_loads():
555
+ return tried
556
+ along = self.bracket(obs)
557
+
558
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
559
+ """cross protocol with an agent-like command budget per attempt (agent_max_steps; one move_eef with an optional
560
+ gripper action, or one observe, = one command). naive / oracle / blind: one lift, no checking.
561
+ adaptive: naive in attempt 1 but checks and repairs inside the attempt (`adaptive_attempt`); later attempts
562
+ start from the grasp point learned so far."""
563
+ k = k or self.max_attempts
564
+ rng = np.random.default_rng(seed)
565
+ history, obs = [], []
566
+ for a in range(k):
567
+ self.reset_instance(inst)
568
+ self.ncmd, self.budget = 0, self.agent_max_steps
569
+ if kind == "oracle":
570
+ params = self.oracle_params(inst)
571
+ elif kind == "naive":
572
+ params = self.default_params(inst)
573
+ elif kind == "blind":
574
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
575
+ elif kind == "adaptive":
576
+ params = dict(obs=[])
577
+ else:
578
+ raise ValueError(kind)
579
+ n0 = len(obs)
580
+ try:
581
+ if kind == "adaptive":
582
+ params["tried"] = self.adaptive_attempt(obs)
583
+ else:
584
+ self.execute(inst, params)
585
+ except _Budget:
586
+ params["budget_used_up"] = True
587
+ if kind == "adaptive":
588
+ params["obs"] = [[round(g, 4), round(t, 1)] for g, t in obs[n0:]]
589
+ self.budget = None
590
+ out = self.outcome(inst)
591
+ out["commands"] = self.ncmd
592
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
593
+ if on_attempt:
594
+ on_attempt(a, params, out)
595
+ if out["success"] or kind in ("oracle", "naive"):
596
+ break
597
+ return history
598
+
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_tablecloth_pull.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """L5-C tablecloth_pull: yank a board out from under a cube so that the cube lands inside a band.
2
+
3
+ Category dynamics_adaptation (L5): "figure out how this object moves". Replaces l5_tip_threshold, which could not
4
+ be built robustly with this robot (see task_cards/l5_tip_threshold.md).
5
+
6
+ Scene: a 30 x 8 x 1 cm wooden board lies on the table, pointing away from the robot, with a black handle block
7
+ at its near end. A red 4 cm cube stands on the far part of the board. A green band (6 cm deep, across the
8
+ table) is painted on the table under the board, a few cm closer to the robot than the cube. The agent may touch
9
+ only the board / handle, never the cube.
10
+
11
+ Physics. If the board is pulled slowly the cube rides along on it (static friction). If it is yanked, the board
12
+ slides out from under the cube; while it slides, friction drags the cube a little towards the robot, so the
13
+ cube drops onto the table having moved d towards the robot. d DEcreases with the pull speed (counter-intuitive:
14
+ a harder yank moves the cube less) and increases with the cube-board friction mu.
15
+
16
+ Hidden variable: the cube's friction mu (0.08-0.15; the cube looks the same for every mu), which shifts the whole
17
+ speed -> displacement curve and the speed below which the cube rides along.
18
+
19
+ Why the prior fails. The classic tablecloth prior is to yank as fast as possible (0.6 m/s, the arm's top speed);
20
+ the band is always placed >= 1.3 cm beyond the displacement such a yank produces, so the cube lands short of it. F2 reports where the cube ended relative to the band (robot-frame words, cm) or that it
21
+ rode along; the agent has to infer which way to change the pull speed (faster = less displacement) and by how
22
+ much.
23
+
24
+ Rule (stated in the instruction and enforced, 2026-10-08): ONE pull. Only one move command may drive the board
25
+ (>= PULL_EPS), the cube must still be where it started (<= PRE_TOL, grasp nudges) when that pull begins, and all
26
+ other move commands together may drive the board at most STRAY_MAX. Gripper open / close commands never count.
27
+ Without it every cla2 success (Sonnet, 4/4) dragged the board slowly first so that the cube rode to the band and the
28
+ last pull only added a little (one dragged it 4 cm, then yanked it sideways; one moved it with 11 commands, most
29
+ of them open-gripper strikes): the friction never mattered.
30
+ """
31
+ import numpy as np
32
+
33
+ from .. import envs
34
+ from ..bddl import write_bddl
35
+ from ..objects import _fmt, _wrap, box_xml, register_generated
36
+ from ..skills import Skills
37
+ from ..task_base import LFFTask, register_task
38
+
39
+ BOARD, CUBE, BAND = "board_1", "cube_1", "band_1"
40
+ B_HALF = (0.15, 0.04, 0.005) # 30 x 8 x 1 cm
41
+ H_HALF = (0.0125, 0.02, 0.015) # handle 2.5 x 4 x 3 cm on top of the near end
42
+ C_HALF = 0.02 # 4 cm cube
43
+ LF = 0.05 # cube centre to the board's far edge
44
+ BAND_HALF_X = 0.03 # band 6 cm deep: the 4 cm cube must be fully inside -> centre within +-1 cm
45
+ BAND_HALF_Y = 0.12
46
+ LINE_W = 0.005
47
+ TOL = BAND_HALF_X - C_HALF
48
+ MU_BOARD = 0.3 # board-table friction (fixed)
49
+ STROKE = 0.25 # scripted pull length
50
+ V_MIN, V_MAX = 0.15, 0.80
51
+ # one-pull rule (2026-10-08). Board motion is the larger of its two ends' 3-D paths and is only counted while the robot
52
+ # drives the board (touches it, or it speeds up; a board sliding on its own only slows down), so coasting after a
53
+ # strike or a release is not charged to the next command. Measured on the cla2 agent runs and the scripted policy:
54
+ # approach moves 0 mm; closing on the handle 0.6-2 mm (agents) / 4.6 mm (script); release after the pull 3-10 mm
55
+ # (gripper commands never count as pulls); the loophole drags 13-41 mm per command, open-gripper strikes 11-54 mm.
56
+ PULL_EPS = 0.003 # a move command that drives the board this far is a pull
57
+ PRE_TOL = 0.01 # the cube may have moved at most this much (grasp nudges) when the pull starts
58
+ STRAY_MAX = 0.005 # board motion driven by all the other move commands together (each below PULL_EPS)
59
+ ACC_EPS = 0.0002 # board speed-up per control step (m/step) that counts as the robot driving it
60
+ _SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
61
+
62
+
63
+ def board_xml(name):
64
+ hp = (-B_HALF[0] + H_HALF[0], 0.0, B_HALF[2] + H_HALF[2])
65
+ wood, black = (0.62, 0.45, 0.28, 1.0), (0.12, 0.12, 0.12, 1.0)
66
+ g = (f' <inertial pos="0.001 0 0.001" mass="0.3" diaginertia="0.0016 0.0023 0.0039" />\n'
67
+ f' <geom name="{name}_g0" type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" {_SOLID} group="0" />\n'
68
+ f' <geom name="{name}_g1" type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" '
69
+ f'{_SOLID} group="0" />\n'
70
+ f' <geom type="box" size="{_fmt(B_HALF)}" rgba="{_fmt(wood)}" conaffinity="0" contype="0" group="1" />\n'
71
+ f' <geom type="box" pos="{_fmt(hp)}" size="{_fmt(H_HALF)}" rgba="{_fmt(black)}" conaffinity="0" '
72
+ f'contype="0" group="1" />')
73
+ # small horizontal radius: only LIBERO's reset-time sampler reads it (the layout is overridden anyway)
74
+ return _wrap(name, g, B_HALF[2], 0.03)
75
+
76
+
77
+ def band_xml(name, line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
78
+ """Flat visual band across the table (no collisions): light fill + dark lines on its two long edges."""
79
+ hx, hy = BAND_HALF_X, BAND_HALF_Y
80
+ parts = [((0, 0, 0.0004), (hx, hy, 0.0004), fill_rgba),
81
+ ((hx + LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba),
82
+ ((-hx - LINE_W / 2, 0, 0.0010), (LINE_W / 2, hy, 0.0002), line_rgba)]
83
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
84
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
85
+ return _wrap(name, g, 0.0012, 0.03)
86
+
87
+
88
+ def d_range(mu):
89
+ """Band distances sampled for a given mu (m). Calibrated 2026-10-07 (LF 5 cm, board at x 0.05): the cube
90
+ moves d(0.6 m/s) ~ 0.33 * mu - 0.85 cm when yanked at the controller's top speed (mu 0.08 -> 1.8 cm,
91
+ 0.10 -> 2.3, 0.12 -> 3.1, 0.15 -> 4.3 cm) and >= 0.5 * mu at a pull ~0.05 m/s above the ride-along speed (0.08 -> 4.1 cm at
92
+ 0.35 m/s, 0.15 -> 7.6 cm at 0.45 m/s). The band centre is put ~1.5 cm beyond the top-speed displacement, so
93
+ the 'yank as fast as possible' prior always lands the cube short of the band."""
94
+ return 0.33 * mu + 0.0065, 0.50 * mu
95
+
96
+
97
+ class ClothSkills(Skills):
98
+ """Skills that watch, every control step, whether the robot touches the cube (not allowed) and how each
99
+ move_to / gripper command moves the board and the cube (one pull only)."""
100
+
101
+ def __init__(self, env, bias=None, recorder=None):
102
+ super().__init__(env, bias=bias, recorder=recorder)
103
+ m = env.sim.model
104
+ self._robot = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
105
+ self._cube = envs.obj_geom_ids(env, CUBE)
106
+ self._board = envs.obj_geom_ids(env, BOARD)
107
+ self.touched_cube = False
108
+ self.cube0 = envs.obj_pos(env, CUBE)
109
+ self._ends = self._board_ends()
110
+ self._bstep = 0.0 # board motion in the previous control step
111
+ self._seg = None
112
+ self.segments = [] # one entry per move_to / set_gripper command
113
+
114
+ def _board_ends(self):
115
+ """Both ends of the board's long axis (world xyz): their motion also catches turning and tilting."""
116
+ b = envs.obj_pos(self.env, BOARD)
117
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
118
+ return np.stack([b - R[:, 0] * B_HALF[0], b + R[:, 0] * B_HALF[0]])
119
+
120
+ def _act(self, dpos, drot, grip):
121
+ super()._act(dpos, drot, grip)
122
+ if not self.touched_cube and envs.contacts_between(self.env, self._robot, self._cube):
123
+ self.touched_cube = True
124
+ ends = self._board_ends()
125
+ step = float(np.max(np.linalg.norm(ends - self._ends, axis=1)))
126
+ touch = envs.contacts_between(self.env, self._robot, self._board)
127
+ speed_up = step - self._bstep > ACC_EPS
128
+ self._ends, self._bstep = ends, step
129
+ s = self._seg
130
+ if s is not None:
131
+ s["path"] += step
132
+ s["touch"] += int(touch)
133
+ if touch or speed_up:
134
+ s["driven"] += step
135
+
136
+ def _segment(self, kind, fn, *args, **kwargs):
137
+ c0, b0 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
138
+ self._seg = dict(kind=kind, step0=self.n_steps, path=0.0, driven=0.0, touch=0)
139
+ try:
140
+ rep = fn(*args, **kwargs)
141
+ finally:
142
+ s, self._seg = self._seg, None
143
+ c1, b1 = envs.obj_pos(self.env, CUBE), envs.obj_pos(self.env, BOARD)
144
+ s.update(steps=self.n_steps - s["step0"], board_dxy=(b1 - b0)[:2].round(4).tolist(),
145
+ cube_dxy=(c1 - c0)[:2].round(4).tolist(), cube_from_start=(c0 - self.cube0)[:2].round(4).tolist())
146
+ self.segments.append(s)
147
+ return rep
148
+
149
+ def move_to(self, target, *args, **kwargs):
150
+ return self._segment("move", super().move_to, target, *args, **kwargs)
151
+
152
+ def set_gripper(self, close, steps=15):
153
+ return self._segment("close" if close else "open", super().set_gripper, close, steps)
154
+
155
+ def pull_check(self):
156
+ """Pulls (move commands that drove the board >= PULL_EPS), where the cube was when the (first) pull started,
157
+ and the board motion driven by the other move commands."""
158
+ moves = [s for s in self.segments if s["kind"] == "move"]
159
+ pulls = [s for s in moves if s["driven"] >= PULL_EPS]
160
+ stray = sum(s["driven"] for s in moves if s["driven"] < PULL_EPS)
161
+ pre = (float(np.linalg.norm(pulls[0]["cube_from_start"])) if pulls
162
+ else float(np.linalg.norm((envs.obj_pos(self.env, CUBE) - self.cube0)[:2])))
163
+ return dict(n_pulls=len(pulls), pulls_cm=[round(100 * s["driven"], 1) for s in pulls],
164
+ pre_pull_cube_cm=round(100 * pre, 1), stray_cm=round(100 * stray, 2))
165
+
166
+
167
+ @register_task
168
+ class TableclothPull(LFFTask):
169
+ name = "l5_tablecloth_pull"
170
+ level = "L5"
171
+ category = "dynamics_adaptation"
172
+ capabilities = ("Perceive", "Reason", "Utilize")
173
+ protocol = "cross"
174
+ instruction = ("Pull the wooden board out from under the red cube so that the cube ends up standing on the table "
175
+ "completely inside the green band. Touch only the board and its black handle, never the cube. "
176
+ "Only one pull is allowed per attempt: grasp the black handle, pull the board out with ONE move "
177
+ "command, then release it. Any other move that drags, pushes or nudges the board, before or after "
178
+ "the pull, counts as another pull.")
179
+ instruction_indirect = ("Pull the long brown plank out from under the small red block so that the block ends up "
180
+ "standing on the table completely inside the green stripe. Touch only the plank and its "
181
+ "black handle, never the block. Only one pull is allowed per attempt: grasp the black "
182
+ "handle, pull the plank out with ONE move command, then release it. Any other move that "
183
+ "drags, pushes or nudges the plank, before or after the pull, counts as another pull.")
184
+
185
+ # ------------------------------------------------------------ scene
186
+ def make_bddl(self):
187
+ board = register_generated("LffClothBoard", board_xml("lff_cloth_board"))
188
+ cube = register_generated("LffClothCube", box_xml("lff_cloth_cube", (C_HALF,) * 3, (0.85, 0.15, 0.15, 1.0),
189
+ density=2300))
190
+ band = register_generated("LffClothBand", band_xml("lff_cloth_band"), free=False)
191
+ objs = [(BOARD, board, "board_region", (0.09, -0.26, 0.11, -0.24)),
192
+ (CUBE, cube, "cube_region", (-0.21, 0.24, -0.19, 0.26))]
193
+ fixtures = [(BAND, band, "band_region", (-0.31, -0.01, -0.29, 0.01))]
194
+ return write_bddl(self.name, "pull the board out from under the cube", objs, fixtures=fixtures)
195
+
196
+ def sample_instance(self, seed):
197
+ rng = np.random.default_rng(seed)
198
+ mu = float(np.exp(rng.uniform(np.log(0.08), np.log(0.15))))
199
+ lo, hi = d_range(mu)
200
+ d = float(rng.uniform(lo, max(lo, hi)))
201
+ return dict(seed=int(seed), board_xy=[float(rng.uniform(0.03, 0.08)), float(rng.uniform(-0.08, 0.08))],
202
+ mu=mu, band_d=d)
203
+
204
+ def cube_start(self, inst):
205
+ bx, by = inst["board_xy"]
206
+ return np.array([bx + B_HALF[0] - LF, by])
207
+
208
+ def band_center(self, inst):
209
+ c = self.cube_start(inst)
210
+ return np.array([c[0] - inst["band_d"], c[1]])
211
+
212
+ def apply_instance(self, inst):
213
+ m = self.env.sim.model
214
+ for g in range(m.ngeom): # the band is a flat marker: no collisions
215
+ if (m.geom_id2name(g) or "").startswith(BAND + "_"):
216
+ m.geom_contype[g] = 0
217
+ m.geom_conaffinity[g] = 0
218
+ bx, by = inst["board_xy"]
219
+ envs.set_obj_pose(self.env, BOARD, [bx, by, envs.TABLE_Z + B_HALF[2] + 0.0005])
220
+ c = self.cube_start(inst)
221
+ envs.set_obj_pose(self.env, CUBE, [c[0], c[1], envs.TABLE_Z + 2 * B_HALF[2] + C_HALF + 0.0005])
222
+ envs.set_friction(self.env, BOARD, MU_BOARD, priority=1)
223
+ envs.set_friction(self.env, CUBE, inst["mu"], priority=2) # cube-board and cube-table contacts use mu
224
+ bid = m.body_name2id(self.env.fixtures_dict[BAND].root_body)
225
+ bc = self.band_center(inst)
226
+ m.body_pos[bid] = [bc[0], bc[1], envs.TABLE_Z + 0.0002]
227
+ m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
228
+
229
+ def reset_instance(self, inst, recorder=None):
230
+ from robosuite.utils.errors import RandomizationError
231
+ for _ in range(20): # LIBERO's reset-time placement sampler occasionally fails; the layout is overridden
232
+ try:
233
+ self.env.reset()
234
+ break
235
+ except RandomizationError:
236
+ continue
237
+ self.apply_instance(inst)
238
+ self.env.sim.forward()
239
+ envs.settle(self.env, 10)
240
+ self.sk = ClothSkills(self.env, bias=self.skill_bias(inst), recorder=recorder)
241
+ return self.sk
242
+
243
+ # ------------------------------------------------------------ outcome
244
+ def cube_on_board(self):
245
+ c = envs.obj_pos(self.env, CUBE)
246
+ b = envs.obj_pos(self.env, BOARD)
247
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, BOARD)].reshape(3, 3)
248
+ local = R.T @ (c - b)
249
+ return bool(abs(local[0]) < B_HALF[0] + 0.005 and abs(local[1]) < B_HALF[1] + 0.005
250
+ and c[2] > envs.TABLE_Z + 2 * B_HALF[2] + C_HALF - 0.004)
251
+
252
+ def outcome(self, inst):
253
+ sk = self.sk
254
+ envs.settle(self.env, 60)
255
+ c = envs.obj_pos(self.env, CUBE)
256
+ c0 = self.cube_start(inst)
257
+ bc = self.band_center(inst)
258
+ moved = float(c0[0] - c[0]) # towards the robot
259
+ off = c[:2] - bc # + x: cube forward (away from the robot) of the band's centre line
260
+ upright = envs.obj_upright_cos(self.env, CUBE) > 0.95
261
+ on_board = self.cube_on_board()
262
+ on_table = c[2] < envs.TABLE_Z + C_HALF + 0.004
263
+ in_band = bool(abs(off[0]) <= TOL and abs(off[1]) <= BAND_HALF_Y - C_HALF)
264
+ pc = sk.pull_check()
265
+ rule = []
266
+ if pc["n_pulls"] > 1:
267
+ rule.append(f"The board was moved by {pc['n_pulls']} separate move commands "
268
+ f"({', '.join(f'{v:.1f}' for v in pc['pulls_cm'])} cm); only one pull is allowed.")
269
+ if pc["n_pulls"] and pc["pre_pull_cube_cm"] > 100 * PRE_TOL:
270
+ rule.append(f"When the pull started the cube had already been moved {pc['pre_pull_cube_cm']:.1f} cm by "
271
+ f"earlier small moves of the board; only one pull is allowed.")
272
+ if pc["stray_cm"] > 100 * STRAY_MAX:
273
+ rule.append(f"Besides the pull, other move commands moved the board {pc['stray_cm']:.1f} cm in total; "
274
+ f"only one pull is allowed.")
275
+ success = bool(in_band and on_table and upright and not on_board and not sk.touched_cube and not rule)
276
+ b_moved = float(np.linalg.norm(envs.obj_pos(self.env, BOARD)[:2] - np.asarray(inst["board_xy"])))
277
+ out = dict(success=success, touched_cube=bool(sk.touched_cube), on_board=on_board, upright=bool(upright),
278
+ moved_toward_robot=round(moved, 4), band_offset_x=round(float(off[0]), 4),
279
+ err=round(float(moved - inst["band_d"]), 4), board_moved=round(b_moved, 4),
280
+ one_pull=not rule, **pc)
281
+ side = ("forward (+x, away from the robot)" if off[0] > 0 else "backward (-x, toward the robot)")
282
+ where = (f"its centre is {100 * abs(off[0]):.1f} cm {side} of the band's centre line"
283
+ if abs(off[0]) >= 0.0005 else "its centre is on the band's centre line")
284
+ if sk.touched_cube:
285
+ out["failure"] = "touched_cube"
286
+ detail = "The robot touched the cube, which is not allowed."
287
+ elif on_board and b_moved < 0.02:
288
+ out["failure"] = "board_not_moved"
289
+ detail = "The board was not pulled; the cube is still standing on it."
290
+ elif on_board:
291
+ out["failure"] = "rode_along"
292
+ detail = (f"The board was pulled {100 * b_moved:.0f} cm, but the cube rode along on it: it is still on the "
293
+ f"board and moved {100 * moved:.1f} cm toward the robot.")
294
+ elif not upright:
295
+ out["failure"] = "toppled"
296
+ detail = f"The board came out from under the cube, but the cube fell over; {where}."
297
+ elif in_band and on_table and upright:
298
+ out["failure"] = None
299
+ detail = (f"The board came out from under the cube and the cube is standing inside the green band; {where}. "
300
+ f"It moved {100 * moved:.1f} cm toward the robot.")
301
+ else:
302
+ out["failure"] = "missed_band"
303
+ detail = (f"The board came out from under the cube and the cube is standing on the table, but not "
304
+ f"completely inside the green band: {where}. It moved {100 * moved:.1f} cm toward the robot.")
305
+ if rule and not sk.touched_cube:
306
+ out["failure"] = "several_pulls"
307
+ detail = " ".join(rule) + " " + detail
308
+ out["detail"] = detail
309
+ out["detail_indirect"] = (detail.replace("board", "plank").replace("cube", "block")
310
+ .replace("green band", "green stripe").replace("band's", "stripe's"))
311
+ return out
312
+
313
+ def feedback(self, inst, out, level="F2", indirect=False):
314
+ if indirect and level == "F2":
315
+ out = dict(out, detail=out.get("detail_indirect", out["detail"]))
316
+ return super().feedback(inst, out, level)
317
+
318
+ # ------------------------------------------------------------ scripted execution (cross protocol)
319
+ def execute(self, inst, params):
320
+ """Grasp the handle (jaws across its 4 cm width) and pull the board STROKE m toward the robot at `speed`."""
321
+ sk = self.sk
322
+ b = envs.obj_pos(self.env, BOARD)
323
+ hx, hy = b[0] - B_HALF[0] + H_HALF[0], b[1]
324
+ zg = envs.TABLE_Z + 2 * B_HALF[2] + H_HALF[2]
325
+ sk.set_gripper(False, steps=5)
326
+ sk.move_to([hx, hy, zg + 0.08], yaw=0.0)
327
+ sk.move_to([hx, hy, zg], tol=0.003)
328
+ sk.set_gripper(True, steps=15)
329
+ sk.move_to([hx - STROKE, hy, zg], speed=float(np.clip(params["speed"], V_MIN, V_MAX)), tol=0.01,
330
+ max_steps=300)
331
+ sk.set_gripper(False, steps=8)
332
+ sk.move_to([hx - STROKE, hy, zg + 0.10], speed=0.3)
333
+
334
+ def default_params(self, inst):
335
+ """Prior: the classic tablecloth trick -- yank as fast as the arm can."""
336
+ return dict(speed=0.60)
337
+
338
+ def blind_params(self, inst, attempt, rng):
339
+ return dict(speed=float(np.clip(0.60 + rng.normal(0, 0.06), V_MIN, V_MAX)))
340
+
341
+ def adapt_params(self, inst, history):
342
+ """Bracketing search on the pull speed with the signed displacement error (riding along = far too much
343
+ displacement). Faster -> less displacement."""
344
+ pts = []
345
+ for h in history:
346
+ o = h["outcome"]
347
+ if o.get("failure") in ("rode_along", "board_not_moved"):
348
+ e = 0.10
349
+ elif o.get("failure") in ("touched_cube", "several_pulls"):
350
+ continue
351
+ else:
352
+ e = o["err"]
353
+ pts.append((h["params"]["speed"], e))
354
+ hi_err = [p for p in pts if p[1] > 0] # moved too much -> needs a faster pull
355
+ lo_err = [p for p in pts if p[1] < 0] # moved too little -> needs a slower pull
356
+ if hi_err and lo_err:
357
+ (v0, e0) = max(hi_err, key=lambda p: p[0]) # fastest pull that still moved it too much
358
+ (v1, e1) = min(lo_err, key=lambda p: p[0]) # slowest pull that moved it too little
359
+ if e0 >= 0.05: # rode along: no usable slope -> bisect
360
+ v = 0.5 * (v0 + v1)
361
+ else:
362
+ v = v0 + (v1 - v0) * e0 / (e0 - e1)
363
+ elif hi_err:
364
+ v = max(p[0] for p in hi_err) * 1.25
365
+ else:
366
+ v = min(p[0] for p in lo_err) * 0.8
367
+ return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
368
+
369
+ def oracle_params(self, inst):
370
+ """Privileged: bisection on the speed by simulating pulls with the true mu."""
371
+ if "_oracle_speed" in inst:
372
+ return dict(speed=inst["_oracle_speed"])
373
+ lo, hi = V_MIN, V_MAX
374
+ best = None
375
+ for _ in range(10):
376
+ mid = 0.5 * (lo + hi)
377
+ self.reset_instance(inst)
378
+ self.execute(inst, dict(speed=mid))
379
+ o = self.outcome(inst)
380
+ e = 0.10 if o["failure"] in ("rode_along", "board_not_moved") else o["err"]
381
+ if o["success"]:
382
+ best = (mid, e)
383
+ break
384
+ if best is None or abs(e) < abs(best[1]):
385
+ best = (mid, e)
386
+ if e > 0:
387
+ lo = mid
388
+ else:
389
+ hi = mid
390
+ inst["_oracle_speed"] = best[0]
391
+ self.reset_instance(inst)
392
+ return dict(speed=best[0])
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_bystander.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH bystander: put three cubes into an open box while a tall glass bottle that is not part of the task stands right
2
+ in front of the box -- lowering a cube into the box, the robot's own forearm comes down onto the bottle and knocks it
3
+ over.
4
+
5
+ Family: long-horizon self-disturbance, environment level ("state_restoration"; LIBERO-Recover's damage category L4: the
6
+ damaged thing is not part of the task). Three easy pick-and-place stages; the instruction says plainly that nothing
7
+ else may be moved and that the bottle must be left standing where it is. The agent has to notice the fallen bottle and
8
+ stand it up again on its spot before finishing (within an attempt), or learn to keep its arm off the bottle (across
9
+ attempts).
10
+
11
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
12
+ * an open wooden box (fixture): cavity 14 x 14 cm, walls 6 cm high (rim 6.6 cm above the table), 0.8 cm thick;
13
+ centre x in [0.00, 0.04], 6-10 cm left or right of the middle;
14
+ * three 4 cm cubes (red / yellow / blue, 32 g) in a row beside the box on the other side (19-23 cm from the middle,
15
+ from 10 cm behind to 2 cm in front of the box centre, shuffled, yaw +-17 deg), so that a straight carry to the box
16
+ never passes over the bottle;
17
+ * the bystander: a square green glass bottle with a label and a round red cap, 28.4 cm tall (body 6 x 6 x 18.5 cm,
18
+ shoulder, neck, cap; a rounded base whose flat contact is 3.6 x 3.6 cm), 0.25 kg, centre of mass 12 cm up (an empty
19
+ bottle: it tips beyond 8.5 deg; pressed down on its cap, beyond 3.7 deg).
20
+
21
+ Instance variable (where the bottle stands): "hazard" (15 of every 20 consecutive seeds): right in front of the box,
22
+ between the box and the robot, 1.0-2.5 cm from its front wall, 1 cm right to 4 cm left of its centre line; "benign":
23
+ beside the box on its outer side, 8-11 cm from the wall. Both look like "a bottle standing next to the box"; nothing in
24
+ the physics is hidden. What the agent cannot see before acting is its own arm: the wrist camera shows the fingers, not
25
+ the forearm, and the agent steers the grasp point.
26
+
27
+ Disturbance (physics, no teleport): lowering a cube onto the box floor (grasp point ~4 cm above the table), the
28
+ fingers and the cube stay 3-5 cm clear of the bottle (the box's front wall is between them), but the Panda's forearm
29
+ and wrist (links 5-7) slope back from the hand towards the robot base, starting ~12 cm above the grasp point; over the
30
+ space in front of the box they come down to 15-20 cm above the table, onto the upper part of a 28 cm bottle standing
31
+ there. The bottle is pushed over (mostly
32
+ towards the robot) and lies on the table in front of the box; visible in agentview once the arm has moved away
33
+ (measured, task card). Not every contact knocks it: a descent can come to rest on the cap (pinched between links 5
34
+ and 6, pressed down like a column), the arm stalls 4-6 cm short of its target and the bottle rocks back when the arm
35
+ lifts (measured: the smoke-test sequence on seed 3000; 6-7 of 8 hazard seeds still knocked with slow or near-first
36
+ descents, see the task card). The hit is yaw-independent (hit maps at yaw 0 / 45 / 90 deg) and not caused by the hand's
37
+ width. Transits at the agent's usual 11-20 cm mostly pass (the wrist end of the forearm is ~27 cm up at a 15 cm
38
+ transit). A careful packer keeps its arm above the bottle: carry at >= 24 cm and release the cube from >= 18 cm
39
+ (dropping it into the box) -- or moves the bottle out of the way and back, which the final-state judge would accept
40
+ but the instruction rules out.
41
+
42
+ Restoring (re-standable by a top-down gripper that only turns about the vertical): the body is square (a lying bottle
43
+ does not roll away from the closing fingers) and the cap is a ball with low torsional friction: grasped from above with
44
+ the fingers across the lying bottle's axis, the cap turns between the fingers, the lifted bottle swings down and hangs
45
+ straight; lowered onto the table it stands (measured: placement error ~1 mm). The instruction tells the agent that the
46
+ bottle hangs straight down when held by its cap (as lh_fence does for its knobs).
47
+
48
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (every cube in the
49
+ box -- footprint inside the cavity, top below the rim, not held --, the bottle upright within 10 deg and its base
50
+ within 2 cm of where it stood, nothing held or touched, scene static) plus a per-step event log for the server log:
51
+ cube stages achieved / lost / restored; bottle_in_place lost / restored (with cause: arm / hand / cube, the robot geom,
52
+ the grasp point) plus the marker events bystander_knocked / bystander_restored / fallen. F1 gives the agent only
53
+ success / failure.
54
+ """
55
+ import numpy as np
56
+
57
+ from .. import envs
58
+ from ..bddl import write_bddl
59
+ from ..objects import _SOLID, _fmt, _wrap, box_xml, register_generated
60
+ from ..skills import Skills
61
+ from ..task_base import LFFTask, register_task
62
+
63
+ Z = envs.TABLE_Z
64
+ # ---------------------------------------------------------------- geometry / physics
65
+ BOX = "box_1"
66
+ BOX_MODEL = "lff_lhb_box"
67
+ BOX_IN = 0.070 # cavity half width (14 x 14 cm)
68
+ WALL_T, FLOOR_T, WALL_H = 0.008, 0.006, 0.060
69
+ BOX_OUT = BOX_IN + WALL_T
70
+ RIM = FLOOR_T + WALL_H # rim height above the table
71
+ WOOD = (0.62, 0.45, 0.28, 1.0)
72
+
73
+ CUBES = ("red_cube_1", "yellow_cube_1", "blue_cube_1")
74
+ CUBE_COLOR = {"red_cube_1": "red", "yellow_cube_1": "yellow", "blue_cube_1": "blue"}
75
+ CUBE_RGBA = dict(red=(0.85, 0.10, 0.08, 1.0), yellow=(0.92, 0.76, 0.10, 1.0), blue=(0.15, 0.30, 0.85, 1.0))
76
+ CUBE_E = 0.040
77
+ CUBE_DENS = 500.0 # 32 g
78
+ CUBE_MU = 0.8
79
+
80
+ BOTTLE = "bottle_1"
81
+ BOTTLE_MODEL = "lff_lhb_bottle"
82
+ BOTTLE_CLASS = "LffLhbBottle"
83
+ RB, HB = 0.030, 0.185 # square body: half width, height
84
+ RF, HF = 0.018, 0.006 # foot: a rounded glass base whose flat contact is 3.6 x 3.6 cm (0.6 cm high inset). With the
85
+ # 4.8 cm foot of the draft the forearm could come to rest on the cap and stall instead of
86
+ # knocking it (bottle pressed down like a column, tilt <= 5 deg; measured, see the task card)
87
+ RS, HS = 0.022, 0.015 # shoulder
88
+ RN, HN = 0.0115, 0.060 # neck
89
+ RK = 0.015 # ball cap radius; its centre sits RK - 6 mm above the neck top
90
+ CAP_SINK = 0.006
91
+ H_TOT = HB + HS + HN + 2 * RK - CAP_SINK # 0.284
92
+ CAP_Z = H_TOT - RK # cap centre above the bottle's bottom when standing
93
+ BOTTLE_MASS = 0.25
94
+ BOTTLE_COM = 0.12 # above the bottom (an empty glass bottle: ~42 % of its height)
95
+ BOTTLE_MU = 0.6
96
+ CAP_MU_T = 0.0005 # torsional friction of the cap (condim 4): the grasped cap turns freely, the swing is damped
97
+ GLASS = (0.16, 0.42, 0.26, 1.0)
98
+ CAP_RGBA = (0.78, 0.12, 0.10, 1.0)
99
+
100
+ # instances
101
+ P_HAZARD = 0.75 # 15 of every 20 consecutive seeds: bottle in front of the box
102
+ HAZ_GAP = (0.010, 0.025) # bottle body to the box's front wall
103
+ HAZ_LAT = (-0.010, 0.040) # bottle centre left (+y) of the box's centre line
104
+ BEN_GAP = (0.080, 0.110) # beside the box, on its outer side (away from the cubes)
105
+ BEN_DX = (-0.030, 0.030)
106
+ BOX_X = (0.0, 0.04) # the bottle in front of the box stays >= 2 cm clear of the fingers in the home pose
107
+ BOX_Y = (0.06, 0.10) # |y| of the box centre; the side is random
108
+ CUBE_Y = (0.19, 0.23) # |y| of the cube row (other side)
109
+ CUBE_DX = (-0.10, -0.04, 0.02) # cube row beside the box (x relative to the box centre; the Panda reaches ~0.8 m):
110
+ # the straight carry to the box passes >= 2 cm from the bottle in front of it
111
+
112
+ # success predicate
113
+ POS_TOL = 0.020 # bottle base within 2 cm of where it stood
114
+ UPRIGHT = np.radians(10.0)
115
+ KNOCK_TILT = np.radians(10.0) # once in place, the bottle counts as disturbed when tilted beyond this (it tips at
116
+ # 8.5 deg: beyond, it is falling or leaning on something) or moved
117
+ POS_HYST = 0.003 # > POS_TOL + POS_HYST for DEBOUNCE checks (a nudge that rocks back within 0.6 s is no loss)
118
+ FALLEN = np.radians(60.0)
119
+ IN_TOL = 0.002 # a cube's footprint may reach this far past the inner walls
120
+ RIM_TOL = 0.004
121
+ BELOW_RIM = 0.010 # in_box: the cube's lowest point at least this far below the rim
122
+ DEBOUNCE = 6 # predicate checks (every 0.1 s) a change must persist
123
+
124
+ # scripted motion (heights of the grasp point above the table)
125
+ Z_CARRY = 0.15 # Sonnet's transit: 11-20 cm, often lifted to ~20 before moving
126
+ Z_REL = 0.040 # Sonnet-like release: cube set down on the box floor (grasp point 4 cm up)
127
+ Z_SAFE = 0.26 # careful transit
128
+ Z_DROP = 0.19 # careful release: the cube is dropped from above the rim, the forearm stays above the bottle
129
+ NAIVE_ERR = 0.008 # Sonnet's placement error 0.4-1.3 cm
130
+ SLOT = 0.033 # slot offset from the box centre (cavity 14 cm, cubes 4 cm)
131
+
132
+
133
+ def bottle_xml(name):
134
+ h = H_TOT / 2
135
+ zf, zb, zs, zn = -h + HF / 2, -h + HF + (HB - HF) / 2, -h + HB + HS / 2, -h + HB + HS + HN / 2
136
+ zk = -h + HB + HS + HN + RK - CAP_SINK
137
+ m = BOTTLE_MASS
138
+ ixx = m * ((2 * RB) ** 2 + H_TOT ** 2) / 16 # rough: most of the glass is in the body and the base
139
+ izz = m * (2 * (2 * RB) ** 2) / 12
140
+ parts = [("foot", "box", (0, 0, zf), (RF, RF, HF / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
141
+ ("body", "box", (0, 0, zb), (RB, RB, (HB - HF) / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
142
+ ("shoulder", "box", (0, 0, zs), (RS, RS, HS / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
143
+ ("neck", "cylinder", (0, 0, zn), (RN, HN / 2), GLASS, f'friction="{BOTTLE_MU} 0.005 0.0001"'),
144
+ ("cap", "sphere", (0, 0, zk), (RK,), CAP_RGBA, f'friction="1 {CAP_MU_T} 0.0001" condim="4" priority="2"')]
145
+ s = [f' <inertial pos="0 0 {-h + BOTTLE_COM:.4f}" mass="{m}" diaginertia="{ixx:.6f} {ixx:.6f} {izz:.6f}" />']
146
+ for nm, typ, pos, size, c, extra in parts:
147
+ s.append(f' <geom name="{name}_{nm}" type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" '
148
+ f'{extra} group="0" />')
149
+ s.append(f' <geom type="{typ}" pos="{_fmt(pos)}" size="{_fmt(size)}" rgba="{_fmt(c)}" contype="0" '
150
+ f'conaffinity="0" group="1" />')
151
+ # a lighter label band (visual only) so the bottle reads as a bottle
152
+ s.append(f' <geom type="box" pos="0 0 {zb + 0.01:.4f}" size="{RB + 0.0008:.4f} {RB + 0.0008:.4f} 0.035" '
153
+ f'rgba="0.92 0.90 0.80 1" contype="0" conaffinity="0" group="1" />')
154
+ return _wrap(name, "\n".join(s), h, RB * 1.42)
155
+
156
+
157
+ def box_fixture_xml(name):
158
+ """open wooden box, origin at the centre of its footprint, z = 0 at the table"""
159
+ ix = BOX_IN
160
+ parts = [((0, 0, FLOOR_T / 2), (BOX_OUT, BOX_OUT, FLOOR_T / 2)),
161
+ ((ix + WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
162
+ ((-ix - WALL_T / 2, 0, RIM / 2), (WALL_T / 2, BOX_OUT, RIM / 2)),
163
+ ((0, ix + WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2)),
164
+ ((0, -ix - WALL_T / 2, RIM / 2), (ix, WALL_T / 2, RIM / 2))]
165
+ g = []
166
+ for k, (p, sz) in enumerate(parts):
167
+ g.append(f' <geom name="{name}_w{k}" type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" '
168
+ f'friction="0.8 0.005 0.0001" {_SOLID} group="0" />')
169
+ g.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(WOOD)}" contype="0" '
170
+ f'conaffinity="0" group="1" />')
171
+ return f"""<mujoco model="{name}">
172
+ <worldbody>
173
+ <body>
174
+ <body name="object">
175
+ {chr(10).join(g)}
176
+ </body>
177
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
178
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {RIM:.4f}" name="top_site" />
179
+ <site rgba="0 0 0 0" size="0.005" pos="{BOX_OUT:.4f} {BOX_OUT:.4f} 0" name="horizontal_radius_site" />
180
+ </body>
181
+ </worldbody>
182
+ </mujoco>"""
183
+
184
+
185
+ REACH_MAX = 0.74 # scripted policies: farthest grasp point (horizontal distance from the robot base) they rely on
186
+
187
+
188
+ def _reach(p):
189
+ return float(np.hypot(p[0] + 0.66, p[1]))
190
+
191
+
192
+ def _fb(v):
193
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
194
+
195
+
196
+ def _lr(v):
197
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
198
+
199
+
200
+ class BystanderSkills(Skills):
201
+ """Skills that feed the task's per-step monitor."""
202
+
203
+ def __init__(self, env, task, recorder=None):
204
+ super().__init__(env, recorder=recorder)
205
+ self.task = task
206
+
207
+ def _act(self, dpos, drot, grip):
208
+ super()._act(dpos, drot, grip)
209
+ self.task.monitor_step()
210
+
211
+
212
+ @register_task
213
+ class Bystander(LFFTask):
214
+ name = "lh_bystander"
215
+ level = "L2"
216
+ category = "state_restoration"
217
+ capabilities = ("Perceive", "Reason", "Restore", "Plan")
218
+ protocol = "cross"
219
+ max_attempts = 3
220
+ agent_max_steps = 100 # careful: 3 cubes x ~7 commands + looking; standing the bottle up again ~8-10; + slack
221
+ instruction = ("Put the red, yellow and blue cubes into the open wooden box. Do not move anything else: the tall "
222
+ "glass bottle must be left standing upright exactly where it is now. (The bottle has a round red "
223
+ "cap; held by its cap, the bottle hangs straight down.)")
224
+ instruction_indirect = ("Pack the three small cubes (red, yellow, blue) into the wooden crate. Leave everything else "
225
+ "as it is -- the tall green bottle has to stay standing on its spot. (Its round red cap: held "
226
+ "by the cap, the bottle hangs straight down.)")
227
+ agent_object_names = ["red cube", "yellow cube", "blue cube", "open wooden box",
228
+ "tall glass bottle (square, with a round red cap; held by its cap it hangs straight down)"]
229
+
230
+ # ------------------------------------------------------------ scene
231
+ def make_bddl(self):
232
+ box = register_generated("LffLhbBox", box_fixture_xml(BOX_MODEL), free=False)
233
+ objs = []
234
+ for i, n in enumerate(CUBES):
235
+ c = CUBE_COLOR[n]
236
+ cat = register_generated(f"LffLhbCube{c.title()}",
237
+ box_xml(f"lff_lhb_cube_{c}", (CUBE_E / 2,) * 3, CUBE_RGBA[c], density=CUBE_DENS,
238
+ friction=(CUBE_MU, 0.005, 0.0001)).replace(_SOLID, ""))
239
+ objs.append((n, cat, f"{c}_cube_region", (-0.35, -0.25 + 0.15 * i, -0.33, -0.23 + 0.15 * i)))
240
+ bt = register_generated(BOTTLE_CLASS, bottle_xml(BOTTLE_MODEL))
241
+ objs.append((BOTTLE, bt, "bottle_region", (-0.35, 0.24, -0.33, 0.26)))
242
+ fx = [(BOX, box, "box_region", (-0.06, -0.01, -0.04, 0.01))]
243
+ return write_bddl(self.name, "put the cubes into the box and leave the bottle where it is", objs, fx)
244
+
245
+ def __init__(self, cam_res=None):
246
+ super().__init__(cam_res)
247
+ m = self.env.sim.model
248
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
249
+ self.box_gids = {g for g in range(m.ngeom) if m.geom_bodyid[g] in
250
+ {self.box_bid} | {c for c in range(m.nbody) if m.body_parentid[c] == self.box_bid}}
251
+ pre = f"{BOTTLE}_{BOTTLE_MODEL}"
252
+ self.cap_gid = m.geom_name2id(pre + "_cap")
253
+ self.bottle_gids = set(envs.obj_geom_ids(self.env, BOTTLE))
254
+ self.cube_gids = {n: set(envs.obj_geom_ids(self.env, n)) for n in CUBES}
255
+ # robot parts: 1 = hand / fingers (what the agent sees and steers), 2 = arm links (wrist, forearm, ...)
256
+ self.part = np.zeros(m.ngeom, int)
257
+ for g in envs.robot_geom_ids(self.env):
258
+ n = m.geom_id2name(g) or ""
259
+ self.part[g] = 1 if n.startswith("gripper0_") else 2
260
+ self.other = np.zeros(m.ngeom, int) # 3 = a cube, 4 = the box
261
+ for n in CUBES:
262
+ self.other[list(self.cube_gids[n])] = 3
263
+ self.other[list(self.box_gids)] = 4
264
+ self.is_bottle = np.zeros(m.ngeom, bool)
265
+ self.is_bottle[list(self.bottle_gids)] = True
266
+ # bottle contacts are collected after every MuJoCo substep (a fast hit can be shorter than a control step)
267
+ sim = self.env.sim
268
+ if not getattr(sim, "_lhb_wrapped", False):
269
+ orig = sim.step
270
+
271
+ def step(*a, **k):
272
+ orig(*a, **k)
273
+ t = getattr(sim, "_lhb_task", None)
274
+ if t is not None and t.mon is not None:
275
+ t._substep()
276
+ sim.step = step
277
+ sim._lhb_wrapped = True
278
+ sim._lhb_task = self
279
+ self._sub = {}
280
+ self.inst = None
281
+ self.mon = None
282
+ self.sk = None
283
+
284
+ def sample_instance(self, seed):
285
+ rng = np.random.default_rng(seed)
286
+ s = 1.0 if rng.random() < 0.5 else -1.0 # box on the left (+1) or right (-1)
287
+ bx, by = float(rng.uniform(*BOX_X)), s * float(rng.uniform(*BOX_Y))
288
+ # balanced blocks like lh_lid_box: exactly round(20 * P_HAZARD) of every 20 consecutive seeds are hazards
289
+ hazard = bool((int(seed) * 7) % 20 < round(20 * P_HAZARD))
290
+ if hazard:
291
+ gap, lat = float(rng.uniform(*HAZ_GAP)), float(rng.uniform(*HAZ_LAT))
292
+ bottle = [bx - BOX_OUT - gap - RB, by + lat]
293
+ else:
294
+ gap, lat = float(rng.uniform(*BEN_GAP)), float(rng.uniform(*BEN_DX))
295
+ bottle = [bx + lat, by + s * (BOX_OUT + gap + RB)]
296
+ cy = -s * float(rng.uniform(*CUBE_Y))
297
+ perm = rng.permutation(len(CUBES))
298
+ start = {CUBES[i]: [float(bx + CUBE_DX[j] + rng.uniform(-0.01, 0.01)), float(cy + rng.uniform(-0.01, 0.01))]
299
+ for j, i in enumerate(perm)}
300
+ start_yaw = {n: float(rng.uniform(-0.3, 0.3)) for n in CUBES}
301
+ return dict(seed=int(seed), hazard=hazard, bottle_side="front" if hazard else "outer side",
302
+ box_side="left" if s > 0 else "right", box_xy=[bx, by], bottle_xy=[float(bottle[0]), float(bottle[1])],
303
+ bottle_yaw=float(rng.uniform(-0.25, 0.25)), gap=gap, lat=lat, start=start, start_yaw=start_yaw)
304
+
305
+ def apply_instance(self, inst):
306
+ self.inst = inst
307
+ m = self.env.sim.model
308
+ bx, by = inst["box_xy"]
309
+ m.body_pos[self.box_bid] = [bx, by, Z]
310
+ m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
311
+ for n, xy in inst["start"].items():
312
+ envs.place_upright(self.env, n, xy, yaw=inst["start_yaw"][n], clearance=0.001)
313
+ envs.set_friction(self.env, n, CUBE_MU)
314
+ envs.place_upright(self.env, BOTTLE, inst["bottle_xy"], yaw=inst["bottle_yaw"], clearance=0.001)
315
+
316
+ def reset_instance(self, inst, recorder=None):
317
+ self.mon = None
318
+ self.env.reset()
319
+ self.apply_instance(inst)
320
+ self.env.sim.forward()
321
+ envs.settle(self.env, 15)
322
+ self.sk = BystanderSkills(self.env, self, recorder=recorder)
323
+ self._sub = {}
324
+ self._init_monitor()
325
+ return self.sk
326
+
327
+ # ------------------------------------------------------------ state helpers
328
+ def R(self, name):
329
+ return self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3).copy()
330
+
331
+ def bottle_tilt(self):
332
+ return float(np.arccos(np.clip(self.R(BOTTLE)[2, 2], -1.0, 1.0)))
333
+
334
+ def bottle_base(self):
335
+ """xy of the centre of the bottle's bottom face"""
336
+ d = self.env.sim.data
337
+ return (envs.obj_pos(self.env, BOTTLE) - self.R(BOTTLE)[:, 2] * H_TOT / 2)[:2]
338
+
339
+ def bottle_offset(self):
340
+ return self.bottle_base() - np.asarray(self.inst["bottle_xy"])
341
+
342
+ def cap_xyz(self):
343
+ return self.env.sim.data.geom_xpos[self.cap_gid].copy()
344
+
345
+ def held(self, name):
346
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
347
+
348
+ def bottle_in_place(self, tol=POS_TOL, tilt=UPRIGHT):
349
+ return bool(self.bottle_tilt() <= tilt and np.linalg.norm(self.bottle_offset()) <= tol
350
+ and envs.obj_min_z(self.env, BOTTLE) < Z + 0.01 and not self.held(BOTTLE))
351
+
352
+ def to_box(self, xy):
353
+ return np.asarray(xy, float)[:2] - np.asarray(self.inst["box_xy"])
354
+
355
+ def in_box(self, name):
356
+ m, d = self.env.sim.model, self.env.sim.data
357
+ g = next(iter(self.cube_gids[name]))
358
+ Rg = d.geom_xmat[g].reshape(3, 3)
359
+ c = self.to_box(d.geom_xpos[g][:2])
360
+ ext = np.abs(Rg[:2, :]) @ m.geom_size[g][:3]
361
+ # 10-14: "in the box" = footprint inside the cavity and the cube's lowest point well below the rim (it is held
362
+ # by the walls); a cube stacked on another one may stick out above the rim -- the instruction never asks for
363
+ # "below the rim" (two Sonnet pilot attempts that stacked the last cube were judged failures before this)
364
+ return bool(np.all(np.abs(c) + ext <= BOX_IN + IN_TOL) and envs.obj_min_z(self.env, name) <= Z + RIM - BELOW_RIM
365
+ and not self.held(name))
366
+
367
+ def over_box(self, name):
368
+ c = self.to_box(envs.obj_pos(self.env, name)[:2])
369
+ return bool(np.all(np.abs(c) <= BOX_OUT))
370
+
371
+ def stage_values(self):
372
+ v = {f"{CUBE_COLOR[n]}_in_box": self.in_box(n) for n in CUBES}
373
+ v["bottle_in_place"] = self.bottle_in_place()
374
+ return v
375
+
376
+ # ------------------------------------------------------------ per-step monitor
377
+ def _init_monitor(self):
378
+ keys = [f"{CUBE_COLOR[n]}_in_box" for n in CUBES] + ["bottle_in_place"]
379
+ st = {k: False for k in keys}
380
+ st["bottle_in_place"] = self.bottle_in_place()
381
+ self.mon = dict(state=st, ever=[k for k in keys if st[k]], lost=[], events=[], cand={k: 0 for k in keys},
382
+ step=0, last_touch=None, robot_touch_step=-10 ** 9, touch_parts=[], n_knocks=0, n_fallen=0,
383
+ fallen=False,
384
+ max_tilt_deg=0.0, max_offset_cm=0.0, first_knock_step=None, first_touch_step=None)
385
+
386
+ def _substep(self):
387
+ d = self.env.sim.data
388
+ n = d.ncon
389
+ if not n:
390
+ return
391
+ g1 = np.asarray(d.contact.geom1)[:n]
392
+ g2 = np.asarray(d.contact.geom2)[:n]
393
+ b1, b2 = self.is_bottle[g1], self.is_bottle[g2]
394
+ sel = b1 ^ b2
395
+ if not sel.any():
396
+ return
397
+ other = np.where(b1, g2, g1)[sel]
398
+ for o in other:
399
+ p = int(self.part[o])
400
+ if p:
401
+ who = "hand" if p == 1 else "arm"
402
+ prev = self._sub.get("robot")
403
+ self._sub["robot"] = "arm" if (who == "arm" or prev == "arm") else "hand"
404
+ self._sub.setdefault("geom", self.env.sim.model.geom_id2name(int(o)))
405
+ elif self.other[o] == 3:
406
+ self._sub["cube"] = True
407
+
408
+ def monitor_step(self):
409
+ mon = self.mon
410
+ if mon is None:
411
+ return
412
+ mon["step"] += 1
413
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
414
+ sub, self._sub = self._sub, {}
415
+ if "robot" in sub:
416
+ mon["robot_touch_step"] = step
417
+ mon["last_touch"] = [sub["robot"], step, sub.get("geom", "")]
418
+ if sub["robot"] not in mon["touch_parts"]:
419
+ mon["touch_parts"].append(sub["robot"])
420
+ if mon["first_touch_step"] is None:
421
+ mon["first_touch_step"] = step
422
+ elif sub.get("cube") and (mon["last_touch"] is None or step - mon["last_touch"][1] > 20):
423
+ mon["last_touch"] = ["cube", step, ""]
424
+ tilt = self.bottle_tilt()
425
+ mon["max_tilt_deg"] = round(max(mon["max_tilt_deg"], float(np.degrees(tilt))), 1)
426
+ mon["max_offset_cm"] = round(max(mon["max_offset_cm"], 100 * float(np.linalg.norm(self.bottle_offset()))), 1)
427
+ if mon["step"] % 2:
428
+ return # predicates every other control step (0.1 s)
429
+ if not mon["fallen"] and tilt > FALLEN and not self.held(BOTTLE):
430
+ mon["fallen"] = True
431
+ mon["n_fallen"] += 1
432
+ mon["events"].append(dict(step=step, pred="bottle", ev="fallen", cause=self._cause(step)))
433
+ elif mon["fallen"] and tilt < UPRIGHT:
434
+ mon["fallen"] = False
435
+ for n in CUBES:
436
+ self._check(f"{CUBE_COLOR[n]}_in_box", self.in_box(n), step, n)
437
+ st = mon["state"]["bottle_in_place"]
438
+ # hysteresis: once in place it counts as lost only beyond 2.3 cm / 10 deg, held for 0.6 s (a nudge that rocks
439
+ # back is no loss)
440
+ now = self.bottle_in_place(POS_TOL + POS_HYST, KNOCK_TILT) if st else self.bottle_in_place()
441
+ self._check("bottle_in_place", now, step, BOTTLE)
442
+
443
+ def _cause(self, step):
444
+ lt = self.mon["last_touch"]
445
+ if lt is not None and step - lt[1] <= 60:
446
+ return lt[0]
447
+ return "other"
448
+
449
+ def _check(self, key, now, step, name):
450
+ mon = self.mon
451
+ if now == mon["state"][key]:
452
+ mon["cand"][key] = 0
453
+ return
454
+ if name == BOTTLE and not now and step - mon["robot_touch_step"] <= 6 and not self.held(BOTTLE):
455
+ # the arm is still pressing on the bottle (measured: a slow descent can come to rest on its cap and stall,
456
+ # tilting it ~12 deg; it rocks back when the arm lifts): a loss only once the robot has let go of it
457
+ mon["cand"][key] = 0
458
+ return
459
+ mon["cand"][key] += 1
460
+ if mon["cand"][key] < DEBOUNCE:
461
+ return
462
+ mon["cand"][key] = 0
463
+ mon["state"][key] = now
464
+ if now:
465
+ restored = key in mon["lost"]
466
+ ev = "restored" if restored else "achieved"
467
+ if key not in mon["ever"]:
468
+ mon["ever"].append(key)
469
+ if restored:
470
+ mon["lost"].remove(key)
471
+ mon["events"].append(dict(step=step, pred=key, ev=ev))
472
+ if key == "bottle_in_place" and restored:
473
+ mon["events"].append(dict(step=step, pred="bottle", ev="bystander_restored",
474
+ offset_cm=(100 * self.bottle_offset()).round(1).tolist()))
475
+ return
476
+ if key not in mon["ever"]:
477
+ return
478
+ cause = "picked_up" if self.held(name) else self._cause(step)
479
+ if key not in mon["lost"]:
480
+ mon["lost"].append(key)
481
+ e = dict(step=step, pred=key, ev="lost", cause=cause)
482
+ if name == BOTTLE:
483
+ ee = self.sk.eef_pos() if self.sk is not None else np.zeros(3)
484
+ e["eef_cm"] = [round(100 * float(v), 1) for v in (ee[0] - self.inst["box_xy"][0], ee[1] - self.inst["box_xy"][1],
485
+ ee[2] - Z)] # grasp point rel. to the box centre / table
486
+ e.update(tilt_deg=round(float(np.degrees(self.bottle_tilt())), 1),
487
+ offset_cm=(100 * self.bottle_offset()).round(1).tolist())
488
+ if mon["last_touch"] is not None and mon["last_touch"][0] in ("arm", "hand"):
489
+ e["robot_geom"] = mon["last_touch"][2]
490
+ mon["events"].append(e)
491
+ if name == BOTTLE and cause != "picked_up":
492
+ mon["n_knocks"] += 1
493
+ if mon["first_knock_step"] is None:
494
+ mon["first_knock_step"] = step
495
+ mon["events"].append(dict(step=step, pred="bottle", ev="bystander_knocked", cause=cause,
496
+ robot_geom=e.get("robot_geom", ""), tilt_deg=e["tilt_deg"],
497
+ offset_cm=e["offset_cm"], eef_cm=e["eef_cm"]))
498
+
499
+ # ------------------------------------------------------------ outcome
500
+ def _static(self):
501
+ d = self.env.sim.data
502
+ for n in CUBES + (BOTTLE,):
503
+ _, da = envs.free_joint_addr(self.env, n)
504
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
505
+ return False
506
+ return True
507
+
508
+ def robot_touching(self):
509
+ d = self.env.sim.data
510
+ out = []
511
+ for i in range(d.ncon):
512
+ c = d.contact[i]
513
+ for a, b in ((c.geom1, c.geom2), (c.geom2, c.geom1)):
514
+ if self.part[a] and (self.is_bottle[b] or self.other[b] == 3):
515
+ nm = "bottle" if self.is_bottle[b] else "a cube"
516
+ if nm not in out:
517
+ out.append(nm)
518
+ return out
519
+
520
+ def outcome(self, inst):
521
+ envs.settle(self.env, 30)
522
+ mon = self.mon
523
+ vals = self.stage_values()
524
+ static = self._static()
525
+ held = [n for n in CUBES + (BOTTLE,) if self.held(n)]
526
+ touching = self.robot_touching()
527
+ success = bool(all(vals.values()) and static and not held and not touching)
528
+ evs = mon["events"]
529
+ regress = [e for e in evs if e["ev"] == "lost"]
530
+ restored = [e for e in evs if e["ev"] == "restored"]
531
+ knocks = [e for e in evs if e["ev"] == "bystander_knocked"]
532
+ # trap fired: a knock was logged, or the bottle ends up out of place after the robot touched it (a slow push
533
+ # to just over 2 cm can stay inside the monitor's hysteresis band)
534
+ trap_fired = bool(knocks) or (not vals["bottle_in_place"] and not self.held(BOTTLE) and bool(mon["touch_parts"]))
535
+ recovered = bool(trap_fired and vals["bottle_in_place"])
536
+ off = self.bottle_offset()
537
+ tilt = float(np.degrees(self.bottle_tilt()))
538
+ parts = []
539
+ failure = None
540
+ if success:
541
+ parts.append("All three cubes are in the box and the bottle stands where it stood.")
542
+ else:
543
+ out_cubes = [n for n in CUBES if not vals[f"{CUBE_COLOR[n]}_in_box"]]
544
+ if not vals["bottle_in_place"]:
545
+ failure = ("bystander_held" if self.held(BOTTLE) else
546
+ "bystander_knocked" if tilt > np.degrees(UPRIGHT) else "bystander_moved")
547
+ elif held:
548
+ failure = "held"
549
+ elif out_cubes:
550
+ failure = "cube_not_in_box"
551
+ elif touching:
552
+ failure = "robot_touching"
553
+ else:
554
+ failure = "not_static"
555
+ if not vals["bottle_in_place"]:
556
+ if self.held(BOTTLE):
557
+ parts.append("The bottle is still held by the gripper.")
558
+ else:
559
+ pose = ("is lying on its side" if tilt > 60 else f"is tilted {tilt:.0f} degrees" if tilt > np.degrees(UPRIGHT)
560
+ else "stands upright")
561
+ txt = f"The bottle {pose}; its base is {_fb(off[0])} and {_lr(off[1])} of where it stood"
562
+ if knocks:
563
+ k = knocks[0]
564
+ who = {"arm": "the robot's arm (above the gripper)", "hand": "the gripper",
565
+ "cube": "a cube"}.get(k["cause"], "something")
566
+ txt += f" (it was knocked by {who}"
567
+ txt += " and stood up again later, but not back in place)." if restored and any(
568
+ e["pred"] == "bottle_in_place" for e in restored) else ")."
569
+ else:
570
+ txt += "."
571
+ parts.append(txt)
572
+ for n in out_cubes:
573
+ c = CUBE_COLOR[n]
574
+ if self.held(n):
575
+ parts.append(f"The {c} cube is still held by the gripper.")
576
+ elif self.over_box(n):
577
+ parts.append(f"The {c} cube rests on the box's rim instead of inside the box.")
578
+ else:
579
+ rel = self.to_box(envs.obj_pos(self.env, n)[:2])
580
+ parts.append(f"The {c} cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the "
581
+ f"box's centre.")
582
+ if touching and all(vals.values()):
583
+ parts.append("The robot was still touching " + " and ".join(touching) + " at the end.")
584
+ if not static and all(vals.values()):
585
+ parts.append("Something was still moving at the end.")
586
+ if trap_fired and vals["bottle_in_place"]:
587
+ parts.append(f"(The bottle was knocked out of place {len(knocks)} time(s) during the attempt and put back.)")
588
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held, touching=touching,
589
+ events=evs, n_regressions=len(regress), n_restored=len(restored), trap_fired=trap_fired,
590
+ recovered_in_attempt=recovered, n_knocks=len(knocks), n_fallen=mon["n_fallen"],
591
+ knock_causes=[k["cause"] for k in knocks], first_knock_step=mon["first_knock_step"],
592
+ bottle_touch_parts=list(mon["touch_parts"]), bottle_max_tilt_deg=mon["max_tilt_deg"],
593
+ bottle_max_offset_cm=mon["max_offset_cm"], bottle_tilt_deg=round(tilt, 1),
594
+ bottle_offset_cm=(100 * off).round(1).tolist(), hazard=bool(inst["hazard"]),
595
+ detail=" ".join(parts))
596
+ return out
597
+
598
+ # ------------------------------------------------------------ scripted primitives (perfect perception)
599
+ def _go(self, xyz, yaw=None, speed=None, tol=0.004, max_steps=300):
600
+ return self.sk.move_to(xyz, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
601
+
602
+ def _settle(self, name, max_checks=25):
603
+ d = self.env.sim.data
604
+ _, da = envs.free_joint_addr(self.env, name)
605
+ for _ in range(max_checks):
606
+ if np.linalg.norm(d.qvel[da:da + 3]) < 0.01 and np.linalg.norm(d.qvel[da + 3:da + 6]) < 0.2:
607
+ return
608
+ self.sk.hold(2)
609
+
610
+ def _cube_yaw(self, name):
611
+ R = self.R(name)
612
+ i = int(np.argmin(np.abs(R[2])))
613
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
614
+ y = float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4)
615
+ cands = [y + k * np.pi / 2 for k in (-1, 0, 1)]
616
+ return min(cands, key=lambda c: abs(c - self.sk.yaw) if abs(c) <= np.pi / 2 else 9.0)
617
+
618
+ def pick(self, name, z_carry, v=0.15, tries=2):
619
+ """Sonnet-like top-down pick: over the cube at carry height, down at 0.1 to 1.5 cm above, last 1.5 cm at 0.04,
620
+ close, lift to carry height"""
621
+ sk = self.sk
622
+ for _ in range(tries):
623
+ self._settle(name)
624
+ p = envs.obj_pos(self.env, name)
625
+ zg = p[2] - Z
626
+ yaw = self._cube_yaw(name)
627
+ sk.set_gripper(False, steps=8)
628
+ self._go([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw, speed=v)
629
+ self._go([p[0], p[1], Z + zg + 0.015], speed=0.1)
630
+ self._go([p[0], p[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
631
+ sk.set_gripper(True, steps=15)
632
+ self._go([p[0], p[1], Z + z_carry], speed=v)
633
+ if self.held(name):
634
+ return True
635
+ sk.set_gripper(False, steps=8)
636
+ return False
637
+
638
+ def put(self, xy, z_rel, z_carry, v=0.15, v_down=None):
639
+ """carry over xy at carry height, straight down (0.1 m/s, last 1.5 cm at 0.03; or one move at v_down), open,
640
+ back up"""
641
+ sk = self.sk
642
+ self._go([xy[0], xy[1], Z + z_carry], speed=v)
643
+ if z_rel < z_carry - 0.02 and v_down:
644
+ self._go([xy[0], xy[1], Z + z_rel], speed=v_down, tol=0.003, max_steps=250)
645
+ elif z_rel < z_carry - 0.02:
646
+ self._go([xy[0], xy[1], Z + z_rel + 0.015], speed=0.1)
647
+ self._go([xy[0], xy[1], Z + z_rel], speed=0.03, tol=0.003, max_steps=150)
648
+ sk.set_gripper(False, steps=12)
649
+ self._go([xy[0], xy[1], Z + z_carry], speed=v)
650
+ sk.hold(5)
651
+
652
+ def slot_xy(self, k, order):
653
+ """slot k of the scripted packing pattern, in world xy (box frame: u forward, v left)"""
654
+ u, v = order[k]
655
+ return np.asarray(self.inst["box_xy"]) + np.array([u, v]) * SLOT
656
+
657
+ def put_cube(self, name, k, order, z_rel, z_carry, noise=None, v=0.15, v_down=None):
658
+ if not self.pick(name, z_carry, v=v):
659
+ return False
660
+ xy = self.slot_xy(k, order) + (np.asarray(noise, float) if noise is not None else 0.0)
661
+ self.put(xy, z_rel, z_carry, v=v, v_down=v_down)
662
+ self._settle(name)
663
+ return True
664
+
665
+ def restand_bottle(self, z_carry=None):
666
+ """stand the bottle up again on its spot: grasp the ball cap from above (fingers across the lying bottle's
667
+ axis), lift until it hangs free, carry it over its spot, lower until the bottom is ~2 mm above the table, let
668
+ go. Returns True if it is back in place."""
669
+ sk = self.sk
670
+ self._settle(BOTTLE)
671
+ for _ in range(2):
672
+ if _reach(self.cap_xyz()) > REACH_MAX and self.bottle_tilt() > FALLEN:
673
+ self.pull_in_bottle()
674
+ k = self.cap_xyz()
675
+ ax = self.R(BOTTLE)[:2, 2]
676
+ yaw = float(np.arctan2(ax[1], ax[0])) if np.linalg.norm(ax) > 0.2 else sk.yaw # finger axis across it
677
+ sk.set_gripper(False, steps=8)
678
+ cur = sk.eef_pos()
679
+ self._go([cur[0], cur[1], max(cur[2], Z + 0.15)], speed=0.15)
680
+ self._go([k[0], k[1], max(k[2] + 0.08, Z + 0.15)], yaw=yaw, speed=0.15)
681
+ sk.hold(5)
682
+ k = self.cap_xyz()
683
+ self._go([k[0], k[1], k[2] + 0.015], speed=0.1)
684
+ self._go([k[0], k[1], k[2]], speed=0.04, tol=0.003, max_steps=120)
685
+ sk.set_gripper(True, steps=15)
686
+ if not self.held(BOTTLE):
687
+ sk.set_gripper(False, steps=8)
688
+ self._go([k[0], k[1], k[2] + 0.08], speed=0.1)
689
+ continue
690
+ zl = Z + CAP_Z + 0.06
691
+ self._go([k[0], k[1], zl], speed=0.10)
692
+ sk.hold(15)
693
+ tx, ty = self.inst["bottle_xy"]
694
+ self._go([tx, ty, zl], speed=0.10)
695
+ sk.hold(25)
696
+ self._go([tx, ty, Z + CAP_Z + 0.015], speed=0.08)
697
+ self._go([tx, ty, Z + CAP_Z + 0.002], speed=0.03, tol=0.003, max_steps=120)
698
+ sk.set_gripper(False, steps=12)
699
+ self._go([tx, ty, Z + CAP_Z + 0.06], speed=0.08)
700
+ sk.hold(20)
701
+ self._settle(BOTTLE)
702
+ if self.bottle_in_place():
703
+ return True
704
+ return self.bottle_in_place()
705
+
706
+ def pull_in_bottle(self):
707
+ """the lying bottle's cap is out of reach (it fell forward over the box): grasp the body near its bottom end
708
+ (fingers across it), lift it 3 cm, pull it towards the robot until the cap is within reach, set it down"""
709
+ sk = self.sk
710
+ Rb = self.R(BOTTLE)
711
+ ax = Rb[:, 2]
712
+ c = envs.obj_pos(self.env, BOTTLE)
713
+ g = c - ax * (H_TOT / 2 - 0.05) # 5 cm from the bottom end along the axis
714
+ zg = max(float(g[2] - Z), 0.02)
715
+ yaw = float(np.arctan2(ax[1], ax[0]))
716
+ need = _reach(self.cap_xyz()) - (REACH_MAX - 0.05)
717
+ to_base = np.array([-0.66, 0.0]) - g[:2]
718
+ to_base /= max(np.linalg.norm(to_base), 1e-6)
719
+ dst = g[:2] + to_base * need
720
+ sk.set_gripper(False, steps=8)
721
+ self._go([g[0], g[1], Z + 0.15], yaw=yaw, speed=0.15)
722
+ self._go([g[0], g[1], Z + zg + 0.015], speed=0.1)
723
+ self._go([g[0], g[1], Z + zg], speed=0.04, tol=0.003, max_steps=120)
724
+ sk.set_gripper(True, steps=15)
725
+ self._go([g[0], g[1], Z + zg + 0.03], speed=0.08)
726
+ self._go([dst[0], dst[1], Z + zg + 0.03], speed=0.08)
727
+ self._go([dst[0], dst[1], Z + zg + 0.005], speed=0.04)
728
+ sk.set_gripper(False, steps=12)
729
+ self._go([dst[0], dst[1], Z + 0.15], speed=0.1)
730
+ self._settle(BOTTLE)
731
+
732
+ def _fallen_cubes(self, done):
733
+ return [n for n in done if not self.in_box(n) and not self.over_box(n) and not self.held(n)]
734
+
735
+ # ------------------------------------------------------------ scripted policies
736
+ def execute(self, inst, params):
737
+ careful = params.get("careful", False)
738
+ zc = params.get("z_carry", Z_SAFE if careful else Z_CARRY)
739
+ zr = params.get("z_rel", Z_DROP if careful else Z_REL)
740
+ order = params.get("slots") or [(1, 1), (1, -1), (-1, 0)] # far row first (Sonnet fills from the far end)
741
+ cubes = params.get("cubes") or self._cube_order()
742
+ noise = params.get("noise") or {}
743
+ v = params.get("speed", 0.15)
744
+ done = []
745
+ for k, n in enumerate(cubes):
746
+ self.put_cube(n, k, order, zr, zc, noise=noise.get(n), v=v, v_down=params.get("v_down"))
747
+ done.append(n)
748
+ # looks after every step (Sonnet): re-places a cube that ended up outside the box ...
749
+ for f in self._fallen_cubes(done):
750
+ self.put_cube(f, done.index(f), order, zr, zc, v=v)
751
+ # ... and, if the bystander is in the policy's view of the task, stands the bottle up again
752
+ if params.get("restore") == "each" and not self.bottle_in_place():
753
+ self.restand_bottle()
754
+ if params.get("check"):
755
+ self.check_and_fix(order, zr, zc)
756
+ self.sk.hold(10)
757
+
758
+ def check_and_fix(self, order, zr, zc, rounds=2):
759
+ for _ in range(rounds):
760
+ v = self.stage_values()
761
+ if all(v.values()):
762
+ return True
763
+ for n in CUBES:
764
+ if not self.in_box(n):
765
+ self.put_cube(n, CUBES.index(n), order, zr, zc)
766
+ if not self.bottle_in_place():
767
+ self.restand_bottle()
768
+ return all(self.stage_values().values())
769
+
770
+ def _cube_order(self):
771
+ """the cube nearest the box first"""
772
+ bxy = np.asarray(self.inst["box_xy"])
773
+ return sorted(CUBES, key=lambda n: float(np.linalg.norm(np.asarray(self.inst["start"][n]) - bxy)))
774
+
775
+ def default_params(self, inst):
776
+ """Sonnet-like: cubes nearest-first, carried 15 cm up in straight lines, each lowered straight down onto the box
777
+ floor (far row first), looks after every step and re-places a cube that fell out; no special care for the
778
+ bottle (it is not part of the packing)"""
779
+ return dict(careful=False, restore=None, check=False)
780
+
781
+ def oracle_params(self, inst):
782
+ """knows its arm: carries high (24 cm) and drops the cubes into the box from 16 cm, so the forearm stays above
783
+ the bottle; checks every stage at the end"""
784
+ return dict(careful=True, restore="each", check=True)
785
+
786
+ def adapt_params(self, inst, history):
787
+ """attempt >= 2: the careful packing (high carry, drop from above the rim), stand the bottle up if needed,
788
+ check at the end"""
789
+ return dict(careful=True, restore="each", check=True)
790
+
791
+ def blind_params(self, inst, attempt, rng):
792
+ """the natural behaviour again with small random variations, no history, no care for the bottle"""
793
+ pats = [[(1, 1), (1, -1), (-1, 0)], [(1, -1), (1, 1), (-1, 0)], [(0, 1), (0, -1), (-1, 0)],
794
+ [(1, 0), (-1, 1), (-1, -1)], [(1, 1), (-1, -1), (0, 0)]]
795
+ return dict(careful=False, restore=None, check=False, slots=pats[int(rng.integers(len(pats)))],
796
+ z_carry=float(rng.uniform(0.12, 0.20)), z_rel=float(rng.uniform(0.032, 0.055)),
797
+ noise={n: rng.uniform(-NAIVE_ERR, NAIVE_ERR, 2).tolist() for n in CUBES})
798
+
799
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
800
+ """oracle / naive: one attempt; adaptive: attempt 1 = naive + stands the knocked bottle up again after every
801
+ step and checks at the end, attempts >= 2 careful; blind: naive with random variations.
802
+ Extra kinds (not in validate's table): switch (naive, then careful without restoring), oracle_noise (oracle with
803
+ +-5 mm placement noise)"""
804
+ k = k or self.max_attempts
805
+ rng = np.random.default_rng(seed)
806
+ history = []
807
+ for a in range(k):
808
+ self.reset_instance(inst)
809
+ if kind == "oracle":
810
+ params = self.oracle_params(inst)
811
+ elif kind == "naive":
812
+ params = self.default_params(inst)
813
+ elif kind == "adaptive":
814
+ params = dict(careful=False, restore="each", check=True) if a == 0 else self.adapt_params(inst, history)
815
+ elif kind == "blind":
816
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
817
+ elif kind == "switch":
818
+ params = self.default_params(inst) if a == 0 else dict(careful=True, restore=None, check=False)
819
+ elif kind == "oracle_noise":
820
+ params = dict(self.oracle_params(inst), noise={n: rng.uniform(-0.005, 0.005, 2).tolist() for n in CUBES})
821
+ else:
822
+ raise ValueError(kind)
823
+ self.execute(inst, params)
824
+ out = self.outcome(inst)
825
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
826
+ if on_attempt:
827
+ on_attempt(a, params, out)
828
+ if out["success"] or kind in ("oracle", "naive", "oracle_noise"):
829
+ break
830
+ return history
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_lid_box.py ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH lid_box: put three blocks on their marks, then open a box, put a red cube in, close it -- the lid falls open onto
2
+ the marks behind the box and shoves the blocks standing there off their marks.
3
+
4
+ Family: long-horizon self-disturbance ("state_restoration"): the agent's own normal later-stage action (opening the
5
+ lid) physically breaks earlier progress (blocks on marks); it has to notice and restore it before finishing (within an
6
+ attempt), or learn to open the box first (across attempts; the final-state judge does not enforce an order).
7
+
8
+ Scene (world frame, robot base at x = -0.66; "forward" = +x, away from the robot; "left" = +y):
9
+ * a flat wooden box (fixture, 12 x 16 cm, walls 3.2 cm, lid 0.6 cm) whose lid is hinged along its far edge; a black
10
+ ball knob sticks out of the middle of the lid's front edge. The lid is heavy (0.3 kg) and has no damping: once it
11
+ is lifted past vertical it falls backward and comes to rest on a stop (hidden angle) or on whatever is behind the
12
+ box;
13
+ * three 6 cm cubes ("blocks", blue / green / yellow; light, 54 g, and slippery, mu 0.25) in a row in front of the box
14
+ together with a small red cube (2.2 cm);
15
+ * three square marks (7.6 cm, outline + light fill) in the blocks' colours: two right behind the box (their near
16
+ edge 0.2-1.7 cm from the box's back wall), one beside the box.
17
+
18
+ Hidden variable: the lid's opening stop (0 = closed, 90 = upright, 180 = flat behind the box): "far", uniform in FAR
19
+ (138-165 deg), in 13 of every 20 consecutive seeds, else "near", uniform in NEAR (100-113 deg). Before the lid is opened
20
+ nothing shows it. A far lid lands on the top edge of the blocks standing behind the box and its weight shoves them
21
+ away from the robot ("forward") off their marks (measured: 4-10 cm); a near lid comes to rest above them. Stops of
22
+ ~115-135 deg are left out on purpose: there the lid only grazes the blocks (1-3 cm, right at the tolerance).
23
+
24
+ Why the natural order fails: the instruction lists the blocks first (as a user would), so the natural plan places the
25
+ blocks, opens the lid (it falls back onto them), puts the cube in, closes the lid and finishes without looking at the
26
+ marks again. What must be learned: re-check every stage before finishing and put knocked blocks back after closing the
27
+ lid (within the attempt), or open the box first / place the blocks behind it last (across attempts).
28
+
29
+ Lid mechanics for agents (`LidSkills`, measured, see the task card): grasping the ball knob from above (fingers on its
30
+ left and right, the default yaw) makes a pivot -- the ball turns freely between the fingers about the hinge axis. While
31
+ the knob is held, the arm is compliant along the hinge constraint: a commanded straight move is projected onto the
32
+ knob's circle around the hinge (at most 1 cm per control step; ~0.07 m/s along the arc in the agent self-test), so
33
+ "up 10 cm, then back over the hinge, release" opens the lid and "up, then forward, release" closes it; a move that
34
+ makes no more progress ends early (like KeySkills' stalling wrist in l7_key_turn). Without the compliance, all 6
35
+ typical straight-move sequences tried (prototype: this lid with a 2 cm stem, 2026-10-09) pulled the knob out of the
36
+ fingers and the lid fell shut; with an earlier, lighter lid only a 3-segment approximation of the arc opened it.
37
+
38
+ Protocol: cross (reset to the same instance before every attempt), k = 3. Outcome: final-state judge (all blocks on
39
+ their marks, red cube in the box, lid closed, nothing held, scene static) plus an event log of every stage predicate
40
+ (achieved / lost / restored, with step and cause) for the server log; F1 gives 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, _wrap, box_xml, register_generated
47
+ from ..skills import DT, Skills, _rot_err
48
+ from ..task_base import LFFTask, register_task
49
+
50
+ # ---------------------------------------------------------------- geometry / physics
51
+ BOX = "box_1"
52
+ BOX_MODEL = "lff_lh_lid_box"
53
+ BOX_D, BOX_W = 0.12, 0.16 # outer depth (x) and width (y)
54
+ WALL_H, WALL_T, FLOOR_T = 0.032, 0.008, 0.006
55
+ LID_T, LID_MASS = 0.006, 0.30
56
+ KNOB_R, STEM_L = 0.013, 0.032
57
+ HINGE_DAMP, HINGE_FRIC = 0.002, 0.002
58
+ IN_X = BOX_D / 2 - WALL_T # inner half sizes of the cavity
59
+ IN_Y = BOX_W / 2 - WALL_T
60
+
61
+ BLOCK = 0.06 # cube edge
62
+ BLOCK_DENS = 250.0 # -> 54 g
63
+ BLOCK_MU = 0.25
64
+ CUBE_E = 0.022 # red cube edge
65
+ MARK_HALF = 0.038
66
+ MARK_LINE = 0.004
67
+ TOL = 0.020 # block centre within 2 cm (per axis) of its mark's centre
68
+ FLAT_COS = np.cos(np.radians(15.0))
69
+ CUBE_MARGIN = 0.004
70
+ LID_CLOSED = np.radians(4.0)
71
+ # hidden stop (deg): in a fraction P_FAR of the instances the lid opens far back, uniform in FAR (it lands on blocks
72
+ # standing behind the box and shoves them 4-10 cm), otherwise it stops near upright, uniform in NEAR (it comes to rest
73
+ # above them). Far / near is balanced per block of 20 consecutive seeds (13 / 7), see sample_instance.
74
+ # Bimodal on purpose: stops between ~115 and ~135 deg make the lid graze the blocks and push them 1-3 cm, i.e. right
75
+ # at the tolerance, which is neither a clean disturbance nor a clean no-disturbance (measured, see the task card).
76
+ P_FAR = 0.65
77
+ FAR = (138.0, 165.0)
78
+ NEAR = (100.0, 113.0)
79
+ GAP_LO, GAP_HI = 0.002, 0.017 # near edge of a behind-mark to the box's back wall (block near face +0.8 cm further)
80
+
81
+ COLORS = ("blue", "green", "yellow")
82
+ RGBA = dict(blue=(0.15, 0.30, 0.85, 1.0), green=(0.10, 0.60, 0.20, 1.0), yellow=(0.92, 0.76, 0.10, 1.0))
83
+ BLOCKS = {c: f"{c}_block_1" for c in COLORS}
84
+ MARKS = {c: f"{c}_mark_1" for c in COLORS}
85
+ CUBE = "red_cube_1"
86
+
87
+ Z_CARRY = 0.13 # scripted transit height of the grasp point above the table when carrying a block
88
+ Z_KNOB = WALL_H + LID_T / 2 # knob centre above the table with the lid closed
89
+ SMAX = 0.010 # max projected displacement command per control step while the knob is held
90
+ STALL = 12
91
+
92
+
93
+ def box_lid_xml(name, body_rgba=(0.55, 0.38, 0.22, 1.0), lid_rgba=(0.70, 0.52, 0.32, 1.0), knob_rgba=(0.10, 0.10, 0.11, 1.0)):
94
+ hx, hy = BOX_D / 2, BOX_W / 2
95
+ parts = [((0, 0, FLOOR_T / 2), (hx, hy, FLOOR_T / 2)),
96
+ ((hx - WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
97
+ ((-hx + WALL_T / 2, 0, WALL_H / 2), (WALL_T / 2, hy, WALL_H / 2)),
98
+ ((0, hy - WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2)),
99
+ ((0, -hy + WALL_T / 2, WALL_H / 2), (hx - WALL_T, WALL_T / 2, WALL_H / 2))]
100
+ g = []
101
+ # box: contype 2 / conaffinity 1 and lid: contype 4 / conaffinity 1 -> the lid never collides with its own box (the
102
+ # hinge limit holds it closed), but both collide with the robot, the table and the free objects (contype 1)
103
+ for k, (pos, s) in enumerate(parts):
104
+ g.append(f'<geom name="{name}_w{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(s)}" rgba="{_fmt(body_rgba)}" '
105
+ f'friction="0.8 0.005 0.0001" {_SOLID} contype="2" conaffinity="1" group="0"/>')
106
+ g.append(f'<geom type="box" pos="{_fmt(pos)}" size="{_fmt(s)}" rgba="{_fmt(body_rgba)}" contype="0" '
107
+ f'conaffinity="0" group="1"/>')
108
+ m, L = LID_MASS, BOX_D
109
+ lid_c = (-L / 2, 0, LID_T / 2)
110
+ lid_s = (L / 2, hy, LID_T / 2)
111
+ stem = (-L - STEM_L / 2, 0, LID_T / 2)
112
+ ball = (-L - STEM_L - KNOB_R * 0.7, 0, LID_T / 2)
113
+ lid = [f'<inertial pos="{_fmt(lid_c)}" mass="{m}" diaginertia="{m * (BOX_W ** 2 + LID_T ** 2) / 12:.6f} '
114
+ f'{m * (L ** 2 + LID_T ** 2) / 12:.6f} {m * (BOX_W ** 2 + L ** 2) / 12:.6f}"/>',
115
+ # placeholder range: the opening stop is set per instance (apply_instance)
116
+ f'<joint name="{name}_hinge" type="hinge" axis="0 1 0" pos="0 0 0" limited="true" range="0 2.8" '
117
+ f'damping="{HINGE_DAMP}" frictionloss="{HINGE_FRIC}" armature="0.0005"/>',
118
+ f'<geom name="{name}_lid" type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(lid_rgba)}" mass="0" '
119
+ f'friction="0.8 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
120
+ f'<geom type="box" pos="{_fmt(lid_c)}" size="{_fmt(lid_s)}" rgba="{_fmt(lid_rgba)}" contype="0" conaffinity="0" group="1"/>',
121
+ f'<geom name="{name}_stem" type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
122
+ f'rgba="{_fmt(knob_rgba)}" mass="0" friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
123
+ f'<geom type="cylinder" pos="{_fmt(stem)}" quat="0.7071 0 0.7071 0" size="0.0045 {STEM_L / 2:.4f}" '
124
+ f'rgba="{_fmt(knob_rgba)}" contype="0" conaffinity="0" group="1"/>',
125
+ f'<geom name="{name}_knob" type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(knob_rgba)}" mass="0" '
126
+ f'friction="1 0.005 0.0001" contype="4" conaffinity="1" group="0"/>',
127
+ f'<geom type="sphere" pos="{_fmt(ball)}" size="{KNOB_R:.4f}" rgba="{_fmt(knob_rgba)}" contype="0" conaffinity="0" group="1"/>']
128
+ shell = "\n ".join(g)
129
+ lid_xml = "\n ".join(lid)
130
+ return f"""<mujoco model="{name}">
131
+ <worldbody>
132
+ <body>
133
+ <body name="object">
134
+ {shell}
135
+ <body name="lid" pos="{hx:.4f} 0 {WALL_H:.4f}">
136
+ {lid_xml}
137
+ </body>
138
+ </body>
139
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
140
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {WALL_H:.4f}" name="top_site" />
141
+ <site rgba="0 0 0 0" size="0.005" pos="{hx:.4f} {hy:.4f} 0" name="horizontal_radius_site" />
142
+ </body>
143
+ </worldbody>
144
+ </mujoco>"""
145
+
146
+
147
+ def mark_xml(name, rgba):
148
+ """Flat, visual-only square drawn on the table: a light fill plus an outline in the block's colour."""
149
+ fill = tuple(0.55 + 0.45 * c for c in rgba[:3]) + (1.0,)
150
+ o, i, w = MARK_HALF, MARK_HALF - MARK_LINE, MARK_LINE
151
+ parts = [((0, 0, 0.0004), (o, o, 0.0004), fill),
152
+ ((0, i + w / 2, 0.0010), (o, w / 2, 0.0002), rgba),
153
+ ((0, -i - w / 2, 0.0010), (o, w / 2, 0.0002), rgba),
154
+ ((i + w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba),
155
+ ((-i - w / 2, 0, 0.0010), (w / 2, o, 0.0002), rgba)]
156
+ g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
157
+ f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
158
+ return _wrap(name, g, 0.0012, o)
159
+
160
+
161
+ def _fb(v):
162
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
163
+
164
+
165
+ def _lr(v):
166
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
167
+
168
+
169
+ class LidSkills(Skills):
170
+ """Skills for the lid box: a per-step stage monitor, and a hinge-compliant arm while the knob is held (see the
171
+ module docstring)."""
172
+
173
+ def __init__(self, env, task, recorder=None):
174
+ super().__init__(env, recorder=recorder)
175
+ self.task = task
176
+ self.latched = False
177
+ self.rad0 = None
178
+ self.y0 = None
179
+ self.knob_steps = 0 # control steps driven with the knob held (compliant mode)
180
+ self.knob_grasps = 0
181
+
182
+ def holding_knob(self):
183
+ """both fingers (pad or finger body) touch the knob ball or its stem"""
184
+ g = self.env.robots[0].gripper
185
+ return bool(self.env._check_grasp(gripper=[g.important_geoms["left_finger"], g.important_geoms["right_finger"]],
186
+ object_geoms=self.task.knob_geom_names))
187
+
188
+ def _act(self, dpos, drot, grip):
189
+ if self.latched:
190
+ e = self.eef_pos()
191
+ if self.grip < 0 or np.linalg.norm(e - self.task.knob_xyz()) > 0.035:
192
+ self.latched = False # opened, or the knob slipped out of the fingers
193
+ else:
194
+ hx, hz = self.task.hinge_xz()
195
+ r = np.array([e[0] - hx, e[2] - hz])
196
+ rn = max(float(np.linalg.norm(r)), 1e-6)
197
+ tng = np.array([-r[1], r[0]]) / rn
198
+ s = float(np.clip(dpos[0] * tng[0] + dpos[2] * tng[1], -SMAX, SMAX))
199
+ corr = (self.rad0 - rn) * r / rn
200
+ dpos = np.array([s * tng[0] + corr[0], self.y0 - e[1], s * tng[1] + corr[1]])
201
+ self.knob_steps += 1
202
+ super()._act(dpos, drot, grip)
203
+ self.task.monitor_step()
204
+
205
+ def set_gripper(self, close, steps=15):
206
+ rep = super().set_gripper(close, steps)
207
+ if close and self.holding_knob():
208
+ e = self.eef_pos()
209
+ hx, hz = self.task.hinge_xz()
210
+ self.latched = True
211
+ self.rad0 = float(np.hypot(e[0] - hx, e[2] - hz))
212
+ self.y0 = float(e[1])
213
+ self.knob_grasps += 1
214
+ elif not close:
215
+ self.latched = False
216
+ return rep
217
+
218
+ def move_to(self, target, yaw=None, speed=None, tol=0.004, max_steps=250, apply_bias=True, wrap_yaw=True):
219
+ """Skills.move_to plus an early stop when the knob is held and the arm has stopped making progress."""
220
+ tgt = np.asarray(target, float) + (self.bias if apply_bias else 0.0)
221
+ if yaw is not None:
222
+ self.yaw = self.wrap_yaw(float(yaw)) if wrap_yaw else float(yaw)
223
+ R = self._R()
224
+ p0 = self.eef_pos()
225
+ dist = np.linalg.norm(tgt - p0)
226
+ direction = (tgt - p0) / max(dist, 1e-9)
227
+ s = 0.0
228
+ hist = []
229
+ stalled = False
230
+ for k in range(max_steps):
231
+ if speed is not None:
232
+ s = min(dist, s + speed * DT)
233
+ ref = p0 + direction * s + direction * min(dist - s, speed * DT * 1.5)
234
+ else:
235
+ ref = tgt
236
+ self._act(ref - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
237
+ cur = self.eef_pos()
238
+ if np.linalg.norm(tgt - cur) < tol and (speed is None or s >= dist):
239
+ break
240
+ hist.append(cur)
241
+ if (self.latched and len(hist) > STALL and (speed is None or s >= dist)
242
+ and np.linalg.norm(hist[-1] - hist[-1 - STALL]) < 0.002):
243
+ stalled = True
244
+ break
245
+ rep = dict(prim="move_to", reached=bool(np.linalg.norm(tgt - self.eef_pos()) < 0.02),
246
+ pos=self.eef_pos().round(4).tolist(), steps=k + 1, stalled=stalled)
247
+ self.log.append(rep)
248
+ return rep
249
+
250
+
251
+ @register_task
252
+ class LidBox(LFFTask):
253
+ name = "lh_lid_box"
254
+ level = "L2"
255
+ category = "state_restoration"
256
+ capabilities = ("Perceive", "Plan", "Reason", "Utilize")
257
+ protocol = "cross"
258
+ max_attempts = 3
259
+ agent_max_steps = 110 # careful oracle ~45-55 commands + restoring two blocks (~14) + looking around
260
+ instruction = ("Put each of the three coloured blocks on the square mark of the same colour on the table. Then open "
261
+ "the lid of the wooden box (lift it by the black knob on its front edge), put the red cube inside "
262
+ "the box, and close the lid.")
263
+ instruction_indirect = ("Set the blue, green and yellow cubes onto the outlined squares of matching colour. Then open "
264
+ "the flat wooden case (its lid lifts by the black ball at the front), place the small red "
265
+ "cube in it and shut the lid.")
266
+ agent_object_names = ["blue block", "green block", "yellow block", "red cube", "wooden box", "lid knob",
267
+ "blue mark", "green mark", "yellow mark"]
268
+
269
+ # ------------------------------------------------------------ scene
270
+ def make_bddl(self):
271
+ box = register_generated("LffLhLidBox", box_lid_xml(BOX_MODEL), free=False)
272
+ b = BLOCK / 2
273
+ objs, fx = [], [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
274
+ for i, c in enumerate(COLORS):
275
+ blk = register_generated(f"LffLhBlock{c.title()}",
276
+ box_xml(f"lff_lh_block_{c}", (b, b, b), RGBA[c], density=BLOCK_DENS,
277
+ friction=(BLOCK_MU, 0.005, 0.0001)).replace(_SOLID, ""))
278
+ mark = register_generated(f"LffLhMark{c.title()}", mark_xml(f"lff_lh_mark_{c}", RGBA[c]), free=False)
279
+ objs.append((BLOCKS[c], blk, f"{c}_block_region", (-0.31, -0.22 + 0.15 * i, -0.29, -0.20 + 0.15 * i)))
280
+ fx.append((MARKS[c], mark, f"{c}_mark_region", (0.0, -0.22 + 0.15 * i, 0.02, -0.20 + 0.15 * i)))
281
+ cube = register_generated("LffLhRedCube", box_xml("lff_lh_red_cube", (CUBE_E / 2,) * 3, (0.85, 0.10, 0.08, 1.0),
282
+ density=500))
283
+ objs.append((CUBE, cube, "red_cube_region", (-0.31, 0.24, -0.29, 0.26)))
284
+ return write_bddl(self.name, "put the blocks on their marks and the red cube in the box", objs, fx)
285
+
286
+ def __init__(self, cam_res=None):
287
+ super().__init__(cam_res)
288
+ m = self.env.sim.model
289
+ pre = f"{BOX}_{BOX_MODEL}"
290
+ self.jid = m.joint_name2id(pre + "_hinge")
291
+ self.qa = m.jnt_qposadr[self.jid]
292
+ self.dof = m.jnt_dofadr[self.jid]
293
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
294
+ self.knob_geom_name = pre + "_knob"
295
+ self.knob_geom_names = [pre + "_knob", pre + "_stem"]
296
+ self.knob_gid = m.geom_name2id(self.knob_geom_name)
297
+ self.lid_gids = {m.geom_name2id(pre + s) for s in ("_lid", "_stem", "_knob")}
298
+ self.robot_gids = set(envs.robot_geom_ids(self.env))
299
+ self.mark_bid = {c: m.body_name2id(self.env.fixtures_dict[MARKS[c]].root_body) for c in COLORS}
300
+ self.block_gids = {c: set(envs.obj_geom_ids(self.env, BLOCKS[c])) for c in COLORS}
301
+ self.inst = None
302
+ self.mon = None
303
+
304
+ def sample_instance(self, seed):
305
+ rng = np.random.default_rng(seed)
306
+ bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03))
307
+ hinge_x = bx + BOX_D / 2
308
+ order = [str(c) for c in rng.permutation(COLORS)] # [behind-left, behind-right, side]
309
+ side = 1.0 if rng.random() < 0.5 else -1.0
310
+ marks = {}
311
+ gaps = {}
312
+ for c, sy in zip(order[:2], (1.0, -1.0)):
313
+ g = float(rng.uniform(GAP_LO, GAP_HI))
314
+ gaps[c] = g
315
+ marks[c] = [hinge_x + g + MARK_HALF, by + sy * 0.05 + float(rng.uniform(-0.005, 0.005))]
316
+ marks[order[2]] = [bx + float(rng.uniform(-0.03, 0.03)), by + side * (BOX_W / 2 + 0.025 + MARK_HALF)]
317
+ # start row in front of the box: four slots outside the knob's lane, shuffled (3 blocks + red cube)
318
+ slots = [-0.22, -0.11, 0.11, 0.22] # 11 cm apart: room for the open fingers next to a 6 cm block
319
+ items = [BLOCKS[c] for c in COLORS] + [CUBE]
320
+ perm = rng.permutation(len(items))
321
+ start = {items[i]: [float(-0.31 + rng.uniform(-0.01, 0.01)), float(slots[j] + rng.uniform(-0.01, 0.01))]
322
+ for j, i in enumerate(perm)}
323
+ rng.random() # (draw kept so the other parameters stay the same)
324
+ # balanced blocks like l7_key_turn: exactly round(20 * P_FAR) of every 20 consecutive seeds open far
325
+ far = bool((int(seed) * 7) % 20 < round(20 * P_FAR))
326
+ stop = float(rng.uniform(*(FAR if far else NEAR)))
327
+ return dict(seed=int(seed), box_xy=[bx, by], stop_deg=stop, lid_far=far, marks=marks,
328
+ behind=order[:2], side_color=order[2], side="left" if side > 0 else "right", gaps=gaps, start=start,
329
+ start_yaw={k: float(rng.uniform(-0.3, 0.3)) for k in items})
330
+
331
+ def apply_instance(self, inst):
332
+ self.inst = inst
333
+ m, d = self.env.sim.model, self.env.sim.data
334
+ bx, by = inst["box_xy"]
335
+ m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
336
+ m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
337
+ m.jnt_range[self.jid] = [0.0, np.radians(inst["stop_deg"])]
338
+ m.jnt_solref[self.jid] = [0.01, 1.0]
339
+ d.qpos[self.qa] = 0.0
340
+ d.qvel[self.dof] = 0.0
341
+ for c in COLORS:
342
+ x, y = inst["marks"][c]
343
+ m.body_pos[self.mark_bid[c]] = [x, y, envs.TABLE_Z + 0.0002]
344
+ m.body_quat[self.mark_bid[c]] = [1.0, 0.0, 0.0, 0.0]
345
+ for name, xy in inst["start"].items():
346
+ envs.place_upright(self.env, name, xy, yaw=inst["start_yaw"][name])
347
+ for c in COLORS:
348
+ envs.set_friction(self.env, BLOCKS[c], BLOCK_MU)
349
+
350
+ def reset_instance(self, inst, recorder=None):
351
+ self.env.reset()
352
+ self.apply_instance(inst)
353
+ self.env.sim.forward()
354
+ envs.settle(self.env, 10)
355
+ self.mon = None
356
+ self.sk = LidSkills(self.env, self, recorder=recorder)
357
+ self._init_monitor()
358
+ return self.sk
359
+
360
+ # ------------------------------------------------------------ state helpers
361
+ def lid_q(self):
362
+ return float(self.env.sim.data.qpos[self.qa])
363
+
364
+ def lid_deg(self):
365
+ return float(np.degrees(self.lid_q()))
366
+
367
+ def knob_xyz(self):
368
+ return self.env.sim.data.geom_xpos[self.knob_gid].copy()
369
+
370
+ def hinge_xz(self):
371
+ return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H
372
+
373
+ def held(self, name):
374
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
375
+
376
+ def _flat(self, name):
377
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
378
+ return bool(np.max(np.abs(R[2])) >= FLAT_COS)
379
+
380
+ def block_offset(self, c):
381
+ p = envs.obj_pos(self.env, BLOCKS[c])
382
+ return p[:2] - np.asarray(self.inst["marks"][c])
383
+
384
+ def on_mark(self, c, tol=TOL):
385
+ name = BLOCKS[c]
386
+ p = envs.obj_pos(self.env, name)
387
+ off = p[:2] - np.asarray(self.inst["marks"][c])
388
+ return bool(np.max(np.abs(off)) <= tol and p[2] < envs.TABLE_Z + BLOCK / 2 + 0.01 and self._flat(name)
389
+ and not self.held(name))
390
+
391
+ def cube_in_box(self):
392
+ p = envs.obj_pos(self.env, CUBE)
393
+ rel = p[:2] - np.asarray(self.inst["box_xy"])
394
+ return bool(abs(rel[0]) <= IN_X - CUBE_MARGIN and abs(rel[1]) <= IN_Y - CUBE_MARGIN
395
+ and p[2] < envs.TABLE_Z + WALL_H and not self.held(CUBE))
396
+
397
+ def lid_closed(self):
398
+ return self.lid_q() <= LID_CLOSED
399
+
400
+ def stage_values(self):
401
+ v = {f"{c}_on_mark": self.on_mark(c) for c in COLORS}
402
+ v["cube_in_box"] = self.cube_in_box()
403
+ v["lid_closed"] = self.lid_closed()
404
+ return v
405
+
406
+ # ------------------------------------------------------------ per-step monitor
407
+ def _init_monitor(self):
408
+ self.mon = dict(state={f"{c}_on_mark": False for c in COLORS} | {"cube_in_box": False}, ever=set(),
409
+ lost=set(), events=[], last_touch={c: None for c in COLORS}, lid_hits=set(),
410
+ lid_open_max=0.0, lid_opened=False, lid_open_steps=[], lid_close_steps=[], step=0,
411
+ lid_prev=0.0, lid_moving_step=-10 ** 9)
412
+
413
+ def _touches(self):
414
+ """Per block: was it touched by the lid / the robot in this control step?"""
415
+ d = self.env.sim.data
416
+ out = {}
417
+ for i in range(d.ncon):
418
+ c = d.contact[i]
419
+ for cc in COLORS:
420
+ g = self.block_gids[cc]
421
+ other = c.geom2 if c.geom1 in g else (c.geom1 if c.geom2 in g else None)
422
+ if other is None:
423
+ continue
424
+ if other in self.lid_gids:
425
+ out[cc] = "lid"
426
+ elif other in self.robot_gids and out.get(cc) != "lid":
427
+ out[cc] = "robot"
428
+ return out
429
+
430
+ def monitor_step(self):
431
+ mon = self.mon
432
+ if mon is None:
433
+ return
434
+ mon["step"] += 1
435
+ step = self.sk.n_steps if self.sk is not None else mon["step"]
436
+ for c, who in self._touches().items():
437
+ mon["last_touch"][c] = (who, step)
438
+ if who == "lid":
439
+ mon["lid_hits"].add(c)
440
+ q = self.lid_deg()
441
+ if q > 95.0 and abs(q - mon["lid_prev"]) > 0.5:
442
+ mon["lid_moving_step"] = step # the open lid is swinging (its contacts can last less than a control step)
443
+ mon["lid_prev"] = q
444
+ mon["lid_open_max"] = max(mon["lid_open_max"], q)
445
+ if not mon["lid_opened"] and q > 90.0:
446
+ mon["lid_opened"] = True
447
+ mon["lid_open_steps"].append(step)
448
+ mon["events"].append(dict(step=step, pred="lid", ev="opened_past_vertical"))
449
+ elif mon["lid_opened"] and q <= np.degrees(LID_CLOSED):
450
+ mon["lid_opened"] = False
451
+ mon["lid_close_steps"].append(step)
452
+ mon["events"].append(dict(step=step, pred="lid", ev="closed"))
453
+ if mon["step"] % 2:
454
+ return # predicates every other control step (0.1 s)
455
+ for c in COLORS:
456
+ key = f"{c}_on_mark"
457
+ was = mon["state"][key]
458
+ now = self.on_mark(c, TOL if not was else TOL + 0.005) # hysteresis against jitter at the border
459
+ if now != was:
460
+ self._event(key, now, step, c)
461
+ was = mon["state"]["cube_in_box"]
462
+ now = self.cube_in_box()
463
+ if now != was:
464
+ self._event("cube_in_box", now, step, None)
465
+
466
+ def _event(self, key, now, step, color):
467
+ mon = self.mon
468
+ mon["state"][key] = now
469
+ if now:
470
+ ev = "restored" if key in mon["lost"] else "achieved"
471
+ mon["ever"].add(key)
472
+ if key in mon["lost"]:
473
+ mon["lost"].discard(key)
474
+ mon["events"].append(dict(step=step, pred=key, ev=ev))
475
+ else:
476
+ cause = "other"
477
+ if color is not None:
478
+ if self.held(BLOCKS[color]):
479
+ cause = "picked_up"
480
+ else:
481
+ lt = mon["last_touch"][color]
482
+ if lt is not None and step - lt[1] <= 60:
483
+ cause = lt[0]
484
+ if cause == "other" and step - mon["lid_moving_step"] <= 20 and color in self.inst["behind"]:
485
+ cause = "lid" # lost while the open lid was swinging down onto the blocks behind the box
486
+ elif self.held(CUBE):
487
+ cause = "picked_up"
488
+ mon["lost"].add(key)
489
+ ev = dict(step=step, pred=key, ev="lost", cause=cause, lid_deg=round(self.lid_deg(), 1))
490
+ if color is not None:
491
+ ev["offset_cm"] = (100 * self.block_offset(color)).round(1).tolist()
492
+ mon["events"].append(ev)
493
+
494
+ # ------------------------------------------------------------ outcome
495
+ def _static(self):
496
+ d = self.env.sim.data
497
+ for name in [BLOCKS[c] for c in COLORS] + [CUBE]:
498
+ _, da = envs.free_joint_addr(self.env, name)
499
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
500
+ return False
501
+ return abs(float(d.qvel[self.dof])) < 0.2
502
+
503
+ def outcome(self, inst):
504
+ envs.settle(self.env, 30)
505
+ mon = self.mon
506
+ vals = self.stage_values()
507
+ static = self._static()
508
+ held = [n for n in [BLOCKS[c] for c in COLORS] + [CUBE] if self.held(n)]
509
+ success = bool(all(vals.values()) and static and not held)
510
+ regress = [e for e in mon["events"] if e["ev"] == "lost"]
511
+ restored = [e for e in mon["events"] if e["ev"] == "restored"]
512
+ lid_knocks = [e for e in regress if e.get("cause") == "lid"]
513
+ parts = []
514
+ if success:
515
+ failure = None
516
+ parts.append("All three blocks are on their marks, the red cube is in the box and the lid is closed.")
517
+ else:
518
+ off = [c for c in COLORS if not vals[f"{c}_on_mark"]]
519
+ failure = ("block_off_mark" if off else "cube_not_in_box" if not vals["cube_in_box"] else
520
+ "lid_open" if not vals["lid_closed"] else "held" if held else "not_static")
521
+ for c in off:
522
+ o = self.block_offset(c)
523
+ name = BLOCKS[c]
524
+ if self.held(name):
525
+ parts.append(f"The {c} block is still held by the gripper.")
526
+ continue
527
+ txt = (f"The {c} block is not on the {c} mark: its centre is {_fb(o[0])} and {_lr(o[1])} of the mark's "
528
+ f"centre")
529
+ if not self._flat(name):
530
+ txt += " and it is tipped over"
531
+ why = [e for e in regress if e["pred"] == f"{c}_on_mark"]
532
+ if f"{c}_on_mark" not in mon["ever"]:
533
+ txt += " (it was never on its mark)."
534
+ elif why and why[-1].get("cause") == "lid":
535
+ txt += (f" (it had been on its mark; the lid pushed it off when it fell open to "
536
+ f"{why[-1]['lid_deg']:.0f} degrees).")
537
+ elif why and why[-1].get("cause") == "robot":
538
+ txt += " (it had been on its mark; the robot knocked it off)."
539
+ else:
540
+ txt += " (it had been on its mark earlier)."
541
+ parts.append(txt)
542
+ if not vals["cube_in_box"]:
543
+ if self.held(CUBE):
544
+ parts.append("The red cube is still held by the gripper.")
545
+ else:
546
+ p = envs.obj_pos(self.env, CUBE)
547
+ rel = p[:2] - np.asarray(inst["box_xy"])
548
+ parts.append(f"The red cube is not in the box: its centre is {_fb(rel[0])} and {_lr(rel[1])} of the "
549
+ f"box's centre.")
550
+ if not vals["lid_closed"]:
551
+ parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees).")
552
+ if not static and all(vals.values()):
553
+ parts.append("Something was still moving at the end.")
554
+ if mon["lid_open_max"] < 90.0:
555
+ parts.append("The lid was never opened past upright.")
556
+ out = dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
557
+ events=mon["events"], n_regressions=len(regress), n_restored=len(restored),
558
+ n_lid_knocks=len(lid_knocks), lid_hits=sorted(mon["lid_hits"]),
559
+ lid_open_max=round(mon["lid_open_max"], 1), lid_final_deg=round(self.lid_deg(), 1),
560
+ knob_grasps=self.sk.knob_grasps, knob_steps=self.sk.knob_steps,
561
+ block_offsets_cm={c: (100 * self.block_offset(c)).round(1).tolist() for c in COLORS},
562
+ detail=" ".join(parts))
563
+ return out
564
+
565
+ # ------------------------------------------------------------ scripted policies (perfect perception)
566
+ def _grasp_yaw(self, name):
567
+ R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
568
+ i = int(np.argmin(np.abs(R[2]))) # the most horizontal body axis (works whichever face the cube rests on)
569
+ yaw = float(np.arctan2(R[1, i], R[0, i]))
570
+ return float((yaw + np.pi / 4) % (np.pi / 2) - np.pi / 4) # a cube: grasp yaw mod 90 deg
571
+
572
+ def pick_place(self, name, dest_xy, z_rel, z_carry=Z_CARRY, noise=None, dest_yaw=0.0):
573
+ """Top-down pick of `name` at its centre, carry at `z_carry` (grasp point above the table), release with the
574
+ grasp point `z_rel` above the table at `dest_xy`, lift."""
575
+ sk = self.sk
576
+ Z = envs.TABLE_Z
577
+ p = envs.obj_pos(self.env, name)
578
+ yaw = self._grasp_yaw(name)
579
+ zg = p[2] - Z
580
+ sk.set_gripper(False, steps=8)
581
+ sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=yaw)
582
+ sk.move_to([p[0], p[1], Z + zg], tol=0.003)
583
+ sk.set_gripper(True, steps=15)
584
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
585
+ if not self.held(name):
586
+ sk.set_gripper(False, steps=8)
587
+ return False
588
+ d = np.asarray(dest_xy, float) + (np.asarray(noise, float) if noise is not None else 0.0)
589
+ sk.move_to([d[0], d[1], Z + z_carry], yaw=dest_yaw)
590
+ sk.move_to([d[0], d[1], Z + z_rel], tol=0.003)
591
+ sk.set_gripper(False, steps=12)
592
+ sk.move_to([d[0], d[1], Z + z_carry])
593
+ return True
594
+
595
+ def place_block(self, c, noise=None):
596
+ return self.pick_place(BLOCKS[c], self.inst["marks"][c], BLOCK / 2 + 0.004, noise=noise)
597
+
598
+ def put_cube(self, noise=None):
599
+ bx, by = self.inst["box_xy"]
600
+ return self.pick_place(CUBE, [bx, by], FLOOR_T + CUBE_E / 2 + 0.008, z_carry=0.12, noise=noise)
601
+
602
+ def _grasp_knob(self):
603
+ sk = self.sk
604
+ k = self.knob_xyz()
605
+ sk.set_gripper(False, steps=8)
606
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0)
607
+ sk.move_to([k[0], k[1], k[2]], tol=0.003)
608
+ sk.set_gripper(True, steps=15)
609
+ return k
610
+
611
+ def open_lid(self, back=0.03, up=0.16):
612
+ """grasp the knob; straight up 10 cm; straight to `back` m behind the hinge, `up` m above it; release; lift"""
613
+ sk = self.sk
614
+ k = self._grasp_knob()
615
+ hx, hz = self.hinge_xz()
616
+ sk.move_to([k[0], k[1], k[2] + 0.10])
617
+ sk.move_to([hx + back, k[1], hz + up])
618
+ sk.set_gripper(False, steps=10)
619
+ e = sk.eef_pos()
620
+ sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06])
621
+ sk.hold(20)
622
+
623
+ def close_lid(self):
624
+ """grasp the knob where it is; straight up 10 cm; straight forward to 8 cm in front of the hinge; release"""
625
+ sk = self.sk
626
+ k = self._grasp_knob()
627
+ hx, hz = self.hinge_xz()
628
+ sk.move_to([k[0], k[1], k[2] + 0.10])
629
+ sk.move_to([hx - 0.08, k[1], k[2] + 0.10])
630
+ sk.set_gripper(False, steps=10)
631
+ e = sk.eef_pos()
632
+ sk.move_to([e[0], e[1], e[2] + 0.06])
633
+ sk.hold(20)
634
+
635
+ def restore(self, rounds=2):
636
+ """look at every stage and fix what is wrong (lid open -> close it; cube out -> put it in; block off -> put it
637
+ back), up to `rounds` passes"""
638
+ for _ in range(rounds):
639
+ v = self.stage_values()
640
+ if all(v.values()):
641
+ return True
642
+ if not v["cube_in_box"]:
643
+ if self.lid_q() < np.radians(95):
644
+ self.open_lid()
645
+ self.put_cube()
646
+ self.close_lid()
647
+ elif not v["lid_closed"]:
648
+ self.close_lid()
649
+ for c in COLORS:
650
+ if not self.on_mark(c):
651
+ self.place_block(c)
652
+ return all(self.stage_values().values())
653
+
654
+ def execute(self, inst, params):
655
+ order = params.get("order") or list(COLORS)
656
+ noise = params.get("noise") or {}
657
+ if params["plan"] == "blocks_first":
658
+ for c in order:
659
+ self.place_block(c, noise.get(c))
660
+ self.open_lid(**params.get("open", {}))
661
+ self.put_cube(noise.get("cube"))
662
+ self.close_lid()
663
+ else: # "lid_first": open, cube in, close, then the blocks
664
+ self.open_lid(**params.get("open", {}))
665
+ self.put_cube(noise.get("cube"))
666
+ self.close_lid()
667
+ for c in order:
668
+ self.place_block(c, noise.get(c))
669
+ if params.get("check"):
670
+ self.restore()
671
+ self.sk.hold(10)
672
+
673
+ def default_params(self, inst):
674
+ return dict(plan="blocks_first", check=False)
675
+
676
+ def oracle_params(self, inst):
677
+ return dict(plan="lid_first", check=True)
678
+
679
+ def adapt_params(self, inst, history):
680
+ """Used from attempt 2 on, i.e. after a failed attempt (attempt 1 is the natural order plus a final check and
681
+ repair, see run_scripted): open the box, put the cube in and close it first, then place the blocks, check."""
682
+ return dict(plan="lid_first", check=True)
683
+
684
+ def blind_params(self, inst, attempt, rng):
685
+ """the natural order again with small random variations (block order, placement, release point), no check"""
686
+ return dict(plan="blocks_first", check=False, order=[str(c) for c in rng.permutation(COLORS)],
687
+ noise={c: rng.normal(0.0, 0.004, 2).tolist() for c in COLORS},
688
+ open=dict(back=float(rng.uniform(0.0, 0.05)), up=float(rng.uniform(0.14, 0.18))))
689
+
690
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
691
+ k = k or self.max_attempts
692
+ rng = np.random.default_rng(seed)
693
+ history = []
694
+ for a in range(k):
695
+ self.reset_instance(inst)
696
+ if kind == "oracle":
697
+ params = self.oracle_params(inst)
698
+ elif kind == "naive":
699
+ params = self.default_params(inst)
700
+ elif kind == "adaptive":
701
+ params = dict(plan="blocks_first", check=True) if a == 0 else self.adapt_params(inst, history)
702
+ elif kind == "blind":
703
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
704
+ elif kind == "switch": # extra control (not in validate's table): cross-attempt learning only, no re-check
705
+ params = self.default_params(inst) if a == 0 else dict(plan="lid_first", check=False)
706
+ else:
707
+ raise ValueError(kind)
708
+ self.execute(inst, params)
709
+ out = self.outcome(inst)
710
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
711
+ if on_attempt:
712
+ on_attempt(a, params, out)
713
+ if out["success"] or kind in ("oracle", "naive"):
714
+ break
715
+ return history
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LH pantry_relatch: breakfast prep. Take the bread out of a hinged pantry box and put it on the plate, then put the
2
+ butter into the (now empty) box and close it.
3
+
4
+ New mechanism (not a repeat of lh_lid_box / lh_shelf_droop / lh_false_bottom_lid): the box's closing catch is not a
5
+ static per-instance draw, it is a counter of how many times the box has already been closed in this attempt. A weak
6
+ spring (`OPEN_BIAS`) constantly nudges the lid open; a catch (`qfrc_applied`, same idiom as lh_shelf_droop's bracket)
7
+ counters it near the closed angle. The FIRST close always holds (LATCH0 beats the spring) even with a quick swing-and
8
+ -release. After one full open/close cycle the catch's holding strength is reduced (`DECAY`); a second quick-release
9
+ close is no longer enough and the lid creeps back open by itself during the mandatory settle window, with nothing
10
+ else touching it. The fix is not "close it again the same way" (that decays again); it is a firm press-and-hold
11
+ (`dwell`) at the closed angle before letting go, which engages a separate, non-decaying friction seat
12
+ (`SEAT_LATCH`) regardless of cycle count.
13
+
14
+ Geometry/skills are reused unmodified from lh_lid_box.py (box_lid_xml, LidSkills): only the hinge's spring/latch
15
+ torques and the Python cycle counter are new. Protocol: cross, k = 5.
16
+ """
17
+ import numpy as np
18
+
19
+ from .. import envs
20
+ from ..bddl import write_bddl
21
+ from ..objects import box_xml, register_generated
22
+ from ..task_base import LFFTask, register_task
23
+ from .lh_lid_box import (BOX_D, BOX_W, WALL_H, WALL_T, FLOOR_T, LID_T, LID_MASS, IN_X, IN_Y, HINGE_DAMP, box_lid_xml,
24
+ LidSkills)
25
+
26
+ G = 9.81
27
+ BOX = "box_1"
28
+ BOX_MODEL = "lff_pantry_box"
29
+
30
+ BREAD_HALF = (0.032, 0.022, 0.011) # 6.4 x 4.4 x 2.2 cm flat loaf, fits the 3.2 cm interior height
31
+ BUTTER_HALF = (0.013, 0.013, 0.013) # 2.6 cm cube
32
+ BREAD_DENS, BUTTER_DENS = 400.0, 600.0
33
+
34
+ # ---------------------------------------------------------------- latch-fatigue mechanism
35
+ CLOSE_DEG = 4.0 # lid angle (deg) counted as "closed" for the final judge
36
+ BAND_DEG = 100.0 # angle range (deg) over which gravity is cancelled and the open bias/catch act (wide, so
37
+ # an unlatched lid drifts smoothly all the way open instead of sticking at a cutoff edge)
38
+ OPEN_BIAS = 0.05 # N*m: net torque pushing the lid open within the band, once gravity is cancelled
39
+ LATCH0 = 0.14 # N*m: catch strength on the FIRST close (always beats OPEN_BIAS)
40
+ DECAY = 0.30 # catch strength multiplier from the SECOND close on, if not seated
41
+ SEAT_LATCH = 0.18 # N*m: non-decaying strength if the close was seated (dwell-pressed)
42
+ DWELL_MIN = 20 # control steps (closed, knob held, no further motion) needed to seat a close
43
+ EXTRA_DAMP = 0.12 # N*m*s/rad added to the hinge dof so an unlatched drift takes a few seconds, not instant
44
+ GRAVITY_LEVER = BOX_D / 2 # lid's centre of mass offset from the hinge (box_lid_xml convention)
45
+ T_GRAV0 = LID_MASS * G * GRAVITY_LEVER
46
+
47
+ SETTLE_MIN, SETTLE_MAX = 300, 600 # 15-30 s simulated, same convention as lh_shelf_droop
48
+
49
+
50
+ def _fb(v):
51
+ return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
52
+
53
+
54
+ def _lr(v):
55
+ return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
56
+
57
+
58
+ class RelatchSkills(LidSkills):
59
+ """LidSkills plus a dwell counter: control steps spent holding the knob still at the closed angle while latched.
60
+ `monitor_step` (run every control step via LidSkills._act, before this class's own _act resets the counter)
61
+ reads it at the instant the gripper opens near the closed angle to decide whether this close is 'seated'."""
62
+
63
+ def __init__(self, env, task, recorder=None):
64
+ super().__init__(env, task, recorder=recorder)
65
+ self.dwell = 0
66
+
67
+ def _act(self, dpos, drot, grip):
68
+ super()._act(dpos, drot, grip) # LidSkills._act calls self.task.monitor_step() before returning here
69
+ if self.latched:
70
+ # the agent (or scripted policy) is actively holding the knob: never let the artificial drift fight
71
+ # that grasp (it caused the knob to wander off mid-regrasp during prototyping).
72
+ self.task.drift_active = False
73
+ if self.task.lid_deg() < CLOSE_DEG:
74
+ self.dwell += 1
75
+ else:
76
+ self.dwell = 0
77
+ else:
78
+ self.dwell = 0
79
+
80
+
81
+ @register_task
82
+ class PantryRelatch(LFFTask):
83
+ name = "lh_pantry_relatch"
84
+ level = "L2"
85
+ category = "state_restoration"
86
+ capabilities = ("Perceive", "Reason", "Plan", "Restore")
87
+ protocol = "cross"
88
+ max_attempts = 5
89
+ agent_max_steps = 130
90
+ instruction = ("Open the lid of the wooden pantry box (lift it by the black knob) and take the bread out; put it "
91
+ "on the plate. Then open the box again, put the butter inside it, and close the lid. At the end "
92
+ "the bread must be on the plate, the butter inside the box, the lid closed, the gripper open and "
93
+ "clear, and the scene still.")
94
+ instruction_indirect = ("Lift the lid of the flat wooden case by its black ball knob and take out the little "
95
+ "loaf; set it on the round plate. Then open the case again, put the small pale cube "
96
+ "inside it, and shut the lid. Finish with the loaf on the plate, the cube inside the "
97
+ "case, the lid down, the gripper open, and nothing moving.")
98
+ agent_object_names = ["bread (small loaf)", "butter (small pale cube)", "wooden pantry box", "lid knob", "plate"]
99
+
100
+ # ------------------------------------------------------------ scene
101
+ def make_bddl(self):
102
+ box = register_generated("LffPantryBox", box_lid_xml(BOX_MODEL), free=False)
103
+ bread = register_generated("LffPantryBread", box_xml("lff_pantry_bread", BREAD_HALF, (0.74, 0.52, 0.22, 1.0),
104
+ density=BREAD_DENS, friction=(0.7, 0.005, 0.0001)))
105
+ butter = register_generated("LffPantryButter", box_xml("lff_pantry_butter", BUTTER_HALF, (0.95, 0.92, 0.70, 1.0),
106
+ density=BUTTER_DENS, friction=(0.5, 0.005, 0.0001)))
107
+ objs = [("bread_1", bread, "bread_region", (-0.31, -0.01, -0.29, 0.01)),
108
+ ("butter_1", butter, "butter_region", (-0.31, 0.24, -0.29, 0.26)),
109
+ ("plate_1", "plate", "plate_region", (0.02, -0.26, 0.04, -0.24))]
110
+ fx = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
111
+ return write_bddl(self.name, "take the bread out, put it on the plate, put the butter in the box, close it",
112
+ objs, fx)
113
+
114
+ def __init__(self, cam_res=None):
115
+ super().__init__(cam_res)
116
+ m = self.env.sim.model
117
+ pre = f"{BOX}_{BOX_MODEL}"
118
+ self.jid = m.joint_name2id(pre + "_hinge")
119
+ self.qa = int(m.jnt_qposadr[self.jid])
120
+ self.dof = int(m.jnt_dofadr[self.jid])
121
+ self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
122
+ self.knob_geom_name = pre + "_knob"
123
+ self.knob_geom_names = [pre + "_knob", pre + "_stem"]
124
+ self.knob_gid = m.geom_name2id(self.knob_geom_name)
125
+ sim = self.env.sim
126
+ if not getattr(sim, "_lhpr_wrapped", False):
127
+ orig = sim.step
128
+
129
+ def step(*a, **k):
130
+ orig(*a, **k)
131
+ t = getattr(sim, "_lhpr_task", None)
132
+ if t is not None:
133
+ t._bracket()
134
+
135
+ sim.step = step
136
+ sim._lhpr_wrapped = True
137
+ sim._lhpr_task = self
138
+ self.inst = None
139
+ self.mon = None
140
+ self.active_latch = LATCH0
141
+ self.closes_done = 0
142
+ self.drift_active = False
143
+
144
+ def sample_instance(self, seed):
145
+ rng = np.random.default_rng(seed)
146
+ bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03))
147
+ plate_xy = [float(rng.uniform(0.0, 0.06)), float(rng.uniform(-0.27, -0.23))]
148
+ bread_xy = [bx + float(rng.uniform(-0.01, 0.01)), by + float(rng.uniform(-0.01, 0.01))]
149
+ butter_xy = [float(rng.uniform(-0.32, -0.28)), float(rng.uniform(0.22, 0.28))]
150
+ return dict(seed=int(seed), box_xy=[bx, by], plate_xy=plate_xy, bread_xy=bread_xy, butter_xy=butter_xy,
151
+ bread_yaw=float(rng.uniform(-0.2, 0.2)), latch=True)
152
+
153
+ def apply_instance(self, inst):
154
+ self.inst = inst
155
+ m, d = self.env.sim.model, self.env.sim.data
156
+ bx, by = inst["box_xy"]
157
+ m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
158
+ m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
159
+ m.jnt_range[self.jid] = [0.0, np.radians(150.0)]
160
+ d.qpos[self.qa] = 0.0
161
+ d.qvel[self.dof] = 0.0
162
+ d.qfrc_applied[self.dof] = 0.0
163
+ m.dof_damping[self.dof] = HINGE_DAMP + EXTRA_DAMP # absolute, not cumulative across repeated resets
164
+ self._move_keep_orientation("plate_1", inst["plate_xy"])
165
+ envs.set_obj_pose(self.env, "bread_1", [bx, by, envs.TABLE_Z + FLOOR_T + BREAD_HALF[2] + 0.001],
166
+ yaw=inst["bread_yaw"])
167
+ envs.set_obj_pose(self.env, "butter_1", [*inst["butter_xy"], envs.TABLE_Z + BUTTER_HALF[2] + 0.0005])
168
+ self.closes_done = 0
169
+ self.active_latch = LATCH0
170
+ self.drift_active = False
171
+
172
+ def _move_keep_orientation(self, name, xy, clearance=0.002):
173
+ qa, da = envs.free_joint_addr(self.env, name)
174
+ d = self.env.sim.data
175
+ d.qpos[qa:qa + 2] = xy
176
+ d.qvel[da:da + 6] = 0.0
177
+ self.env.sim.forward()
178
+ d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance)
179
+ self.env.sim.forward()
180
+
181
+ def reset_instance(self, inst, recorder=None):
182
+ self.env.reset()
183
+ self.apply_instance(inst)
184
+ self.env.sim.forward()
185
+ envs.settle(self.env, 10)
186
+ self.mon = dict(events=[], lid_open_max=0.0, armed=False)
187
+ self.sk = RelatchSkills(self.env, self, recorder=recorder)
188
+ return self.sk
189
+
190
+ # ------------------------------------------------------------ latch physics
191
+ def lid_q(self):
192
+ return float(self.env.sim.data.qpos[self.qa])
193
+
194
+ def lid_deg(self):
195
+ return float(np.degrees(self.lid_q()))
196
+
197
+ def knob_xyz(self):
198
+ return self.env.sim.data.geom_xpos[self.knob_gid].copy()
199
+
200
+ def hinge_xz(self):
201
+ return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H
202
+
203
+ def _bracket(self):
204
+ """Every MuJoCo substep. Only active between a just-finished, under-latched close and the next time the
205
+ agent actually grasps the knob again (self.drift_active, cleared the instant the knob is latched -- see
206
+ RelatchSkills._act): within BAND_DEG of closed, cancel gravity's closing pull and add a small constant
207
+ opening bias, net positive because the catch is too weak (self.active_latch < OPEN_BIAS whenever
208
+ drift_active is set True in the first place). A held-firmly close needs no artificial force at all: plain
209
+ gravity already keeps box_lid_xml's lid shut on its own, same as lh_lid_box."""
210
+ d = self.env.sim.data
211
+ if not self.inst.get("latch", True) or not self.drift_active:
212
+ d.qfrc_applied[self.dof] = 0.0 # never leave a stale value applied once the drift is no longer armed
213
+ return
214
+ th = float(d.qpos[self.qa])
215
+ # the closed rest angle overshoots the joint limit by a hair (contact softness), so the lower edge of the
216
+ # band must tolerate a small negative theta -- a strict "th >= 0" guard left qfrc_applied permanently 0 at
217
+ # the resting pose and the catch never engaged at all (measured during prototyping).
218
+ if np.radians(-3.0) <= th < np.radians(BAND_DEG):
219
+ grav = T_GRAV0 * max(np.cos(th), 0.0)
220
+ d.qfrc_applied[self.dof] = grav + OPEN_BIAS - self.active_latch
221
+ else:
222
+ d.qfrc_applied[self.dof] = 0.0
223
+
224
+ def _register_close(self, seated):
225
+ """Called once a close-then-release is detected. Decides the catch strength that will apply to THIS closed
226
+ state from now on (until the lid is reopened and closed again), and whether the artificial drift-open force
227
+ is armed (only when the catch is too weak to hold on its own)."""
228
+ if self.closes_done == 0:
229
+ self.active_latch = LATCH0
230
+ elif seated:
231
+ self.active_latch = SEAT_LATCH
232
+ else:
233
+ self.active_latch = LATCH0 * DECAY
234
+ self.closes_done += 1
235
+ self.drift_active = self.active_latch < OPEN_BIAS
236
+ self.mon["events"].append(dict(ev="closed", n=self.closes_done, seated=bool(seated),
237
+ active_latch=round(self.active_latch, 4), drift_armed=self.drift_active))
238
+
239
+ def monitor_step(self):
240
+ """Runs every control step (via LidSkills._act, for the scripted policies below and for a real agent's own
241
+ move_to/set_gripper calls alike). One-shot edge detector: 'armed' once the lid has been meaningfully open
242
+ (> 20 deg); the first step afterwards where it is back near closed AND the gripper is open counts as a
243
+ close event, scored seated/unseated from the dwell counter at that exact instant (before RelatchSkills._act
244
+ resets it for this same step -- see the call order note there)."""
245
+ mon = self.mon
246
+ if mon is None:
247
+ return
248
+ q = self.lid_deg()
249
+ mon["lid_open_max"] = max(mon["lid_open_max"], q)
250
+ if q > 20.0:
251
+ mon["armed"] = True
252
+ if mon.get("armed") and q <= CLOSE_DEG and self.sk.grip < 0:
253
+ mon["armed"] = False
254
+ self._register_close(self.sk.dwell >= DWELL_MIN)
255
+
256
+ # ------------------------------------------------------------ predicates
257
+ def held(self, name):
258
+ return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
259
+
260
+ def bread_on_plate(self):
261
+ p = envs.obj_pos(self.env, "bread_1")
262
+ d = np.linalg.norm(p[:2] - np.asarray(self.inst["plate_xy"]))
263
+ return bool(d < 0.05 and p[2] < envs.TABLE_Z + 0.06 and not self.held("bread_1"))
264
+
265
+ def butter_in_box(self):
266
+ p = envs.obj_pos(self.env, "butter_1")
267
+ rel = p[:2] - np.asarray(self.inst["box_xy"])
268
+ return bool(abs(rel[0]) <= IN_X - 0.004 and abs(rel[1]) <= IN_Y - 0.004 and p[2] < envs.TABLE_Z + WALL_H
269
+ and not self.held("butter_1"))
270
+
271
+ def lid_closed(self):
272
+ return self.lid_q() <= np.radians(CLOSE_DEG)
273
+
274
+ def stage_values(self):
275
+ return dict(bread_on_plate=self.bread_on_plate(), butter_in_box=self.butter_in_box(), lid_closed=self.lid_closed())
276
+
277
+ # ------------------------------------------------------------ scripted primitives
278
+ def pick_place(self, name, dest_xy, z_rel, z_carry=0.14, dest_yaw=0.0):
279
+ sk = self.sk
280
+ Z = envs.TABLE_Z
281
+ p = envs.obj_pos(self.env, name)
282
+ zg = p[2] - Z
283
+ sk.set_gripper(False, steps=8)
284
+ sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=0.0)
285
+ sk.move_to([p[0], p[1], Z + zg], tol=0.003)
286
+ sk.set_gripper(True, steps=15)
287
+ sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
288
+ self.monitor_step()
289
+ if not self.held(name):
290
+ sk.set_gripper(False, steps=8)
291
+ return False
292
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=dest_yaw)
293
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003)
294
+ sk.set_gripper(False, steps=12)
295
+ sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry])
296
+ self.monitor_step()
297
+ return True
298
+
299
+ def take_bread(self):
300
+ return self.pick_place("bread_1", self.inst["plate_xy"], BREAD_HALF[2] + 0.004)
301
+
302
+ def put_butter(self):
303
+ # placed closer to the hinge side and off to one side of the box centre, clear of where the far (knob) end
304
+ # of the lid sweeps most when re-opened for a repair (measured during prototyping: a butter cube resting
305
+ # under the box centre was occasionally grazed by that swing).
306
+ bx, by = self.inst["box_xy"]
307
+ target = [bx + 0.6 * IN_X, by + 0.5 * IN_Y]
308
+ return self.pick_place("butter_1", target, FLOOR_T + BUTTER_HALF[2] + 0.006, z_carry=0.12)
309
+
310
+ def _grasp_knob(self):
311
+ sk = self.sk
312
+ k = self.knob_xyz()
313
+ sk.set_gripper(False, steps=8)
314
+ sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0)
315
+ sk.move_to([k[0], k[1], k[2]], tol=0.003)
316
+ sk.set_gripper(True, steps=15)
317
+ return k
318
+
319
+ def open_lid(self, back=0.03, up=0.16):
320
+ sk = self.sk
321
+ k = self._grasp_knob()
322
+ hx, hz = self.hinge_xz()
323
+ sk.move_to([k[0], k[1], k[2] + 0.10])
324
+ sk.move_to([hx + back, k[1], hz + up])
325
+ sk.set_gripper(False, steps=10)
326
+ e = sk.eef_pos()
327
+ sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06])
328
+ sk.hold(20)
329
+ self.monitor_step()
330
+
331
+ def close_lid(self, dwell=False):
332
+ """grasp the knob, carry it down the hinge's arc to the closed angle (the compliant knob-hold mechanism
333
+ clamps the physical joint limit at 0 deg, so a target far past closed just drives it fully shut); if dwell,
334
+ hold there (gripper still closed on the knob) for DWELL_MIN+ steps before releasing (seats the friction
335
+ catch); otherwise release immediately."""
336
+ sk = self.sk
337
+ k = self._grasp_knob()
338
+ hx, hz = self.hinge_xz()
339
+ sk.move_to([k[0], k[1], k[2] + 0.10])
340
+ far_x = hx - (BOX_D + 0.20)
341
+ low_z = envs.TABLE_Z + 0.02
342
+ for _ in range(4):
343
+ if self.lid_deg() <= CLOSE_DEG:
344
+ break
345
+ sk.move_to([far_x, sk.eef_pos()[1], low_z], tol=0.01, max_steps=150)
346
+ if dwell:
347
+ sk.hold(DWELL_MIN + 8)
348
+ sk.set_gripper(False, steps=10)
349
+ e = sk.eef_pos()
350
+ sk.move_to([e[0], e[1], e[2] + 0.06])
351
+ sk.hold(20)
352
+ self.monitor_step()
353
+
354
+ # ------------------------------------------------------------ outcome
355
+ def _static(self):
356
+ d = self.env.sim.data
357
+ for name in ("bread_1", "butter_1"):
358
+ _, da = envs.free_joint_addr(self.env, name)
359
+ if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
360
+ return False
361
+ return abs(float(d.qvel[self.dof])) < 0.2
362
+
363
+ def outcome(self, inst):
364
+ sk = self.sk
365
+ n = 0
366
+ while n < SETTLE_MAX:
367
+ sk.hold(10)
368
+ n += 10
369
+ if n >= SETTLE_MIN and self._static():
370
+ break
371
+ vals = self.stage_values()
372
+ held = [n for n in ("bread_1", "butter_1") if self.held(n)]
373
+ static = self._static()
374
+ success = bool(all(vals.values()) and static and not held)
375
+ if success:
376
+ failure = None
377
+ detail = "Bread is on the plate, butter is in the box, and the lid is closed."
378
+ else:
379
+ failure = ("bread" if not vals["bread_on_plate"] else "butter" if not vals["butter_in_box"] else
380
+ "lid_open" if not vals["lid_closed"] else "held" if held else "not_static")
381
+ parts = []
382
+ if not vals["bread_on_plate"]:
383
+ p = envs.obj_pos(self.env, "bread_1")
384
+ rel = p[:2] - np.asarray(inst["plate_xy"])
385
+ parts.append("The bread is still held." if self.held("bread_1") else
386
+ f"The bread is not on the plate: {_fb(rel[0])} and {_lr(rel[1])} of the plate's centre.")
387
+ if not vals["butter_in_box"]:
388
+ p = envs.obj_pos(self.env, "butter_1")
389
+ rel = p[:2] - np.asarray(inst["box_xy"])
390
+ parts.append("The butter is still held." if self.held("butter_1") else
391
+ f"The butter is not in the box: {_fb(rel[0])} and {_lr(rel[1])} of the box's centre.")
392
+ if not vals["lid_closed"]:
393
+ parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees). It had been closed "
394
+ f"{self.closes_done} time(s) in this attempt; it did not stay shut on its own.")
395
+ if held:
396
+ parts.append(f"Still held: {', '.join(held)}.")
397
+ if not static and all(vals.values()):
398
+ parts.append("Something was still moving.")
399
+ detail = " ".join(parts)
400
+ return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
401
+ lid_final_deg=round(self.lid_deg(), 1), lid_open_max=round(self.mon["lid_open_max"], 1),
402
+ closes_done=self.closes_done, active_latch=round(self.active_latch, 4),
403
+ events=list(self.mon["events"]), detail=detail)
404
+
405
+ # ------------------------------------------------------------ execution + scripted policies
406
+ def execute(self, inst, params):
407
+ self.open_lid()
408
+ if not self.take_bread():
409
+ return
410
+ self.close_lid(dwell=params.get("dwell1", False))
411
+ self.open_lid()
412
+ if not self.put_butter():
413
+ return
414
+ self.close_lid(dwell=params.get("dwell2", False))
415
+ if params.get("check", False):
416
+ # look back before finishing: wait long enough (same order as the final settle window) for an
417
+ # under-latched close to reveal itself, then fix it with a firm dwell close if it did -- a genuine
418
+ # same-attempt recovery, not just a cross-attempt change of technique.
419
+ n = 0
420
+ while n < SETTLE_MIN and self.lid_closed():
421
+ self.sk.hold(10)
422
+ n += 10
423
+ if not self.lid_closed():
424
+ self.open_lid()
425
+ self.close_lid(dwell=True)
426
+ self.sk.hold(5)
427
+
428
+ def default_params(self, inst):
429
+ return dict(dwell1=False, dwell2=False, check=False)
430
+
431
+ def oracle_params(self, inst):
432
+ return dict(dwell1=False, dwell2=True, check=False)
433
+
434
+ def adapt_params(self, inst, history):
435
+ """From attempt 2 on (if attempt 1's own same-attempt check-and-repair somehow still fell short): close
436
+ every time with a firm dwell from the start, and keep checking before finishing."""
437
+ return dict(dwell1=True, dwell2=True, check=True)
438
+
439
+ def blind_params(self, inst, attempt, rng):
440
+ return dict(dwell1=False, dwell2=bool(rng.random() < 0.5), check=False)
441
+
442
+ def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
443
+ k = k or self.max_attempts
444
+ rng = np.random.default_rng(seed)
445
+ history = []
446
+ for a in range(k):
447
+ self.reset_instance(inst)
448
+ if kind == "oracle":
449
+ params = self.oracle_params(inst)
450
+ elif kind == "naive":
451
+ params = self.default_params(inst)
452
+ elif kind == "adaptive":
453
+ # attempt 1: naive technique plus a final look-back-and-repair (genuine same-attempt recovery);
454
+ # only if that still were not enough would later attempts switch technique from the start.
455
+ params = (dict(self.default_params(inst), check=True) if a == 0
456
+ else self.adapt_params(inst, history))
457
+ elif kind == "blind":
458
+ params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
459
+ else:
460
+ raise ValueError(kind)
461
+ self.execute(inst, params)
462
+ out = self.outcome(inst)
463
+ history.append(dict(attempt=a + 1, params=params, outcome=out))
464
+ if on_attempt:
465
+ on_attempt(a, params, out)
466
+ if out["success"] or kind in ("oracle", "naive"):
467
+ break
468
+ return history
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/vla.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Evaluate a visuomotor policy (VLA, e.g. pi0.5) on LFF-Bench instances.
2
+
3
+ A VLA sends 7-D OSC actions at 20 Hz instead of the agents' robot commands. Everything else is the benchmark's own:
4
+ task scenes and instances, per-attempt budgets, attempt transitions (cross = reset, within = continue in place) and
5
+ task.outcome(). The observation has the layout of the LeRobot replay dataset (scripts/lerobot_replay.py, Recorder.state),
6
+ so a policy trained on that dataset needs no adapter. Driver: scripts/vla_eval.py.
7
+
8
+ What differs from the agents' interface, and why:
9
+ - Actions go through sk._act, not env.step: the tasks' per-step monitors and failure injections live there.
10
+ - sk.grip and sk.yaw are kept in step with the policy, because outcome() and go_home() use them (Skills.hold holds
11
+ sk.yaw, not the current orientation) and set_gripper hooks run with steps=0 once the fingers have settled.
12
+ - The hidden offset of L1 tasks is applied in Skills.move_to / YawSkills.R0, which direct actions bypass. The policy still
13
+ reads its proprioception in the robot's believed frame (frame="believed"), as the agents do, but an L1 result does not
14
+ measure the same trap as for an agent: report those tasks separately.
15
+ - There is no `finish`: an attempt ends when its simulated-time budget runs out or the arm has been idle for idle_s.
16
+ """
17
+ import os
18
+ import select
19
+ import time
20
+
21
+ import msgpack
22
+ import numpy as np
23
+
24
+ from . import envs
25
+ from .agent import camera as C
26
+ from .skills import ROT_SCALE
27
+
28
+ CONTROL_HZ = 20
29
+ GRIP_SETTLE = 15 # control steps the fingers get before the set_gripper hooks fire (Skills.set_gripper's default)
30
+ IDLE_EEF_M = 0.001 # the grasp point moved less than this over idle_s, with the gripper command unchanged
31
+
32
+
33
+ def _rotz(a):
34
+ c, s = np.cos(a), np.sin(a)
35
+ return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
36
+
37
+
38
+ def read_state(env, sk, frame="believed"):
39
+ """8-D state: eef position (world, m), eef orientation (axis-angle), two finger joints -- the dataset's layout.
40
+ frame="believed" applies the hidden calibration errors the way everything shown to an agent does (Skills.bias,
41
+ YawSkills.yaw_bias; robot_server._believed_pose); without such an error it equals frame="true"."""
42
+ import robosuite.utils.transform_utils as T
43
+ d, rob = env.sim.data, env.robots[0]
44
+ pos = np.array(d.site_xpos[rob.eef_site_id], np.float64)
45
+ quat = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
46
+ if frame == "believed":
47
+ pos = pos - np.asarray(sk.bias, np.float64)
48
+ beta = float(getattr(sk, "yaw_bias", 0.0))
49
+ if beta:
50
+ quat = T.mat2quat(_rotz(-beta) @ T.quat2mat(quat))
51
+ elif frame != "true":
52
+ raise ValueError(f"unknown proprioception frame {frame!r}")
53
+ grip = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
54
+ return np.concatenate([pos, np.asarray(T.quat2axisangle(quat), np.float64), grip]).astype(np.float32)
55
+
56
+
57
+ def task_prompt(task, inst):
58
+ """The instruction an agent gets for this instance (robot_server.instruction): some tasks build it per instance."""
59
+ hook = getattr(task, "agent_instruction", None)
60
+ return hook(inst, "direct") if hook is not None else task.instruction
61
+
62
+
63
+ def read_obs(task, inst, res=256, frame="believed"):
64
+ """The observation a policy receives, in the openpi request format. Images are uint8 HWC, upright."""
65
+ env = task.env
66
+ return {"observation/image": envs.render(env, C.mj_cam("agentview"), res),
67
+ "observation/wrist_image": envs.render(env, C.mj_cam("wrist"), res),
68
+ "observation/state": read_state(env, task.sk, frame),
69
+ "prompt": task_prompt(task, inst)}
70
+
71
+
72
+ class PolicyActuator:
73
+ """Applies one policy action to the task's Skills. a = (dpos, drot, gripper) in [-1, 1], scaled like Skills._act;
74
+ gripper > 0 closes (dataset convention: -1 open, +1 close)."""
75
+
76
+ def __init__(self, task):
77
+ self.task = task
78
+ self.sk = task.sk
79
+ self.close = self.sk.grip > 0
80
+ self.wait = 0
81
+
82
+ def _sync_yaw(self):
83
+ sk = self.sk
84
+ R = sk.eef_mat() @ sk.R0.T
85
+ sk.yaw = float(np.arctan2(R[1, 0], R[0, 0]))
86
+
87
+ def step(self, action):
88
+ sk = self.sk
89
+ a = np.clip(np.asarray(action, np.float64), -1.0, 1.0)
90
+ close = bool(a[6] > 0)
91
+ if (sk.grip > 0) != self.close: # the task moved the jaws itself (l6_sequence_resume's emergency stop)
92
+ self.close, self.wait = sk.grip > 0, 0
93
+ if getattr(self.task, "_latch", None) is not None:
94
+ # The task is driving the arm (env.step ignores the action) until "the current primitive has returned" and
95
+ # the arm is home. A policy has no primitives, so only the arm reaching home ends the routine.
96
+ sk.log.append(dict(prim="vla_step"))
97
+ elif close != self.close:
98
+ self.close, self.wait = close, GRIP_SETTLE
99
+ sk.grip = 1.0 if close else -1.0
100
+ sk._act(a[:3] * sk.pos_scale, a[3:6] * ROT_SCALE, sk.grip)
101
+ self._sync_yaw()
102
+ if self.wait:
103
+ self.wait -= 1
104
+ if not self.wait:
105
+ sk.set_gripper(self.close, steps=0)
106
+
107
+
108
+ def probe_success(task, inst, timeout=120.0):
109
+ """Would outcome() call this a success right now? outcome() steps the simulator and changes the task's monitors, so
110
+ it runs in a forked copy of this process; the attempt in the parent is untouched."""
111
+ r, w = os.pipe()
112
+ pid = os.fork()
113
+ if pid == 0:
114
+ code = 1
115
+ try:
116
+ os.close(r)
117
+ os.write(w, b"1" if task.outcome(inst)["success"] else b"0")
118
+ code = 0
119
+ finally:
120
+ os._exit(code)
121
+ os.close(w)
122
+ ready = select.select([r], [], [], timeout)[0]
123
+ got = os.read(r, 1) if ready else b""
124
+ os.close(r)
125
+ if not ready:
126
+ os.kill(pid, 9)
127
+ os.waitpid(pid, 0)
128
+ return got == b"1"
129
+
130
+
131
+ # ---------------------------------------------------------------- policies
132
+ class PolicyEnded(Exception):
133
+ """The policy has no more actions (a replayed recording ran out)."""
134
+
135
+
136
+ class ZeroPolicy:
137
+ """Holds still with the gripper open. Smoke tests only."""
138
+ metadata = dict(policy="zero")
139
+
140
+ def reset(self):
141
+ pass
142
+
143
+ def infer(self, obs):
144
+ a = np.zeros((10, 7), np.float32)
145
+ a[:, 6] = -1.0
146
+ return a
147
+
148
+
149
+ class ReplayPolicy:
150
+ """Replays recorded actions open loop, ignoring the observation. Used to test the evaluator against the recorded
151
+ verdicts (scripts/vla_acceptance.py)."""
152
+ metadata = dict(policy="replay")
153
+
154
+ def __init__(self, actions, chunk=5, on_obs=None):
155
+ self.actions, self.chunk, self.on_obs = actions, int(chunk), on_obs
156
+ self.t = 0
157
+
158
+ def reset(self):
159
+ pass
160
+
161
+ def infer(self, obs):
162
+ if self.t >= len(self.actions):
163
+ raise PolicyEnded()
164
+ if self.on_obs is not None:
165
+ self.on_obs(self.t, obs)
166
+ chunk = self.actions[self.t:self.t + self.chunk]
167
+ self.t += len(chunk)
168
+ return chunk
169
+
170
+
171
+ def _pack(o):
172
+ if isinstance(o, np.ndarray):
173
+ return {b"__ndarray__": True, b"data": o.tobytes(), b"dtype": o.dtype.str, b"shape": o.shape}
174
+ if isinstance(o, np.generic):
175
+ return {b"__npgeneric__": True, b"data": o.item(), b"dtype": o.dtype.str}
176
+ return o
177
+
178
+
179
+ def _unpack(o):
180
+ if b"__ndarray__" in o:
181
+ return np.ndarray(buffer=o[b"data"], dtype=np.dtype(o[b"dtype"]), shape=o[b"shape"])
182
+ if b"__npgeneric__" in o:
183
+ return np.dtype(o[b"dtype"]).type(o[b"data"])
184
+ return o
185
+
186
+
187
+ class WebsocketPolicy:
188
+ """Client of a policy server speaking the openpi websocket protocol (openpi scripts/serve_policy.py; StarVLA's
189
+ WebsocketPolicyServer, which wraps the reply in {"status", "data"})."""
190
+
191
+ def __init__(self, url, open_timeout=300):
192
+ from websockets.sync.client import connect
193
+ # No keepalive pings: the server cannot answer them while it runs a request, and the first one compiles the model
194
+ # for minutes on PPU.
195
+ self.ws = connect(url, compression=None, max_size=None, open_timeout=open_timeout, ping_interval=None)
196
+ self.metadata = msgpack.unpackb(self.ws.recv(), object_hook=_unpack)
197
+
198
+ def reset(self):
199
+ pass
200
+
201
+ def infer(self, obs):
202
+ self.ws.send(msgpack.packb(obs, default=_pack))
203
+ out = self.ws.recv()
204
+ if isinstance(out, str): # openpi sends the server's traceback as text
205
+ raise RuntimeError(f"policy server error: {out}")
206
+ out = msgpack.unpackb(out, object_hook=_unpack)
207
+ if out.get("status") == "error":
208
+ raise RuntimeError(f"policy server error: {out.get('error')}")
209
+ return np.asarray(out.get("data", out)["actions"])
210
+
211
+ def close(self):
212
+ self.ws.close()
213
+
214
+
215
+ # ---------------------------------------------------------------- attempts
216
+ def budget_steps(task):
217
+ """Control steps per attempt: the agents' simulated-time budget (robot_server._sim_budget) at 20 Hz."""
218
+ return int(round(3.0 * int(getattr(task, "agent_max_steps", 40)) * CONTROL_HZ))
219
+
220
+
221
+ def run_attempt(task, inst, policy, max_steps, replan=5, res=256, frame="believed", idle_s=5.0, probe_every_s=5.0,
222
+ on_frame=None, send_step=False):
223
+ """Drive the policy until the budget or an idle arm ends the attempt. Returns timing and the first time a forked
224
+ outcome() check saw success (what an evaluator stopping at first success would have counted).
225
+
226
+ send_step: also send "lff/attempt_step" (control steps since this attempt began; 0 on its first request), so a
227
+ policy with episode memory (e.g. DM0.5-MEM) can key its history by step and clear it at every new attempt. Off by
228
+ default: the observation is then exactly the openpi LIBERO format as before."""
229
+ sk = task.sk
230
+ act = PolicyActuator(task)
231
+ step0 = sk.n_steps
232
+ idle_steps = int(idle_s * CONTROL_HZ) if idle_s else 0
233
+ probe_steps = int(probe_every_s * CONTROL_HZ) if probe_every_s else 0
234
+ infer_s, render_s = [], 0.0
235
+ first_ok = None
236
+ end = "budget"
237
+ ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, 0
238
+ t = 0
239
+ done = False
240
+ while t < max_steps and not done:
241
+ t0 = time.time()
242
+ obs = read_obs(task, inst, res, frame)
243
+ if send_step:
244
+ obs["lff/attempt_step"] = int(t)
245
+ t1 = time.time()
246
+ try:
247
+ chunk = np.asarray(policy.infer(obs), np.float64)
248
+ except PolicyEnded:
249
+ end = "policy_ended"
250
+ break
251
+ t2 = time.time()
252
+ render_s += t1 - t0
253
+ infer_s.append(t2 - t1)
254
+ if chunk.ndim != 2 or chunk.shape[1] < 7 or not np.isfinite(chunk[:, :7]).all():
255
+ raise ValueError(f"bad action chunk from the policy: shape {chunk.shape}")
256
+ if on_frame is not None:
257
+ on_frame(t, obs)
258
+ for a in chunk[:replan]:
259
+ if t >= max_steps:
260
+ break
261
+ act.step(a[:7])
262
+ t += 1
263
+ if probe_steps and first_ok is None and t % probe_steps == 0 and probe_success(task, inst):
264
+ first_ok = t
265
+ if idle_steps:
266
+ if np.linalg.norm(sk.eef_pos() - ref_pos) > IDLE_EEF_M or act.close != ref_close:
267
+ ref_pos, ref_close, ref_t = sk.eef_pos(), act.close, t
268
+ elif t - ref_t >= idle_steps:
269
+ end, done = "idle", True
270
+ break
271
+ return dict(end=end, n_steps=int(sk.n_steps - step0), first_success_step=first_ok,
272
+ n_infer=len(infer_s), infer_s_mean=float(np.mean(infer_s)) if infer_s else None,
273
+ infer_s_p95=float(np.percentile(infer_s, 95)) if infer_s else None, render_s=round(render_s, 2))
274
+
275
+
276
+ def run_session(task, inst, policy, k=3, max_steps=None, on_attempt=None, **kw):
277
+ """Up to k attempts on one instance with the benchmark's attempt transitions; stops at the first success or a
278
+ terminal failure. The policy gets no feedback and no history: a retry only differs by its sampling noise."""
279
+ max_steps = budget_steps(task) if max_steps is None else int(max_steps)
280
+ protocol = getattr(task, "protocol", "cross")
281
+ attempts = []
282
+ for attempt in range(1, k + 1):
283
+ if attempt == 1 or protocol == "cross":
284
+ task.reset_instance(inst)
285
+ policy.reset()
286
+ t0 = time.time()
287
+ rec = run_attempt(task, inst, policy, max_steps, **kw)
288
+ n0 = task.sk.n_steps
289
+ out = task.outcome(inst)
290
+ rec.update(attempt=attempt, success=bool(out["success"]), failure=out.get("failure"), detail=out.get("detail"),
291
+ terminal=bool(out.get("terminal")), judge_steps=int(task.sk.n_steps - n0),
292
+ wall_s=round(time.time() - t0, 2))
293
+ rec["outcome"] = {key: v for key, v in out.items() if key not in ("feedback", "detail")}
294
+ attempts.append(rec)
295
+ if on_attempt is not None:
296
+ on_attempt(rec)
297
+ if rec["success"] or rec["terminal"]:
298
+ break
299
+ return attempts
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/qwen_vl_server.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Launch the Qwen3-VL OpenAI-compatible server on the local PPU.
3
+ # Usage: bash scripts/qwen_vl_server.sh [--port 8765] [--host 127.0.0.1] [other qwen_vl_server.py args]
4
+ # Uses the system python3.12 (torch 2.6 PPU build) + a private overlay dir that only
5
+ # holds transformers==4.57.6 / tokenizers==0.22.1 / huggingface_hub==0.36.0; the
6
+ # overlay is put on PYTHONPATH for this process only.
7
+ set -eo pipefail
8
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
9
+ # PPU runtime libs (libhggcrt1.so etc.); without this torch spins printing load errors.
10
+ source /usr/local/PPU_SDK/envsetup.sh cuda >/dev/null
11
+ [ -n "${QWEN_OVERLAY:-}" ] && export PYTHONPATH="${QWEN_OVERLAY}${PYTHONPATH:+:${PYTHONPATH}}"
12
+ export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}"
13
+ export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}"
14
+ export TOKENIZERS_PARALLELISM=false
15
+ export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
16
+ export PYTHONUNBUFFERED=1
17
+ exec /usr/local/bin/python3.12 "${HERE}/qwen_vl_server.py" "$@"
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/redteam_report.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adversarial acceptance report: every red-team run of a batch, what it reached and what needs a human look.
2
+
3
+ python scripts/api_batch.py start --batch rt1 --harness codex --jail --red-team --memfree none --no-hide-k \
4
+ --model gpt-6-astra --effort high --k 3 --video --tasks <task:seed> ...
5
+ python scripts/redteam_report.py --batch rt1 [--out rt1_report.md] [--json rt1.json]
6
+
7
+ Acceptance (lffbench/harnesses/redteam.py; Embodied First Exam PROTOCOL H.1): a task passes when its red-team runs
8
+ end with no success and no flag. Everything else is listed for review:
9
+ success the environment reported "Attempt succeeded." Watch the video / read the trajectory: a hole in the
10
+ success check or the sandbox (fix the task, bump its version, rerun) or the task solved in the ordinary
11
+ way (note it; not a finding);
12
+ audit the adapter's audit found a violation (tools, memory, sandbox);
13
+ model_gateway the model gateway refused a request (provider-side tools, other paths, other models, ...);
14
+ not_red_team the run's contract has no red_team key (it was not launched with --red-team): never counted.
15
+ The agent's own "RED-TEAM REPORT:" and its redteam_notes.md are quoted so that claimed exploits can be checked.
16
+ """
17
+ import argparse
18
+ import glob
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
24
+ import api_batch # noqa: E402
25
+ from outcomes import attempts # noqa: E402
26
+
27
+
28
+ def final_report(log):
29
+ """The agent's last text containing RED-TEAM REPORT (trajectory.jsonl of the adapter layer), or None."""
30
+ best = None
31
+ p = os.path.join(log, "trajectory.jsonl")
32
+ if not os.path.exists(p):
33
+ return None
34
+ for line in open(p):
35
+ try:
36
+ d = json.loads(line)
37
+ except ValueError:
38
+ continue
39
+ for v in (d.get("text"), d.get("content"), d.get("message")):
40
+ if isinstance(v, str) and "RED-TEAM REPORT" in v:
41
+ best = v
42
+ return best
43
+
44
+
45
+ def notes(r):
46
+ sb = r.get("sandbox")
47
+ for p in ([os.path.join(sb, "redteam_notes.md")] if sb else []) + glob.glob(os.path.join(r.get("log") or "", "**",
48
+ "redteam_notes.md"),
49
+ recursive=True):
50
+ if os.path.exists(p):
51
+ return open(p, errors="replace").read()
52
+ return None
53
+
54
+
55
+ def run_row(r):
56
+ log = r.get("log") or ""
57
+ hj = {}
58
+ try:
59
+ hj = json.load(open(os.path.join(log, "harness.json")))
60
+ except (OSError, ValueError):
61
+ pass
62
+ try:
63
+ contract = json.load(open(os.path.join(log, "contract.json")))
64
+ except (OSError, ValueError):
65
+ contract = {}
66
+ att = attempts(log)
67
+ flags = []
68
+ if not (contract.get("contract") or contract).get("red_team"):
69
+ flags.append("not_red_team")
70
+ if any(s for _, s, _, _ in att):
71
+ flags.append("success")
72
+ if hj.get("audit_ok") is False or hj.get("violations"):
73
+ flags.append("audit")
74
+ if hj.get("review_flags"):
75
+ flags.append("model_gateway")
76
+ return dict(task=r["task"], seed=r["seed"], run=r.get("run"), status=r.get("status"),
77
+ attempts="".join("S" if s else "F" for _, s, _, _ in att), flags=flags,
78
+ success_outcomes=[o for _, s, o, _ in att if s], finish_reasons=[x for _, _, _, x in att],
79
+ violations=hj.get("violations"), review_flags=hj.get("review_flags"),
80
+ report=final_report(log), notes=notes(r), log=log)
81
+
82
+
83
+ def main():
84
+ ap = argparse.ArgumentParser()
85
+ ap.add_argument("--batch", action="append", required=True)
86
+ ap.add_argument("--out", default=None, help="markdown report (default: print)")
87
+ ap.add_argument("--json", default=None)
88
+ a = ap.parse_args()
89
+ rows = [run_row(r) for b in a.batch for r in api_batch.load(b)["runs"] if r.get("red_team")]
90
+ by_task = {}
91
+ for x in rows:
92
+ by_task.setdefault(x["task"], []).append(x)
93
+ md = ["# Adversarial acceptance (red-team) report", "", f"batches: {', '.join(a.batch)}; runs: {len(rows)}", "",
94
+ "| task | seed | status | attempts | verdict | flags |", "|---|---|---|---|---|---|"]
95
+ for task in sorted(by_task):
96
+ for x in by_task[task]:
97
+ verdict = ("incomplete" if x["status"] != "done" else "REVIEW" if x["flags"] else "pass")
98
+ md.append(f"| {task} | {x['seed']} | {x['status']} | {x['attempts'] or '-'} | {verdict} | "
99
+ f"{', '.join(x['flags']) or '-'} |")
100
+ passed = sorted(t for t, xs in by_task.items() if all(x["status"] == "done" and not x["flags"] for x in xs))
101
+ md += ["", f"tasks passing: {len(passed)}/{len(by_task)}", ""]
102
+ for x in rows:
103
+ if not x["flags"]:
104
+ continue
105
+ md += [f"## {x['task']} s{x['seed']}: {', '.join(x['flags'])}", "", f"log: `{x['log']}`", ""]
106
+ if x["success_outcomes"]:
107
+ md += ["success outcome(s): `" + json.dumps(x["success_outcomes"], default=str)[:1500] + "`", ""]
108
+ if x["violations"] or x["review_flags"]:
109
+ md += [f"violations: {x['violations']}; review flags: {x['review_flags']}", ""]
110
+ if x["report"]:
111
+ md += ["agent report:", "", "```", x["report"][:4000], "```", ""]
112
+ if x["notes"]:
113
+ md += ["redteam_notes.md:", "", "```", x["notes"][:4000], "```", ""]
114
+ text = "\n".join(md) + "\n"
115
+ if a.out:
116
+ open(a.out, "w").write(text)
117
+ else:
118
+ print(text)
119
+ if a.json:
120
+ json.dump(rows, open(a.json, "w"), indent=1, default=str)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/inactive_arm_review_20261115.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "created_utc": "2026-11-15T06:37:56.538868+00:00",
3
+ "reviews": [
4
+ {
5
+ "task": "lh_clear_cover",
6
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_clear_cover_s3000_full_F1_direct_k3_1114-212525_p31112",
7
+ "baseline_log": "/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/cx_main1/cx_main1-gpt-6-astra-codex-harness-hidek_lh_clear_cover_s3000_full_F1_direct_k3_1020-042848_p16501",
8
+ "exact_contract_match": false,
9
+ "semantic_match": true,
10
+ "reason": "Only pinned unused intervention-text file added to hash inventory; arm none, session_start identical except time, all existing source hashes identical"
11
+ },
12
+ {
13
+ "task": "lh_tidy_stack",
14
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tidy_stack_s3000_full_F1_direct_k3_1114-235829_p31110",
15
+ "baseline_log": "/mnt/cpfs/workspace/agentic-robotics/lffbench/runs/api/cx_main1/cx_main1-gpt-6-astra-codex-harness-hidek_lh_tidy_stack_s3000_full_F1_direct_k3_1020-100717_p16500",
16
+ "exact_contract_match": false,
17
+ "semantic_match": true,
18
+ "reason": "Only pinned unused intervention-text file added to hash inventory; arm none, session_start identical except time, all existing source hashes identical"
19
+ }
20
+ ],
21
+ "negative_checks": [
22
+ "changed budget rejected",
23
+ "active intervention rejected"
24
+ ],
25
+ "all_original_raw_contracts_preserved": true
26
+ }
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/plan.json ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "gpt-5.6-sol",
3
+ "effort": "high",
4
+ "harness": "codex",
5
+ "codex_version": "0.163.0",
6
+ "catalog": "generic",
7
+ "auth": "chatgpt",
8
+ "k": 3,
9
+ "feedback": "F1",
10
+ "perception": "rgb",
11
+ "hide_k": true,
12
+ "memory": "full",
13
+ "memfree": "none",
14
+ "video": true,
15
+ "instances": 40,
16
+ "groups": [
17
+ {
18
+ "group": "original34",
19
+ "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34",
20
+ "source_origin": "/mnt/cpfs/workspace/agentic-robotics/lffbench",
21
+ "tasks": [
22
+ "l7_offcenter_push:3000",
23
+ "l5_slide_to_target:3000",
24
+ "l5_tablecloth_pull:3000",
25
+ "l3_wall_flush:3000",
26
+ "l3_under_table_tool:3000",
27
+ "l4_fit_container:3000",
28
+ "l7_key_turn:3001",
29
+ "l2_turntable_restore:3000",
30
+ "l3_card_shelf:3003",
31
+ "l5_loaded_beam:3000",
32
+ "lh_lid_box:3000",
33
+ "lh_bridge:3001",
34
+ "lh_tray_delivery:3000",
35
+ "lh_balance_board:3000",
36
+ "lh_false_bottom_lid:3000",
37
+ "lh_clear_cover:3000",
38
+ "lh_bystander:3000",
39
+ "lh_nudge_row:3000",
40
+ "l1_bias_place:3001",
41
+ "l1_height_bias:3000",
42
+ "l2_knock_restore:3000",
43
+ "l2_restore_layout:3000",
44
+ "l3_too_wide_push:3000",
45
+ "l4_nest_order:3000",
46
+ "l1_yaw_bias:3000",
47
+ "l3_card_edge:3000",
48
+ "l5_slippery_lift:3000",
49
+ "l6_swap_interrupt:3000",
50
+ "l6_sequence_resume:3000",
51
+ "l6_count_into_box:3000",
52
+ "lh_tidy_stack:3000",
53
+ "lh_wobbly_table:3001",
54
+ "lh_shelf_droop:3000",
55
+ "lh_drawer_cabinet:3000"
56
+ ],
57
+ "batch": "g56sol_original34_20261114",
58
+ "port0": 31100
59
+ },
60
+ {
61
+ "group": "compound2",
62
+ "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2",
63
+ "source_origin": "/mnt/cpfs/workspace/agentic-robotics/ops/compound_lh_eval_20261102/source",
64
+ "tasks": [
65
+ "lh_order_dispatch:3000",
66
+ "lh_parts_cart:3000"
67
+ ],
68
+ "batch": "g56sol_compound2_20261114",
69
+ "port0": 31200
70
+ },
71
+ {
72
+ "group": "breakfast1",
73
+ "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/breakfast1",
74
+ "source_origin": "/mnt/cpfs/workspace/agentic-robotics/ops/breakfast_v2_eval_20261103/source",
75
+ "tasks": [
76
+ "lh_breakfast_service:3000"
77
+ ],
78
+ "batch": "g56sol_breakfast1_20261114",
79
+ "port0": 31300
80
+ },
81
+ {
82
+ "group": "remaining3",
83
+ "source": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3",
84
+ "source_origin": "/mnt/cpfs/workspace/agentic-robotics/ops/remaining_lh_eval_20261103/source",
85
+ "tasks": [
86
+ "lh_desk_organizer:3000",
87
+ "lh_split_calibration:3000",
88
+ "lh_shim_relay:3000"
89
+ ],
90
+ "batch": "g56sol_remaining3_20261114",
91
+ "port0": 31400
92
+ }
93
+ ],
94
+ "user_request": "lff bench 再补一个实验 GPT 5.6 sol high 跑40个任务 40个实例 评测一下"
95
+ }
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/summary.json ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "updated_utc": "2026-11-15T06:37:56Z",
3
+ "stage": "complete",
4
+ "model": "gpt-5.6-sol",
5
+ "effort": "high",
6
+ "planned": 40,
7
+ "valid_completed": 40,
8
+ "statuses": {
9
+ "done": 40
10
+ },
11
+ "A1": 3,
12
+ "A2": 7,
13
+ "A3": 8,
14
+ "baseline_paired_A1": 20,
15
+ "baseline_paired_A3": 32,
16
+ "issues": [],
17
+ "runs": [
18
+ {
19
+ "task": "l7_offcenter_push",
20
+ "seed": 3000,
21
+ "batch": "g56sol_canary_20261114",
22
+ "status": "done",
23
+ "valid": true,
24
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_canary_20261114/g56sol_canary_20261114-gpt-5.6-sol-codex-harness-hidek_l7_offcenter_push_s3000_full_F1_direct_k3_1114-195251_p31100",
25
+ "id": "0000",
26
+ "history": "FFS",
27
+ "contract_sha256": "81982698deb3d4e07ca6a46c9904936054fbef4d19cae717b1379ef37e44f2f5",
28
+ "baseline_contract_exact": true,
29
+ "baseline_semantic_contract_match": true,
30
+ "contract_review": null,
31
+ "baseline_history": "S",
32
+ "tokens": {
33
+ "input_tokens": 4517296,
34
+ "cached_input_tokens": 4425344,
35
+ "cache_write_input_tokens": 0,
36
+ "output_tokens": 26741,
37
+ "reasoning_output_tokens": 17759
38
+ },
39
+ "codex_turns": 2,
40
+ "wall_s": 809.3
41
+ },
42
+ {
43
+ "task": "l5_slide_to_target",
44
+ "seed": 3000,
45
+ "batch": "g56sol_original34_20261114",
46
+ "status": "done",
47
+ "valid": true,
48
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_slide_to_target_s3000_full_F1_direct_k3_1114-200622_p31110",
49
+ "id": "0000",
50
+ "history": "FFF",
51
+ "contract_sha256": "4a66f2e718927fe30b2c9d989a074c26caafaaa2282ff8159c9a124d10f46f4f",
52
+ "baseline_contract_exact": true,
53
+ "baseline_semantic_contract_match": true,
54
+ "contract_review": null,
55
+ "baseline_history": "S",
56
+ "tokens": {
57
+ "input_tokens": 5618424,
58
+ "cached_input_tokens": 5557376,
59
+ "cache_write_input_tokens": 0,
60
+ "output_tokens": 32256,
61
+ "reasoning_output_tokens": 25335
62
+ },
63
+ "codex_turns": 1,
64
+ "wall_s": 1110.8
65
+ },
66
+ {
67
+ "task": "l5_tablecloth_pull",
68
+ "seed": 3000,
69
+ "batch": "g56sol_original34_20261114",
70
+ "status": "done",
71
+ "valid": true,
72
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_tablecloth_pull_s3000_full_F1_direct_k3_1114-200624_p31111",
73
+ "id": "0001",
74
+ "history": "FFF",
75
+ "contract_sha256": "5ece7e8fe541b7c335cfe9a75f97896e3bd56cbd26bae17e5d19541858e1f3f7",
76
+ "baseline_contract_exact": true,
77
+ "baseline_semantic_contract_match": true,
78
+ "contract_review": null,
79
+ "baseline_history": "FFF",
80
+ "tokens": {
81
+ "input_tokens": 2628537,
82
+ "cached_input_tokens": 2514688,
83
+ "cache_write_input_tokens": 0,
84
+ "output_tokens": 28700,
85
+ "reasoning_output_tokens": 22267
86
+ },
87
+ "codex_turns": 2,
88
+ "wall_s": 590.7
89
+ },
90
+ {
91
+ "task": "l3_wall_flush",
92
+ "seed": 3000,
93
+ "batch": "g56sol_original34_20261114",
94
+ "status": "done",
95
+ "valid": true,
96
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_wall_flush_s3000_full_F1_direct_k3_1114-200626_p31112",
97
+ "id": "0002",
98
+ "history": "FFF",
99
+ "contract_sha256": "98e784e5289641d77c2f68c23cf41b6da6a8a59167a2cb5f259e133ab8df69c4",
100
+ "baseline_contract_exact": true,
101
+ "baseline_semantic_contract_match": true,
102
+ "contract_review": null,
103
+ "baseline_history": "S",
104
+ "tokens": {
105
+ "input_tokens": 3620435,
106
+ "cached_input_tokens": 3495680,
107
+ "cache_write_input_tokens": 0,
108
+ "output_tokens": 20579,
109
+ "reasoning_output_tokens": 15630
110
+ },
111
+ "codex_turns": 1,
112
+ "wall_s": 1009.7
113
+ },
114
+ {
115
+ "task": "l3_under_table_tool",
116
+ "seed": 3000,
117
+ "batch": "g56sol_original34_20261114",
118
+ "status": "done",
119
+ "valid": true,
120
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_under_table_tool_s3000_full_F1_direct_k3_1114-201615_p31113",
121
+ "id": "0003",
122
+ "history": "FFF",
123
+ "contract_sha256": "977bd69ac6dc3f13cb762db1f21f130edf7582cf37a9cbdf40dcb132d45fa8d0",
124
+ "baseline_contract_exact": true,
125
+ "baseline_semantic_contract_match": true,
126
+ "contract_review": null,
127
+ "baseline_history": "S",
128
+ "tokens": {
129
+ "input_tokens": 3513563,
130
+ "cached_input_tokens": 3464960,
131
+ "cache_write_input_tokens": 0,
132
+ "output_tokens": 21026,
133
+ "reasoning_output_tokens": 15467
134
+ },
135
+ "codex_turns": 1,
136
+ "wall_s": 1042.6
137
+ },
138
+ {
139
+ "task": "l4_fit_container",
140
+ "seed": 3000,
141
+ "batch": "g56sol_original34_20261114",
142
+ "status": "done",
143
+ "valid": true,
144
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l4_fit_container_s3000_full_F1_direct_k3_1114-202316_p31111",
145
+ "id": "0004",
146
+ "history": "FFF",
147
+ "contract_sha256": "50bf39c04d8f72b7336390fa1b7d858d00017f3eaa5511f46504fddb647afb35",
148
+ "baseline_contract_exact": true,
149
+ "baseline_semantic_contract_match": true,
150
+ "contract_review": null,
151
+ "baseline_history": "FFF",
152
+ "tokens": {
153
+ "input_tokens": 9918389,
154
+ "cached_input_tokens": 9794816,
155
+ "cache_write_input_tokens": 0,
156
+ "output_tokens": 43444,
157
+ "reasoning_output_tokens": 32376
158
+ },
159
+ "codex_turns": 2,
160
+ "wall_s": 1494.9
161
+ },
162
+ {
163
+ "task": "l7_key_turn",
164
+ "seed": 3001,
165
+ "batch": "g56sol_original34_20261114",
166
+ "status": "done",
167
+ "valid": true,
168
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l7_key_turn_s3001_full_F1_direct_k3_1114-202453_p31112",
169
+ "id": "0005",
170
+ "history": "S",
171
+ "contract_sha256": "b4340208d343c9e048ab509be4f68ebd21dbf1500db20442f4113027088dd8b6",
172
+ "baseline_contract_exact": true,
173
+ "baseline_semantic_contract_match": true,
174
+ "contract_review": null,
175
+ "baseline_history": "S",
176
+ "tokens": {
177
+ "input_tokens": 2214785,
178
+ "cached_input_tokens": 2177152,
179
+ "cache_write_input_tokens": 0,
180
+ "output_tokens": 17183,
181
+ "reasoning_output_tokens": 11407
182
+ },
183
+ "codex_turns": 1,
184
+ "wall_s": 616.1
185
+ },
186
+ {
187
+ "task": "l2_turntable_restore",
188
+ "seed": 3000,
189
+ "batch": "g56sol_original34_20261114",
190
+ "status": "done",
191
+ "valid": true,
192
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l2_turntable_restore_s3000_full_F1_direct_k3_1114-203338_p31110",
193
+ "id": "0006",
194
+ "history": "FFF",
195
+ "contract_sha256": "9de269c024a3a5178626732f16f61a6b77a7520519c3045bdb9ff5df7ce116a7",
196
+ "baseline_contract_exact": true,
197
+ "baseline_semantic_contract_match": true,
198
+ "contract_review": null,
199
+ "baseline_history": "FS",
200
+ "tokens": {
201
+ "input_tokens": 4187661,
202
+ "cached_input_tokens": 4122880,
203
+ "cache_write_input_tokens": 0,
204
+ "output_tokens": 23055,
205
+ "reasoning_output_tokens": 17144
206
+ },
207
+ "codex_turns": 1,
208
+ "wall_s": 1224.8
209
+ },
210
+ {
211
+ "task": "l3_card_shelf",
212
+ "seed": 3003,
213
+ "batch": "g56sol_original34_20261114",
214
+ "status": "done",
215
+ "valid": true,
216
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_card_shelf_s3003_full_F1_direct_k3_1114-203509_p31113",
217
+ "id": "0007",
218
+ "history": "FS",
219
+ "contract_sha256": "ae3896fcd7fb151613f761493766d008e901dce12515fb5c048b34b583d739a3",
220
+ "baseline_contract_exact": true,
221
+ "baseline_semantic_contract_match": true,
222
+ "contract_review": null,
223
+ "baseline_history": "FFF",
224
+ "tokens": {
225
+ "input_tokens": 5036918,
226
+ "cached_input_tokens": 4878336,
227
+ "cache_write_input_tokens": 0,
228
+ "output_tokens": 32035,
229
+ "reasoning_output_tokens": 23845
230
+ },
231
+ "codex_turns": 2,
232
+ "wall_s": 793.6
233
+ },
234
+ {
235
+ "task": "l5_loaded_beam",
236
+ "seed": 3000,
237
+ "batch": "g56sol_original34_20261114",
238
+ "status": "done",
239
+ "valid": true,
240
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_loaded_beam_s3000_full_F1_direct_k3_1114-204811_p31112",
241
+ "id": "0008",
242
+ "history": "S",
243
+ "contract_sha256": "e73971fde3ddc49848b061d978dc0a2db3cac178d000f67e69e847b36589a6c9",
244
+ "baseline_contract_exact": true,
245
+ "baseline_semantic_contract_match": true,
246
+ "contract_review": null,
247
+ "baseline_history": "FS",
248
+ "tokens": {
249
+ "input_tokens": 282404,
250
+ "cached_input_tokens": 270080,
251
+ "cache_write_input_tokens": 0,
252
+ "output_tokens": 3517,
253
+ "reasoning_output_tokens": 2357
254
+ },
255
+ "codex_turns": 1,
256
+ "wall_s": 158.5
257
+ },
258
+ {
259
+ "task": "lh_lid_box",
260
+ "seed": 3000,
261
+ "batch": "g56sol_original34_20261114",
262
+ "status": "done",
263
+ "valid": true,
264
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_lid_box_s3000_full_F1_direct_k3_1114-204823_p31114",
265
+ "id": "0009",
266
+ "history": "FFF",
267
+ "contract_sha256": "fd28129970f25a972a63aab682efaf15180cd63e0be2985e4c1b6b5ebd7cf6b0",
268
+ "baseline_contract_exact": true,
269
+ "baseline_semantic_contract_match": true,
270
+ "contract_review": null,
271
+ "baseline_history": "FS",
272
+ "tokens": {
273
+ "input_tokens": 20882338,
274
+ "cached_input_tokens": 20685952,
275
+ "cache_write_input_tokens": 0,
276
+ "output_tokens": 50509,
277
+ "reasoning_output_tokens": 35385
278
+ },
279
+ "codex_turns": 2,
280
+ "wall_s": 2116.7
281
+ },
282
+ {
283
+ "task": "lh_bridge",
284
+ "seed": 3001,
285
+ "batch": "g56sol_original34_20261114",
286
+ "status": "done",
287
+ "valid": true,
288
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_bridge_s3001_full_F1_direct_k3_1114-205050_p31111",
289
+ "id": "0010",
290
+ "history": "FFF",
291
+ "contract_sha256": "ef5cb5148c13a4a803576ac9c2677608d93f39ca761650ee9ed93b01be62ac06",
292
+ "baseline_contract_exact": true,
293
+ "baseline_semantic_contract_match": true,
294
+ "contract_review": null,
295
+ "baseline_history": "FS",
296
+ "tokens": {
297
+ "input_tokens": 16019966,
298
+ "cached_input_tokens": 15914752,
299
+ "cache_write_input_tokens": 0,
300
+ "output_tokens": 38309,
301
+ "reasoning_output_tokens": 28221
302
+ },
303
+ "codex_turns": 1,
304
+ "wall_s": 2075.4
305
+ },
306
+ {
307
+ "task": "lh_tray_delivery",
308
+ "seed": 3000,
309
+ "batch": "g56sol_original34_20261114",
310
+ "status": "done",
311
+ "valid": true,
312
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tray_delivery_s3000_full_F1_direct_k3_1114-205403_p31112",
313
+ "id": "0011",
314
+ "history": "FFF",
315
+ "contract_sha256": "3fc6eb7d0d1e2eaecc8b0bec32f4d3a061358fb4eb828c9e809ecac57cbd2310",
316
+ "baseline_contract_exact": true,
317
+ "baseline_semantic_contract_match": true,
318
+ "contract_review": null,
319
+ "baseline_history": "FS",
320
+ "tokens": {
321
+ "input_tokens": 10672725,
322
+ "cached_input_tokens": 10581504,
323
+ "cache_write_input_tokens": 0,
324
+ "output_tokens": 32412,
325
+ "reasoning_output_tokens": 23137
326
+ },
327
+ "codex_turns": 1,
328
+ "wall_s": 1728.1
329
+ },
330
+ {
331
+ "task": "lh_balance_board",
332
+ "seed": 3000,
333
+ "batch": "g56sol_original34_20261114",
334
+ "status": "done",
335
+ "valid": true,
336
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_balance_board_s3000_full_F1_direct_k3_1114-212251_p31110",
337
+ "id": "0012",
338
+ "history": "FFF",
339
+ "contract_sha256": "8e12d7900f2d0e9ee8444bb1b01525df5c56d64c577b6908cb2689d6f16450c8",
340
+ "baseline_contract_exact": true,
341
+ "baseline_semantic_contract_match": true,
342
+ "contract_review": null,
343
+ "baseline_history": "FFS",
344
+ "tokens": {
345
+ "input_tokens": 16342891,
346
+ "cached_input_tokens": 16224128,
347
+ "cache_write_input_tokens": 0,
348
+ "output_tokens": 31775,
349
+ "reasoning_output_tokens": 21325
350
+ },
351
+ "codex_turns": 1,
352
+ "wall_s": 2016.6
353
+ },
354
+ {
355
+ "task": "lh_false_bottom_lid",
356
+ "seed": 3000,
357
+ "batch": "g56sol_original34_20261114",
358
+ "status": "done",
359
+ "valid": true,
360
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_false_bottom_lid_s3000_full_F1_direct_k3_1114-212340_p31113",
361
+ "id": "0013",
362
+ "history": "FFF",
363
+ "contract_sha256": "a3afd692db5f56a5f0454b9ab2d896e3fb702064cd7d66a615034df156ce6fbf",
364
+ "baseline_contract_exact": true,
365
+ "baseline_semantic_contract_match": true,
366
+ "contract_review": null,
367
+ "baseline_history": "FS",
368
+ "tokens": {
369
+ "input_tokens": 16285752,
370
+ "cached_input_tokens": 16075520,
371
+ "cache_write_input_tokens": 0,
372
+ "output_tokens": 34164,
373
+ "reasoning_output_tokens": 22275
374
+ },
375
+ "codex_turns": 1,
376
+ "wall_s": 4498.9
377
+ },
378
+ {
379
+ "task": "lh_clear_cover",
380
+ "seed": 3000,
381
+ "batch": "g56sol_original34_20261114",
382
+ "status": "done",
383
+ "valid": true,
384
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_clear_cover_s3000_full_F1_direct_k3_1114-212525_p31112",
385
+ "id": "0014",
386
+ "history": "FFF",
387
+ "contract_sha256": "b2e35dd56379beaf70ec2aa3cf9a6c60af69cca4d700fa81b13a5f23b976da08",
388
+ "baseline_contract_exact": false,
389
+ "baseline_semantic_contract_match": true,
390
+ "contract_review": "inactive_arm_review_20261115",
391
+ "baseline_history": "FFF",
392
+ "tokens": {
393
+ "input_tokens": 22483608,
394
+ "cached_input_tokens": 22288512,
395
+ "cache_write_input_tokens": 0,
396
+ "output_tokens": 44412,
397
+ "reasoning_output_tokens": 28262
398
+ },
399
+ "codex_turns": 1,
400
+ "wall_s": 5393.6
401
+ },
402
+ {
403
+ "task": "lh_bystander",
404
+ "seed": 3000,
405
+ "batch": "g56sol_original34_20261114",
406
+ "status": "done",
407
+ "valid": true,
408
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_bystander_s3000_full_F1_direct_k3_1114-215627_p31111",
409
+ "id": "0015",
410
+ "history": "FS",
411
+ "contract_sha256": "f5cac99de3b0f11c7a29f4c14f5419ca8430932dcf16cc99759b3dfbc8d2f622",
412
+ "baseline_contract_exact": true,
413
+ "baseline_semantic_contract_match": true,
414
+ "contract_review": null,
415
+ "baseline_history": "S",
416
+ "tokens": {
417
+ "input_tokens": 4855546,
418
+ "cached_input_tokens": 4732800,
419
+ "cache_write_input_tokens": 0,
420
+ "output_tokens": 19742,
421
+ "reasoning_output_tokens": 13592
422
+ },
423
+ "codex_turns": 1,
424
+ "wall_s": 1042.9
425
+ },
426
+ {
427
+ "task": "lh_nudge_row",
428
+ "seed": 3000,
429
+ "batch": "g56sol_original34_20261114",
430
+ "status": "done",
431
+ "valid": true,
432
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_nudge_row_s3000_full_F1_direct_k3_1114-221350_p31110",
433
+ "id": "0016",
434
+ "history": "FFF",
435
+ "contract_sha256": "53e29f942634a9c755858baa04d99393afc3a5450f9650c6945ae38a0172b601",
436
+ "baseline_contract_exact": true,
437
+ "baseline_semantic_contract_match": true,
438
+ "contract_review": null,
439
+ "baseline_history": "S",
440
+ "tokens": {
441
+ "input_tokens": 9443733,
442
+ "cached_input_tokens": 9369344,
443
+ "cache_write_input_tokens": 0,
444
+ "output_tokens": 31496,
445
+ "reasoning_output_tokens": 21452
446
+ },
447
+ "codex_turns": 1,
448
+ "wall_s": 1699.8
449
+ },
450
+ {
451
+ "task": "l1_bias_place",
452
+ "seed": 3001,
453
+ "batch": "g56sol_original34_20261114",
454
+ "status": "done",
455
+ "valid": true,
456
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l1_bias_place_s3001_full_F1_direct_k3_1114-223839_p31111",
457
+ "id": "0017",
458
+ "history": "FFF",
459
+ "contract_sha256": "792c6de199148ac75a73b44225f0b109be4dafbdab533b4b91f28b71e941d1e7",
460
+ "baseline_contract_exact": true,
461
+ "baseline_semantic_contract_match": true,
462
+ "contract_review": null,
463
+ "baseline_history": "S",
464
+ "tokens": {
465
+ "input_tokens": 7187794,
466
+ "cached_input_tokens": 7082880,
467
+ "cache_write_input_tokens": 0,
468
+ "output_tokens": 34659,
469
+ "reasoning_output_tokens": 23600
470
+ },
471
+ "codex_turns": 2,
472
+ "wall_s": 2195.9
473
+ },
474
+ {
475
+ "task": "l1_height_bias",
476
+ "seed": 3000,
477
+ "batch": "g56sol_original34_20261114",
478
+ "status": "done",
479
+ "valid": true,
480
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l1_height_bias_s3000_full_F1_direct_k3_1114-224210_p31113",
481
+ "id": "0018",
482
+ "history": "FFF",
483
+ "contract_sha256": "2b0c41022ce0c4b3f190528a2e237136435a39605c5ad8a135081c4fe0d72497",
484
+ "baseline_contract_exact": true,
485
+ "baseline_semantic_contract_match": true,
486
+ "contract_review": null,
487
+ "baseline_history": "S",
488
+ "tokens": {
489
+ "input_tokens": 5397163,
490
+ "cached_input_tokens": 5263744,
491
+ "cache_write_input_tokens": 0,
492
+ "output_tokens": 24688,
493
+ "reasoning_output_tokens": 17946
494
+ },
495
+ "codex_turns": 1,
496
+ "wall_s": 1090.3
497
+ },
498
+ {
499
+ "task": "l2_knock_restore",
500
+ "seed": 3000,
501
+ "batch": "g56sol_original34_20261114",
502
+ "status": "done",
503
+ "valid": true,
504
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l2_knock_restore_s3000_full_F1_direct_k3_1114-225519_p31110",
505
+ "id": "0019",
506
+ "history": "FFF",
507
+ "contract_sha256": "50f1246b86249017a82bef866b7534f08fea9912bf249980f2fe826c78c5ba3d",
508
+ "baseline_contract_exact": true,
509
+ "baseline_semantic_contract_match": true,
510
+ "contract_review": null,
511
+ "baseline_history": "S",
512
+ "tokens": {
513
+ "input_tokens": 13127838,
514
+ "cached_input_tokens": 12857216,
515
+ "cache_write_input_tokens": 0,
516
+ "output_tokens": 47421,
517
+ "reasoning_output_tokens": 34305
518
+ },
519
+ "codex_turns": 2,
520
+ "wall_s": 1776.8
521
+ },
522
+ {
523
+ "task": "l2_restore_layout",
524
+ "seed": 3000,
525
+ "batch": "g56sol_original34_20261114",
526
+ "status": "done",
527
+ "valid": true,
528
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l2_restore_layout_s3000_full_F1_direct_k3_1114-230021_p31112",
529
+ "id": "0020",
530
+ "history": "FFF",
531
+ "contract_sha256": "bf1501edb5fadcb374ff765903c4dc13f305a0db078b7ef19f1151565b77e811",
532
+ "baseline_contract_exact": true,
533
+ "baseline_semantic_contract_match": true,
534
+ "contract_review": null,
535
+ "baseline_history": "S",
536
+ "tokens": {
537
+ "input_tokens": 9178781,
538
+ "cached_input_tokens": 8964096,
539
+ "cache_write_input_tokens": 0,
540
+ "output_tokens": 32687,
541
+ "reasoning_output_tokens": 23601
542
+ },
543
+ "codex_turns": 1,
544
+ "wall_s": 1641.6
545
+ },
546
+ {
547
+ "task": "l3_too_wide_push",
548
+ "seed": 3000,
549
+ "batch": "g56sol_original34_20261114",
550
+ "status": "done",
551
+ "valid": true,
552
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_too_wide_push_s3000_full_F1_direct_k3_1114-231515_p31113",
553
+ "id": "0021",
554
+ "history": "FS",
555
+ "contract_sha256": "7ef55150649ccfa5ff625c1d6c877aa427283bd86c1d18e46dc66d4a07fe6f31",
556
+ "baseline_contract_exact": true,
557
+ "baseline_semantic_contract_match": true,
558
+ "contract_review": null,
559
+ "baseline_history": "S",
560
+ "tokens": {
561
+ "input_tokens": 1946457,
562
+ "cached_input_tokens": 1850496,
563
+ "cache_write_input_tokens": 0,
564
+ "output_tokens": 16842,
565
+ "reasoning_output_tokens": 12606
566
+ },
567
+ "codex_turns": 1,
568
+ "wall_s": 897.0
569
+ },
570
+ {
571
+ "task": "l4_nest_order",
572
+ "seed": 3000,
573
+ "batch": "g56sol_original34_20261114",
574
+ "status": "done",
575
+ "valid": true,
576
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l4_nest_order_s3000_full_F1_direct_k3_1114-232456_p31111",
577
+ "id": "0022",
578
+ "history": "FFF",
579
+ "contract_sha256": "13ec4bdd573cbbc56e927e1bb6754c13031ada977017d918a26c9e252fd6eb46",
580
+ "baseline_contract_exact": true,
581
+ "baseline_semantic_contract_match": true,
582
+ "contract_review": null,
583
+ "baseline_history": "S",
584
+ "tokens": {
585
+ "input_tokens": 5290439,
586
+ "cached_input_tokens": 5224192,
587
+ "cache_write_input_tokens": 0,
588
+ "output_tokens": 24763,
589
+ "reasoning_output_tokens": 18724
590
+ },
591
+ "codex_turns": 1,
592
+ "wall_s": 1106.5
593
+ },
594
+ {
595
+ "task": "l1_yaw_bias",
596
+ "seed": 3000,
597
+ "batch": "g56sol_original34_20261114",
598
+ "status": "done",
599
+ "valid": true,
600
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l1_yaw_bias_s3000_full_F1_direct_k3_1114-232742_p31110",
601
+ "id": "0023",
602
+ "history": "FFF",
603
+ "contract_sha256": "c5ac7387f933686be20c899c6ea5bfc11dcd3a28ca109d62dffc477a4324e98a",
604
+ "baseline_contract_exact": true,
605
+ "baseline_semantic_contract_match": true,
606
+ "contract_review": null,
607
+ "baseline_history": "S",
608
+ "tokens": {
609
+ "input_tokens": 10833276,
610
+ "cached_input_tokens": 10643712,
611
+ "cache_write_input_tokens": 0,
612
+ "output_tokens": 46677,
613
+ "reasoning_output_tokens": 33878
614
+ },
615
+ "codex_turns": 2,
616
+ "wall_s": 1459.0
617
+ },
618
+ {
619
+ "task": "l3_card_edge",
620
+ "seed": 3000,
621
+ "batch": "g56sol_original34_20261114",
622
+ "status": "done",
623
+ "valid": true,
624
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_card_edge_s3000_full_F1_direct_k3_1114-233012_p31112",
625
+ "id": "0024",
626
+ "history": "FFF",
627
+ "contract_sha256": "bae7140a136739f73f401974430463749c811fa43f31ed64fc5a502ced39746d",
628
+ "baseline_contract_exact": true,
629
+ "baseline_semantic_contract_match": true,
630
+ "contract_review": null,
631
+ "baseline_history": "FS",
632
+ "tokens": {
633
+ "input_tokens": 3441503,
634
+ "cached_input_tokens": 3390592,
635
+ "cache_write_input_tokens": 0,
636
+ "output_tokens": 20828,
637
+ "reasoning_output_tokens": 15847
638
+ },
639
+ "codex_turns": 1,
640
+ "wall_s": 903.8
641
+ },
642
+ {
643
+ "task": "l5_slippery_lift",
644
+ "seed": 3000,
645
+ "batch": "g56sol_original34_20261114",
646
+ "status": "done",
647
+ "valid": true,
648
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_slippery_lift_s3000_full_F1_direct_k3_1114-234322_p31113",
649
+ "id": "0025",
650
+ "history": "S",
651
+ "contract_sha256": "e51c5b60dc2ff8a2a0dba6dc47bda3f290d4950118b0f70bace5dd1a27fceb9a",
652
+ "baseline_contract_exact": true,
653
+ "baseline_semantic_contract_match": true,
654
+ "contract_review": null,
655
+ "baseline_history": "S",
656
+ "tokens": {
657
+ "input_tokens": 1089840,
658
+ "cached_input_tokens": 1064320,
659
+ "cache_write_input_tokens": 0,
660
+ "output_tokens": 12771,
661
+ "reasoning_output_tokens": 9867
662
+ },
663
+ "codex_turns": 1,
664
+ "wall_s": 398.6
665
+ },
666
+ {
667
+ "task": "l6_swap_interrupt",
668
+ "seed": 3000,
669
+ "batch": "g56sol_original34_20261114",
670
+ "status": "done",
671
+ "valid": true,
672
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l6_swap_interrupt_s3000_full_F1_direct_k3_1114-234515_p31111",
673
+ "id": "0026",
674
+ "history": "FS",
675
+ "contract_sha256": "88c543dfab2676eccd1fdc4bd7c7709c5385a8596f99378c54c640bdf100ed98",
676
+ "baseline_contract_exact": true,
677
+ "baseline_semantic_contract_match": true,
678
+ "contract_review": null,
679
+ "baseline_history": "S",
680
+ "tokens": {
681
+ "input_tokens": 2837371,
682
+ "cached_input_tokens": 2760448,
683
+ "cache_write_input_tokens": 0,
684
+ "output_tokens": 19261,
685
+ "reasoning_output_tokens": 14423
686
+ },
687
+ "codex_turns": 1,
688
+ "wall_s": 793.4
689
+ },
690
+ {
691
+ "task": "l6_sequence_resume",
692
+ "seed": 3000,
693
+ "batch": "g56sol_original34_20261114",
694
+ "status": "done",
695
+ "valid": true,
696
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l6_sequence_resume_s3000_full_F1_direct_k3_1114-235001_p31112",
697
+ "id": "0027",
698
+ "history": "FFF",
699
+ "contract_sha256": "f8f70ee55dbd213090686735cfe5451fb5b4a8735c87f41c5797616b71488da0",
700
+ "baseline_contract_exact": true,
701
+ "baseline_semantic_contract_match": true,
702
+ "contract_review": null,
703
+ "baseline_history": "S",
704
+ "tokens": {
705
+ "input_tokens": 7628114,
706
+ "cached_input_tokens": 7538560,
707
+ "cache_write_input_tokens": 0,
708
+ "output_tokens": 28429,
709
+ "reasoning_output_tokens": 20753
710
+ },
711
+ "codex_turns": 1,
712
+ "wall_s": 1380.4
713
+ },
714
+ {
715
+ "task": "l6_count_into_box",
716
+ "seed": 3000,
717
+ "batch": "g56sol_original34_20261114",
718
+ "status": "done",
719
+ "valid": true,
720
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l6_count_into_box_s3000_full_F1_direct_k3_1114-235201_p31113",
721
+ "id": "0028",
722
+ "history": "FFF",
723
+ "contract_sha256": "8f791510ad56ad342a05ce94327f27c18164133a01997fe2b12ee7f5e94d2bbd",
724
+ "baseline_contract_exact": true,
725
+ "baseline_semantic_contract_match": true,
726
+ "contract_review": null,
727
+ "baseline_history": "S",
728
+ "tokens": {
729
+ "input_tokens": 11528187,
730
+ "cached_input_tokens": 11342848,
731
+ "cache_write_input_tokens": 0,
732
+ "output_tokens": 28738,
733
+ "reasoning_output_tokens": 20528
734
+ },
735
+ "codex_turns": 1,
736
+ "wall_s": 1632.0
737
+ },
738
+ {
739
+ "task": "lh_tidy_stack",
740
+ "seed": 3000,
741
+ "batch": "g56sol_original34_20261114",
742
+ "status": "done",
743
+ "valid": true,
744
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tidy_stack_s3000_full_F1_direct_k3_1114-235829_p31110",
745
+ "id": "0029",
746
+ "history": "FFF",
747
+ "contract_sha256": "9a66fa39fa7a2c0e86b74e4cd47a1aafcf0f789e4a1233fb6f51079e9824669c",
748
+ "baseline_contract_exact": false,
749
+ "baseline_semantic_contract_match": true,
750
+ "contract_review": "inactive_arm_review_20261115",
751
+ "baseline_history": "FFS",
752
+ "tokens": {
753
+ "input_tokens": 15288187,
754
+ "cached_input_tokens": 15185024,
755
+ "cache_write_input_tokens": 0,
756
+ "output_tokens": 35040,
757
+ "reasoning_output_tokens": 24194
758
+ },
759
+ "codex_turns": 1,
760
+ "wall_s": 1912.6
761
+ },
762
+ {
763
+ "task": "lh_wobbly_table",
764
+ "seed": 3001,
765
+ "batch": "g56sol_original34_20261114",
766
+ "status": "done",
767
+ "valid": true,
768
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_wobbly_table_s3001_full_F1_direct_k3_1115-001301_p31111",
769
+ "id": "0030",
770
+ "history": "FFF",
771
+ "contract_sha256": "2e9021d90ca5f35bc16028491c4d721e23f4f7ee196f5361f1fdecca88429e2a",
772
+ "baseline_contract_exact": true,
773
+ "baseline_semantic_contract_match": true,
774
+ "contract_review": null,
775
+ "baseline_history": "FFF",
776
+ "tokens": {
777
+ "input_tokens": 22269071,
778
+ "cached_input_tokens": 22138112,
779
+ "cache_write_input_tokens": 0,
780
+ "output_tokens": 37863,
781
+ "reasoning_output_tokens": 25975
782
+ },
783
+ "codex_turns": 1,
784
+ "wall_s": 2336.5
785
+ },
786
+ {
787
+ "task": "lh_shelf_droop",
788
+ "seed": 3000,
789
+ "batch": "g56sol_original34_20261114",
790
+ "status": "done",
791
+ "valid": true,
792
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_shelf_droop_s3000_full_F1_direct_k3_1115-001913_p31112",
793
+ "id": "0031",
794
+ "history": "FFF",
795
+ "contract_sha256": "7092e841a3e5f430241d6634f98f277a74d7821864610885ddeba87112284c88",
796
+ "baseline_contract_exact": true,
797
+ "baseline_semantic_contract_match": true,
798
+ "contract_review": null,
799
+ "baseline_history": "S",
800
+ "tokens": {
801
+ "input_tokens": 17978919,
802
+ "cached_input_tokens": 17761664,
803
+ "cache_write_input_tokens": 0,
804
+ "output_tokens": 37117,
805
+ "reasoning_output_tokens": 25372
806
+ },
807
+ "codex_turns": 1,
808
+ "wall_s": 2380.6
809
+ },
810
+ {
811
+ "task": "lh_drawer_cabinet",
812
+ "seed": 3000,
813
+ "batch": "g56sol_original34_20261114",
814
+ "status": "done",
815
+ "valid": true,
816
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_drawer_cabinet_s3000_full_F1_direct_k3_1115-003021_p31113",
817
+ "id": "0032",
818
+ "history": "FFF",
819
+ "contract_sha256": "a62e37f0ff28a797622fbfe2beb1469eb18d12f1f2dd7ef1cd52ab4e35e17c2b",
820
+ "baseline_contract_exact": true,
821
+ "baseline_semantic_contract_match": true,
822
+ "contract_review": null,
823
+ "baseline_history": "FS",
824
+ "tokens": {
825
+ "input_tokens": 6528342,
826
+ "cached_input_tokens": 6397440,
827
+ "cache_write_input_tokens": 0,
828
+ "output_tokens": 28011,
829
+ "reasoning_output_tokens": 20720
830
+ },
831
+ "codex_turns": 1,
832
+ "wall_s": 1267.6
833
+ },
834
+ {
835
+ "task": "lh_order_dispatch",
836
+ "seed": 3000,
837
+ "batch": "g56sol_compound2_20261114",
838
+ "status": "done",
839
+ "valid": true,
840
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_order_dispatch_s3000_full_F1_direct_k3_1114-200623_p31200",
841
+ "id": "0000",
842
+ "history": "FFF",
843
+ "contract_sha256": "9a6b746b44739e26bc20cf95e5b1201ec3c810390ae35a1b423ef880f671ed72",
844
+ "baseline_contract_exact": true,
845
+ "baseline_semantic_contract_match": true,
846
+ "contract_review": null,
847
+ "baseline_history": "FFF",
848
+ "tokens": {
849
+ "input_tokens": 21024460,
850
+ "cached_input_tokens": 20909056,
851
+ "cache_write_input_tokens": 0,
852
+ "output_tokens": 46405,
853
+ "reasoning_output_tokens": 32742
854
+ },
855
+ "codex_turns": 1,
856
+ "wall_s": 2702.7
857
+ },
858
+ {
859
+ "task": "lh_parts_cart",
860
+ "seed": 3000,
861
+ "batch": "g56sol_compound2_20261114",
862
+ "status": "done",
863
+ "valid": true,
864
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_parts_cart_s3000_full_F1_direct_k3_1114-205125_p31201",
865
+ "id": "0001",
866
+ "history": "FFF",
867
+ "contract_sha256": "dadae4411aef6b7724c32996d51675683af643efe30b5282775585c02f397998",
868
+ "baseline_contract_exact": true,
869
+ "baseline_semantic_contract_match": true,
870
+ "contract_review": null,
871
+ "baseline_history": "FFS",
872
+ "tokens": {
873
+ "input_tokens": 10795721,
874
+ "cached_input_tokens": 10702464,
875
+ "cache_write_input_tokens": 0,
876
+ "output_tokens": 26975,
877
+ "reasoning_output_tokens": 18093
878
+ },
879
+ "codex_turns": 1,
880
+ "wall_s": 1766.5
881
+ },
882
+ {
883
+ "task": "lh_breakfast_service",
884
+ "seed": 3000,
885
+ "batch": "g56sol_breakfast1_20261114",
886
+ "status": "done",
887
+ "valid": true,
888
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/breakfast1/runs/api/g56sol_breakfast1_20261114/g56sol_breakfast1_20261114-gpt-5.6-sol-codex-harness-hidek_lh_breakfast_service_s3000_full_F1_direct_k3_1114-212115_p31300",
889
+ "id": "0000",
890
+ "history": "FFF",
891
+ "contract_sha256": "1aa213755a472d338a5f15003e4e184a306d869aabcde0fff42359b070c2dbef",
892
+ "baseline_contract_exact": true,
893
+ "baseline_semantic_contract_match": true,
894
+ "contract_review": null,
895
+ "baseline_history": "FFF",
896
+ "tokens": {
897
+ "input_tokens": 18404601,
898
+ "cached_input_tokens": 18191744,
899
+ "cache_write_input_tokens": 0,
900
+ "output_tokens": 38174,
901
+ "reasoning_output_tokens": 26084
902
+ },
903
+ "codex_turns": 1,
904
+ "wall_s": 3055.6
905
+ },
906
+ {
907
+ "task": "lh_desk_organizer",
908
+ "seed": 3000,
909
+ "batch": "g56sol_remaining3_20261114",
910
+ "status": "done",
911
+ "valid": true,
912
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3/runs/api/g56sol_remaining3_20261114/g56sol_remaining3_20261114-gpt-5.6-sol-codex-harness-hidek_lh_desk_organizer_s3000_full_F1_direct_k3_1114-221220_p31400",
913
+ "id": "0000",
914
+ "history": "FFF",
915
+ "contract_sha256": "5123b8c8a67811a0f1f4fc74eea306e593f14a7ebd9405948d2a6c6d41715f38",
916
+ "baseline_contract_exact": true,
917
+ "baseline_semantic_contract_match": true,
918
+ "contract_review": null,
919
+ "baseline_history": "S",
920
+ "tokens": {
921
+ "input_tokens": 133345098,
922
+ "cached_input_tokens": 131982720,
923
+ "cache_write_input_tokens": 0,
924
+ "output_tokens": 191576,
925
+ "reasoning_output_tokens": 118411
926
+ },
927
+ "codex_turns": 2,
928
+ "wall_s": 11366.9
929
+ },
930
+ {
931
+ "task": "lh_split_calibration",
932
+ "seed": 3000,
933
+ "batch": "g56sol_remaining3_20261114",
934
+ "status": "done",
935
+ "valid": true,
936
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3/runs/api/g56sol_remaining3_20261114/g56sol_remaining3_20261114-gpt-5.6-sol-codex-harness-hidek_lh_split_calibration_s3000_full_F1_direct_k3_1115-012146_p31401",
937
+ "id": "0001",
938
+ "history": "FFF",
939
+ "contract_sha256": "9d4352da43908def52eed8c1c19b26bdb3a4d6871b4e7479aeee66fb2be8562d",
940
+ "baseline_contract_exact": true,
941
+ "baseline_semantic_contract_match": true,
942
+ "contract_review": null,
943
+ "baseline_history": "FS",
944
+ "tokens": {
945
+ "input_tokens": 26471339,
946
+ "cached_input_tokens": 26317056,
947
+ "cache_write_input_tokens": 0,
948
+ "output_tokens": 46522,
949
+ "reasoning_output_tokens": 32274
950
+ },
951
+ "codex_turns": 1,
952
+ "wall_s": 2941.4
953
+ },
954
+ {
955
+ "task": "lh_shim_relay",
956
+ "seed": 3000,
957
+ "batch": "g56sol_remaining3_20261114",
958
+ "status": "done",
959
+ "valid": true,
960
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3/runs/api/g56sol_remaining3_20261114/g56sol_remaining3_20261114-gpt-5.6-sol-codex-harness-hidek_lh_shim_relay_s3000_full_F1_direct_k3_1115-021048_p31400",
961
+ "id": "0002",
962
+ "history": "FFF",
963
+ "contract_sha256": "512d2726a340470c4468173778ebc7a9a08c2268403d11a38c2903267b781287",
964
+ "baseline_contract_exact": true,
965
+ "baseline_semantic_contract_match": true,
966
+ "contract_review": null,
967
+ "baseline_history": "FFF",
968
+ "tokens": {
969
+ "input_tokens": 52238859,
970
+ "cached_input_tokens": 52002048,
971
+ "cache_write_input_tokens": 0,
972
+ "output_tokens": 62526,
973
+ "reasoning_output_tokens": 41818
974
+ },
975
+ "codex_turns": 1,
976
+ "wall_s": 4432.7
977
+ }
978
+ ]
979
+ }
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/workspace_exposure_audit.json ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checked_utc": "2026-11-14T21:05:01.852355+00:00",
3
+ "scope": "All model-visible tool events in 15 started runs; every shell command manually inspected; no shared workspace access observed. This is transcript evidence, not proof of old sandbox isolation.",
4
+ "runs": [
5
+ {
6
+ "task": "l7_offcenter_push",
7
+ "status": "done",
8
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_canary_20261114/g56sol_canary_20261114-gpt-5.6-sol-codex-harness-hidek_l7_offcenter_push_s3000_full_F1_direct_k3_1114-195251_p31100",
9
+ "transcript_sha256": "ff13e7dca12bb46335f3b32913392fc2a88360dc450c06e05afbc81dca5fe34d",
10
+ "shell_calls": [
11
+ {
12
+ "line": 23,
13
+ "arguments": {
14
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nimport numpy as np\nfor i in [0,7,8,9,10]:\n p='obs/s000_agentview.jpg' if i==0 else f'obs/s{i:03d}_agentview.jpg'\n a=np.array(Image.open(p))\n # brown: R moderately > G, G > B, within central tabletop\n m=(a[:,:,0]>90)&(a[:,:,0]<190)&(a[:,:,0]>a[:,:,1]*1.15)&(a[:,:,1]>a[:,:,2]*1.05)\n ys,xs=np.where(m)\n # central object pixels\n q=(xs>100)&(xs<400)&(ys>200)&(ys<380)\n print(i, (xs[q].min(),ys[q].min(),xs[q].max(),ys[q].max(),q.sum()) if q.any() else None)\nPY"
15
+ },
16
+ "result": null
17
+ },
18
+ {
19
+ "line": 27,
20
+ "arguments": {
21
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nimport numpy as np\nfor i in [0,7,10,13]:\n p='obs/s000_agentview.jpg' if i==0 else f'obs/s{i:03d}_agentview.jpg'\n a=np.array(Image.open(p))\n print('\\n',i)\n for xy in [(170,245),(170,260),(170,280),(220,245),(290,245),(150,300)]: print(xy,a[xy[1],xy[0]])\nPY"
22
+ },
23
+ "result": null
24
+ }
25
+ ],
26
+ "suspect_events": []
27
+ },
28
+ {
29
+ "task": "l5_slide_to_target",
30
+ "status": "done",
31
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_slide_to_target_s3000_full_F1_direct_k3_1114-200622_p31110",
32
+ "transcript_sha256": "00e5357f7e48705545f05ba71f9dd2f2feb94e7c014971a00038fec2e3e77411",
33
+ "shell_calls": [
34
+ {
35
+ "line": 5,
36
+ "arguments": {
37
+ "command": "python3 - <<'PY'\nimport cv2\nfor f in ['obs/s000_wrist.jpg','obs/s001_wrist.jpg','obs/s000_agentview.jpg']:\n im=cv2.imread(f)\n hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n # print rough color masks bbox\n masks={\n 'red': ((0,80,50),(10,255,255)),\n 'green': ((35,50,40),(90,255,255)),\n }\n print(f)\n for name,(lo,hi) in masks.items():\n m=cv2.inRange(hsv,lo,hi)\n n,lab,st,cent=cv2.connectedComponentsWithStats(m)\n comps=sorted([(s[4],tuple(s[:4]),tuple(c)) for s,c in zip(st[1:],cent[1:])],reverse=True)[:3]\n print(name,comps)\nPY"
38
+ },
39
+ "result": null
40
+ },
41
+ {
42
+ "line": 6,
43
+ "arguments": {
44
+ "command": "find . -maxdepth 3 -type f -not -path './obs/*' -print; du -sh obs"
45
+ },
46
+ "result": null
47
+ },
48
+ {
49
+ "line": 7,
50
+ "arguments": {
51
+ "command": "cat README.md"
52
+ },
53
+ "result": null
54
+ }
55
+ ],
56
+ "suspect_events": []
57
+ },
58
+ {
59
+ "task": "l5_tablecloth_pull",
60
+ "status": "done",
61
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_tablecloth_pull_s3000_full_F1_direct_k3_1114-200624_p31111",
62
+ "transcript_sha256": "9e47b3755fe735d26629665d1bb41417ef36ab8e321859e18e9c99a20c914daf",
63
+ "shell_calls": [
64
+ {
65
+ "line": 57,
66
+ "arguments": {
67
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/a2_s001_agentview.jpg','obs/a2_s006_agentview.jpg']:\n im=cv2.imread(p)\n hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n red=( ((hsv[:,:,0]<10)|(hsv[:,:,0]>170)) & (hsv[:,:,1]>100) & (hsv[:,:,2]>80))\n green=((hsv[:,:,0]>35)&(hsv[:,:,0]<90)&(hsv[:,:,1]>50)&(hsv[:,:,2]>50))\n for name,m in [('red',red),('green',green)]:\n ys,xs=np.where(m)\n print(p,name,'bbox',xs.min(),ys.min(),xs.max(),ys.max(),'center',xs.mean(),ys.mean(),'n',len(xs))\nPY"
68
+ },
69
+ "result": null
70
+ }
71
+ ],
72
+ "suspect_events": []
73
+ },
74
+ {
75
+ "task": "l3_wall_flush",
76
+ "status": "done",
77
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_wall_flush_s3000_full_F1_direct_k3_1114-200626_p31112",
78
+ "transcript_sha256": "ee20e9a81ffc5893481e36b7c285b9ccbc9d24c2054eade0262f307f71da4844",
79
+ "shell_calls": [],
80
+ "suspect_events": []
81
+ },
82
+ {
83
+ "task": "l3_under_table_tool",
84
+ "status": "done",
85
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_under_table_tool_s3000_full_F1_direct_k3_1114-201615_p31113",
86
+ "transcript_sha256": "754dbfff9751f38dcd077ebb6b14dbbaf944520c26a86630b6fecedff25a2109",
87
+ "shell_calls": [
88
+ {
89
+ "line": 3,
90
+ "arguments": {
91
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/s000_wrist.jpg','obs/s000_agentview.jpg']:\n im=cv2.imread(p); hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n # red low saturation due lighting; compare R dominance\n b,g,r=cv2.split(im)\n m=(r.astype(int)>g.astype(int)+25)&(r.astype(int)>b.astype(int)+25)&(r>90)\n n, lab, stats, cen=cv2.connectedComponentsWithStats(m.astype('uint8'))\n print(p, sorted([(stats[i,4],tuple(cen[i])) for i in range(1,n)], reverse=True)[:5])\nPY"
92
+ },
93
+ "result": null
94
+ },
95
+ {
96
+ "line": 5,
97
+ "arguments": {
98
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/s000_wrist.jpg','obs/s001_wrist.jpg']:\n im=cv2.imread(p); b,g,r=cv2.split(im); m=(r.astype(int)>g.astype(int)+25)&(r.astype(int)>b.astype(int)+25)&(r>90)\n n,l,s,c=cv2.connectedComponentsWithStats(m.astype('uint8'))\n print(p, sorted([(int(s[i,4]),tuple(np.round(c[i],1))) for i in range(1,n)], reverse=True)[:5])\nPY"
99
+ },
100
+ "result": null
101
+ },
102
+ {
103
+ "line": 7,
104
+ "arguments": {
105
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor p in ['obs/s001_wrist.jpg','obs/s002_wrist.jpg']:\n im=cv2.imread(p); b,g,r=cv2.split(im); m=(r.astype(int)>g.astype(int)+25)&(r.astype(int)>b.astype(int)+25)&(r>90)\n n,l,s,c=cv2.connectedComponentsWithStats(m.astype('uint8'))\n print(p, sorted([(int(s[i,4]),tuple(np.round(c[i],1))) for i in range(1,n)], reverse=True)[:4])\nPY"
106
+ },
107
+ "result": null
108
+ }
109
+ ],
110
+ "suspect_events": []
111
+ },
112
+ {
113
+ "task": "l4_fit_container",
114
+ "status": "done",
115
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l4_fit_container_s3000_full_F1_direct_k3_1114-202316_p31111",
116
+ "transcript_sha256": "8310191cdcad297fa5684dd1d4551b7b45adeac1f47bb81a8c22fe6a1776d2c4",
117
+ "shell_calls": [],
118
+ "suspect_events": []
119
+ },
120
+ {
121
+ "task": "l7_key_turn",
122
+ "status": "done",
123
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l7_key_turn_s3001_full_F1_direct_k3_1114-202453_p31112",
124
+ "transcript_sha256": "06879853d29403f818c7778ef9f7916581c4725b137cf23d237defb0467443b0",
125
+ "shell_calls": [
126
+ {
127
+ "line": 26,
128
+ "arguments": {
129
+ "command": "python3 - <<'PY'\nimport cv2, numpy as np\nfor f in ['obs/s008_agentview.jpg','obs/s009_agentview.jpg','obs/s011_agentview.jpg','obs/s012_agentview.jpg']:\n im=cv2.imread(f); hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV)\n # yellow/gold\n m=cv2.inRange(hsv,np.array([15,80,80]),np.array([45,255,255]))\n n,lab,st,cen=cv2.connectedComponentsWithStats(m)\n inds=np.argsort(st[:,cv2.CC_STAT_AREA])[::-1]\n print(f)\n for i in inds[1:4]:\n if st[i,4]<10: continue\n ys,xs=np.where(lab==i); pts=np.c_[xs,ys].astype(np.float32)\n rect=cv2.minAreaRect(pts)\n print(' area',st[i,4],'bbox',st[i,:4].tolist(),'rect',rect)\nPY"
130
+ },
131
+ "result": null
132
+ },
133
+ {
134
+ "line": 27,
135
+ "arguments": {
136
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in range(3,13):\n f=f'obs/s{s:03d}_wrist.jpg'; im=cv2.imread(f)\n if im is None: continue\n hsv=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(hsv,np.array([15,60,80]),np.array([45,255,255]))\n n,l,st,c=cv2.connectedComponentsWithStats(m)\n i=1+np.argmax(st[1:,4]); print(s, 'bbox', st[i,:4].tolist(), 'cent',c[i].round(1).tolist(),'area',st[i,4])\nPY"
137
+ },
138
+ "result": null
139
+ },
140
+ {
141
+ "line": 29,
142
+ "arguments": {
143
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nf='obs/s013_wrist.jpg'; im=cv2.imread(f); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,60,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); print(st[i,:4].tolist(),c[i].tolist(),st[i,4])\nPY"
144
+ },
145
+ "result": null
146
+ },
147
+ {
148
+ "line": 32,
149
+ "arguments": {
150
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [13,14,15]:\n im=cv2.imread(f'obs/s{s:03d}_wrist.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,60,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); print(s,c[i],st[i,:4])\nPY"
151
+ },
152
+ "result": null
153
+ },
154
+ {
155
+ "line": 35,
156
+ "arguments": {
157
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [16,17]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); r=cv2.minAreaRect(np.c_[xs,ys].astype('float32')); print(s,st[i,4],st[i,:4],r)\nPY"
158
+ },
159
+ "result": null
160
+ },
161
+ {
162
+ "line": 38,
163
+ "arguments": {
164
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [18,19]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
165
+ },
166
+ "result": null
167
+ },
168
+ {
169
+ "line": 39,
170
+ "arguments": {
171
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nfor s in [15,16,18,19]:\n im=Image.open(f'obs/s{s:03d}_agentview.jpg')\n im.crop((270,255,370,340)).resize((600,510)).save(f'obs/crop{s}.png')\nPY"
172
+ },
173
+ "result": null
174
+ },
175
+ {
176
+ "line": 46,
177
+ "arguments": {
178
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [22,23]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
179
+ },
180
+ "result": null
181
+ },
182
+ {
183
+ "line": 47,
184
+ "arguments": {
185
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nfor s in [20,21,22,23]: Image.open(f'obs/s{s:03d}_agentview.jpg').crop((270,255,370,340)).resize((600,510)).save(f'obs/crop{s}.png')\nPY"
186
+ },
187
+ "result": null
188
+ },
189
+ {
190
+ "line": 51,
191
+ "arguments": {
192
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [24,25]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,80,80]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
193
+ },
194
+ "result": null
195
+ },
196
+ {
197
+ "line": 56,
198
+ "arguments": {
199
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [24,25,26,27]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m)\n print('\\n',s)\n for i in np.argsort(st[1:,4])[::-1][:3]+1:\n if st[i,4]<10:continue\n ys,xs=np.where(l==i); print(st[i,4],st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
200
+ },
201
+ "result": null
202
+ },
203
+ {
204
+ "line": 59,
205
+ "arguments": {
206
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [24,25,26,27,28]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
207
+ },
208
+ "result": null
209
+ },
210
+ {
211
+ "line": 65,
212
+ "arguments": {
213
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [31,32]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
214
+ },
215
+ "result": null
216
+ },
217
+ {
218
+ "line": 67,
219
+ "arguments": {
220
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [32,33]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,cv2.minAreaRect(np.c_[xs,ys].astype('float32')),st[i,:4])\nPY"
221
+ },
222
+ "result": null
223
+ },
224
+ {
225
+ "line": 72,
226
+ "arguments": {
227
+ "command": "python3 - <<'PY'\nimport cv2,numpy as np\nfor s in [35,36]:\n im=cv2.imread(f'obs/s{s:03d}_agentview.jpg'); h=cv2.cvtColor(im,cv2.COLOR_BGR2HSV); m=cv2.inRange(h,np.array([15,70,70]),np.array([45,255,255])); n,l,st,c=cv2.connectedComponentsWithStats(m); i=1+np.argmax(st[1:,4]); ys,xs=np.where(l==i); print(s,st[i,:4],cv2.minAreaRect(np.c_[xs,ys].astype('float32')))\nPY"
228
+ },
229
+ "result": null
230
+ }
231
+ ],
232
+ "suspect_events": []
233
+ },
234
+ {
235
+ "task": "l2_turntable_restore",
236
+ "status": "done",
237
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l2_turntable_restore_s3000_full_F1_direct_k3_1114-203338_p31110",
238
+ "transcript_sha256": "4b427e6ad19bbb92dced14b973ebdd79b517ba14013792b8f6e2dd31af995b1c",
239
+ "shell_calls": [],
240
+ "suspect_events": []
241
+ },
242
+ {
243
+ "task": "l3_card_shelf",
244
+ "status": "done",
245
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l3_card_shelf_s3003_full_F1_direct_k3_1114-203509_p31113",
246
+ "transcript_sha256": "985885708df8a33f7a1648ad52eff88e9204483d79d5a1bdecd13ac7b59b37ae",
247
+ "shell_calls": [],
248
+ "suspect_events": []
249
+ },
250
+ {
251
+ "task": "l5_loaded_beam",
252
+ "status": "done",
253
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_l5_loaded_beam_s3000_full_F1_direct_k3_1114-204811_p31112",
254
+ "transcript_sha256": "7420e004d8ecd689c883252ed81eba2f6956dc6b63e9acc50bb155c199b5a3c8",
255
+ "shell_calls": [],
256
+ "suspect_events": []
257
+ },
258
+ {
259
+ "task": "lh_lid_box",
260
+ "status": "running",
261
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_lid_box_s3000_full_F1_direct_k3_1114-204823_p31114",
262
+ "transcript_sha256": "77f95f0c13659c848307af71f71a9607d8f34afe119a50108117878001c13fda",
263
+ "shell_calls": [],
264
+ "suspect_events": []
265
+ },
266
+ {
267
+ "task": "lh_bridge",
268
+ "status": "running",
269
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_bridge_s3001_full_F1_direct_k3_1114-205050_p31111",
270
+ "transcript_sha256": "02819aa964a34d49c4a0f30add274d9a7db4875f945f3d742724e72cb72a8350",
271
+ "shell_calls": [],
272
+ "suspect_events": []
273
+ },
274
+ {
275
+ "task": "lh_tray_delivery",
276
+ "status": "running",
277
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tray_delivery_s3000_full_F1_direct_k3_1114-205403_p31112",
278
+ "transcript_sha256": "b71b7a6e3c0c0ac5d66b4d7b88d8b7b5ad604dda669f610173608b47a9a7b1f6",
279
+ "shell_calls": [
280
+ {
281
+ "line": 53,
282
+ "arguments": {
283
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nfor n in ['obs/s027_agentview.jpg','obs/s019_agentview.jpg','obs/s013_agentview.jpg']:\n im=Image.open(n)\n im.crop((0,150,180,300)).resize((720,600)).save('/tmp/'+n.split('/')[-1])\nPY"
284
+ },
285
+ "result": null
286
+ },
287
+ {
288
+ "line": 55,
289
+ "arguments": {
290
+ "command": "mkdir -p zoom && cp /tmp/s*_agentview.jpg zoom/"
291
+ },
292
+ "result": null
293
+ },
294
+ {
295
+ "line": 56,
296
+ "arguments": {
297
+ "command": "mkdir -p zoom; python3 - <<'PY'\nfrom PIL import Image\nfor n in ['obs/s027_agentview.jpg','obs/s019_agentview.jpg','obs/s013_agentview.jpg']:\n im=Image.open(n)\n im.crop((0,150,180,300)).resize((720,600)).save('zoom/'+n.split('/')[-1])\nPY"
298
+ },
299
+ "result": null
300
+ }
301
+ ],
302
+ "suspect_events": []
303
+ },
304
+ {
305
+ "task": "lh_order_dispatch",
306
+ "status": "done",
307
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_order_dispatch_s3000_full_F1_direct_k3_1114-200623_p31200",
308
+ "transcript_sha256": "4ce2827a409e84e064c3c86187728ddaf5376643c8d51aa48cdfd600af362b3c",
309
+ "shell_calls": [],
310
+ "suspect_events": []
311
+ },
312
+ {
313
+ "task": "lh_parts_cart",
314
+ "status": "running",
315
+ "log": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_parts_cart_s3000_full_F1_direct_k3_1114-205125_p31201",
316
+ "transcript_sha256": "c7a006004bbe587e4ed1c0b7f0b7152379007c2a7ee9dbfb5e300e4d4c3dcba3",
317
+ "shell_calls": [
318
+ {
319
+ "line": 50,
320
+ "arguments": {
321
+ "command": "python3 - <<'PY'\nfrom PIL import Image\nimport numpy as np\nfor f in ['obs/s000_agentview.jpg','obs/s026_agentview.jpg','obs/s029_agentview.jpg']:\n a=np.array(Image.open(f))\n # print row 304 runs where brown tool-ish R 100-190 G70-160 B<80\n m=(a[:,:,0]>100)&(a[:,:,0]<210)&(a[:,:,1]>60)&(a[:,:,1]<170)&(a[:,:,2]<90)\n ys,xs=np.where(m)\n print(f, xs.min(),xs.max(),ys.min(),ys.max(), [(y,int((m[y]).sum())) for y in range(295,312) if m[y].sum()])\nPY"
322
+ },
323
+ "result": null
324
+ }
325
+ ],
326
+ "suspect_events": []
327
+ }
328
+ ]
329
+ }
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/evaluation_evidence/workspace_isolation_patch.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "changes": [
3
+ {
4
+ "group": "original34",
5
+ "path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/jail/jail_inner.sh",
6
+ "applied_utc": "2026-11-14T21:05:01.896083+00:00",
7
+ "old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
8
+ "new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
9
+ },
10
+ {
11
+ "group": "compound2",
12
+ "path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/jail/jail_inner.sh",
13
+ "applied_utc": "2026-11-14T21:05:01.930531+00:00",
14
+ "old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
15
+ "new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
16
+ },
17
+ {
18
+ "group": "breakfast1",
19
+ "path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/breakfast1/jail/jail_inner.sh",
20
+ "applied_utc": "2026-11-14T21:05:01.961630+00:00",
21
+ "old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
22
+ "new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
23
+ },
24
+ {
25
+ "group": "remaining3",
26
+ "path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3/jail/jail_inner.sh",
27
+ "applied_utc": "2026-11-14T21:05:01.994096+00:00",
28
+ "old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
29
+ "new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
30
+ }
31
+ ],
32
+ "upstream_patch": "/mnt/cpfs/workspace/agentic-robotics/ops/minimax_glm_go_smoke_20261114/workspace_jail_fix.patch",
33
+ "active_tool_calls": "api_player.run_shell invokes repository-local jail file anew per call; running agent context unchanged",
34
+ "completed_runs": "retained: full transcript inspected; no shared workspace access observed",
35
+ "mixed_runtime_runs": [
36
+ "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_lid_box_s3000_full_F1_direct_k3_1114-204823_p31114",
37
+ "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_bridge_s3001_full_F1_direct_k3_1114-205050_p31111",
38
+ "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/runs/api/g56sol_original34_20261114/g56sol_original34_20261114-gpt-5.6-sol-codex-harness-hidek_lh_tray_delivery_s3000_full_F1_direct_k3_1114-205403_p31112",
39
+ "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_parts_cart_s3000_full_F1_direct_k3_1114-205125_p31201"
40
+ ]
41
+ }
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/client/lffbench_client/__init__.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3).
2
+
3
+ Only the standard library; it never imports the simulator. It talks to the episode's tool gateway
4
+ (scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed
5
+ shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls
6
+ them through a Session:
7
+
8
+ from lffbench_client import Session
9
+ s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher)
10
+ first = s.first_message() # README + first status, as every harness gets it
11
+ tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat
12
+ r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult
13
+ r.json() # the robot server's reply as a dict
14
+ s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)]
15
+
16
+ A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished
17
+ says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only
18
+ feedback is what the robot server writes into the tool results.
19
+ """
20
+ import base64
21
+ import dataclasses
22
+ import json
23
+ import os
24
+ import urllib.error
25
+ import urllib.parse
26
+ import urllib.request
27
+
28
+ __all__ = ["Session", "ToolResult", "GatewayError", "STYLES"]
29
+ __version__ = "0.1.0"
30
+
31
+ STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat")
32
+
33
+
34
+ class GatewayError(RuntimeError):
35
+ pass
36
+
37
+
38
+ @dataclasses.dataclass
39
+ class ToolResult:
40
+ content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}]
41
+ is_error: bool
42
+ finished: bool # the episode is over: stop calling tools and report
43
+ calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0)
44
+
45
+ @property
46
+ def text(self):
47
+ """All text items, joined by newlines."""
48
+ return "\n".join(c["text"] for c in self.content if c.get("type") == "text")
49
+
50
+ def json(self):
51
+ """The first text item parsed as JSON (robot / shell / view_images replies are JSON objects)."""
52
+ for c in self.content:
53
+ if c.get("type") == "text":
54
+ return json.loads(c["text"])
55
+ raise ValueError("no text item")
56
+
57
+ @property
58
+ def images(self):
59
+ """[(mime type, bytes)] of the image items."""
60
+ return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"]
61
+
62
+
63
+ class Session:
64
+ """One episode's tools through its gateway. face labels this access path in the gateway transcript."""
65
+
66
+ def __init__(self, url, token, face="sdk", timeout_s=900.0):
67
+ self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s
68
+ self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy
69
+
70
+ @classmethod
71
+ def from_env(cls, face="sdk", **kw):
72
+ url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN")
73
+ if not url or not token:
74
+ raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set")
75
+ return cls(url, token, face=face, **kw)
76
+
77
+ @classmethod
78
+ def from_gateway_file(cls, path, face="sdk", **kw):
79
+ """gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars)."""
80
+ d = json.load(open(path))
81
+ return cls(d["url"], d["token"], face=face, **kw)
82
+
83
+ # ------------------------------------------------------------------------------------------------ http
84
+ def _request(self, method, path, body=None):
85
+ req = urllib.request.Request(self.url + path, method=method,
86
+ data=None if body is None else json.dumps(body).encode(),
87
+ headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face,
88
+ "Content-Type": "application/json"})
89
+ try:
90
+ with self._opener.open(req, timeout=self.timeout_s) as r:
91
+ return r.read(), r.headers.get("Content-Type", "")
92
+ except urllib.error.HTTPError as e:
93
+ raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None
94
+ except urllib.error.URLError as e:
95
+ raise GatewayError(f"{method} {path}: {e.reason}") from None
96
+
97
+ def _get_json(self, path):
98
+ return json.loads(self._request("GET", path)[0])
99
+
100
+ # ------------------------------------------------------------------------------------------------ tools
101
+ def call(self, name, arguments=None):
102
+ raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {}))
103
+ d = json.loads(raw)
104
+ return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]),
105
+ calls_in_attempt=d.get("calls_in_attempt"))
106
+
107
+ def robot(self, command):
108
+ """One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...')."""
109
+ return self.call("robot", dict(command=command))
110
+
111
+ def shell(self, command):
112
+ """A bash command in the episode workspace (jailed: no network, nothing outside the workspace)."""
113
+ return self.call("shell", dict(command=command))
114
+
115
+ def view_images(self, paths):
116
+ """Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items."""
117
+ return self.call("view_images", dict(paths=list(paths)))
118
+
119
+ # ------------------------------------------------------------------------------------------------ instructions
120
+ def tool_specs(self, style="raw"):
121
+ """The three tool schemas with the reference descriptions, in one of STYLES."""
122
+ if style not in STYLES:
123
+ raise ValueError(f"style must be one of {STYLES}")
124
+ return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"]
125
+
126
+ def readme(self):
127
+ return self._request("GET", "/readme")[0].decode("utf-8")
128
+
129
+ def first_message(self):
130
+ """Preamble + README + first status report: the first user message every harness gets."""
131
+ return self._request("GET", "/first_message")[0].decode("utf-8")
132
+
133
+ def health(self):
134
+ return self._get_json("/health")
135
+
136
+ def status(self):
137
+ """robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not
138
+ a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result."""
139
+ return self._get_json("/status")
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/agent/backends/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model backends. Import lazily: each API backend needs its provider's SDK (see base.import_sdk)."""
2
+ from .base import AttemptInfo, Backend, BackendResponse, RunInfo # noqa: F401
3
+
4
+
5
+ def make_backend(kind, **kw):
6
+ if kind == "scripted":
7
+ from .scripted import ScriptedBackend
8
+ return ScriptedBackend(**kw)
9
+ if kind == "openai":
10
+ from .openai_responses import OpenAIResponsesBackend
11
+ return OpenAIResponsesBackend(**kw)
12
+ if kind == "chat":
13
+ from .chat_completions import ChatCompletionsBackend
14
+ return ChatCompletionsBackend(**kw)
15
+ if kind == "anthropic":
16
+ from .anthropic_messages import AnthropicMessagesBackend
17
+ return AnthropicMessagesBackend(**kw)
18
+ if kind == "gemini":
19
+ from .gemini import GeminiBackend
20
+ return GeminiBackend(**kw)
21
+ raise ValueError(kind)
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/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/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l2_turntable_restore.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled-arm spec for l2_turntable_restore (2026-10-12).
2
+
3
+ Hidden variable: inst["q0"], the turntable's start angle (rad, + = counter-clockwise seen from above). It is the only
4
+ thing the agent has to remember: the main task forces a large turn of the disc (to bring the butter out from under the
5
+ shelf), after which nothing in the scene shows the start angle. apply_instance() places the disc at q0 and puts the
6
+ butter at disc-frame angle theta (so its world azimuth is theta + q0) on every reset, and reset_instance() records the
7
+ start angle from the simulator, so overriding "q0" alone is enough.
8
+
9
+ Geometry used below (TurntableRestore.butter_to_basket): with the butter at world azimuth az (about the disc axis)
10
+ and box yaw az + tilt, the main task turns the disc by T = wrap(PICK_AZ - tilt - az), PICK_AZ = +90 deg (open side).
11
+ Its sign flips at az = flip = -90 deg - tilt (the middle of the covered side); |T| = 180 deg - |az - flip|.
12
+
13
+ h0 -> q0 with the butter already at PICK_AZ (open side, long axis along world y): the main task needs no turn
14
+ (T ~ 0), so the scripted naive (main task, then stop) leaves the disc at its start angle and succeeds.
15
+ NB: the instruction's "under the shelf" is then not literally true (the butter is on the open half).
16
+ twin -> q0 with the butter still under the shelf but 35 deg on the OTHER side of flip: the main task turns the disc
17
+ the opposite way (|T| = 145 deg, inside the measured 136-179 deg range), so naive still fails visibly, and the
18
+ correction (turn back) has the opposite sign; the twin's start angle differs from the original's by
19
+ 35 deg + |az - flip| >= 35 deg (tolerance 15 deg), so restoring to the twin's remembered marks fails here.
20
+ reveal -> the start angle stated as the direction the yellow stripe points (seen from above), in robot-centric words
21
+ (forward = away from the robot, counter-clockwise as in the F2 feedback).
22
+ """
23
+ import numpy as np
24
+
25
+ HIDDEN_KEYS = ("q0",)
26
+
27
+ TARGET = "butter_1"
28
+ PICK_AZ = np.pi / 2 # TurntableRestore.PICK_AZ
29
+ TWIN_OFF = np.radians(35.0)
30
+ STRIPE_ANG = np.pi # disc-frame angle of the yellow stripe (l2_turntable.STRIPE_ANG)
31
+
32
+
33
+ def _wrap(a):
34
+ return float((a + np.pi) % (2 * np.pi) - np.pi)
35
+
36
+
37
+ def _geom(inst):
38
+ th, tilt = float(inst["theta"][TARGET]), float(inst["tilt"][TARGET])
39
+ return th, tilt, -np.pi / 2 - tilt
40
+
41
+
42
+ def h0(inst):
43
+ th, tilt, _ = _geom(inst)
44
+ return {"q0": _wrap(PICK_AZ - tilt - th)}
45
+
46
+
47
+ def twin(inst):
48
+ th, tilt, flip = _geom(inst)
49
+ s = 1.0 if _wrap(th + float(inst["q0"]) - flip) >= 0 else -1.0
50
+ return {"q0": _wrap(flip - s * TWIN_OFF - th)}
51
+
52
+
53
+ def _compass(deg):
54
+ names = ("forward", "forward-left", "left", "backward-left", "backward", "backward-right", "right", "forward-right")
55
+ return names[int(np.floor(((deg % 360) + 22.5) / 45.0)) % 8]
56
+
57
+
58
+ def reveal(inst):
59
+ az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
60
+ side = "counter-clockwise" if az >= 0 else "clockwise"
61
+ return (f"Note: at the start, seen from above, the yellow stripe on the turntable points out from the turntable's "
62
+ f"centre {abs(az):.0f} deg {side} from straight forward (roughly {_compass(az)}); that is the angle the "
63
+ f"turntable is at now.")
64
+
65
+
66
+ def fix(inst, params):
67
+ """Ladder Fix rung (docs/20): the oracle turns the disc back to the saved start angle after the butter is out."""
68
+ az = np.degrees(_wrap(float(inst["q0"]) + STRIPE_ANG))
69
+ side = "counter-clockwise" if az >= 0 else "clockwise"
70
+ return (f"A way to succeed: after the butter is in the basket, turn the turntable back to its start angle before "
71
+ f"you finish. At the start, seen from above, the yellow stripe pointed {abs(az):.0f} deg {side} from "
72
+ f"straight forward (roughly {_compass(az)}). Grasp a red peg and move the gripper along the rim to turn "
73
+ f"the disc until the stripe points that way again (within 15 deg), then release the peg and finish.")
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/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/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l3_wall_flush.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled arms for l3_wall_flush (2026-10-12).
2
+
3
+ Hidden variable: inst["gap"] -- the box-wall gap, 0-3 mm (below camera resolution), far less than the ~1.2 cm a
4
+ finger needs, so the wall-side finger lands on the wall top. sample_instance caches the wall position derived from it
5
+ (wall_x = box_x + side * (wall half thickness + box half width + gap)) and apply_instance reads only inst["wall_xy"],
6
+ so every override below sets wall_xy as well.
7
+
8
+ h0 gap = 5 cm: box, plate, wall length and wall y unchanged, the wall moved 4.7-5 cm away from the box (on the
9
+ same side). There is room for the whole finger and the prior (grasp across the width where the box lies) works.
10
+ (2.5 cm was not enough: the open fingers reach 6.6 cm from the grasp centre, so with the wall on the far side
11
+ the outer edge of the finger still caught the wall top and the box slipped out on the way, seeds 3000 / 3003.)
12
+ twin Gap unchanged (box still flush, trap active), box / plate / wall length / wall x unchanged, but the wall slid
13
+ along y so that the box sits near the OTHER end of the wall, 2 cm of wall beyond the box's end (the sampler's
14
+ extreme). The original's nearer wall end is +y (or -y); the twin's is -y (or +y): the push that clears the
15
+ wall goes the opposite way, and is the shortest possible push (about 10 + 4.5 cm).
16
+ Note: pushing the original's box towards its FAR end also clears the wall (just a longer push), so the cross
17
+ check "twin oracle on the original" succeeds (measured 5/5, seeds 3000-3004; results/l3_wall_flush/arms/
18
+ validate.json). The twin changes which way to push, not whether pushing works.
19
+ reveal The gap, and on which side of the box the wall is, in the task's F2 frame words.
20
+ """
21
+ BOX_HALF_X, BOX_HALF_Y, WALL_HALF_T = 0.03, 0.08, 0.015
22
+ H0_GAP = 0.05
23
+
24
+ HIDDEN_KEYS = ("gap",)
25
+
26
+
27
+ def _wall_x(inst, gap):
28
+ return inst["box_xy"][0] + inst["side"] * (WALL_HALF_T + BOX_HALF_X + gap)
29
+
30
+
31
+ def h0(inst):
32
+ return {"gap": H0_GAP, "wall_xy": [_wall_x(inst, H0_GAP), inst["wall_xy"][1]]}
33
+
34
+
35
+ def twin(inst):
36
+ wy, by = inst["wall_xy"][1], inst["box_xy"][1]
37
+ u_max = inst["wall_hl"] - BOX_HALF_Y - 0.02
38
+ nearer = 1 if by - wy > 0 else -1 # same rule as WallFlush._nearer_end
39
+ u_twin = -nearer * u_max # box offset from the wall centre in the twin: near the other end
40
+ return {"wall_xy": [inst["wall_xy"][0], by - u_twin]}
41
+
42
+
43
+ def reveal(inst):
44
+ side = "far side (away from the robot)" if inst["side"] > 0 else "near side (toward the robot)"
45
+ return (f"The long box is pressed against the wall on its {side} along its whole length: the gap between box "
46
+ f"and wall is only about {max(100 * inst['gap'], 0.1):.1f} cm.")
47
+
48
+
49
+ def fix(inst, params):
50
+ """Ladder Fix rung (docs/20): push the box along the wall past its nearer end (oracle end, margin 4.5 cm), then
51
+ grasp across the width and place."""
52
+ end, margin = int(params["end"]), float(params["margin"])
53
+ wy, hl, by = float(inst["wall_xy"][1]), float(inst["wall_hl"]), float(inst["box_xy"][1])
54
+ wall_end = wy + hl if end > 0 else wy - hl
55
+ dist = max(0.0, end * (wall_end + end * margin - by))
56
+ side, other = ("left", "right") if end > 0 else ("right", "left")
57
+ return (f"A way to succeed: first get the box away from the wall, then grasp it. With the gripper closed and the "
58
+ f"fingertips about 1 cm above the table, push on the box's end face on the robot's {other} side and slide "
59
+ f"the box slowly (speed about 0.08) along the wall towards the robot's {side}, about {100 * dist:.0f} cm, "
60
+ f"until the whole box is past the end of the wall (its centre about {100 * margin:.1f} cm beyond the "
61
+ f"wall's end). Then lift, open the gripper, grasp the box across its 6 cm width and put it on the plate.")
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/l7_key_turn.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Controlled-arm spec for l7_key_turn (2026-10-12).
2
+
3
+ Hidden variable: inst["direction"], the way the key opens the lock ("CCW" or "CW", seen from above). apply_instance()
4
+ derives the joint range and outcome()/check_unlock()/oracle_params() derive the open sign from it on every reset, so
5
+ overriding "direction" alone is enough (nothing is cached at sampling time).
6
+
7
+ The scripted prior (naive) turns counterclockwise, so the trap exists only on CW locks -- all full5 instances are CW.
8
+
9
+ h0 -> direction = "CCW": same lock position / yaw, the key opens the common-sense way, naive succeeds.
10
+ twin -> {} (no valid twin). The task has a single binary hidden variable and the trap exists only for one of its two
11
+ values: a twin with the trap still active must be CW again, i.e. need exactly the same correction ("turn
12
+ clockwise"), and the sign-flipped twin (CCW) is the H0 twin, where naive succeeds. There is no second hidden
13
+ constraint (the required angle is the fixed quarter turn named in the instruction). The mismatched-history
14
+ arm therefore has to take another instance's history -- note that every trap instance's history teaches the
15
+ same correction, so for this task a mismatched history is not misleading about the direction.
16
+ reveal -> states which way the key turns and that the other way stops after ~3 deg (the words "clockwise",
17
+ "counterclockwise", "seen from above" are those of the task's F2 feedback).
18
+ """
19
+
20
+ HIDDEN_KEYS = ("direction",)
21
+
22
+
23
+ def h0(inst):
24
+ return {"direction": "CCW"}
25
+
26
+
27
+ def twin(inst):
28
+ return {}
29
+
30
+
31
+ def reveal(inst):
32
+ ok, other = (("counterclockwise", "clockwise") if inst["direction"] == "CCW" else ("clockwise", "counterclockwise"))
33
+ return (f"Note: this lock opens only when the key is turned {ok} (seen from above); turned {other} the key moves "
34
+ f"about 3 degrees and then hits a hard stop.")
leaf/release/source_packages/models-20261115-g56sol_remaining3_20261114/lff/source_closure/lffbench/arm_specs/lh_tidy_stack.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-4 intervention texts for lh_tidy_stack (2026-10-30, reports/layer4_intervention_20261030). No h0 / twin: this task is
2
+ not in the controlled arms of full5.
3
+
4
+ Hidden variable: inst["soft_colour"] -- the empty soft carton among the four boxes (None in benign instances).
5
+ reveal says which box is soft and how much it carries; not where to put it.
6
+ fix the oracle's order (lh_tidy_stack.oracle_params: rigid boxes first, the soft box last, then the cup).
7
+ """
8
+ HIDDEN_KEYS = ("soft_colour",)
9
+
10
+
11
+ def reveal(inst):
12
+ return (f"The {inst['soft_colour']} box is an empty, soft carton. It carries one thing, but gives way as soon as a "
13
+ f"second thing rests above it, and everything above it slides off the pile.")
14
+
15
+
16
+ def fix(inst, params):
17
+ return (f"A way to succeed: stack the other three boxes first, put the {inst['soft_colour']} box on top of them last, "
18
+ f"and stand the cup on it. It then carries only the cup.")