PeterXie666 commited on
Commit
af3fa80
·
verified ·
1 Parent(s): cfe6cc6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. leaf/code/v1.5/backfill-20261102-tw_opus/lerobot_export.py +431 -0
  2. leaf/code/v1.5/v1.4/validate_dataset.py +57 -0
  3. leaf/final/episode_000173_wrist_image.png +3 -0
  4. leaf/final/episode_000523_wrist_image.png +3 -0
  5. leaf/final/episode_000561.npz +3 -0
  6. leaf/final/episode_000798.npz +3 -0
  7. leaf/final/episode_001822_wrist_image.png +3 -0
  8. leaf/final/episode_001831.npz +3 -0
  9. leaf/final/episode_001963_wrist_image.png +3 -0
  10. leaf/final/episode_002252_wrist_image.png +3 -0
  11. leaf/final/episode_002291_wrist_image.png +3 -0
  12. leaf/final/episode_002739_wrist_image.png +3 -0
  13. leaf/final/episode_003182_wrist_image.png +3 -0
  14. leaf/final/episode_003203_wrist_image.png +3 -0
  15. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/batches.json +9 -0
  16. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/rejected.json +1 -0
  17. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/client/pyproject.toml +13 -0
  18. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/__init__.py +1 -0
  19. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/bddl.py +66 -0
  20. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/envs.py +325 -0
  21. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/objects.py +98 -0
  22. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/skills.py +156 -0
  23. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/task_base.py +129 -0
  24. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/vla.py +293 -0
  25. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/agent_compare.py +40 -0
  26. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/agent_cost.py +77 -0
  27. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/api_batch.py +704 -0
  28. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_breakfast_geometry.py +41 -0
  29. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_breakfast_mechanisms.py +79 -0
  30. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_breakfast_tool_interface.py +57 -0
  31. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_lh_pantry_relatch.py +138 -0
  32. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_setup.py +175 -0
  33. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/claude_batch.py +309 -0
  34. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/cs_ir_report.py +87 -0
  35. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/feedback_ladder.py +428 -0
  36. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/full_report.py +89 -0
  37. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/full_waves.sh +38 -0
  38. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/gpt_player.py +20 -0
  39. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/gptpolicy_player.sh +37 -0
  40. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/harness_run.py +431 -0
  41. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/headroom_parts_cart.py +19 -0
  42. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/l6_controls.py +92 -0
  43. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/ladder_plan.py +120 -0
  44. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/layer4_plan.py +174 -0
  45. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/lerobot_export.py +431 -0
  46. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/lerobot_replay.py +744 -0
  47. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/lerobot_sft_dataset.py +473 -0
  48. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/make_dossier.py +103 -0
  49. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/make_video.py +132 -0
  50. leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/mismatch_plan.py +149 -0
leaf/code/v1.5/backfill-20261102-tw_opus/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/code/v1.5/v1.4/validate_dataset.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate the exported dataset against the plan and the raw recordings (lerobot env).
2
+
3
+ python validate_dataset.py <dataset_root> <work_dir> [n_samples]"""
4
+ import json
5
+ import os
6
+ import random
7
+ from pathlib import Path
8
+ import sys
9
+
10
+ import av
11
+ from video_frame import frame_at
12
+ import numpy as np
13
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
14
+
15
+ root, work = sys.argv[1], sys.argv[2]
16
+ n_samples = int(sys.argv[3]) if len(sys.argv) > 3 else 60
17
+ plan = json.load(open(os.path.join(work, "plan.json")))
18
+ eps = plan["episodes"]
19
+ ds = LeRobotDataset(plan["repo_id"], root=root)
20
+ rep = dict(codebase_version=ds.meta.info["codebase_version"], episodes=ds.num_episodes, frames=ds.num_frames,
21
+ plan_episodes=len(eps), plan_frames=plan["total_frames"])
22
+ assert ds.num_episodes == len(eps) and ds.num_frames == plan["total_frames"], rep
23
+ lens = ds.meta.episodes["length"]
24
+ assert [int(x) for x in lens] == [e["n"] for e in eps], "episode lengths differ from the plan"
25
+ lff = os.path.join(root, "lff")
26
+ for e in eps:
27
+ i = e["index"]
28
+ assert os.path.exists(os.path.join(lff, "annotations", f"episode_{i:06d}.json"))
29
+ s = np.load(os.path.join(lff, "sim_state", f"episode_{i:06d}.npy"), mmap_mode="r")
30
+ assert s.shape[0] == e["n"], (i, s.shape, e["n"])
31
+ rng = random.Random(0)
32
+ worst_img, worst_num = 0.0, 0.0
33
+ new_eps = [e for e in eps if e["index"] >= 596] if Path(root).name == "dataset" else eps
34
+ old_eps = [e for e in eps if e["index"] < 596] if Path(root).name == "dataset" else []
35
+ n_old = 50 if old_eps else 0
36
+ assert n_samples >= len(new_eps) + n_old
37
+ sample_eps = new_eps + [rng.choice(new_eps) for _ in range(n_samples - n_old - len(new_eps))] + [rng.choice(old_eps) for _ in range(n_old)]
38
+ for sample_i, e in enumerate(sample_eps):
39
+ k = rng.randrange(e["n"])
40
+ item = ds[e["from"] + k]
41
+ assert int(item["episode_index"]) == e["index"] and int(item["frame_index"]) == k
42
+ fr = np.load(os.path.join(e["dir"], "frames.npz"))
43
+ st = np.concatenate([fr["eef_pos"][k], fr["eef_axis_angle"][k], fr["gripper_qpos"][k]])
44
+ worst_num = max(worst_num, float(np.abs(item["observation.state"].numpy() - st).max()),
45
+ float(np.abs(item["action"].numpy() - fr["action"][k]).max()))
46
+ assert int(item["annotation.attempt_index"]) == int(fr["attempt"][k])
47
+ for key, cam in (("observation.images.image", "agentview"), ("observation.images.wrist_image", "wrist")):
48
+ ref = frame_at(os.path.join(e["dir"], f"{cam}.mp4"), k).astype(float)
49
+ img = item[key].permute(1, 2, 0).numpy() * 255.0
50
+ worst_img = max(worst_img, float(np.abs(img - ref).mean()))
51
+ if (sample_i + 1) % 25 == 0:
52
+ print(f"checked {sample_i + 1}/{n_samples}", flush=True)
53
+ rep.update(new_samples=n_samples-n_old, old_samples=n_old, every_new_episode_sampled=True, samples=n_samples, max_state_action_abs_err=worst_num, max_mean_abs_pixel_err=round(worst_img, 3))
54
+ assert worst_num < 1e-5 and worst_img < 6.0, rep
55
+ print(json.dumps(rep))
56
+ with open(os.path.join(work, "validation_report.json"), "w") as f:
57
+ json.dump(dict(rep, status="pass"), f, indent=1)
leaf/final/episode_000173_wrist_image.png ADDED

Git LFS Details

  • SHA256: 1a29d2043dac29102ab05b397ef306d6875a7843b8f232135088ce14b81daa2d
  • Pointer size: 130 Bytes
  • Size of remote file: 50.3 kB
leaf/final/episode_000523_wrist_image.png ADDED

Git LFS Details

  • SHA256: a6cde99b12dfc61f8c40c137dd924f9ec556935a348db4cb08e3cf55f1159ea2
  • Pointer size: 130 Bytes
  • Size of remote file: 40.8 kB
leaf/final/episode_000561.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:00926be8e61a584f86a5b55cc8758944ccdabcc6e7b4f114093d620ca0ebb5e9
3
+ size 3942
leaf/final/episode_000798.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d8f420f50bce94e8cb953c1f040f9bcd2ee579bd7420814ca491ccd4d4630dff
3
+ size 3942
leaf/final/episode_001822_wrist_image.png ADDED

Git LFS Details

  • SHA256: 42239f817a6ef9e6f0fbca6314e446c8f0fc938aeb158c513c24381e3af55a30
  • Pointer size: 130 Bytes
  • Size of remote file: 32.1 kB
leaf/final/episode_001831.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8954981032cc6c70941f4f6e5869306956013aaf742883ec89387a330bac7fc1
3
+ size 4150
leaf/final/episode_001963_wrist_image.png ADDED

Git LFS Details

  • SHA256: 2dea6316f5a0dfb2833d1ecf45b775e831b232b004830c56afa88441f04e885d
  • Pointer size: 130 Bytes
  • Size of remote file: 38 kB
leaf/final/episode_002252_wrist_image.png ADDED

Git LFS Details

  • SHA256: fd262a0ce8efc459e6e988da23b7eeb01a77e1da099653936e3ea827ae48567c
  • Pointer size: 129 Bytes
  • Size of remote file: 9.12 kB
leaf/final/episode_002291_wrist_image.png ADDED

Git LFS Details

  • SHA256: 5c33e4999b4d87df8da3df1a689d40a02f4a30767a4955addad82fe529effa93
  • Pointer size: 130 Bytes
  • Size of remote file: 39 kB
leaf/final/episode_002739_wrist_image.png ADDED

Git LFS Details

  • SHA256: 795b7ad6d94d2798eaf37e069ed7063cc8a05edf86f820304edfc8639c2caeb5
  • Pointer size: 130 Bytes
  • Size of remote file: 36.1 kB
leaf/final/episode_003182_wrist_image.png ADDED

Git LFS Details

  • SHA256: 1ea8a128ccda68136f3f667b0f4eec13451dd5d556af8ce1164c66bd1434db6f
  • Pointer size: 130 Bytes
  • Size of remote file: 46.3 kB
leaf/final/episode_003203_wrist_image.png ADDED

Git LFS Details

  • SHA256: be4e0f3622ee2ad8979c77011ef728102617ca78f8c8dd6b86494f3fd8c1f49d
  • Pointer size: 130 Bytes
  • Size of remote file: 37.7 kB
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/batches.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "breakfast_v2_20261103_deepseek": {
3
+ "source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/breakfast_v2_eval_20261103/source/runs/api/breakfast_v2_20261103_deepseek/manifest.json",
4
+ "supplement": true,
5
+ "selected_runs": 9,
6
+ "exported_runs": 9,
7
+ "note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config."
8
+ }
9
+ }
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/rejected.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/lffbench/objects.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Procedurally generated objects for LFF-Bench, registered into LIBERO's object registry.
2
+
3
+ Each generated object is an MJCF file with the layout robosuite's MujocoXMLObject expects
4
+ (an outer body containing body "object" plus bottom/top/horizontal_radius sites).
5
+ """
6
+ import os
7
+ import re
8
+
9
+ import numpy as np
10
+ from robosuite.models.objects import MujocoXMLObject
11
+
12
+ from libero.libero.envs.base_object import OBJECTS_DICT, register_object
13
+
14
+ GEN_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "assets_gen")
15
+ os.makedirs(GEN_DIR, exist_ok=True)
16
+
17
+ _SOLID = 'solimp="0.998 0.998 0.001" solref="0.001 1"'
18
+
19
+
20
+ def _fmt(v):
21
+ return " ".join(f"{x:.5f}" for x in v)
22
+
23
+
24
+ def _wrap(model_name, geoms_xml, half_height, radius):
25
+ return f"""<mujoco model="{model_name}">
26
+ <worldbody>
27
+ <body>
28
+ <body name="object">
29
+ {geoms_xml}
30
+ </body>
31
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {-half_height:.5f}" name="bottom_site" />
32
+ <site rgba="0 0 0 0" size="0.005" pos="0 0 {half_height:.5f}" name="top_site" />
33
+ <site rgba="0 0 0 0" size="0.005" pos="{radius:.5f} {radius:.5f} 0" name="horizontal_radius_site" />
34
+ </body>
35
+ </worldbody>
36
+ </mujoco>
37
+ """
38
+
39
+
40
+ def box_xml(model_name, half, rgba, density=500.0, friction=(1.0, 0.005, 0.0001)):
41
+ """Solid box; one geom used for both collision and rendering."""
42
+ g = (f' <geom name="{model_name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
43
+ f'density="{density}" friction="{_fmt(friction)}" {_SOLID} group="0" />\n'
44
+ f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />')
45
+ return _wrap(model_name, g, half[2], float(np.hypot(half[0], half[1])))
46
+
47
+
48
+ def bin_xml(model_name, inner_half_xy, wall_h, wall_t=0.006, floor_t=0.006, rgba=(0.6, 0.6, 0.65, 1.0),
49
+ density=800.0):
50
+ """Open-top box. Origin at the center of the outer footprint, z=0 at mid height."""
51
+ ix, iy = inner_half_xy
52
+ H = (wall_h + floor_t) / 2.0
53
+ geoms = []
54
+ parts = [
55
+ ((0, 0, -H + floor_t / 2), (ix + wall_t, iy + wall_t, floor_t / 2)), # floor
56
+ ((ix + wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # +x wall
57
+ ((-ix - wall_t / 2, 0, floor_t / 2), (wall_t / 2, iy + wall_t, wall_h / 2)), # -x wall
58
+ ((0, iy + wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # +y wall
59
+ ((0, -iy - wall_t / 2, floor_t / 2), (ix, wall_t / 2, wall_h / 2)), # -y wall
60
+ ]
61
+ for k, (p, s) in enumerate(parts):
62
+ geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" '
63
+ f'rgba="{_fmt(rgba)}" density="{density}" friction="1.0 0.005 0.0001" {_SOLID} group="0" />')
64
+ geoms.append(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" '
65
+ f'conaffinity="0" contype="0" group="1" />')
66
+ return _wrap(model_name, "\n".join(geoms), H, float(np.hypot(ix + wall_t, iy + wall_t)))
67
+
68
+
69
+ def _key(class_name):
70
+ return "_".join(re.sub(r"([A-Z0-9])", r" \1", class_name).split()).lower()
71
+
72
+
73
+ def register_generated(class_name, xml_text, free=True):
74
+ """Write the MJCF and register a LIBERO object class. Returns the BDDL category name."""
75
+ key = _key(class_name)
76
+ path = os.path.join(GEN_DIR, f"{key}.xml")
77
+ # write to a private temp file and rename atomically: several servers / validators may build the same task at
78
+ # once, and a reader must never see a half-written file (seen 2026-10-09 by the lh_* builders)
79
+ tmp = f"{path}.{os.getpid()}.tmp"
80
+ with open(tmp, "w") as f:
81
+ f.write(xml_text)
82
+ os.replace(tmp, path)
83
+ if key in OBJECTS_DICT:
84
+ return key
85
+
86
+ default_joints = [dict(type="free", damping="0.0005")] if free else None
87
+
88
+ def __init__(self, name=key, joints="default"):
89
+ j = default_joints if joints == "default" else joints
90
+ MujocoXMLObject.__init__(self, path, name=name, joints=j, obj_type="all", duplicate_collision_geoms=False)
91
+ self.category_name = key
92
+ self.rotation = (0.0, 0.0)
93
+ self.rotation_axis = "z"
94
+ self.object_properties = {"vis_site_names": {}}
95
+
96
+ cls = type(class_name, (MujocoXMLObject,), {"__init__": __init__})
97
+ register_object(cls)
98
+ return key
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/agent_compare.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ΔICL between two agent run directories on the same seeds.
2
+
3
+ python scripts/agent_compare.py --with runs/agent/<task>/<full-memory run> --iid runs/agent/<task>/<memory-none run>
4
+
5
+ ΔICL = succ@k(with history) - pass@k_iid(independent retries), paired by instance seed, with a paired
6
+ bootstrap 95% interval. Also prints the analytic i.i.d. reference 1-(1-p1)^k from the 'with' run.
7
+ """
8
+ import argparse
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
14
+
15
+ from lffbench.agent.metrics import paired_delta # noqa: E402
16
+
17
+
18
+ def load(d):
19
+ with open(os.path.join(d, "summary.json")) as f:
20
+ return json.load(f)
21
+
22
+
23
+ def main():
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--with", dest="with_", required=True)
26
+ ap.add_argument("--iid", required=True)
27
+ ap.add_argument("--k", type=int, default=None)
28
+ a = ap.parse_args()
29
+ w, i = load(a.with_), load(a.iid)
30
+ k = a.k or min(w["k"], i["k"])
31
+ res = paired_delta(w["runs"], i["runs"], k)
32
+ res["k"] = k
33
+ res["with"] = dict(memory=w["memory"], feedback=w["feedback"], attempt1=w["aggregate"]["attempt1_success"],
34
+ pass_at_k_iid_analytic=w["aggregate"]["pass_at_k_iid_analytic"])
35
+ res["iid"] = dict(memory=i["memory"], feedback=i["feedback"])
36
+ print(json.dumps(res, indent=1))
37
+
38
+
39
+ if __name__ == "__main__":
40
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/agent_cost.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Project GPT-6 cost / latency of a protocol from a run directory.
2
+
3
+ Works on (a) a real OpenAI run (uses the logged usage and latencies) or (b) a dry run of another backend made
4
+ with --dry-run-payload (uses the logged request sizes of every call). For (b) all numbers are ESTIMATES:
5
+ input tokens per call = text_chars / 4 + n_images * 256 (512 px images; image accounting is an assumption)
6
+ cached tokens per call = input tokens of the previous call in the same attempt (append-only prefix) --
7
+ the first call of an attempt is counted as uncached (conservative)
8
+ output tokens per call = --out-tokens (reasoning + visible; unknown for GPT-6 Astra, default 1500)
9
+ latency per call = --latency (seconds; RoboICL measured ~30-50 s per GPT-6 Astra call at 50-90K input
10
+ tokens and high/xhigh effort -- treat as an upper-range planning number)
11
+ The number of model calls of a scripted run is a LOWER bound for an LLM agent (no perception / checking calls).
12
+
13
+ python scripts/agent_cost.py runs/agent/l5_slide_to_target/<run> --out-tokens 1500 --latency 20 --calls-scale 2
14
+ """
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+ from collections import defaultdict
20
+
21
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+
23
+ from lffbench.agent.cost import PRICES, call_cost # noqa: E402
24
+
25
+
26
+ def main():
27
+ ap = argparse.ArgumentParser()
28
+ ap.add_argument("run_dir")
29
+ ap.add_argument("--model", default="gpt-6-astra")
30
+ ap.add_argument("--out-tokens", type=float, default=1500)
31
+ ap.add_argument("--latency", type=float, default=20.0)
32
+ ap.add_argument("--calls-scale", type=float, default=1.0, help="multiply the call count (LLM vs scripted)")
33
+ a = ap.parse_args()
34
+ ev = [json.loads(l) for l in open(os.path.join(a.run_dir, "events.jsonl"))]
35
+ calls = [e for e in ev if e["type"] == "llm_call"]
36
+ runs = {e["seed"] for e in ev if e["type"] == "run_start"}
37
+ real = [c for c in calls if c.get("usage")]
38
+ if real and not any("dry_run_request" in c for c in calls):
39
+ cost = sum(call_cost(c["usage"], a.model) or 0 for c in real)
40
+ lat = [c["latency_s"] for c in real]
41
+ u = defaultdict(int)
42
+ for c in real:
43
+ for kk, v in c["usage"].items():
44
+ u[kk] += v
45
+ out = dict(mode="measured", runs=len(runs), calls=len(real), calls_per_run=len(real) / max(len(runs), 1),
46
+ usage=dict(u), cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
47
+ latency_mean_s=sum(lat) / len(lat), api_time_per_run_s=sum(lat) / max(len(runs), 1))
48
+ else:
49
+ prev = {}
50
+ tot_in = tot_cached = 0
51
+ cost1 = 0.0 # priced per call (the long-context surcharge applies per request)
52
+ for c in calls:
53
+ d = c.get("dry_run_request")
54
+ if not d:
55
+ continue
56
+ key = (c["seed"], c["attempt"])
57
+ tin = d["est_input_tokens"]
58
+ cached = min(prev.get(key, 0), tin)
59
+ prev[key] = tin
60
+ tot_in += tin
61
+ tot_cached += cached
62
+ cost1 += call_cost(dict(input_tokens=tin, cached_tokens=cached, output_tokens=a.out_tokens), a.model)
63
+ n = len(calls) * a.calls_scale
64
+ scale = a.calls_scale
65
+ usage = dict(input_tokens=tot_in * scale, cached_tokens=tot_cached * scale, output_tokens=n * a.out_tokens)
66
+ cost = cost1 * scale
67
+ out = dict(mode="estimate (dry run)", runs=len(runs), calls=n, calls_per_run=n / max(len(runs), 1),
68
+ input_tokens_per_call=tot_in / max(len(calls), 1), cached_fraction=tot_cached / max(tot_in, 1),
69
+ usage=usage, cost_usd=cost, cost_per_run=cost / max(len(runs), 1),
70
+ api_time_per_run_s=n * a.latency / max(len(runs), 1), prices=PRICES.get(a.model),
71
+ assumptions=dict(out_tokens_per_call=a.out_tokens, latency_s_per_call=a.latency,
72
+ calls_scale=a.calls_scale, image_tokens_512px=256))
73
+ print(json.dumps(out, indent=1, default=str))
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/api_batch.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Batch of runs with a concurrency limit: the runner for the paper's main table (reference driver scripts/api_player.py)
2
+ and, with --harness, for native agent harnesses (side table, docs/15).
3
+
4
+ start python scripts/api_batch.py start --batch m1_opus --provider anthropic --model claude-opus-5-5 --effort high \
5
+ --tasks l1_height_bias:3000,3001 lh_bridge:3000 --k 3 --concurrency 6 --video
6
+ -> writes runs/api/<batch>/manifest.json (one entry per run, status "pending") and starts a background
7
+ runner that keeps at most --concurrency runs going (robot server + api_player each) and stops each
8
+ server when its player exits.
9
+ status python scripts/api_batch.py status --batch m1_opus
10
+ table python scripts/api_batch.py table --batch m1_opus [--batch ...] (same table as claude_batch + tokens)
11
+ stop python scripts/api_batch.py stop --batch m1_opus (runner, players, servers; runs -> "stopped")
12
+ retry python scripts/api_batch.py retry --batch m1_opus [--runs <run> ...] (default: every failed / stopped / timeout run;
13
+ old logs stay, listed under "superseded"; starts the runner again)
14
+ followup python scripts/api_batch.py followup --batch m1_opus (switch a batch started before 2026-10-19 to
15
+ --memfree followup: plans the memory-free retries due for its finished history runs; then `retry` starts them)
16
+ contract python scripts/api_batch.py contract --batch b1 [--batch b2 ...] (contract_sha256 per instance and condition;
17
+ flags instances whose hash differs between batches: those cells must not share a table)
18
+ pause touch runs/api/<batch>/PAUSE: the runner launches no new run while the file exists; the runs going on finish
19
+ and are recorded as usual (rm the file to go on). Used by quota watchers to stay below a usage window.
20
+
21
+ --harness (default ours): which agent harness drives each run, through scripts/harness_run.py (lffbench/harnesses):
22
+ ours scripts/api_player.py, unchanged (--provider as before)
23
+ claude_code Claude Code CLI --bare, only our MCP tools, one-time config dirs (arm B; provider anthropic)
24
+ claude_code_full Claude Code CLI without --bare (full system prompt), otherwise the same (arm B');
25
+ --claude-auth oauth (default): the subscription token of `claude setup-token` (LFF_CLAUDE_OAUTH_FILE),
26
+ apikey: ANTHROPIC_API_KEY (claude_code takes only apikey)
27
+ codex Codex CLI exec --ephemeral, empty CODEX_HOME, only our MCP tools reachable (arm F; provider openai);
28
+ --codex-auth chatgpt (default): the ChatGPT subscription login, apikey: OPENAI_API_KEY
29
+ dsh DeepSeek Harness headless, only our MCP tools, one-time dirs (lffbench/harnesses/dsh.py; provider
30
+ deepseek, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)
31
+ Native harnesses are refused at launch (status "refused") unless their preset prompt / tool list matches the pin
32
+ written by tests/harness_selfcheck (--allow-unpinned to launch anyway; the preflight still runs). Every run gets
33
+ harness.json, contract.json, trajectory.jsonl and harness_audit.json in its log dir.
34
+
35
+ Conditions (same as claude_batch): harness = memory full, k attempts in one agent; noharness = independent single-attempt
36
+ agents (memory none, k=1). History runs use --hide-k (README and status say 1 attempt, byte-identical to an independent
37
+ run; more attempts are announced only after a failure; --no-hide-k to show k).
38
+ --memfree, how the memory-free retries (pass@k without history) are run:
39
+ followup (default, 2026-10-19): one history run per instance. Its attempt 1 is also the first memory-free attempt,
40
+ since under --hide-k it sees exactly what a fresh agent sees. Only if attempt 1 fails does the runner add a
41
+ fresh single-attempt agent (noharness rep 1, "chain" = the history run's id); if that one fails too, the
42
+ next (rep 2), up to k-1 of them; the first success ends the chain. An instance solved on attempt 1 thus
43
+ costs one attempt in all. Not for tasks whose scene persists between attempts (task protocol "within"):
44
+ a fresh agent would start from the initial scene, the history run's attempt 2 from the failed one, so the
45
+ two conditions would differ; these tasks are reported without memory-free retries (user 2026-10-20).
46
+ upfront the 2026-10-11 protocol: --indep-reps independent runs per instance (default k, all of them run), all
47
+ before the history runs (--conds order; --no-barrier to mix the phases).
48
+ none history runs only.
49
+ --seeds-per-task N keeps the first N seeds of each task:seeds (e.g. 1 = one instance per task).
50
+ API keys come from LFF_ENV_FILE (default <repo>/.env, KEY=value lines) or the environment.
51
+ """
52
+ import argparse
53
+ import json
54
+ import os
55
+ import re
56
+ import shlex
57
+ import signal
58
+ import subprocess
59
+ import sys
60
+ import threading
61
+ import time
62
+
63
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
64
+ sys.path.insert(0, os.path.join(ROOT, "scripts"))
65
+ import claude_batch # noqa: E402
66
+
67
+ RUNS = os.path.join(ROOT, "runs", "api")
68
+ ENV_FILE = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
69
+ ACTIVE = ("starting", "running")
70
+ RETRYABLE = ("failed", "stopped", "timeout", "server_failed")
71
+ sys.path.insert(0, ROOT)
72
+ from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER as HARNESS_PROVIDER
73
+
74
+
75
+
76
+ def bdir(batch):
77
+ return os.path.join(RUNS, batch)
78
+
79
+
80
+ def mpath(batch):
81
+ return os.path.join(bdir(batch), "manifest.json")
82
+
83
+
84
+ def load(batch):
85
+ with open(mpath(batch)) as f:
86
+ return json.load(f)
87
+
88
+
89
+ def save(batch, m):
90
+ os.makedirs(bdir(batch), exist_ok=True)
91
+ tmp = mpath(batch) + ".tmp"
92
+ with open(tmp, "w") as f:
93
+ json.dump(m, f, indent=1)
94
+ os.replace(tmp, mpath(batch))
95
+
96
+
97
+ def alive(pid):
98
+ try:
99
+ os.kill(int(pid), 0)
100
+ return True
101
+ except (ProcessLookupError, PermissionError, TypeError, ValueError):
102
+ return False
103
+
104
+
105
+ def runner_alive(batch):
106
+ p = os.path.join(bdir(batch), "runner.pid")
107
+ return os.path.exists(p) and alive(open(p).read().strip())
108
+
109
+
110
+ def launch_runner(batch):
111
+ log = open(os.path.join(bdir(batch), "runner.log"), "a")
112
+ p = subprocess.Popen([sys.executable, os.path.abspath(__file__), "_runner", "--batch", batch], cwd=ROOT,
113
+ start_new_session=True, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT)
114
+ with open(os.path.join(bdir(batch), "runner.pid"), "w") as f:
115
+ f.write(str(p.pid))
116
+ return p.pid
117
+
118
+
119
+ def next_id(m):
120
+ return f"{max((int(r['id']) for r in m['runs']), default=-1) + 1:04d}"
121
+
122
+
123
+ # ------------------------------------------------------------------------------------------------- memory-free chains
124
+ # --memfree followup: per instance, history run (cond harness, followup=True) -> noharness rep 1 -> ... -> rep k-1,
125
+ # each link planned only after the previous attempts all failed. Attempt 1 of the history run is the chain's first
126
+ # attempt (--hide-k makes it identical to a fresh agent's), so the memory-free pass@k of an instance is: attempt 1 of
127
+ # the history run, or any of its chain runs, succeeded.
128
+ PLAN_KEYS = ("task", "seed", "provider", "agent_harness", "api_base_url", "max_budget_usd", "allow_unpinned", "jail",
129
+ "codex_auth", "claude_auth", "codex_catalog", "codex_provider",
130
+ "rpent_sessions", "rpent_attempts_per_session", "rpent_max_turns",
131
+ "model", "effort", "perception", "video", "style", "feedback", "phase", "nominal", "red_team")
132
+
133
+
134
+ def attempt_results(log):
135
+ """[success of attempt 1, of attempt 2, ...] from the robot server log ([] if there is none)."""
136
+ p = os.path.join(log or "", "events.jsonl")
137
+ if not os.path.exists(p):
138
+ return []
139
+ res = {}
140
+ for line in open(p):
141
+ e = json.loads(line)
142
+ if e.get("ev") == "done":
143
+ res[e["attempt"]] = bool(e["success"])
144
+ return [res[i] for i in sorted(res)]
145
+
146
+
147
+ def episode_protocol(log):
148
+ """The task's attempt protocol ("cross": reset between attempts, "within": the scene persists) from the robot
149
+ server log's session_start line; None if unknown."""
150
+ p = os.path.join(log or "", "events.jsonl")
151
+ if os.path.exists(p):
152
+ for line in open(p):
153
+ e = json.loads(line)
154
+ if e.get("ev") == "session_start":
155
+ return e.get("protocol")
156
+ return None
157
+
158
+
159
+ def plan_followup(m, r):
160
+ """Run r has finished: append the next memory-free retry of its instance if one is due; returns it or None."""
161
+ if r["status"] != "done":
162
+ return None
163
+ if r["cond"] == "harness" and r.get("followup"):
164
+ if episode_protocol(r.get("log")) == "within": # no like-for-like fresh agent (module docstring)
165
+ return None
166
+ root, nxt, res = r, 1, attempt_results(r.get("log"))[:1]
167
+ elif r.get("chain"):
168
+ root = next((x for x in m["runs"] if x["id"] == r["chain"]), None)
169
+ nxt, res = r["rep"] + 1, attempt_results(r.get("log"))
170
+ else:
171
+ return None
172
+ if root is None or not res or any(res) or nxt >= root["k"]:
173
+ return None
174
+ if any(x.get("chain") == root["id"] and x["rep"] == nxt for x in m["runs"]):
175
+ return None
176
+ new = {k: root.get(k) for k in PLAN_KEYS}
177
+ new.update(id=next_id(m), cond="noharness", rep=nxt, k=1, mem="none", hide_k=False, chain=root["id"],
178
+ status="pending")
179
+ m["runs"].append(new)
180
+ return new
181
+
182
+
183
+ def memfree_chain(m, root):
184
+ """Table rows for the memory-free retries of root's instance: its attempt 1 (rep 0, only_attempt=1) and the chain
185
+ runs after it. [] while the chain has not ended (a success, or k attempts)."""
186
+ first = attempt_results(root.get("log"))[:1]
187
+ if not first:
188
+ return []
189
+ rows = [dict(root, cond="noharness", rep=0, k=1, only_attempt=1)]
190
+ if first[0]:
191
+ return rows
192
+ chain = {x["rep"]: x for x in m["runs"] if x.get("chain") == root["id"] and x["status"] == "done" and x.get("log")}
193
+ for rep in range(1, root["k"]):
194
+ if rep not in chain:
195
+ return []
196
+ rows.append(dict(chain[rep]))
197
+ if any(attempt_results(chain[rep]["log"])):
198
+ break
199
+ return rows
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------------------ start
203
+ def cmd_start(a):
204
+ a.codex_auth = a.codex_auth or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
205
+ if a.harness == "rpent_codex" and a.codex_auth != "apikey":
206
+ sys.exit("Historical RPent adapter supports apikey only")
207
+ if runner_alive(a.batch):
208
+ sys.exit(f"batch {a.batch}: runner already running; stop it first or use another batch name")
209
+ m = load(a.batch) if os.path.exists(mpath(a.batch)) else dict(batch=a.batch, runs=[], superseded=[])
210
+ m.update(concurrency=a.concurrency, barrier=not a.no_barrier, port0=a.port0, run_timeout_s=a.run_timeout)
211
+ reps = a.k if a.indep_reps is None else a.indep_reps
212
+ if a.harness != "ours":
213
+ need = HARNESS_PROVIDER[a.harness]
214
+ if a.provider and a.provider != need:
215
+ sys.exit(f"--harness {a.harness} drives {need} models only (got --provider {a.provider})")
216
+ a.provider = need
217
+ elif not a.provider:
218
+ sys.exit("--provider is required with --harness ours")
219
+ claude_auth = None
220
+ if a.harness.startswith("claude_code"):
221
+ claude_auth = a.claude_auth or ("apikey" if a.harness == "claude_code" else "oauth")
222
+ if claude_auth == "oauth" and a.harness == "claude_code":
223
+ sys.exit("--harness claude_code (--bare) takes only an API key; use claude_code_full for a subscription")
224
+ elif a.claude_auth:
225
+ sys.exit("--claude-auth is for --harness claude_code / claude_code_full")
226
+ if a.jail and a.harness == "ours":
227
+ sys.exit("--jail is for native harnesses (the reference driver runs our own code)")
228
+ if a.red_team and a.harness == "ours":
229
+ sys.exit("--red-team is for native harnesses (lffbench/harnesses/redteam.py)")
230
+ if a.memfree == "upfront":
231
+ conds = [c.strip() for c in (a.conds or "noharness,harness").split(",") if c.strip()]
232
+ else:
233
+ if a.conds and a.conds.replace(" ", "") != "harness":
234
+ sys.exit(f"--conds is for --memfree upfront (--memfree {a.memfree} plans history runs only)")
235
+ if a.memfree == "followup" and a.no_hide_k:
236
+ sys.exit("--memfree followup shares attempt 1 of the history run with the memory-free retries: needs --hide-k")
237
+ conds = ["harness"]
238
+ dossiers = json.load(open(a.dossiers)) if a.dossiers else None
239
+ if dossiers is not None: # task:seed -> record dir (scripts/make_dossier.py); every planned instance needs one
240
+ miss = [f"{spec.split(':')[0]}:{sd}" for spec in a.tasks for sd in spec.split(":")[1].split(",")[:a.seeds_per_task]
241
+ if f"{spec.split(':')[0]}:{sd}" not in dossiers]
242
+ if miss:
243
+ sys.exit(f"--dossiers has no record for {miss}")
244
+ bad = [d for d in dossiers.values() if not os.path.isfile(os.path.join(d, "README.md")) or any(c.isspace() for c in d)]
245
+ if bad:
246
+ sys.exit(f"--dossiers: not a record dir (or path with spaces): {bad}")
247
+ n0 = len(m["runs"])
248
+ for cond in conds: # the order of --conds is the order of the phases
249
+ for spec in a.tasks:
250
+ task, seeds = spec.split(":")
251
+ for seed in seeds.split(",")[:a.seeds_per_task]:
252
+ plan = [("harness", "full", a.k, 0)] if cond == "harness" else \
253
+ [("noharness", "none", 1, i) for i in range(reps)]
254
+ for c, mem, k, rep in plan:
255
+ m["runs"].append(dict(id=next_id(m), task=task, seed=int(seed), provider=a.provider,
256
+ agent_harness=a.harness, api_base_url=a.api_base_url,
257
+ max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
258
+ jail=a.jail, codex_auth=(("apikey" if a.codex_provider in ("deepseek", "opencode") else a.codex_auth)
259
+ if a.harness in ("codex", *ROBOT_HARNESSES) else None),
260
+ claude_auth=claude_auth,
261
+ codex_catalog=(a.codex_catalog if a.harness in ("codex", *ROBOT_HARNESSES)
262
+ else None),
263
+ **(dict(rpent_sessions=a.rpent_sessions,
264
+ rpent_attempts_per_session=a.rpent_attempts_per_session,
265
+ rpent_max_turns=a.rpent_max_turns)
266
+ if a.harness == "rpent_codex" else {}),
267
+ codex_provider=(a.codex_provider if a.harness == "codex" else None),
268
+ model=a.model, effort=a.effort, cond=c, rep=rep, k=k, mem=mem,
269
+ hide_k=(c == "harness" and not a.no_hide_k), perception=a.perception,
270
+ video=a.video, style="la", feedback=a.feedback, phase=conds.index(cond),
271
+ nominal=a.nominal, followup=(c == "harness" and a.memfree == "followup"),
272
+ arm=a.arm, red_team=a.red_team, dossier=(os.path.abspath(dossiers[f"{task}:{seed}"]) if dossiers else None),
273
+ status="pending"))
274
+ save(a.batch, m)
275
+ print(f"{len(m['runs']) - n0} runs planned ({', '.join(conds)}, --memfree {a.memfree}); manifest {mpath(a.batch)}")
276
+ if a.memfree == "followup":
277
+ print("memory-free retries are added while the batch runs, for instances whose attempt 1 failed")
278
+ print("runner pid", launch_runner(a.batch))
279
+
280
+
281
+ # ------------------------------------------------------------------------------------------------------------ runner
282
+ class Runner:
283
+ def __init__(self, batch):
284
+ self.batch = batch
285
+ self.lock = threading.Lock()
286
+ self.m = load(batch)
287
+ self.used_ports = set()
288
+ self.stop = False
289
+
290
+ def update(self, r, **kw):
291
+ with self.lock:
292
+ r.update(kw)
293
+ save(self.batch, self.m)
294
+
295
+ def next_run(self):
296
+ with self.lock:
297
+ runs = self.m["runs"]
298
+ pending = [r for r in runs if r["status"] == "pending"]
299
+ if not pending:
300
+ # a run still going may yet add a memory-free retry (--memfree followup)
301
+ if any(r["status"] in ACTIVE and (r.get("followup") or r.get("chain")) for r in runs):
302
+ return "wait"
303
+ return None
304
+ if self.m.get("barrier", True):
305
+ phase = min(r["phase"] for r in pending)
306
+ if any(r["status"] in ACTIVE and r["phase"] < phase for r in runs):
307
+ return "wait"
308
+ pending = [r for r in pending if r["phase"] == phase]
309
+ if os.path.exists(os.path.join(bdir(self.batch), "PAUSE")):
310
+ return "wait"
311
+ r = pending[0]
312
+ r["status"] = "starting"
313
+ save(self.batch, self.m)
314
+ return r
315
+
316
+ def port(self):
317
+ with self.lock:
318
+ p = int(self.m.get("port0", 14000))
319
+ while p in self.used_ports or not claude_batch.port_free(p):
320
+ p += 1
321
+ self.used_ports.add(p)
322
+ return p
323
+
324
+ def run_one(self, r):
325
+ port = self.port()
326
+ model_tag = re.sub(r"[^A-Za-z0-9.-]+", "-", r["model"])[:40]
327
+ ah = r.get("agent_harness", "ours")
328
+ if ah != "ours":
329
+ model_tag += "-" + ah.replace("_", "")
330
+ tag = (f"{self.batch}-{model_tag}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
331
+ + ("-hidek" if r["hide_k"] else "") + ("-nominal" if r.get("nominal") else "")
332
+ + (f"-{r['arm']}" if r.get("arm", "none") != "none" else "") + ("-dossier" if r.get("dossier") else "")
333
+ + ("-redteam" if r.get("red_team") else ""))
334
+ extra = (" --hide-k" if r["hide_k"] else "") + (" --nominal" if r.get("nominal") else "")
335
+ # docs/14 §6 arms (robot_server --arm / --dossier); LFF_EXTRA_ARGS is word-split, so no spaces in the path
336
+ extra += (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "") + (f" --dossier {r['dossier']}" if r.get("dossier") else "")
337
+ t0 = time.time()
338
+ try:
339
+ sb, log = claude_batch.start_one(r["task"], r["seed"], r["mem"], r["k"], port, tag, r["perception"],
340
+ r["video"], r["style"], extra.strip(), r["feedback"])
341
+ except Exception as e: # server did not come up
342
+ self.update(r, status="server_failed", error=str(e)[-500:], port=port)
343
+ with self.lock:
344
+ self.used_ports.discard(port)
345
+ return
346
+ self.update(r, status="running", port=port, sandbox=sb, log=log, run=os.path.basename(log), t_start=t0)
347
+ opts = ""
348
+ if r.get("api_base_url"):
349
+ opts += f" --api-base-url {shlex.quote(r['api_base_url'])}"
350
+ if r.get("max_budget_usd"):
351
+ opts += f" --max-budget-usd {r['max_budget_usd']}"
352
+ if r.get("allow_unpinned"):
353
+ opts += " --allow-unpinned"
354
+ if r.get("jail"):
355
+ opts += " --jail"
356
+ if r.get("red_team"):
357
+ opts += " --red-team"
358
+ if r.get("codex_auth"):
359
+ opts += f" --codex-auth {r['codex_auth']}"
360
+ if r.get("claude_auth"):
361
+ opts += f" --claude-auth {r['claude_auth']}"
362
+ if r.get("agent_harness") in ("codex", *ROBOT_HARNESSES) and r.get("agent_harness") != "rpent_codex": # runs planned before 10-20 have no catalog: Codex's native one
363
+ opts += f" --codex-catalog {r.get('codex_catalog') or 'native'}"
364
+ if r.get("codex_provider") in ("deepseek", "opencode"):
365
+ opts += f" --codex-provider {r['codex_provider']}"
366
+ if r.get("agent_harness") == "rpent_codex":
367
+ opts += (f" --codex-catalog {r.get('codex_catalog') or 'generic'}"
368
+ f" --rpent-sessions {r.get('rpent_sessions') or 5}"
369
+ f" --rpent-attempts-per-session {r.get('rpent_attempts_per_session', 1)}"
370
+ f" --rpent-max-turns {r.get('rpent_max_turns') or 100}")
371
+ # every harness (also ours: api_player.py with the same arguments as before, its output still in
372
+ # api_player.log) goes through the adapter layer, which adds harness.json / contract.json / trajectory.jsonl
373
+ player = (f"cd {ROOT} && source run_env.sh >/dev/null 2>&1 && "
374
+ f"{{ [ ! -f {ENV_FILE} ] || {{ set -a && source {ENV_FILE} && set +a; }}; }} && "
375
+ f"exec python scripts/harness_run.py --harness {ah} --session {log}/session.json "
376
+ f"--provider {r['provider']} --model {shlex.quote(r['model'])} --effort {r['effort']} "
377
+ f"--timeout {int(self.m.get('run_timeout_s', 28800))}{opts} > {log}/harness_run.log 2>&1")
378
+ p = subprocess.Popen(["bash", "-c", player], start_new_session=True, stdin=subprocess.DEVNULL,
379
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
380
+ self.update(r, player_pid=p.pid)
381
+ status = None
382
+ try:
383
+ code = p.wait(timeout=self.m.get("run_timeout_s", 28800))
384
+ except subprocess.TimeoutExpired:
385
+ os.killpg(p.pid, signal.SIGTERM)
386
+ code, status = p.wait(), "timeout"
387
+ self.stop_server(log)
388
+ if status is None:
389
+ status = "stopped" if self.stop else ("done" if code == 0 else "refused" if code == 2 else "failed")
390
+ self.update(r, status=status, exit_code=code, t_end=time.time(), wall_s=round(time.time() - t0, 1))
391
+ with self.lock:
392
+ self.used_ports.discard(port)
393
+ if plan_followup(self.m, r):
394
+ save(self.batch, self.m)
395
+
396
+ @staticmethod
397
+ def stop_server(log):
398
+ pf = os.path.join(log, "server.pid")
399
+ if not os.path.exists(pf):
400
+ return
401
+ pid = int(open(pf).read())
402
+ try:
403
+ os.kill(pid, signal.SIGTERM) # the server closes rollout.mp4 first
404
+ except ProcessLookupError:
405
+ return
406
+ for _ in range(120):
407
+ if not alive(pid):
408
+ return
409
+ time.sleep(0.5)
410
+
411
+ def worker(self):
412
+ while not self.stop:
413
+ r = self.next_run()
414
+ if r is None:
415
+ return
416
+ if r == "wait":
417
+ time.sleep(5)
418
+ continue
419
+ try:
420
+ self.run_one(r)
421
+ except Exception as e: # keep the other workers going
422
+ self.update(r, status="failed", error=f"runner: {type(e).__name__}: {e}"[:500])
423
+
424
+ def main(self):
425
+ os.environ["LFF_RUNS_DIR"] = bdir(self.batch) # claude_batch.start_one puts the run logs here
426
+ for r in self.m["runs"]: # a previous runner died: its half-started runs go back to pending
427
+ if r["status"] in ACTIVE:
428
+ r["status"] = "pending"
429
+ for r in list(self.m["runs"]): # memory-free retries due but not yet planned (runner died, `followup`)
430
+ plan_followup(self.m, r)
431
+ save(self.batch, self.m)
432
+
433
+ def on_term(*_):
434
+ self.stop = True
435
+ with self.lock:
436
+ for r in self.m["runs"]:
437
+ if r["status"] == "running" and r.get("player_pid"):
438
+ try:
439
+ os.killpg(r["player_pid"], signal.SIGTERM)
440
+ except ProcessLookupError:
441
+ pass
442
+ signal.signal(signal.SIGTERM, on_term)
443
+ ths = [threading.Thread(target=self.worker, daemon=True) for _ in range(int(self.m.get("concurrency", 4)))]
444
+ for t in ths:
445
+ t.start()
446
+ time.sleep(2) # stagger server start-ups
447
+ for t in ths:
448
+ t.join()
449
+ print(time.strftime("%F %T"), "runner finished", flush=True)
450
+
451
+
452
+ def cmd_runner(a):
453
+ Runner(a.batch).main()
454
+
455
+
456
+ # ------------------------------------------------------------------------------------------------------------ views
457
+ def transcript_usage(log):
458
+ tot = dict(calls=0, input_tokens=0, cached_tokens=0, output_tokens=0, api_errors=0, end=None)
459
+ p = os.path.join(log or "", "transcript.jsonl")
460
+ if not os.path.exists(p): # native harness: totals from the unified trajectory
461
+ sys.path.insert(0, ROOT)
462
+ from lffbench.harnesses.trajectory import usage_summary
463
+ u = usage_summary(log)
464
+ if u:
465
+ tot.update(calls=u.get("calls", 0), input_tokens=u.get("total_prompt_tokens") or 0,
466
+ cached_tokens=u.get("total_cached_tokens") or 0,
467
+ output_tokens=u.get("total_completion_tokens") or 0, end=u.get("exit_reason"),
468
+ cost_usd=u.get("total_cost_usd"))
469
+ return tot
470
+ for line in open(p):
471
+ d = json.loads(line)
472
+ if d["ev"] == "assistant":
473
+ tot["calls"] += 1
474
+ for k in ("input_tokens", "cached_tokens", "output_tokens"):
475
+ tot[k] += (d.get("usage") or {}).get(k, 0)
476
+ elif d["ev"] == "api_error":
477
+ tot["api_errors"] += 1
478
+ elif d["ev"] in ("end", "abort"):
479
+ tot["end"] = d["ev"] if d["ev"] == "end" else "abort: " + d.get("reason", "")
480
+ return tot
481
+
482
+
483
+ def cmd_status(a):
484
+ m = load(a.batch)
485
+ counts = {}
486
+ for r in m["runs"]:
487
+ counts[r["status"]] = counts.get(r["status"], 0) + 1
488
+ att = ""
489
+ if r.get("log") and os.path.exists(os.path.join(r["log"], "events.jsonl")):
490
+ ev = [json.loads(line) for line in open(os.path.join(r["log"], "events.jsonl"))]
491
+ att = "".join("S" if e["success"] else "F" for e in ev if e["ev"] == "done")
492
+ u = transcript_usage(r.get("log"))
493
+ print(f"{r['id']} {r['status']:13s} {r.get('agent_harness', 'ours'):16s} "
494
+ f"{r['cond']:9s}{r['rep'] if r['cond'] == 'noharness' else '':1} "
495
+ f"{r['task']:24s} s{r['seed']} {att:4s} calls={u['calls']:3d} api_err={u['api_errors']} "
496
+ f"in={u['input_tokens'] / 1e6:.2f}M out={u['output_tokens'] / 1e3:.0f}k {u['end'] or ''}"
497
+ + (f" (memory-free attempt {r['rep'] + 1} after {r['chain']})" if r.get("chain") else ""))
498
+ print("runner", "alive" if runner_alive(a.batch) else "not running", "|", counts)
499
+
500
+
501
+ def cmd_table(a):
502
+ def done_runs(b):
503
+ m = load(b)
504
+ runs = []
505
+ for r in m["runs"]:
506
+ if not (r.get("log") and r["status"] == "done") or r.get("chain"):
507
+ continue
508
+ runs.append(dict(r))
509
+ if r["cond"] == "harness" and r.get("followup"): # its memory-free chain, once finished
510
+ runs += memfree_chain(m, r)
511
+ for r in runs: # the harness is part of the table's "model" column (claude_batch groups by task, model)
512
+ if r.get("agent_harness", "ours") != "ours":
513
+ r["model"] = f"{r['model']} @ {r['agent_harness']}"
514
+ return dict(m, runs=runs)
515
+ claude_batch.load = done_runs # same manifest fields (task, seed, model, cond, rep, k, log): reuse its table
516
+ # token totals: every run once (the rep-0 row of a chain is attempt 1 of a history run, already counted)
517
+ rows = [r for b in a.batch for r in done_runs(b)["runs"] if not r.get("only_attempt")]
518
+ claude_batch.cmd_table(argparse.Namespace(batch=a.batch))
519
+ by = {}
520
+ for r in rows:
521
+ u = transcript_usage(r["log"])
522
+ t = by.setdefault((r.get("agent_harness", "ours"), r["provider"], r["model"], r["effort"]), [0, 0, 0, 0, 0])
523
+ t[0] += 1
524
+ t[1] += u["calls"]
525
+ t[2] += u["input_tokens"]
526
+ t[3] += u["cached_tokens"]
527
+ t[4] += u["output_tokens"]
528
+ print("\n| harness | provider | model | effort | runs done | model calls | input tokens (M) | of which cached (M) | output tokens (M) |")
529
+ print("|---|---|---|---|---|---|---|---|---|")
530
+ for (h, p, mo, e), t in sorted(by.items()):
531
+ print(f"| {h} | {p} | {mo} | {e} | {t[0]} | {t[1]} | {t[2] / 1e6:.1f} | {t[3] / 1e6:.1f} | {t[4] / 1e6:.2f} |")
532
+
533
+
534
+ def cmd_contract(a):
535
+ """contract_sha256 per (task, seed, cond) and batch; an instance whose hash differs between batches is flagged."""
536
+ import collections
537
+ seen = collections.defaultdict(dict)
538
+ for b in a.batch:
539
+ for r in load(b)["runs"]:
540
+ p = os.path.join(r.get("log") or "", "contract.json")
541
+ if r.get("log") and os.path.exists(p):
542
+ sha = json.load(open(p))["contract_sha256"]
543
+ seen[(r["task"], r["seed"], r["cond"])].setdefault(b, set()).add(sha)
544
+ bad = 0
545
+ print("| task | seed | cond | " + " | ".join(a.batch) + " | same |")
546
+ print("|---|---|---|" + "---|" * len(a.batch) + "---|")
547
+ for (task, seed, cond), per in sorted(seen.items()):
548
+ shas = set().union(*per.values())
549
+ same = len(shas) == 1
550
+ bad += not same
551
+ cells = [",".join(sorted(x[:12] for x in per.get(b, []))) or "-" for b in a.batch]
552
+ print(f"| {task} | {seed} | {cond} | " + " | ".join(cells) + f" | {'yes' if same else '**NO**'} |")
553
+ print(f"\n{len(seen)} instance/condition rows, {bad} with differing contracts")
554
+
555
+
556
+ def cmd_stop(a):
557
+ pf = os.path.join(bdir(a.batch), "runner.pid")
558
+ if os.path.exists(pf) and alive(open(pf).read().strip()):
559
+ os.kill(int(open(pf).read().strip()), signal.SIGTERM) # the runner stops its players and servers
560
+ for _ in range(240):
561
+ if not runner_alive(a.batch):
562
+ break
563
+ time.sleep(0.5)
564
+ m = load(a.batch)
565
+ for r in m["runs"]: # anything left over (runner killed hard)
566
+ if r["status"] in ACTIVE:
567
+ if r.get("player_pid"):
568
+ try:
569
+ os.killpg(r["player_pid"], signal.SIGTERM)
570
+ except ProcessLookupError:
571
+ pass
572
+ if r.get("log"):
573
+ Runner.stop_server(r["log"])
574
+ r["status"] = "stopped"
575
+ save(a.batch, m)
576
+ print("stopped")
577
+
578
+
579
+ def cmd_retry(a):
580
+ if runner_alive(a.batch):
581
+ sys.exit("runner still running: stop it first")
582
+ m = load(a.batch)
583
+ reset = []
584
+ for r in m["runs"]:
585
+ if (a.runs and (r.get("run") in a.runs or r["id"] in a.runs)) or (not a.runs and r["status"] in RETRYABLE):
586
+ if r.get("log"):
587
+ m.setdefault("superseded", []).append(dict(r))
588
+ for k in ("port", "sandbox", "log", "run", "player_pid", "exit_code", "t_start", "t_end", "wall_s", "error"):
589
+ r.pop(k, None)
590
+ r["status"] = "pending"
591
+ reset.append(r)
592
+ # memory-free retries planned after a run that is now re-run were based on attempts that no longer count
593
+ stale = [x for x in m["runs"] if x.get("chain") and all(x is not y for y in reset) and any(
594
+ x["chain"] == y["id"] or (x["chain"] == y.get("chain") and x["rep"] > y["rep"]) for y in reset)]
595
+ for x in stale:
596
+ m["runs"].remove(x)
597
+ if x.get("log"):
598
+ m.setdefault("superseded", []).append(dict(x, superseded_because="earlier attempt of its chain re-run"))
599
+ save(a.batch, m)
600
+ print(len(reset), "runs reset to pending" + (f", {len(stale)} memory-free retries after them dropped" if stale else "")
601
+ + "; runner pid", launch_runner(a.batch))
602
+
603
+
604
+ def cmd_followup(a):
605
+ """Switch a batch to --memfree followup: mark its --hide-k history runs and plan the memory-free retries due for
606
+ those already done. `retry` then starts the runner (and re-runs failed / stopped runs)."""
607
+ if runner_alive(a.batch):
608
+ sys.exit("runner still running: stop it first")
609
+ m = load(a.batch)
610
+ marked = left = 0
611
+ for r in m["runs"]:
612
+ if r["cond"] == "harness" and not r.get("followup"):
613
+ if r.get("hide_k"):
614
+ r["followup"] = True
615
+ marked += 1
616
+ else:
617
+ left += 1
618
+ new = [x for r in list(m["runs"]) for x in [plan_followup(m, r)] if x]
619
+ save(a.batch, m)
620
+ print(f"{marked} history runs switched to --memfree followup"
621
+ + (f" ({left} without --hide-k left out: their attempt 1 is not a fresh agent's)" if left else "")
622
+ + f"; {len(new)} memory-free retries planned")
623
+ print(f"start the runner with: python scripts/api_batch.py retry --batch {a.batch}")
624
+
625
+
626
+ def main():
627
+ ap = argparse.ArgumentParser()
628
+ sub = ap.add_subparsers(dest="cmd", required=True)
629
+ s = sub.add_parser("start")
630
+ s.add_argument("--batch", required=True)
631
+ s.add_argument("--harness", default="ours", choices=NAMES,
632
+ help="agent harness (docs/15); native harnesses imply the provider; rpent_codex = RPent on Codex "
633
+ "(docs/18), OpenAI API key only (LFF_OPENAI_API_KEY)")
634
+ s.add_argument("--provider", default=None, choices=["openai", "anthropic", "gemini", "chat"],
635
+ help="required for --harness ours")
636
+ s.add_argument("--api-base-url", default=None, help="native harnesses: model API endpoint (see harness_run.py)")
637
+ s.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: per-run dollar cap")
638
+ s.add_argument("--allow-unpinned", action="store_true", help="native harnesses: launch without a pin")
639
+ s.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
640
+ help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
641
+ "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
642
+ s.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
643
+ help="claude_code*: subscription token (default for claude_code_full) or ANTHROPIC_API_KEY "
644
+ "(claude_code, --bare: apikey only)")
645
+ s.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
646
+ help="codex: model provider; deepseek / opencode (OpenCode Go) imply --codex-auth apikey "
647
+ "(see harness_run.py)")
648
+ s.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
649
+ help="codex: model configuration, the main table's shared one (default) or Codex's native one "
650
+ "(control; see lffbench/harnesses/codex.py)")
651
+ s.add_argument("--rpent-sessions", type=int, default=5, help="rpent_codex: planner sessions per episode")
652
+ s.add_argument("--rpent-attempts-per-session", type=int, default=1,
653
+ help="rpent_codex: attempts one session may use (1 = variant H, default; 0 = no limit)")
654
+ s.add_argument("--rpent-max-turns", type=int, default=100, help="rpent_codex: model responses per session")
655
+ s.add_argument("--jail", action="store_true",
656
+ help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4, lffbench/harnesses/jail.py)")
657
+ s.add_argument("--model", required=True)
658
+ s.add_argument("--effort", default="high")
659
+ s.add_argument("--tasks", nargs="+", required=True, help="task:seed,seed ...")
660
+ s.add_argument("--k", type=int, default=3)
661
+ s.add_argument("--seeds-per-task", type=int, default=None, help="only the first N seeds of each task:seeds")
662
+ s.add_argument("--memfree", default="followup", choices=["followup", "upfront", "none"],
663
+ help="memory-free retries: followup (default) = fresh single-attempt agents only after the history "
664
+ "run's attempt 1 failed, one at a time, up to k attempts in all, stop at the first success; "
665
+ "upfront = --indep-reps independent runs per instance before the history runs; none = no "
666
+ "memory-free retries (see the module docstring)")
667
+ s.add_argument("--indep-reps", type=int, default=None, help="--memfree upfront: independent runs per instance (default k)")
668
+ s.add_argument("--conds", default=None, help="--memfree upfront: conditions in phase order (default noharness,harness)")
669
+ s.add_argument("--no-barrier", action="store_true", help="do not wait for one phase to finish before the next")
670
+ s.add_argument("--no-hide-k", action="store_true", help="history runs: README / status show all k attempts")
671
+ s.add_argument("--concurrency", type=int, default=4)
672
+ s.add_argument("--port0", type=int, default=14000)
673
+ s.add_argument("--run-timeout", type=int, default=28800,
674
+ help="seconds per run before the player is killed (default 8 h: a long-horizon history run can need 300+ model calls)")
675
+ s.add_argument("--perception", default="rgb", choices=["rgb", "rgbd"])
676
+ s.add_argument("--video", action="store_true")
677
+ s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
678
+ s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
679
+ s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
680
+ help="docs/14 §6 controlled arm for every run: twin = same layout, other value of the hidden variable")
681
+ s.add_argument("--red-team", action="store_true",
682
+ help="adversarial acceptance runs (lffbench/harnesses/redteam.py): the agent is told to get a success "
683
+ "without doing the task; own contract; read with scripts/redteam_report.py")
684
+ s.add_argument("--dossiers", default=None,
685
+ help="JSON {\"task:seed\": record dir from scripts/make_dossier.py}: each run gets that record in "
686
+ "history/ and a README section saying an earlier attempt failed (own vs mismatched history)")
687
+ r = sub.add_parser("_runner")
688
+ r.add_argument("--batch", required=True)
689
+ for name in ("status", "stop", "followup"):
690
+ sub.add_parser(name).add_argument("--batch", required=True)
691
+ t = sub.add_parser("table")
692
+ t.add_argument("--batch", nargs="+", required=True)
693
+ ct = sub.add_parser("contract")
694
+ ct.add_argument("--batch", nargs="+", required=True)
695
+ rt = sub.add_parser("retry")
696
+ rt.add_argument("--batch", required=True)
697
+ rt.add_argument("--runs", nargs="*", default=[])
698
+ a = ap.parse_args()
699
+ dict(start=cmd_start, _runner=cmd_runner, status=cmd_status, table=cmd_table, stop=cmd_stop, retry=cmd_retry,
700
+ contract=cmd_contract, followup=cmd_followup)[a.cmd](a)
701
+
702
+
703
+ if __name__ == "__main__":
704
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_breakfast_geometry.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """V2 physical height/orientation controls. Initialization interventions are diagnostics only."""
2
+ import json
3
+ from pathlib import Path
4
+ from PIL import Image
5
+ from lffbench import envs
6
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
7
+
8
+ def main():
9
+ out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/geometry_v2/geometry_controls'
10
+ out.mkdir(parents=True,exist_ok=True);rows=[];t=BreakfastService()
11
+ for seed in range(1000,1003):
12
+ inst=t.sample_instance(seed);t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
13
+ # Move bread clear only at diagnostic initialization, so the obstacle is unambiguous.
14
+ envs.set_obj_pose(t.env,'bread_1',[-.09,-.32,.94]);t.env.sim.forward()
15
+ def state(stage):
16
+ r=dict(seed=seed,stage=stage,lid_deg=t.lid_deg(),butter_height_cm=100*t.butter_height(),
17
+ butter_lid_contact=bool(t.butter_lid_contact()),butter_fits=t.butter_in_box(),
18
+ applied_torque=float(t.env.sim.data.qfrc_applied[t.dof]))
19
+ assert r['applied_torque']==0.,r
20
+ rows.append(r);print(json.dumps(r),flush=True)
21
+ Image.fromarray(envs.render(t.env,res=512)).save(out/f'{seed}_{stage}.png')
22
+ (out/'progress.json').write_text(json.dumps(rows,indent=2))
23
+ return r
24
+ # Two empty-box closes prove that the removed closure-count mechanism does not reappear.
25
+ for cycle in range(2):
26
+ # Let the freely swinging open lid settle before targeting its knob again.
27
+ t.open_lid();t.sk.hold(100);t.close_lid(False);t.sk.hold(80)
28
+ r=state('empty_close_'+str(cycle+1));assert r['lid_deg']<4
29
+ t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
30
+ r=state('upright_blocked')
31
+ assert r['lid_deg']>10 and r['butter_lid_contact'] and r['butter_height_cm']>7 and not r['butter_fits'],r
32
+ # Remove precisely that obstacle, leaving all geometry, forces and joint limits unchanged.
33
+ t.open_lid();assert t.pick_place('butter_1',inst['butter_xy'],t.butter_height()/2+.003)
34
+ t.close_lid(False);t.sk.hold(80);r=state('obstacle_removed');assert r['lid_deg']<4
35
+ assert t.lay_butter_flat();r=state('laid_flat');assert r['butter_height_cm']<2.9
36
+ t.open_lid();assert t.put_butter();t.close_lid(False);t.sk.hold(100)
37
+ r=state('flat_inside_closed');assert r['lid_deg']<4 and r['butter_fits'] and not r['butter_lid_contact'],r
38
+ (out/'result.json').write_text(json.dumps(dict(passed=True,rows=rows),indent=2))
39
+ t.env.close()
40
+
41
+ if __name__=='__main__':main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_breakfast_mechanisms.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mechanism-on/off controls and negative judge fixtures, separate from rollouts."""
2
+ import argparse, copy, json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
6
+ from lffbench import envs
7
+
8
+ def main():
9
+ p=argparse.ArgumentParser();p.add_argument('--liquid-only',action='store_true')
10
+ p.add_argument('--judge-only',action='store_true');args=p.parse_args()
11
+ out=Path(__file__).resolve().parents[1]/'results/lh_breakfast_service/mechanisms'
12
+ out.mkdir(parents=True,exist_ok=True);t=BreakfastService();rows=[]
13
+ if args.judge_only:rows=json.loads((out/'controls_progress.json').read_text())
14
+ for seed in ([] if args.liquid_only or args.judge_only else range(1000,1003)):
15
+ for enabled in (True,False):
16
+ inst=t.sample_instance(seed);inst['mechanisms']['L1']=enabled;t.reset_instance(inst)
17
+ t.calibration_probe();row=dict(seed=seed,mechanism='L1',enabled=enabled,triggered=t.traps['L1'])
18
+ rows.append(row);print(json.dumps(row),flush=True)
19
+ assert row['triggered']==enabled,row
20
+ inst=t.sample_instance(seed);inst['mechanisms']['L3']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
21
+ t.direct_carton_lift();row=dict(seed=seed,mechanism='L3',enabled=enabled,**t.pull_probe)
22
+ rows.append(row);print(json.dumps(row),flush=True)
23
+ assert row['held_before'] and ((row['displacement_m']<.01) if enabled else (row['displacement_m']>.04)),row
24
+ inst=t.sample_instance(seed);inst['mechanisms']['L2']=enabled;t.reset_instance(inst);t.sk.correction=t.sk.bias.copy()
25
+ for _ in range(2):t.open_lid();t.close_lid(False)
26
+ t.sk.hold(300);failure=t.lid_deg()
27
+ if enabled:t.open_lid();t.close_lid(True);t.sk.hold(300)
28
+ row=dict(seed=seed,mechanism='L2',enabled=enabled,lid_after_quick_closes=failure,final_lid=t.lid_deg())
29
+ rows.append(row);print(json.dumps(row),flush=True)
30
+ assert (failure>10 if enabled else failure<4) and row['final_lid']<4,row
31
+ (out/'controls_progress.json').write_text(json.dumps(rows,indent=2))
32
+ liquid_controls=json.loads((out/'liquid_controls.json').read_text()) if args.judge_only else []
33
+ for case in ([] if args.judge_only else ('upright','tilted_aligned','tilted_misaligned')):
34
+ inst=t.sample_instance(1000);t.reset_instance(inst)
35
+ if case!='upright':t.env.sim.data.qpos[t.pour_qa]=1.35
36
+ if case=='tilted_misaligned':t.env.sim.model.body_pos[t.cup_bid,0]+=.20
37
+ t.env.sim.forward();t.sk.hold(160)
38
+ q=t.liquid;inflight=sum(p['ml'] for p in q['parcels'])
39
+ row=dict(case=case,cup_ml=q['cup'],spill_ml=q['spill'],reservoir_ml=q['reservoir'],
40
+ conservation_error_ml=abs(300-q['cup']-q['spill']-q['reservoir']-inflight))
41
+ liquid_controls.append(row);print(json.dumps(row),flush=True)
42
+ assert row['conservation_error_ml']<1e-8,row
43
+ if case=='upright':assert q['cup']==q['spill']==0,row
44
+ elif case=='tilted_aligned':assert q['cup']>=179 and q['spill']>50,row
45
+ else:assert q['cup']==0 and q['spill']>200,row
46
+ if args.liquid_only:
47
+ (out/'liquid_controls.json').write_text(json.dumps(liquid_controls,indent=2))
48
+ t.env.close();return
49
+ # Obtain a successful physical endpoint before mutating diagnostic scoring fixtures.
50
+ inst=t.sample_instance(1000);t.reset_instance(inst);t.execute(inst,{'mode':'oracle'});baseline=t.outcome(inst)
51
+ assert baseline['success'],baseline
52
+ state=copy.deepcopy(t.env.sim.get_state());liquid=copy.deepcopy(t.liquid)
53
+ mon=copy.deepcopy(t.mon);closes=t.closes_done;latch=t.active_latch
54
+ negatives=[]
55
+ for case in ('no_milk','too_much_milk','spill','bread_off_plate','butter_outside','lid_open','carton_tilted','gripper_closed'):
56
+ t.env.sim.set_state(state);t.env.sim.forward();t.liquid=copy.deepcopy(liquid);t.sk.grip=-1.;t.drift_active=False
57
+ t.mon=copy.deepcopy(mon);t.closes_done=closes;t.active_latch=latch
58
+ if case=='no_milk':t.liquid['reservoir']+=t.liquid['cup'];t.liquid['cup']=0
59
+ elif case=='too_much_milk':
60
+ t.liquid['reservoir']-=175-t.liquid['cup'];t.liquid['cup']=175
61
+ elif case=='spill':t.liquid['reservoir']-=25;t.liquid['spill']=25;t.liquid['spill_xy']=[.2,0]
62
+ elif case=='bread_off_plate':envs.set_obj_pose(t.env,'bread_1',[-.30,.03,.912])
63
+ elif case=='butter_outside':envs.set_obj_pose(t.env,'butter_1',[-.35,-.32,.914])
64
+ elif case=='lid_open':t.env.sim.data.qpos[t.qa]=1.0
65
+ elif case=='carton_tilted':t.env.sim.data.qpos[t.pour_qa]=1.35
66
+ elif case=='gripper_closed':t.sk.grip=1.
67
+ t.env.sim.forward();result=t.outcome(inst)
68
+ negatives.append(dict(case=case,accepted=result['success'],failure=result['failure'],stages=result['stages']))
69
+ print(json.dumps(negatives[-1],default=lambda v:v.item()),flush=True)
70
+ predicate={'no_milk':'milk_served','too_much_milk':'milk_served','spill':'spill_ok',
71
+ 'bread_off_plate':'bread_on_plate','butter_outside':'butter_in_box','lid_open':'lid_closed',
72
+ 'carton_tilted':'carton_upright','gripper_closed':'gripper_open'}[case]
73
+ assert not result['success'] and not result['stages'][predicate],case
74
+ data=dict(controls=rows,liquid_controls=liquid_controls,negative_fixtures=negatives,
75
+ scope='Controlled interventions are diagnostics, not agent rollouts')
76
+ (out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
77
+ t.env.close()
78
+
79
+ if __name__=='__main__':main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_breakfast_tool_interface.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Execute the reference through the real public ToolExecutor, including default motion limits.
2
+ Privileged reference observations remain allowed; all actuation goes through public tools.
3
+ """
4
+ import argparse, json, math
5
+ from pathlib import Path
6
+ from lffbench.tasks.lh_breakfast_service import BreakfastService
7
+ from lffbench.agent.tools import ToolExecutor
8
+
9
+ class PublicSkills:
10
+ def __init__(self,base,executor):
11
+ object.__setattr__(self,'base',base);object.__setattr__(self,'executor',executor)
12
+ object.__setattr__(self,'calls',[])
13
+ # Learned compensation belongs in the caller's command coordinates, not the environment.
14
+ object.__setattr__(self,'correction',base.correction.copy());base.correction[:]=0
15
+ def __getattr__(self,name):return getattr(self.base,name)
16
+ def __setattr__(self,name,value):
17
+ if name=='correction':object.__setattr__(self,name,value)
18
+ else:setattr(self.base,name,value)
19
+ def call(self,name,args):
20
+ result=self.executor.call(name,args)
21
+ self.calls.append(dict(name=name,args=args,ok=result.ok,report=result.report))
22
+ if not result.ok:raise RuntimeError(result.report)
23
+ return result.report
24
+ def move_to(self,target,yaw=None,speed=None,**kwargs):
25
+ target=target-self.correction
26
+ return self.call('move_to',dict(x=float(target[0]),y=float(target[1]),z=float(target[2]),
27
+ yaw=math.degrees(self.base.yaw if yaw is None else yaw),speed=speed))
28
+ def set_gripper(self,close,steps=15):
29
+ result=self.call('close_gripper' if close else 'open_gripper',{})
30
+ if steps>15:self.hold(steps-15)
31
+ return result
32
+ def hold(self,steps=10):
33
+ for _ in range(steps//15):self.call('close_gripper' if self.base.grip>0 else 'open_gripper',{})
34
+ for _ in range(steps%15):
35
+ self.move_to(self.base.eef_pos()-self.base.bias+self.correction)
36
+
37
+ def main():
38
+ p=argparse.ArgumentParser();p.add_argument('--out');p.add_argument('--seed',type=int,default=1000);args=p.parse_args()
39
+ root=Path(__file__).resolve().parents[1]
40
+ out=Path(args.out) if args.out else root/'results/lh_breakfast_service/geometry_v2/tool_interface'
41
+ out.mkdir(parents=True,exist_ok=True)
42
+ t=BreakfastService();inst=t.sample_instance(args.seed);t.reset_instance(inst)
43
+ executor=ToolExecutor(t,inst,image_res=128)
44
+ proxy=PublicSkills(t.sk,executor);t.sk=proxy
45
+ t.phase_hook=lambda text,state:print(json.dumps(state),flush=True)
46
+ t.execute(inst,{'mode':'adaptive'})
47
+ # The final judge's mandatory settle is environment work, not additional agent tool calls.
48
+ t.sk=proxy.base
49
+ result=t.outcome(inst)
50
+ data=dict(outcome=result,calls=proxy.calls,call_count=len(proxy.calls),trace=t.trace,
51
+ environment_correction=proxy.base.correction.tolist(),compensation_in_tool_arguments=True,
52
+ scope='Reference with privileged observations; actual public ToolExecutor actuation, not an LLM evaluation')
53
+ (out/'result.json').write_text(json.dumps(data,indent=2,default=lambda v:v.item()))
54
+ print('OUTCOME',result,flush=True)
55
+ assert result['success'] and all(result['traps'].values()) and len(proxy.calls)<=t.agent_max_steps,dict(outcome=result,call_count=len(proxy.calls))
56
+
57
+ if __name__=='__main__':main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_lh_pantry_relatch.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Physical checks for lh_pantry_relatch: confirm the latch-fatigue mechanism actually behaves as designed before
2
+ any acceptance validation. Not the formal n>=20 k=5 headroom run (see scripts/validate.py for that).
3
+
4
+ Usage:
5
+ cd lffbench && source run_env.sh && OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py mechanism
6
+ OMP_NUM_THREADS=1 python scripts/check_lh_pantry_relatch.py seeds --seeds 1000,1001,1002 --out <path>
7
+ """
8
+ import argparse
9
+ import copy
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import sys
14
+
15
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
16
+
17
+ import numpy as np
18
+
19
+ from lffbench import envs
20
+ from lffbench.tasks.lh_pantry_relatch import PantryRelatch
21
+
22
+
23
+ def source_hash():
24
+ path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "lffbench", "tasks",
25
+ "lh_pantry_relatch.py")
26
+ return hashlib.sha256(open(path, "rb").read()).hexdigest()
27
+
28
+
29
+ def mechanism_check(seed=1000, out=None):
30
+ """Isolate the latch mechanism: close 1 (quick) should hold; close 2 (quick) should drift open on its own
31
+ during the settle window; close 2 (dwell) should hold. No bread/butter picking involved -- just the lid."""
32
+ task = PantryRelatch()
33
+ rows = []
34
+ for label, dwell1, dwell2 in [("quick_quick", False, False), ("quick_dwell", False, True)]:
35
+ inst = task.sample_instance(seed)
36
+ task.reset_instance(inst)
37
+ task.open_lid()
38
+ task.close_lid(dwell=dwell1)
39
+ after_close1 = task.lid_deg()
40
+ n = 0
41
+ while n < 300:
42
+ task.sk.hold(10)
43
+ n += 10
44
+ settled1 = task.lid_deg()
45
+ task.open_lid()
46
+ task.close_lid(dwell=dwell2)
47
+ after_close2 = task.lid_deg()
48
+ n = 0
49
+ while n < 500:
50
+ task.sk.hold(10)
51
+ n += 10
52
+ settled2 = task.lid_deg()
53
+ row = dict(label=label, dwell1=dwell1, dwell2=dwell2, after_close1_deg=round(after_close1, 2),
54
+ settled1_deg=round(settled1, 2), after_close2_deg=round(after_close2, 2),
55
+ settled2_deg=round(settled2, 2), closes_done=task.closes_done,
56
+ active_latch_final=round(task.active_latch, 4))
57
+ rows.append(row)
58
+ print(row, flush=True)
59
+ print("expect: quick_quick settled2_deg clearly > quick_dwell settled2_deg (fatigue visible without dwell)")
60
+ if out:
61
+ with open(out, "w") as f:
62
+ json.dump(dict(rows=rows, source_sha256=source_hash()), f, indent=1)
63
+ return rows
64
+
65
+
66
+ def ablation_no_decay(seed=1000, out=None):
67
+ """Ablation: force DECAY=1.0 (no fatigue). Quick-release close 2 should then also hold."""
68
+ import lffbench.tasks.lh_pantry_relatch as mod
69
+ orig = mod.DECAY
70
+ mod.DECAY = 1.0
71
+ try:
72
+ task = PantryRelatch()
73
+ inst = task.sample_instance(seed)
74
+ task.reset_instance(inst)
75
+ task.open_lid()
76
+ task.close_lid(dwell=False)
77
+ task.open_lid()
78
+ task.close_lid(dwell=False)
79
+ n = 0
80
+ while n < 500:
81
+ task.sk.hold(10)
82
+ n += 10
83
+ settled2 = task.lid_deg()
84
+ row = dict(decay_forced=1.0, settled2_deg=round(settled2, 2), closes_done=task.closes_done)
85
+ print(row, flush=True)
86
+ finally:
87
+ mod.DECAY = orig
88
+ if out:
89
+ with open(out, "w") as f:
90
+ json.dump(row, f, indent=1)
91
+ return row
92
+
93
+
94
+ def full_episode(seed, kind, out_dir=None):
95
+ """Full pick-bread / put-butter episode with a given scripted policy kind."""
96
+ task = PantryRelatch()
97
+ inst = task.sample_instance(seed)
98
+ hist = task.run_scripted(kind, inst, k=task.max_attempts, seed=seed)
99
+ for h in hist:
100
+ o = h["outcome"]
101
+ print(f"seed={seed} kind={kind} attempt={h['attempt']} success={o['success']} failure={o['failure']} "
102
+ f"closes_done={o['closes_done']} lid_final={o['lid_final_deg']} detail={o['detail']}", flush=True)
103
+ return hist
104
+
105
+
106
+ def seeds_check(seeds, out=None):
107
+ task_rows = {}
108
+ for seed in seeds:
109
+ rows = {}
110
+ for kind in ("oracle", "naive", "adaptive"):
111
+ hist = full_episode(seed, kind)
112
+ rows[kind] = [dict(attempt=h["attempt"], success=h["outcome"]["success"],
113
+ failure=h["outcome"]["failure"], closes_done=h["outcome"]["closes_done"],
114
+ lid_final_deg=h["outcome"]["lid_final_deg"]) for h in hist]
115
+ task_rows[seed] = rows
116
+ result = dict(seeds=seeds, rows=task_rows, source_sha256=source_hash())
117
+ if out:
118
+ with open(out, "w") as f:
119
+ json.dump(result, f, indent=1)
120
+ return result
121
+
122
+
123
+ if __name__ == "__main__":
124
+ ap = argparse.ArgumentParser()
125
+ ap.add_argument("mode", choices=["mechanism", "ablation", "seeds", "episode"])
126
+ ap.add_argument("--seed", type=int, default=1000)
127
+ ap.add_argument("--seeds", type=str, default="1000,1001,1002")
128
+ ap.add_argument("--kind", type=str, default="oracle")
129
+ ap.add_argument("--out", type=str, default=None)
130
+ args = ap.parse_args()
131
+ if args.mode == "mechanism":
132
+ mechanism_check(args.seed, args.out)
133
+ elif args.mode == "ablation":
134
+ ablation_no_decay(args.seed, args.out)
135
+ elif args.mode == "episode":
136
+ full_episode(args.seed, args.kind)
137
+ elif args.mode == "seeds":
138
+ seeds_check([int(s) for s in args.seeds.split(",")], args.out)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/check_setup.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Check that this machine can run LFF-Bench. Run after `source run_env.sh`:
2
+
3
+ python scripts/check_setup.py # Python packages, LIBERO config, simulation + rendering, the agent's shell jail
4
+ python scripts/check_setup.py --api # ... plus one tiny text-only request to the model endpoint (OPENAI_API_KEY /
5
+ # OPENAI_BASE_URL from the environment or from .env); costs a few tokens
6
+ python scripts/check_setup.py --api --model gpt-5.5 --skip-sim --skip-jail
7
+
8
+ Exit code 0 when every check that ran passed.
9
+ """
10
+ import argparse
11
+ import os
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ import time
16
+
17
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
18
+ sys.path.insert(0, ROOT)
19
+ JAIL = "/opt/lffjail/jail_inner.sh" # same path as lffbench/agent/robot_server.py and scripts/gpt_player.py
20
+
21
+ results = []
22
+
23
+
24
+ def report(name, ok, detail=""):
25
+ results.append(ok)
26
+ print(f"[{'ok' if ok else 'FAIL'}] {name}" + (f": {detail}" if detail else ""), flush=True)
27
+ return ok
28
+
29
+
30
+ def check_packages():
31
+ report("python 3.10", sys.version_info[:2] == (3, 10), sys.version.split()[0])
32
+ from lffbench.agent.backends.base import import_openai
33
+ for mod in ("numpy", "mujoco", "robosuite", "libero.libero", "openai", "imageio", "cv2"):
34
+ try:
35
+ m = import_openai() if mod == "openai" else __import__(mod, fromlist=["_"])
36
+ report(f"import {mod}", True, getattr(m, "__version__", ""))
37
+ except Exception as e: # noqa: BLE001
38
+ report(f"import {mod}", False, f"{type(e).__name__}: {e}")
39
+ cfg = os.path.join(os.environ.get("LIBERO_CONFIG_PATH", ""), "config.yaml")
40
+ if report("LIBERO config", os.path.isfile(cfg), cfg + ("" if os.path.isfile(cfg) else " missing: run setup/install.sh")):
41
+ import yaml
42
+ assets = yaml.safe_load(open(cfg)).get("assets", "")
43
+ report("LIBERO assets", os.path.isdir(assets), assets)
44
+ report("rendering backend", bool(os.environ.get("MUJOCO_GL")), f"MUJOCO_GL={os.environ.get('MUJOCO_GL')}")
45
+
46
+
47
+ def check_sim(task_name, seed):
48
+ import importlib
49
+ import pkgutil
50
+
51
+ try:
52
+ import lffbench.tasks as task_pkg
53
+ from lffbench.task_base import TASKS
54
+ except Exception as e: # noqa: BLE001
55
+ report("import lffbench", False, f"{type(e).__name__}: {e}")
56
+ return
57
+ try:
58
+ for m in pkgutil.iter_modules(task_pkg.__path__):
59
+ importlib.import_module(f"lffbench.tasks.{m.name}")
60
+ except Exception as e: # noqa: BLE001
61
+ report("import tasks", False, f"{type(e).__name__}: {e}")
62
+ return
63
+ report("tasks registered", len(TASKS) >= 20, f"{len(TASKS)} tasks")
64
+ t0 = time.time()
65
+ try:
66
+ task = TASKS[task_name]()
67
+ inst = task.sample_instance(seed)
68
+ task.reset_instance(inst)
69
+ img = task.snapshot()
70
+ out = task.outcome(inst)
71
+ except Exception as e: # noqa: BLE001
72
+ report(f"simulate + render {task_name}", False, f"{type(e).__name__}: {e}")
73
+ return
74
+ ok = img.ndim == 3 and img.shape[2] == 3 and float(img.std()) > 1.0
75
+ report(f"simulate + render {task_name}", ok,
76
+ f"image {img.shape}, pixel std {img.std():.1f}, untouched scene success={out['success']}, {time.time() - t0:.1f} s")
77
+
78
+
79
+ def check_jail():
80
+ if not report("jail installed", os.access(JAIL, os.X_OK) and os.path.isdir("/opt/lffjail/py"),
81
+ JAIL if os.path.exists(JAIL) else "missing: sudo bash jail/setup_jail.sh"):
82
+ return
83
+ probe = r'''
84
+ echo "pwd=$(pwd)"
85
+ python3 -c "import numpy, scipy, PIL, cv2; print('py=ok')" 2>&1 | tail -1
86
+ echo "mnt_entries=$(ls -A /mnt 2>/dev/null | wc -l) home_entries=$(ls -A /home 2>/dev/null | wc -l)"
87
+ python3 -c "
88
+ import socket
89
+ s = socket.socket(); s.settimeout(3)
90
+ try:
91
+ s.connect(('1.1.1.1', 443)); print('net=open')
92
+ except OSError as e:
93
+ print('net=blocked')
94
+ "
95
+ touch made_in_jail && echo "write=ok"
96
+ '''
97
+ with tempfile.TemporaryDirectory(prefix="lffjail_check_") as ws:
98
+ argv = ["unshare", "--user", "--map-root-user", "--mount", "--net", "--", JAIL, ws,
99
+ "timeout", "-k", "5", "60", "bash", "-c", probe]
100
+ r = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=120)
101
+ kv = dict(l.split("=", 1) for l in r.stdout.split() if "=" in l)
102
+ if r.returncode != 0 and not kv:
103
+ hint = ""
104
+ if "Operation not permitted" in r.stdout or "uid_map" in r.stdout:
105
+ hint = (" | unprivileged user namespaces are blocked; on Ubuntu >= 23.10: "
106
+ "sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0")
107
+ report("jail runs", False, r.stdout.strip()[-400:] + hint)
108
+ return
109
+ report("jail runs", True, f"workdir {kv.get('pwd')}")
110
+ report("jail python (numpy/scipy/Pillow/OpenCV)", kv.get("py") == "ok", kv.get("py", r.stdout[-300:]))
111
+ report("jail hides host data", kv.get("mnt_entries") == "0" and kv.get("home_entries") == "0",
112
+ f"/mnt entries {kv.get('mnt_entries')}, /home entries {kv.get('home_entries')}")
113
+ report("jail has no network", kv.get("net") == "blocked", kv.get("net", "?"))
114
+ report("jail writes the workspace", kv.get("write") == "ok" and os.path.exists(os.path.join(ws, "made_in_jail")))
115
+
116
+
117
+ def load_env_file():
118
+ path = os.environ.get("LFF_ENV_FILE") or os.path.join(ROOT, ".env")
119
+ if not os.path.isfile(path):
120
+ return None
121
+ for line in open(path):
122
+ line = line.strip()
123
+ if line and not line.startswith("#") and "=" in line:
124
+ k, v = line.split("=", 1)
125
+ os.environ.setdefault(k.removeprefix("export ").strip(), v.strip().strip("'\""))
126
+ return path
127
+
128
+
129
+ def check_api(model, effort):
130
+ src = load_env_file()
131
+ if not os.environ.get("SSL_CERT_FILE") and os.path.exists("/etc/ssl/certs/ca-certificates.crt"):
132
+ os.environ["SSL_CERT_FILE"] = "/etc/ssl/certs/ca-certificates.crt" # same as scripts/gpt_player.py
133
+ if not report("OPENAI_API_KEY set", bool(os.environ.get("OPENAI_API_KEY")),
134
+ f"from {src}" if src else "from the environment (no .env)"):
135
+ return
136
+ base = os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1 (default)"
137
+ from lffbench.agent.backends.openai_responses import OpenAIResponsesBackend
138
+ t0 = time.time()
139
+ try:
140
+ client = OpenAIResponsesBackend(model=model, reasoning_effort=effort, timeout=120.0, max_retries=1).client()
141
+ resp = client.responses.create(model=model, instructions="Reply with exactly the word OK.", input="ping",
142
+ reasoning=dict(effort=effort), store=False, max_output_tokens=256)
143
+ text = (resp.output_text or "").strip()
144
+ u = resp.usage
145
+ report(f"API {model} @ {base}", bool(text), f"reply {text[:40]!r}, {time.time() - t0:.1f} s, "
146
+ f"tokens in {u.input_tokens} / out {u.output_tokens}")
147
+ except Exception as e: # noqa: BLE001
148
+ report(f"API {model} @ {base}", False, f"{type(e).__name__}: {str(e)[:300]}")
149
+
150
+
151
+ def main():
152
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
153
+ ap.add_argument("--api", action="store_true", help="also send one tiny request to the model endpoint")
154
+ ap.add_argument("--model", default="gpt-6-astra")
155
+ ap.add_argument("--effort", default="low")
156
+ ap.add_argument("--task", default="l5_slide_to_target")
157
+ ap.add_argument("--seed", type=int, default=1000)
158
+ ap.add_argument("--skip-sim", action="store_true")
159
+ ap.add_argument("--skip-jail", action="store_true")
160
+ a = ap.parse_args()
161
+ os.environ.setdefault("OMP_NUM_THREADS", "1")
162
+ check_packages()
163
+ if not a.skip_sim:
164
+ check_sim(a.task, a.seed)
165
+ if not a.skip_jail:
166
+ check_jail()
167
+ if a.api:
168
+ check_api(a.model, a.effort)
169
+ n_bad = results.count(False)
170
+ print(f"\n{len(results) - n_bad}/{len(results)} checks passed")
171
+ sys.exit(1 if n_bad else 0)
172
+
173
+
174
+ if __name__ == "__main__":
175
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/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_deepseek/lff/source_closure/scripts/cs_ir_report.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reproduce the CS/IR audit tables from read-only manifests and hash-bound evidence."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import api_batch
7
+ import outcomes
8
+ from outcome_audit import load_audit, sha256
9
+
10
+ GROUPS = {"GPT": ["cx_main1"], "Sonnet": ["cc_main1"], "Opus": ["cc_opus1"],
11
+ "DeepSeek": ["ds_cx1", "ds_cx1b"]}
12
+
13
+
14
+ def main():
15
+ parser = argparse.ArgumentParser()
16
+ parser.add_argument("--runs-root", required=True)
17
+ parser.add_argument("--audit", required=True)
18
+ parser.add_argument("--out", required=True)
19
+ args = parser.parse_args()
20
+ api_batch.RUNS = str(Path(args.runs_root).resolve())
21
+ audit = load_audit(args.audit)
22
+ output = Path(args.out)
23
+ output.mkdir(parents=True, exist_ok=True)
24
+ all_rows, models, manifests, coverage = [], {}, {}, {}
25
+ for model, batches in GROUPS.items():
26
+ old, new = [], []
27
+ for batch in batches:
28
+ manifest = api_batch.load(batch)
29
+ manifests[batch] = sha256(api_batch.mpath(batch))
30
+ old += outcomes.instance_rows(manifest, batch=batch)
31
+ new += outcomes.instance_rows(manifest, audit=audit, batch=batch)
32
+ for run in manifest["runs"]:
33
+ if not (run["cond"] == "harness" and run.get("followup") and run["status"] == "done"):
34
+ continue
35
+ attempts = outcomes.attempts(run["log"])
36
+ if attempts:
37
+ coverage.setdefault(run["task"], set()).update(
38
+ k for k in outcomes.ERROR_FLAGS + outcomes.ERROR_COUNTS if k in attempts[0][2])
39
+ before, after = outcomes.summary(old), outcomes.summary(new)
40
+ for key in ("n", "A1", "A3", "XR", "F", "n_paired", "A3_paired", "passk_paired", "delta_paired"):
41
+ assert before[key] == after[key], f"Audit unexpectedly changed {model} {key}"
42
+ assert len({(r["task"], r["seed"]) for r in new}) == len(new), "duplicate model/task/seed"
43
+ models[model] = dict(before=before, after=after)
44
+ all_rows += [dict(r, model=model) for r in new]
45
+ payload = dict(schema="lff-cs-ir-report-1", source_manifests_sha256=manifests,
46
+ audit_sha256=sha256(args.audit), models=models, rows=all_rows,
47
+ legacy_counter_coverage={k: sorted(v) for k, v in coverage.items()})
48
+ (output / "summary.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n")
49
+ lines = ["# CS / IR 证据审计表(2026-10-24)", "",
50
+ "本表由 `scripts/cs_ir_report.py` 生成;定义、局限、合并说明见同目录 `README.md`。",
51
+ "旧口径是 task counter heuristic;新口径是逐 run 的物理失败 + 主动修复证据审计。",
52
+ "A1、A3、XR、F、配对样本及 Δ_hist 均逐项断言保持不变。", "",
53
+ "| 模型 | 旧 CS / IR / S? | 审计 CS / IR / S? | 原 S? 已补 | A1 | A3 |",
54
+ "|---|---|---|---|---|---|"]
55
+ for model, pair in models.items():
56
+ b, a = pair["before"], pair["after"]
57
+ resolved = sum(r["model"] == model and r["legacy_cls"] == "S?" and r["cls"] != "S?" for r in all_rows)
58
+ lines.append(f"| {model} | {b['CS']} / {b['IR']} / {b['S?']} | {a['CS']} / {a['IR']} / {a['S?']} | "
59
+ f"{resolved}/{b['S?']} | {a['A1']}/{a['n']} | {a['A3']}/{a['n']} |")
60
+ lines += ["", "## 每任务新旧分类与原统一字段覆盖", "",
61
+ "`旧→新`;只有一个标签表示未变。`缺失` 不是没有错误;有字段也不代表覆盖抓空/掉落等全部失败。", "",
62
+ "| 任务 | GPT | Sonnet | Opus | DeepSeek | 原统一错误字段 |", "|---|---|---|---|---|---|"]
63
+ for task, counters in coverage.items():
64
+ cells = []
65
+ for model in GROUPS:
66
+ row = next(r for r in all_rows if r["model"] == model and r["task"] == task)
67
+ cells.append(row["cls"] if row["cls"] == row["legacy_cls"] else f"{row['legacy_cls']}→{row['cls']}")
68
+ lines.append("| " + " | ".join([task] + cells + [", ".join(sorted(counters)) or "缺失"]) + " |")
69
+ lines += ["", "## 首次成功的证据链", "", "行号均指原 run 文件,E 为 events.jsonl,T 为 trajectory.jsonl;s 为机器人命令序号。", ""]
70
+ for row in all_rows:
71
+ if not row["a1"]:
72
+ continue
73
+ entry = audit.get((row["batch"], row["run_id"]))
74
+ manifest = api_batch.load(row["batch"])
75
+ run = next(r for r in manifest["runs"] if r["id"] == row["run_id"])
76
+ lines += [f"### {row['model']} · {row['task']} · {row['legacy_cls']} → {row['cls']}", "",
77
+ row["audit_basis"], "", f"[原 events.jsonl]({run['log']}/events.jsonl) · "
78
+ f"[原 trajectory.jsonl]({run['log']}/trajectory.jsonl)", ""]
79
+ if entry:
80
+ lines += [f"证据索引:{entry.get('evidence', '')}", "",
81
+ f"归因范围:`{entry.get('failure_scope', 'not_adjudicated')}`。", ""]
82
+ (output / "TABLES.md").write_text("\n".join(lines) + "\n")
83
+ print(json.dumps(models, ensure_ascii=False, indent=2))
84
+
85
+
86
+ if __name__ == "__main__":
87
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/feedback_ladder.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Frozen first-failure record experiment. No native-session-continuation claim.
2
+
3
+ prepare creates a host-only manifest plus agent-visible, identical history records.
4
+ run starts the serial, resumable controller; player wraps the unchanged native harness.
5
+ """
6
+ import argparse
7
+ import collections
8
+ import datetime as dt
9
+ import hashlib
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import random
14
+ import shutil
15
+ import signal
16
+ import socket
17
+ import subprocess
18
+ import sys
19
+ import time
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ sys.path.insert(0, str(ROOT))
23
+ sys.path.insert(0, str(ROOT / 'scripts'))
24
+ SOURCE = ROOT.parents[1] / 'lffbench'
25
+ REPORT = ROOT.parents[1] / 'reports/feedback_ladder_20261027'
26
+ BATCHES = ('cc_opus1', 'cc_opus_s2', 'cc_opus_s3')
27
+ TASKS = ('l7_offcenter_push','l5_slide_to_target','l5_tablecloth_pull','l3_wall_flush',
28
+ 'l3_under_table_tool','l4_fit_container','l7_key_turn','l2_turntable_restore','l3_card_shelf','l5_loaded_beam')
29
+ ARMS = ('F1', 'F2', 'cause', 'fix')
30
+ ENV_FILE = Path('/mnt/cpfs/workspace/env/claude-releases/cc_opus_s3.env')
31
+ PILOT = ('cc_opus1__l3_card_shelf__3003', 'cc_opus_s2__l4_fit_container__3001')
32
+
33
+
34
+ def now():
35
+ return dt.datetime.now(dt.timezone.utc).isoformat()
36
+
37
+
38
+ def sha(p):
39
+ return hashlib.sha256(Path(p).read_bytes()).hexdigest()
40
+
41
+
42
+ def digest(d):
43
+ return hashlib.sha256(json.dumps(d,sort_keys=True,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
44
+
45
+
46
+ def read(p):
47
+ return json.loads(Path(p).read_text())
48
+
49
+
50
+ def write(p,d):
51
+ p=Path(p);p.parent.mkdir(parents=True,exist_ok=True)
52
+ tmp=p.with_name(p.name+'.tmp');tmp.write_text(json.dumps(d,indent=2,ensure_ascii=False)+'\n');tmp.replace(p)
53
+
54
+
55
+ def jsonl(p):
56
+ return [json.loads(s) for s in Path(p).read_text().splitlines() if s.strip()]
57
+
58
+
59
+ def tree_hash(p):
60
+ return digest({str(f.relative_to(p)):sha(f) for f in sorted(Path(p).rglob('*')) if f.is_file()})
61
+
62
+
63
+ def intervention(a,arm):
64
+ parts=['The earlier attempt failed.']
65
+ if arm not in ARMS:raise ValueError(arm)
66
+ for level,key in [('F2','phenomenon'),('cause','cause'),('fix','fix')]:
67
+ if ARMS.index(arm)>=ARMS.index(level):parts.append(a[key])
68
+ return '\n'.join(parts)
69
+
70
+
71
+ def annotations(task,seed,out,inst):
72
+ """Manual mechanism families, checked against each observed first-attempt outcome.
73
+ F2 contains observations only; privileged mechanism and strategy are separate.
74
+ Unknown/mixed mechanisms are explicitly excluded, not assigned a task-name cause.
75
+ """
76
+ if task=='l3_wall_flush' and out.get('mode')=='placed_off':
77
+ return dict(eligible=False,reason='Placement missed after successful extraction; exact localization/control cause unverified.')
78
+ if task=='l3_under_table_tool':
79
+ return dict(eligible=False,reason='Cube never moved and agent reported wrist limits; transparent-pane mechanism not triggered. Needs separate operational audit.')
80
+ if task=='l5_slide_to_target':
81
+ assert out['failure']=='position' and out['along_err']>0 and out['at_rest']
82
+ return dict(eligible=True,phenomenon='The cube came to rest beyond the far edge of the target square.',
83
+ cause='The cube keeps moving after release: its surface friction is low, so the launch imparted more sliding distance than the remaining distance to the target.',
84
+ fix='Use the previous strike and observed travel as a calibration. Align a short strike toward the square, launch more gently for the remaining distance, withdraw the gripper, and wait for the cube to stop before checking both edges. Preserve a free slide; do not carry or continuously push it into place.',
85
+ basis=['failure=position','along_err>0','at_rest=true','mu in sampled instance','strikes/free_slide_cm'],mechanism='overshoot_after_release')
86
+ if task=='l5_tablecloth_pull':
87
+ assert out['failure']=='missed_band' and out['upright'] and not out['on_board'] and out['band_offset_x']>0
88
+ return dict(eligible=True,phenomenon='The board came out and the cube stayed upright, but the cube stopped short of the green band in the direction of the pull.',
89
+ cause='Friction transfers motion from the board to the cube while they remain in contact. The pull was too fast to move the cube far enough toward the band before the board escaped.',
90
+ fix='On the reset scene, grasp only the handle and use one straight, somewhat slower pull than before, then release. A slower pull carries the cube farther before the board escapes; avoid making it so slow that the cube rides on the board. Check the whole cube against the band after it settles.',
91
+ basis=['failure=missed_band','upright=true','on_board=false','band_offset_x>0','tasks/l5_tablecloth_pull.py adaptive_params'],mechanism='insufficient_frictional_displacement')
92
+ if task=='l3_wall_flush':
93
+ assert out['mode']=='wall_blocked' and not out['lifted']
94
+ return dict(eligible=True,phenomenon='The box was not lifted. During grasp attempts, the wall-side finger came down on the top of the wall.',
95
+ cause='The clearance between box and wall is too small for that finger, and the wall is higher than the box. At the attempted grasp locations the finger still overlapped the wall.',
96
+ fix='With the gripper closed, slide the box along the wall toward an accessible wall end. Move it far enough past that end for both fingers to descend clear of the wall, then open, grasp the box, lift, and place it centered on the plate.',
97
+ basis=['mode=wall_blocked','lifted=false','detail wall collision','gap and wall geometry'],mechanism='wall_blocks_finger')
98
+ if task=='l4_fit_container':
99
+ assert out['failure']=='rim' and out['box_kind'] in ('snug','short_wide','small')
100
+ return dict(eligible=True,phenomenon='The released phone rested on the box rims rather than lying on the bottom inside the box.',
101
+ cause='The selected box is shorter internally than the phone along its long dimension. The phone bridges the rims even when its long axis is aligned with that box.',
102
+ fix='Choose a different box whose internal length and width both clear the phone. Compare the inside edges, orient the phone along the chosen box, lower it through the opening, release it, then withdraw and verify that it lies flat below the rims.',
103
+ basis=['failure=rim','box_kind='+out['box_kind'],'sampled box inner dimensions','detail length mismatch'],mechanism='container_too_short')
104
+ if task=='l3_card_shelf':
105
+ assert out['failure']=='fell_off' and out['tip']['part']=='heavy'
106
+ side=out['tip']['edge'];assert side==inst['heavy_edge']
107
+ return dict(eligible=True,phenomenon=f'The card tipped over the shelf\'s {side} edge and fell flat onto the table before it was lifted.',
108
+ cause=f'The card has a hidden weight toward the end that went over the {side} edge. Its center of mass passed outside the shelf support even with only a small overhang.',
109
+ fix='On the reset shelf, slide the opposite, lighter end toward the opposite shelf edge in small checked moves. Keep the weighted end supported, expose enough of the light end for the fingers to pass the shelf edge, pinch the exposed end across its width, then lift and transfer the card into the bin.',
110
+ basis=['failure=fell_off','tip.part=heavy','tip.edge matches inst.heavy_edge','tipped_off event'],mechanism='heavy_end_over_edge')
111
+ if task=='l5_loaded_beam':
112
+ assert out['failure']=='load_off' and out['n_load_falls']>0
113
+ return dict(eligible=True,phenomenon='The beam tilted during lifting and the blocks slid away from their end positions. At the end, the beam was held up but one block was still displaced inward from its end position.',
114
+ cause='The beam has an off-center hidden weight. The initial grip was away from the loaded balance point, so the beam tilted and displaced its blocks; later leveling did not itself restore their required end positions.',
115
+ fix='First restore both blocks to their original end positions while the beam is supported. Make a low test lift, adjust the grip toward the lower, heavier end until the loaded beam stays level, and only then raise it fully. Recheck both blocks after the lift; if either shifts, set down and restore it before trying again.',
116
+ basis=['failure=load_off','first lift tilt and falls','final loads_on_ends=1','inst.com_total'],mechanism='offcenter_lift_and_unrestored_load',mixed=True)
117
+ raise ValueError(f'No reviewed feedback for {task} seed {seed}')
118
+
119
+
120
+ def record_prefix(log,outdir,done):
121
+ """Only host-logged model-visible MCP text before first verdict, plus first images.
122
+ Do NOT copy session_start.inst, evaluator outcome, later attempts, or native hidden reasoning.
123
+ The final call is replaced by its closing reason + F1 verdict, to avoid reset-image leakage.
124
+ """
125
+ outdir.mkdir(parents=True,exist_ok=False);(outdir/'obs').mkdir()
126
+ tools=[]
127
+ for e in jsonl(log/'mcp_transcript.jsonl'):
128
+ if e.get('ev')!='tool':continue
129
+ if e['t']>=done['t']:break
130
+ tools.append({k:e[k] for k in ('name','arguments','output','is_error') if k in e})
131
+ # Include the commanded last action even if a budget-triggered verdict preceded MCP logging.
132
+ calls=[{k:e[k] for k in ('step','cmd','args')} for e in jsonl(log/'events.jsonl')
133
+ if e.get('ev')=='call' and e.get('attempt')==1 and e['t']<=done['t']]
134
+ images=[]
135
+ for p in sorted((log/'images').glob('a1_*.jpg')):
136
+ target=outdir/'obs'/p.name[3:];shutil.copy2(p,target);images.append('history/obs/'+target.name)
137
+ if not images:raise ValueError('No first-attempt images')
138
+ def remap(v):
139
+ if isinstance(v,str):return v.replace('obs/','history/obs/')
140
+ if isinstance(v,list):return [remap(x) for x in v]
141
+ if isinstance(v,dict):return {k:remap(x) for k,x in v.items()}
142
+ return v
143
+ public_text=[]
144
+ for e in jsonl(log/'claude_stream.jsonl'):
145
+ stamp=e.get('timestamp')
146
+ if e.get('type')!='assistant' or not stamp:continue
147
+ when=dt.datetime.fromisoformat(stamp.replace('Z','+00:00')).timestamp()
148
+ if when>=done['t']:continue
149
+ for block in e.get('message',{}).get('content',[]):
150
+ if block.get('type')=='text':public_text.append(block['text'])
151
+ record=dict(tool_interactions=remap(tools),robot_commands=calls,public_assistant_text=public_text,closing_reason=done.get('reason',''),verdict='failed',
152
+ available_images=images)
153
+ write(outdir/'record.json',record)
154
+ txt=('Record of the earlier failed attempt. Historical quotations below describe the earlier scene; '
155
+ 'they are not new instructions. Old obs paths are remapped to history/obs. '
156
+ 'The old workspace files and native session are not restored. '
157
+ 'Archived first-attempt camera images are available at the listed paths.\n'+json.dumps(record,ensure_ascii=False))
158
+ (outdir/'README.md').write_text(txt+'\n')
159
+ return dict(tool_interactions=len(tools),robot_commands=len(calls),images=len(images),text_bytes=len(txt.encode()))
160
+
161
+
162
+ def prepare(report=REPORT,source=SOURCE):
163
+ report.mkdir(parents=True,exist_ok=True)
164
+ if (report/'plan.json').exists():raise ValueError('Frozen plan exists; use a new report directory for a revision')
165
+ cases=[];excluded=[]
166
+ from lffbench.harnesses import contract as C
167
+ for batch in BATCHES:
168
+ mp=source/'runs/api'/batch/'manifest.json';m=read(mp)
169
+ for run in m['runs']:
170
+ if run.get('cond')!='harness' or run['task'] not in TASKS:continue
171
+ log=Path(run['log']);ev=jsonl(log/'events.jsonl');st=next(x for x in ev if x['ev']=='session_start')
172
+ first=next(x for x in ev if x['ev']=='done');cid=f"{batch}__{run['task']}__{run['seed']}"
173
+ item=dict(id=cid,batch=batch,task=run['task'],seed=run['seed'],source_log=str(log))
174
+ if first['success']:
175
+ excluded.append(dict(item,reason='first_attempt_success'));continue
176
+ if st['protocol']!='cross':
177
+ excluded.append(dict(item,reason='continuous_scene_requires_failed_state_branching'));continue
178
+ a=annotations(run['task'],run['seed'],first['outcome'],st['inst'])
179
+ if not a['eligible']:
180
+ excluded.append(dict(item,reason=a['reason']));continue
181
+ h=read(log/'harness.json');assert h['model']=='claude-opus-5-5' and h['audit_ok']
182
+ old=read(log/'contract.json')['contract'];_,codes=C.server_code_sha(run['task'])
183
+ if codes!=old['server_code_files']:raise ValueError(f'Scene/scoring source changed for {cid}')
184
+ rec=report/'records'/cid
185
+ stats=record_prefix(log,rec,first)
186
+ case=dict(item,annotation=a,record=str(rec),record_sha256=tree_hash(rec),record_stats=stats,
187
+ original_contract_sha256=h['contract_sha256'],server_code_files=codes,
188
+ source_hashes={f:sha(log/f) for f in ['events.jsonl','mcp_transcript.jsonl','claude_stream.jsonl','harness.json','contract.json']},
189
+ source_first_outcome=first['outcome'],source_first_reason=first['reason'],source_inst=st['inst'],
190
+ source_budget=old['budget'],source_first_done_time=first['t'])
191
+ for arm in ARMS:
192
+ folder=report/'inputs'/cid/arm
193
+ shutil.copytree(rec,folder)
194
+ (folder/'feedback.txt').write_text(intervention(a,arm)+'\n')
195
+ cases.append(case)
196
+ plan=dict(schema='lff-feedback-ladder-1',created_utc=now(),source=str(source),model='claude-opus-5-5',effort='high',
197
+ harness='claude_code_full',cli_version='2.1.299',auth='oauth',remaining_attempts=2,
198
+ history_mode='frozen_model_visible_tool_record_with_archived_images; fresh native session in ALL arms',
199
+ feedback_schedule='one additive intervention before recovery; subsequent verdicts F1 for all arms',
200
+ original_F1_comparable=False,arms=ARMS,selection='all first-attempt failures in fixed ten-task set and three fixed Opus batches, excluding continuous scene and unverified causes',
201
+ cases=cases,excluded=excluded,pilot_cases=PILOT,concurrency=1,randomization_seed=20261027,
202
+ inference='conditional recovery and paired information benefit; not exact cognitive-stage failure proportions',
203
+ limitations=['single rollout per condition','mechanism cards model-assisted, not independent blinded ground truth',
204
+ 'F1 record replay must not be pooled with original native continuation','archived available images can be revisited; old workspace and hidden reasoning unavailable',
205
+ 'fix text is a strategy, not a calibrated action trajectory; failure need not be execution alone'])
206
+ write(report/'plan.json',plan)
207
+ write(report/'freeze.json',dict(plan_sha256=sha(report/'plan.json'),code_sha256=sha(__file__),inputs={str(p.relative_to(report)):tree_hash(p) for p in sorted((report/'inputs').glob('*/*'))}))
208
+ rows=['# Feedback ladder: frozen protocol','',f'{len(cases)} eligible failures; {len(cases)*4} recovery runs, at most two recovery attempts each.','',
209
+ 'All four arms receive the same first-failure record in a fresh Claude session. F1 is rerun. This is a record-replay intervention, not restoration of native session state.',
210
+ 'F2 is observation-only and is deliberately narrower than existing task F2 strings, which sometimes reveal causes.',
211
+ 'Only the initial feedback varies. Later verdicts remain F1. No precise coordinates or simulator action program are handed to the agent.','',
212
+ '| Case | Observed failure | Cause | Fix |','|---|---|---|---|']
213
+ for c in cases:
214
+ a=c['annotation'];rows.append('| '+' | '.join([c['id'],a['phenomenon'],a['cause'],a['fix']])+' |')
215
+ rows+=['','## Exclusions','']+[f"- {x['id']}: {x['reason']}" for x in excluded]
216
+ (report/'PROTOCOL.md').write_text('\n'.join(rows)+'\n')
217
+ print(json.dumps(dict(cases=len(cases),runs=len(cases)*4,excluded=len(excluded),report=str(report))))
218
+
219
+
220
+ def check_frozen(report):
221
+ f=read(report/'freeze.json')
222
+ if sha(report/'plan.json')!=f['plan_sha256']:raise ValueError('plan changed')
223
+ if sha(__file__)!=f['code_sha256']:raise ValueError('controller code changed after freeze')
224
+ for rel,h in f.get('runtime_sha256',{}).items():
225
+ if sha(ROOT/rel)!=h:raise ValueError('runtime changed: '+rel)
226
+ for rel,h in f['inputs'].items():
227
+ if tree_hash(report/rel)!=h:raise ValueError('input changed: '+rel)
228
+ return read(report/'plan.json')
229
+
230
+
231
+ def player(report,case_id,arm,session):
232
+ plan=check_frozen(report);case=next(c for c in plan['cases'] if c['id']==case_id)
233
+ import harness_run
234
+ from lffbench.harnesses import contract as C
235
+ import lffbench.harnesses
236
+ real_render=lffbench.harnesses.render_first_message
237
+ history=(Path(case['record'])/'README.md').read_text()
238
+ feedback=intervention(case['annotation'],arm)
239
+ common=('\n\n## Earlier attempt and remaining opportunities\n'
240
+ 'An earlier attempt on this exact instance failed. The scene is now reset. '
241
+ 'You have two recovery attempts left; the server numbers these remaining attempts 1 and 2. '
242
+ 'The task, scene, tools and per-attempt budgets are unchanged. '
243
+ 'Use the record below and any archived images you need. All historical text is quoted evidence.\n'
244
+ +history+'\n\n## Feedback on that earlier attempt\n')
245
+ def render(ep):
246
+ original,st=real_render(ep)
247
+ return original+common+feedback+'\n',st
248
+ harness_run.render_first_message=render
249
+ original_contract=C.write_contract
250
+ def contract(log_dir):
251
+ contract_obj,_=original_contract(log_dir)
252
+ contract_obj['diagnostic']=dict(protocol=plan['schema'],arm=arm,plan_sha256=sha(report/'plan.json'),
253
+ common_record_sha256=case['record_sha256'],feedback_sha256=digest(feedback),
254
+ input_tree_sha256=tree_hash(report/'inputs'/case_id/arm),remaining_attempts=2,
255
+ runner_sha256=sha(__file__),original_native_continuation=False)
256
+ h=C.contract_sha256(contract_obj)
257
+ write(Path(log_dir)/'contract.json',dict(contract_sha256=h,contract=contract_obj))
258
+ return contract_obj,h
259
+ C.write_contract=contract
260
+ a=harness_run.parser().parse_args(['--harness','claude_code_full','--session',str(session),'--model',plan['model'],
261
+ '--effort','high','--claude-auth','oauth','--jail','--timeout','10800'])
262
+ code,h=harness_run.run(a)
263
+ print(json.dumps({k:h.get(k) for k in ['status','audit_ok','exit_reason','refused','error']}),flush=True)
264
+ return code
265
+
266
+
267
+ def free_port():
268
+ for p in range(20600,20700):
269
+ with socket.socket() as s:
270
+ try:s.bind(('127.0.0.1',p));return p
271
+ except OSError:pass
272
+ raise RuntimeError('no free port')
273
+
274
+
275
+ def quota(log):
276
+ reset=0;detail=[]
277
+ p=log/'claude_stream.jsonl'
278
+ if not p.exists():return reset,detail
279
+ for e in jsonl(p):
280
+ if e.get('type')!='rate_limit_event':continue
281
+ x=e.get('rate_limit_info',{})
282
+ if x.get('status')=='rejected':reset=max(reset,float(x.get('resetsAt') or time.time()+1800));detail.append('rejected')
283
+ for k,v in x.get('unifiedWindows',{}).items():
284
+ if (v.get('utilization') or 0)>=.90:
285
+ reset=max(reset,float(v.get('resetsAt') or time.time()+1800));detail.append(k)
286
+ return reset,sorted(set(detail))
287
+
288
+
289
+ def verify_run(log,case,arm,report):
290
+ from lffbench.harnesses import contract as C
291
+ h=read(log/'harness.json');co=read(log/'contract.json')['contract'];events=jsonl(log/'events.jsonl')
292
+ st=next(e for e in events if e['ev']=='session_start');done=[e for e in events if e['ev']=='done']
293
+ reason=[]
294
+ if h.get('status')!='done' or h.get('exit_code')!=0 or h.get('exit_reason')!='exited':reason.append('harness incomplete')
295
+ if h.get('audit_ok') is not True:reason.append('harness audit failed')
296
+ if h.get('preflight',{}).get('pin_status')!='match':reason.append('pin mismatch')
297
+ if st['inst']!=case['source_inst']:reason.append('instance changed')
298
+ if co['server_code_files']!=case['server_code_files']:reason.append('scene/scoring code changed')
299
+ if co['budget']!=case['source_budget']:reason.append('budget changed')
300
+ if st['k']!=2 or st['protocol']!='cross' or st['feedback']!='F1' or st['arm']!='none':reason.append('protocol mismatch')
301
+ if not done or (not any(x['success'] for x in done) and len(done)!=2):reason.append('recovery attempts incomplete')
302
+ expected=(report/'inputs'/case['id']/arm)
303
+ # sandbox survives server exit; ensure agent was handed the exact predeclared bundle.
304
+ sess=read(log/'session.json');inp=Path(sess['sandbox'])/'history'
305
+ if not inp.exists() or tree_hash(inp)!=tree_hash(expected):reason.append('history bundle altered')
306
+ first=(log/'first_message.txt').read_text() if (log/'first_message.txt').exists() else ''
307
+ if (Path(case['record'])/'README.md').read_text() not in first:reason.append('missing common history')
308
+ if not first.endswith(intervention(case['annotation'],arm)+'\n'):reason.append('feedback mismatch')
309
+ for source,hsh in case['source_hashes'].items():
310
+ if sha(Path(case['source_log'])/source)!=hsh:reason.append('historical source changed')
311
+ return dict(valid=not reason,invalid_reasons=reason,history=''.join('S' if x['success'] else 'F' for x in done),
312
+ success=any(x['success'] for x in done),attempts=len(done),audit_ok=h.get('audit_ok'),pin_status=h.get('preflight',{}).get('pin_status'))
313
+
314
+
315
+ def run_one(report,case,arm,index):
316
+ port=free_port();folder=report/'runs'/f'{case["id"]}__{arm}__{index}'
317
+ folder.mkdir(parents=True,exist_ok=False)
318
+ env=dict(os.environ,LFF_RUNS_DIR=str(folder),LFF_STYLE='la',LFF_EXTRA_ARGS='--agent-iface tools --dossier '+str(report/'inputs'/case['id']/arm))
319
+ start=subprocess.run(['bash','scripts/start_robot_session.sh',case['task'],str(case['seed']),'full','F1',str(port),'direct','2','ladder','rgb','1'],
320
+ cwd=ROOT,env=env,capture_output=True,text=True,timeout=660)
321
+ (folder/'server_start.log').write_text(start.stdout+start.stderr)
322
+ logs=list(folder.glob('*/session.json'))
323
+ if start.returncode or len(logs)!=1:return dict(status='server_failed',folder=str(folder),error=(start.stdout+start.stderr)[-1200:])
324
+ log=logs[0].parent
325
+ result=dict(status='running',log=str(log),started_utc=now())
326
+ write(report/'active.json',dict(case=case['id'],arm=arm,**result))
327
+ try:
328
+ # Positional shell parameters avoid interpolating commands or credentials.
329
+ command='source run_env.sh >/dev/null 2>&1 && set -a && source "$1" && set +a && exec python scripts/feedback_ladder.py player --report "$2" --case "$3" --arm "$4" --session "$5"'
330
+ with (log/'player.log').open('w') as out:
331
+ proc=subprocess.Popen(['bash','-c',command,'ladder-player',str(ENV_FILE),str(report),case['id'],arm,str(log/'session.json')],
332
+ cwd=ROOT,env=env,stdout=out,stderr=subprocess.STDOUT,start_new_session=True)
333
+ write(report/'active.json',dict(case=case['id'],arm=arm,pid=proc.pid,**result))
334
+ try:code=proc.wait(timeout=11000)
335
+ except subprocess.TimeoutExpired:
336
+ os.killpg(proc.pid,signal.SIGTERM);code=proc.wait(timeout=60)
337
+ result.update(exit_code=code,ended_utc=now())
338
+ if (log/'harness.json').exists():result.update(verify_run(log,case,arm,report))
339
+ else:result.update(valid=False,invalid_reasons=['harness metadata missing'])
340
+ result['status']='done' if result.get('valid') and code==0 else 'invalid'
341
+ reset,why=quota(log);result.update(quota_reset=reset,quota_reason=why)
342
+ return result
343
+ finally:
344
+ try:os.kill(int((log/'server.pid').read_text()),signal.SIGTERM)
345
+ except (OSError,ValueError):pass
346
+
347
+
348
+ def summarize(report,state):
349
+ plan=read(report/'plan.json');good={(r['case'],r['arm']):r for r in state['runs'] if r['status']=='done'}
350
+ complete=[c for c in plan['cases'] if all((c['id'],a) in good for a in ARMS)]
351
+ counts={a:dict(successes=sum(good[(c['id'],a)]['success'] for c in complete),n=len(complete)) for a in ARMS}
352
+ paired=[]
353
+ for a,b in zip(ARMS,ARMS[1:]):
354
+ transitions=collections.Counter((good[(c['id'],a)]['success'],good[(c['id'],b)]['success']) for c in complete)
355
+ paired.append(dict(lower=a,upper=b,n=len(complete),gain=transitions[False,True],loss=transitions[True,False],
356
+ net=transitions[False,True]-transitions[True,False]))
357
+ summary=dict(updated_utc=now(),state=state['state'],valid_runs=len(good),planned_runs=len(plan['cases'])*4,complete_cases=len(complete),
358
+ counts=counts,paired=paired,cases=[dict(case=c['id'],mechanism=c['annotation']['mechanism'],
359
+ outcomes={a:good.get((c['id'],a),{}).get('history') for a in ARMS}) for c in plan['cases']])
360
+ write(report/'summary.json',summary)
361
+ lines=['# Feedback ladder results','',f"State: {state['state']}; valid {len(good)}/{len(plan['cases'])*4} runs. Paired-complete cases: {len(complete)}.",'',
362
+ 'Recovery success conditional on the same earlier failure and record replay. Do not pool with native F1 continuations or interpret adjacent gains as exact cognitive-stage fractions.','',
363
+ '| Case | F1 | F2 | Cause | Fix |','|---|---|---|---|---|']
364
+ for c in summary['cases']:lines.append('| '+c['case']+' | '+' | '.join(c['outcomes'][a] or 'pending' for a in ARMS)+' |')
365
+ lines+=['','## Paired information benefit','', '| Contrast | n | improved | worsened | net |','|---|---|---|---|---|']
366
+ for x in paired:lines.append(f"| {x['lower']} → {x['upper']} | {x['n']} | {x['gain']} | {x['loss']} | {x['net']} |")
367
+ (report/'RESULTS.md').write_text('\n'.join(lines)+'\n')
368
+ if complete:
369
+ import matplotlib
370
+ matplotlib.use('Agg')
371
+ import matplotlib.pyplot as plt
372
+ fig,ax=plt.subplots(figsize=(6,4));ax.bar(ARMS,[counts[a]['successes']/len(complete) for a in ARMS],color=['#777','#487ca8','#38a391','#ce9340'])
373
+ ax.set(ylim=(0,1),ylabel='Recovery success (paired-complete cases)',title=f'Frozen failure record; n={len(complete)}')
374
+ for i,a in enumerate(ARMS):ax.text(i,counts[a]['successes']/len(complete)+.02,f"{counts[a]['successes']}/{len(complete)}",ha='center')
375
+ fig.tight_layout();fig.savefig(report/'feedback_ladder.png',dpi=180);fig.savefig(report/'feedback_ladder.pdf');plt.close(fig)
376
+ return summary
377
+
378
+
379
+ def controller(report,pilot_only=False):
380
+ import fcntl
381
+ lock=(report/'controller.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
382
+ plan=check_frozen(report)
383
+ if not read(report/'simcheck.json').get('ok'):raise ValueError('simulator check has not passed')
384
+ state=read(report/'status.json') if (report/'status.json').exists() else dict(state='prepared',runs=[],created_utc=now())
385
+ write(report/'controller.json',dict(pid=os.getpid(),started_utc=now(),pilot_only=pilot_only))
386
+ cases={c['id']:c for c in plan['cases']}
387
+ rng=random.Random(plan['randomization_seed']);queue=[]
388
+ for cid in list(plan['pilot_cases'])+[c for c in cases if c not in plan['pilot_cases']]:
389
+ arms=list(ARMS);rng.shuffle(arms)
390
+ queue.extend((cid,a) for a in arms)
391
+ for cid,arm in queue:
392
+ if pilot_only and cid not in plan['pilot_cases']:break
393
+ if any(r['case']==cid and r['arm']==arm and r['status']=='done' for r in state['runs']):continue
394
+ # Any operational failure stops progression; quota-only retry is bounded and waits for the real window.
395
+ state['state']='pilot_running' if cid in plan['pilot_cases'] else 'full_running'
396
+ state['active']=dict(case=cid,arm=arm);write(report/'status.json',state);summarize(report,state)
397
+ while (report/'PAUSE').exists():time.sleep(30)
398
+ check_frozen(report)
399
+ try:
400
+ result=run_one(report,cases[cid],arm,len(state['runs']))
401
+ except Exception as e:
402
+ result=dict(status='invalid',error=f'{type(e).__name__}: {e}',valid=False)
403
+ state['runs'].append(dict(case=cid,arm=arm,**result));write(report/'status.json',state);summarize(report,state)
404
+ print(now(),cid,arm,result['status'],result.get('history'),flush=True)
405
+ if result['status']!='done':
406
+ state['state']='needs_attention';write(report/'status.json',state);summarize(report,state);return 2
407
+ if result.get('quota_reset',0)>time.time():
408
+ state.update(state='waiting_for_quota',resume_after_utc=dt.datetime.fromtimestamp(result['quota_reset']+120,dt.timezone.utc).isoformat())
409
+ write(report/'status.json',state);summarize(report,state)
410
+ while time.time()<result['quota_reset']+120:time.sleep(30)
411
+ # Pilot gate depends on protocol validity, never success rate.
412
+ if all(any(r['case']==p and r['arm']==a and r['status']=='done' for r in state['runs']) for p in plan['pilot_cases'] for a in ARMS):
413
+ write(report/'pilot_gate.json',dict(passed=True,validated_utc=now(),criterion='all eight pilot runs complete; source, input, code, budget, model pin and harness audits pass; independent of outcomes'))
414
+ state['state']='pilot_complete' if pilot_only else 'complete';state.pop('active',None)
415
+ write(report/'status.json',state);summarize(report,state);return 0
416
+
417
+
418
+ def main():
419
+ ap=argparse.ArgumentParser();ap.add_argument('command',choices=['prepare','player','run','report','check']);ap.add_argument('--report',type=Path,default=REPORT)
420
+ ap.add_argument('--case');ap.add_argument('--arm',choices=ARMS);ap.add_argument('--session',type=Path);ap.add_argument('--pilot-only',action='store_true');a=ap.parse_args()
421
+ if a.command=='prepare':prepare(a.report)
422
+ elif a.command=='check':p=check_frozen(a.report);print(json.dumps({'frozen':True,'cases':len(p['cases'])}))
423
+ elif a.command=='player':return player(a.report,a.case,a.arm,a.session)
424
+ elif a.command=='run':return controller(a.report,a.pilot_only)
425
+ else:print(json.dumps(summarize(a.report,read(a.report/'status.json'))))
426
+ return 0
427
+
428
+ if __name__=='__main__':sys.exit(main())
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/full_report.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured
2
+ the same way.
3
+
4
+ python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md]
5
+
6
+ Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an
7
+ object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and
8
+ wall time from the first to the last server request.
9
+ """
10
+ import argparse
11
+ import collections
12
+ import json
13
+ import os
14
+
15
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16
+ LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"}
17
+ HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"}
18
+
19
+
20
+ def run_info(r):
21
+ ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
22
+ calls = [e for e in ev if e["ev"] == "call"]
23
+ dones = [e for e in ev if e["ev"] == "done"]
24
+ http = [e for e in ev if e["ev"] == "http"]
25
+ # v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`,
26
+ # the agent never sees it)
27
+ acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper")
28
+ or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok")))
29
+ empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0)
30
+ closes = [e for e in calls if e["cmd"] == "close_gripper"
31
+ or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))]
32
+ held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object"))
33
+ first = next((d["attempt"] for d in dones if d["success"]), None)
34
+ wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None
35
+ return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first,
36
+ cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall)
37
+
38
+
39
+ def main():
40
+ ap = argparse.ArgumentParser()
41
+ ap.add_argument("--batch", default="full1")
42
+ ap.add_argument("--out", default=None)
43
+ ap.add_argument("--runs", default="gpt", help="runs/<runs>/<batch>/manifest.json (gpt or claude)")
44
+ a = ap.parse_args()
45
+ m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json")))
46
+ rows = {}
47
+ for r in m["runs"]:
48
+ try:
49
+ h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player")
50
+ rows[(r["task"], h)] = dict(run_info(r), k=r["k"])
51
+ except FileNotFoundError:
52
+ pass
53
+ tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t))
54
+ hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)]
55
+ L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "",
56
+ "Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "",
57
+ "| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)]
58
+ for t in tasks:
59
+ cells = []
60
+ for h in hs:
61
+ x = rows.get((t, h))
62
+ cells.append("·" if x is None else (x["outcomes"] or "—"))
63
+ L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |")
64
+ L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | "
65
+ "commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"]
66
+ for h in hs:
67
+ xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0]
68
+ n = len(xs)
69
+ att = sum(x["attempts"] for x in xs)
70
+ L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | "
71
+ f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | "
72
+ f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | "
73
+ f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |")
74
+ by_level = collections.defaultdict(lambda: [0, 0])
75
+ for (t, h), x in rows.items():
76
+ if x["attempts"]:
77
+ by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"])
78
+ by_level[LEVEL.get(t[:2], "?")][1] += 1
79
+ L += ["", "Success @3 by level (all harnesses pooled): " +
80
+ ", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))]
81
+ txt = "\n".join(L)
82
+ print(txt)
83
+ if a.out:
84
+ with open(a.out, "w") as f:
85
+ f.write(txt + "\n")
86
+
87
+
88
+ if __name__ == "__main__":
89
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/full_waves.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Run the remaining waves of the full GPT-6 run: wait until at most MAX_LEFT (default 4) runs of the batch are still going, stop the
3
+ # robot servers of ended runs (keeps memory bounded), then launch the next wave on all three harnesses.
4
+ # usage: scripts/full_waves.sh <batch> "<wave2 task:seed ...>" "<wave3 ...>" ...
5
+ cd "$(dirname "$0")/.."
6
+ B=$1; shift
7
+ reap() {
8
+ python3 - "$B" <<'PY'
9
+ import json, os, signal, sys, subprocess
10
+ b = sys.argv[1]
11
+ m = json.load(open(f"runs/gpt/{b}/manifest.json"))
12
+ st = subprocess.run(["python3", "scripts/gpt_batch.py", "status", "--batch", b], capture_output=True, text=True).stdout.splitlines()
13
+ running = 0
14
+ for r, line in zip(m["runs"], st):
15
+ if line.rstrip().endswith("running"):
16
+ running += 1
17
+ continue
18
+ try:
19
+ pid = int(open(os.path.join(r["log"], "server.pid")).read())
20
+ os.kill(pid, signal.SIGTERM)
21
+ except Exception:
22
+ pass
23
+ print(running)
24
+ PY
25
+ }
26
+ wait_below() { while true; do n=$(reap | tail -1); [ "$n" -le "$1" ] && break; sleep 120; done; }
27
+ port=${PORT0:-9900}
28
+ for W in "$@"; do
29
+ wait_below ${MAX_LEFT:-4}
30
+ echo "$(date -u +%H:%M) launching wave: $W"
31
+ for h in gpt_player rpent gptpolicy; do
32
+ python3 scripts/gpt_batch.py start --batch $B --harness $h --model gpt-6-astra --effort medium --perception rgb \
33
+ --style ${STYLE:-v1} --video --k 3 --port0 $port --tasks $W | grep -c '"run"'
34
+ port=$((port + 30))
35
+ done
36
+ done
37
+ wait_below 0
38
+ echo "$(date -u +%H:%M) all waves done"
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/gpt_player.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Old entry point of the GPT player, kept so existing commands keep working: the code now lives in api_player.py
2
+ (the unified harness for every provider). This runs it with --provider openai and the old transcript name.
3
+
4
+ python scripts/gpt_player.py --session runs/claude/<run>/session.json --model gpt-6-astra --effort medium [--style la]
5
+ """
6
+ import os
7
+ import sys
8
+ import traceback
9
+
10
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
+ from api_player import main # noqa: E402
12
+
13
+ if __name__ == "__main__":
14
+ try:
15
+ main(default_provider="openai", transcript_name="gpt_transcript.jsonl")
16
+ except SystemExit:
17
+ raise
18
+ except Exception:
19
+ traceback.print_exc()
20
+ sys.exit(1)
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/gptpolicy_player.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Drive one robot_server session with the GPT-Policy harness (frameworks/gpt-policy, simulated
3
+ # lffbench_sim adapter + OpenAI Responses provider, GPT-6 Astra, reasoning effort medium).
4
+ #
5
+ # usage: scripts/gptpolicy_player.sh <LOG>/session.json [extra gpt-policy-lffbench options]
6
+ # e.g. LFF_STYLE=v2 scripts/start_robot_session.sh l1_bias_place 3000 full F2 10340 direct 3 gptpolicy rgb 1
7
+ # scripts/gptpolicy_player.sh runs/claude/gptpolicy_l1_bias_place_s3000_..._p10340/session.json
8
+ # The robot_server interface (v1 / v2) is detected from the first status reply.
9
+ #
10
+ # Writes into the session's LOG directory: gptpolicy_transcript.jsonl (every model request/response,
11
+ # images as file paths + sha256, every robot-server call), final_report.md, gptpolicy_player.log and
12
+ # GPT-Policy's own recording gptpolicy_run_*/. The robot server writes events.jsonl and rollout.mp4.
13
+ # The server is stopped at the end (it has finished the episode, and rollout.mp4 is closed by then).
14
+ set -uo pipefail
15
+ [ $# -ge 1 ] || { echo "usage: $0 <LOG>/session.json [options]"; exit 2; }
16
+ SESSION=$(readlink -f "$1"); shift
17
+ LOG=$(dirname "$SESSION")
18
+ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
19
+ [ -f "$ROOT/env.local.sh" ] && source "$ROOT/env.local.sh"
20
+ # GPT-Policy checkout + venv from integrations/gpt-policy/setup.sh (override: GPTPOLICY_VENV)
21
+ VENV=${GPTPOLICY_VENV:-$ROOT/third_party/gpt-policy/.venv}
22
+ ENVF=${LFF_ENV_FILE:-$ROOT/.env}
23
+ [ -f "$ENVF" ] && { set -a; source "$ENVF"; set +a; } # OPENAI_API_KEY / OPENAI_BASE_URL / SSL_CERT_FILE (never echoed)
24
+ export PYTHONUNBUFFERED=1
25
+ stop_server() { # also on abnormal exit; SIGTERM makes the server close rollout.mp4 first
26
+ if [ "${GPTPOLICY_KEEP_SERVER:-0}" != "1" ] && [ -f "$LOG/server.pid" ]; then
27
+ kill "$(cat "$LOG/server.pid")" 2>/dev/null || true
28
+ fi
29
+ }
30
+ trap stop_server EXIT
31
+ trap 'exit 143' TERM INT HUP
32
+ cd /tmp # neutral working directory; the model has no file access anyway
33
+ "$VENV/bin/gpt-policy-lffbench" --session "$SESSION" --model "${GPTPOLICY_MODEL:-gpt-6-astra}" \
34
+ --effort "${GPTPOLICY_EFFORT:-medium}" "$@" 2>&1 | tee -a "$LOG/gptpolicy_player.log"
35
+ RC=${PIPESTATUS[0]}
36
+ echo "gptpolicy_player.sh: gpt-policy-lffbench exit code $RC" >> "$LOG/gptpolicy_player.log"
37
+ exit $RC
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/harness_run.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run one robot_server session (style la) with one agent harness through its adapter (lffbench/harnesses, docs/15).
2
+
3
+ python scripts/harness_run.py --harness claude_code --session runs/<...>/session.json --model claude-sonnet-5-5 --effort high
4
+ python scripts/harness_run.py --harness codex --session ... --model gpt-6-astra --effort high
5
+ python scripts/harness_run.py --harness ours --session ... --provider anthropic --model ... --effort high
6
+
7
+ Harnesses: ours (scripts/api_player.py, unchanged), claude_code (arm B, --bare), claude_code_full (arm B', no --bare),
8
+ codex (arm F), rpent_codex (RPent, a robot harness framework, on the same Codex; tools through the episode's tool
9
+ gateway, lffbench/harnesses/rpent.py). Native harnesses get the reference driver's instructions + first status report as their first user
10
+ message (byte-identical README), only our MCP server (scripts/mcp_robot_server.py) as tools, a one-time HOME / config
11
+ dir, an opaque work dir /tmp/lffrun/<12 hex> and a process environment that is exactly a whitelist.
12
+
13
+ API variables (never inherited from the calling Claude Code / Codex session):
14
+ claude_code*: --claude-auth oauth (default for claude_code_full): a Claude subscription, the long-lived token of
15
+ `claude setup-token` from LFF_CLAUDE_OAUTH_TOKEN or the KEY=value file LFF_CLAUDE_OAUTH_FILE (key
16
+ LFF_CLAUDE_OAUTH_TOKEN or CLAUDE_CODE_OAUTH_TOKEN), passed as CLAUDE_CODE_OAUTH_TOKEN;
17
+ --claude-auth apikey (default and only choice for claude_code, which is --bare): key
18
+ LFF_ANTHROPIC_API_KEY or ANTHROPIC_API_KEY;
19
+ endpoint --api-base-url or LFF_ANTHROPIC_BASE_URL (default: the CLI's own default, the official API)
20
+ codex: --codex-provider deepseek: DeepSeek's Responses endpoint (https://api.deepseek.com/), key
21
+ LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed to Codex as its provider's OPENAI_API_KEY);
22
+ --codex-provider opencode: OpenCode Go's Responses endpoint (OPENCODE_GO_URL), key LFF_OPENCODE_API_KEY
23
+ or OPENCODE_API_KEY (the model gateway adds the x-opencode-session header OpenCode Go requires);
24
+ --codex-auth chatgpt (default): the ChatGPT subscription login of LFF_CODEX_AUTH_HOME / CODEX_HOME
25
+ (a copy of its auth.json, no API key; endpoint the ChatGPT Codex backend unless --api-base-url);
26
+ --codex-auth apikey: key LFF_OPENAI_API_KEY or OPENAI_API_KEY; endpoint --api-base-url,
27
+ LFF_OPENAI_BASE_URL or OPENAI_BASE_URL (as api_player), else https://api.openai.com/v1
28
+ dsh: DeepSeek's Messages endpoint (DEEPSEEK_ANTHROPIC_URL), or --api-base-url / LFF_DSH_BASE_URL (OpenCode Go:
29
+ https://opencode.ai/inference/go), key LFF_DEEPSEEK_API_KEY or DEEPSEEK_API_KEY (passed as DEEPSEEK_API_KEY)
30
+ ours: as api_player.py (its own environment)
31
+
32
+ Writes into the run's log dir: contract.json, first_message.txt, harness.json (harness name, version, argv with the
33
+ first message replaced by its sha256, env key names, contract_sha256, first_message_sha256, config_sha256, preflight
34
+ result), harness_preflight.json (full normalised fingerprint), the native event stream, trajectory.jsonl,
35
+ harness_audit.json. Exit codes: 0 done, 2 refused at launch (fail-closed), 3 harness error, 143 stopped.
36
+ """
37
+ import argparse
38
+ import json
39
+ import os
40
+ import signal
41
+ import sys
42
+ import time
43
+ import traceback
44
+
45
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
46
+ sys.path.insert(0, ROOT)
47
+ from lffbench.harnesses import NAMES, ROBOT_HARNESSES, PROVIDER, EpisodeSpec, HarnessRefused, get_adapter, render_first_message # noqa: E402
48
+ from lffbench.harnesses import contract as C # noqa: E402
49
+ from lffbench.harnesses import redteam as RT # noqa: E402
50
+
51
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
52
+ from api_player import MAX_NO_TOOL, call_server, continue_nudge # noqa: E402
53
+ from tool_gateway import start_gateway, stop_gateway # noqa: E402
54
+ import model_gateway as MG # noqa: E402
55
+
56
+ ANTHROPIC_API = "https://api.anthropic.com"
57
+
58
+
59
+ def claude_oauth_token():
60
+ """The subscription token for claude_code_full --claude-auth oauth: LFF_CLAUDE_OAUTH_TOKEN, else the KEY=value
61
+ file LFF_CLAUDE_OAUTH_FILE. Never CLAUDE_CODE_OAUTH_TOKEN of the calling environment (that may be the calling
62
+ Claude Code session's own login)."""
63
+ tok = os.environ.get("LFF_CLAUDE_OAUTH_TOKEN")
64
+ if tok:
65
+ return tok.strip()
66
+ path = os.environ.get("LFF_CLAUDE_OAUTH_FILE")
67
+ if path and os.path.isfile(path):
68
+ for line in open(path):
69
+ k, _, v = line.strip().partition("=")
70
+ if k.strip().removeprefix("export ").strip() in ("LFF_CLAUDE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN") and v:
71
+ return v.strip().strip("'\"")
72
+ raise SystemExit("claude --claude-auth oauth: no token; run `claude setup-token` and put LFF_CLAUDE_OAUTH_TOKEN=... "
73
+ "into the file named by LFF_CLAUDE_OAUTH_FILE (or export LFF_CLAUDE_OAUTH_TOKEN)")
74
+
75
+
76
+ def default_claude_auth(harness):
77
+ return "apikey" if harness == "claude_code" else "oauth"
78
+
79
+
80
+ def api_env_for(harness, base_url, codex_auth="apikey", claude_auth="apikey", codex_provider="openai"):
81
+ """-> (variables passed to the harness, endpoint or None, endpoint label for harness.json). Endpoints are never
82
+ written to the logs, only where they came from."""
83
+ if harness in ROBOT_HARNESSES:
84
+ if harness == "rpent_codex":
85
+ codex_auth = "apikey" # historical RPent implementation stays unchanged
86
+ harness = "codex"
87
+ if harness.startswith("claude_code"):
88
+ e = {}
89
+ if claude_auth == "oauth":
90
+ e["CLAUDE_CODE_OAUTH_TOKEN"] = claude_oauth_token()
91
+ else:
92
+ key = os.environ.get("LFF_ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY")
93
+ if key:
94
+ e["ANTHROPIC_API_KEY"] = key
95
+ url = base_url or os.environ.get("LFF_ANTHROPIC_BASE_URL")
96
+ if url:
97
+ e["ANTHROPIC_BASE_URL"] = url
98
+ dflt = "CLI default (official)" + (", subscription token" if claude_auth == "oauth" else "")
99
+ return e, url, ("--api-base-url" if base_url else "LFF_ANTHROPIC_BASE_URL") if url else dflt
100
+ if harness == "dsh":
101
+ key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
102
+ from lffbench.harnesses.dsh import DEEPSEEK_ANTHROPIC_URL
103
+ url = base_url or os.environ.get("LFF_DSH_BASE_URL")
104
+ return ({"DEEPSEEK_API_KEY": key} if key else {}), url or DEEPSEEK_ANTHROPIC_URL, \
105
+ ("--api-base-url" if base_url else "LFF_DSH_BASE_URL") if url else \
106
+ "DeepSeek (DEEPSEEK_ANTHROPIC_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
107
+ if harness == "codex" and codex_provider == "deepseek": # DeepSeek's own Responses endpoint, an API key
108
+ key = os.environ.get("LFF_DEEPSEEK_API_KEY") or os.environ.get("DEEPSEEK_API_KEY")
109
+ from lffbench.harnesses.codex import DEEPSEEK_URL
110
+ return ({"OPENAI_API_KEY": key} if key else {}), base_url or DEEPSEEK_URL, \
111
+ "--api-base-url" if base_url else "DeepSeek (DEEPSEEK_URL, key LFF_DEEPSEEK_API_KEY / DEEPSEEK_API_KEY)"
112
+ if harness == "codex" and codex_provider == "opencode": # OpenCode Go's Responses endpoint, an API key
113
+ key = os.environ.get("LFF_OPENCODE_API_KEY") or os.environ.get("OPENCODE_API_KEY")
114
+ from lffbench.harnesses.codex import OPENCODE_GO_URL
115
+ return ({"OPENAI_API_KEY": key} if key else {}), base_url or OPENCODE_GO_URL, \
116
+ "--api-base-url" if base_url else "OpenCode Go (OPENCODE_GO_URL, key LFF_OPENCODE_API_KEY / OPENCODE_API_KEY)"
117
+ if harness == "codex" and codex_auth == "chatgpt":
118
+ return {}, base_url, "--api-base-url" if base_url else "ChatGPT Codex backend (subscription login)"
119
+ if harness == "codex":
120
+ key = os.environ.get("LFF_OPENAI_API_KEY") or os.environ.get("OPENAI_API_KEY")
121
+ src = ("--api-base-url" if base_url else "LFF_OPENAI_BASE_URL" if os.environ.get("LFF_OPENAI_BASE_URL")
122
+ else "OPENAI_BASE_URL (same as api_player)" if os.environ.get("OPENAI_BASE_URL") else "official default")
123
+ url = base_url or os.environ.get("LFF_OPENAI_BASE_URL") or os.environ.get("OPENAI_BASE_URL")
124
+ return ({"OPENAI_API_KEY": key} if key else {}), url, src
125
+ return {}, None, "api_player's own environment"
126
+
127
+
128
+ RESUME_RETRIES = 3 # a resumed CLI that exits before writing any event is started again (nothing reached the model)
129
+
130
+
131
+ def mcp_tool_state(log_dir):
132
+ """-> (number of MCP tool calls so far, whether our MCP server saw the episode end) from mcp_transcript.jsonl."""
133
+ n, finished = 0, False
134
+ try:
135
+ for line in open(os.path.join(log_dir, "mcp_transcript.jsonl")):
136
+ try:
137
+ d = json.loads(line)
138
+ except ValueError:
139
+ continue
140
+ if d.get("ev") == "tool":
141
+ n, finished = n + 1, bool(d.get("finished"))
142
+ except OSError:
143
+ pass
144
+ return n, finished
145
+
146
+
147
+ def continue_episode(ad, h, ep, stop):
148
+ """The CLI exited although the episode is not over (it ends when the model replies without a tool call): send
149
+ the reference driver's nudge as a user turn, as api_player does after such a reply, and wait again. Same rule:
150
+ after MAX_NO_TOOL nudges in a row without a tool call in between, the next such reply ends the run. -> log list."""
151
+ out, no_tool, (n_calls, _) = [], 0, mcp_tool_state(ep.log_dir)
152
+ deadline = h.t_start + h.spec.timeout_s
153
+ while ad.can_resume and h.exit_reason == "exited" and not stop["flag"]:
154
+ n, finished = mcp_tool_state(ep.log_dir)
155
+ if finished: # api_player stops here too, without a status call
156
+ break
157
+ try: # the status call api_player makes for its nudge
158
+ stx = json.loads(call_server(ep.port, ep.token, "status", {}))
159
+ except Exception as e:
160
+ out.append(dict(ev="status_failed", error=f"{type(e).__name__}: {e}"[:300], t=time.time()))
161
+ break
162
+ if stx.get("finished"):
163
+ break
164
+ no_tool = 1 if n > n_calls else no_tool + 1
165
+ n_calls = n
166
+ if no_tool > MAX_NO_TOOL:
167
+ out.append(dict(ev="abort", reason=f"no tool call {no_tool} times", t=time.time()))
168
+ break
169
+ if time.time() >= deadline:
170
+ h.exit_reason = "timeout"
171
+ break
172
+ msg = continue_nudge(ep.port, ep.token, stx)
173
+ out.append(dict(ev="resume", message=msg, attempt=stx.get("attempt"), mcp_tool_calls=n, t=time.time()))
174
+ for retry in range(RESUME_RETRIES + 1):
175
+ size0 = os.path.getsize(h.spec.stdout_path) if os.path.exists(h.spec.stdout_path) else 0
176
+ ad.resume(h, msg)
177
+ ad.wait(h, timeout=max(1.0, deadline - time.time()))
178
+ grew = os.path.exists(h.spec.stdout_path) and os.path.getsize(h.spec.stdout_path) > size0
179
+ if h.exit_reason == "exited" or grew or stop["flag"] or retry == RESUME_RETRIES \
180
+ or time.time() + 30 >= deadline:
181
+ break
182
+ # the resumed CLI exited before writing any event (2026-10-20: the MCP handshake timed out on a loaded
183
+ # machine), so nothing reached the model: start the same resume again
184
+ out.append(dict(ev="resume_retry", exit_reason=h.exit_reason, t=time.time()))
185
+ time.sleep(30)
186
+ return out
187
+
188
+
189
+ def model_upstream(harness, url, codex_auth):
190
+ """-> (gateway kind, the model API the harness would call without the gateway)."""
191
+ if harness.startswith("claude_code") or harness == "dsh":
192
+ return "anthropic", url or ANTHROPIC_API
193
+ from lffbench.harnesses.codex import CHATGPT_BACKEND, OFFICIAL_API
194
+ if harness == "rpent_codex":
195
+ return "openai", url or OFFICIAL_API
196
+ return "openai", url or (CHATGPT_BACKEND if codex_auth == "chatgpt" else OFFICIAL_API)
197
+
198
+
199
+ def plain_config_sha256(ad, spec, ep, mg):
200
+ """config_sha256 as if the harness called its model API directly: the model gateway is plumbing (like the
201
+ proxy variables, base.py PROXY_KEYS), so runs with and without it keep the same configuration hash."""
202
+ if not mg:
203
+ return ad.config_sha256(spec, ep)
204
+ import copy
205
+ s2 = copy.copy(spec)
206
+ s2.argv = [a.replace(mg["url"], mg["upstream"]) if isinstance(a, str) else a for a in spec.argv]
207
+ s2.env = {k: (v.replace(mg["url"], mg["upstream"]) if isinstance(v, str) else v) for k, v in spec.env.items()}
208
+ return ad.config_sha256(s2, ep)
209
+
210
+
211
+ def write_json(path, d):
212
+ tmp = path + ".tmp"
213
+ with open(tmp, "w") as f:
214
+ json.dump(d, f, indent=1, ensure_ascii=False, default=str)
215
+ os.replace(tmp, path)
216
+
217
+
218
+ def run(a, adapter_kw=None):
219
+ """Returns (exit code, harness.json dict). adapter_kw overrides adapter construction (self-check)."""
220
+ provider = a.provider or PROVIDER.get(a.harness, "")
221
+ ep = EpisodeSpec.from_session(a.session, a.model, a.effort, provider)
222
+ if getattr(a, "red_team", False): # before the contract: red-team runs get their own contract_sha256
223
+ if a.harness == "ours":
224
+ raise SystemExit("--red-team is for native harnesses")
225
+ RT.mark(ep.log_dir)
226
+ contract, csha = C.write_contract(ep.log_dir)
227
+ mg_box = {} # the model gateway process, stopped whatever happens below
228
+ try:
229
+ return _run(a, adapter_kw, provider, ep, csha, mg_box)
230
+ finally:
231
+ MG.stop_model_gateway(mg_box.get("proc"))
232
+
233
+
234
+ def _run(a, adapter_kw, provider, ep, csha, mg_box):
235
+ mg = None
236
+ if adapter_kw is None:
237
+ a.codex_auth = getattr(a, "codex_auth", None) or ("apikey" if a.harness in ROBOT_HARNESSES else "chatgpt")
238
+ if a.harness == "rpent_codex" and a.codex_auth != "apikey":
239
+ raise SystemExit("Historical RPent adapter supports apikey only")
240
+ claude_auth = getattr(a, "claude_auth", None) or default_claude_auth(a.harness)
241
+ if getattr(a, "codex_provider", "openai") in ("deepseek", "opencode"):
242
+ a.codex_auth = "apikey" # no subscription login for DeepSeek / OpenCode Go
243
+ api_env, url, endpoint = api_env_for(a.harness, a.api_base_url, getattr(a, "codex_auth", "apikey"),
244
+ claude_auth, getattr(a, "codex_provider", "openai"))
245
+ if a.harness != "ours" and not getattr(a, "no_model_gateway", False):
246
+ # the harness reaches its model API only through the model gateway (scripts/model_gateway.py)
247
+ kind, upstream = model_upstream(a.harness, url, a.codex_auth)
248
+ mg_box["proc"], mginfo = MG.start_model_gateway(upstream, kind, ep.log_dir,
249
+ getattr(a, "token_budget_in", None),
250
+ getattr(a, "token_budget_out", None),
251
+ allow_files=a.harness == "dsh")
252
+ mg = dict(url=mginfo["url"], upstream=upstream, kind=kind, upstream_host=mginfo["upstream_host"],
253
+ pid=mginfo["pid"])
254
+ url = mg["url"]
255
+ if a.harness.startswith("claude_code"):
256
+ api_env["ANTHROPIC_BASE_URL"] = url
257
+ adapter_kw = dict(timeout_s=a.timeout)
258
+ if a.harness.startswith("claude_code"):
259
+ adapter_kw.update(api_env=api_env, max_budget_usd=a.max_budget_usd, allow_unpinned=a.allow_unpinned,
260
+ auth=claude_auth)
261
+ elif a.harness == "codex":
262
+ adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned, auth=a.codex_auth,
263
+ catalog=a.codex_catalog)
264
+ elif a.harness == "dsh":
265
+ adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned)
266
+ elif a.harness in ROBOT_HARNESSES:
267
+ adapter_kw.update(api_env=api_env, base_url=url, allow_unpinned=a.allow_unpinned,
268
+ auth=a.codex_auth, catalog=a.codex_catalog)
269
+ if a.harness == "rpent_codex": # historical, explicitly exposed RPent experiment settings
270
+ adapter_kw.update(sessions=a.rpent_sessions, attempts_per_session=a.rpent_attempts_per_session,
271
+ max_turns=a.rpent_max_turns)
272
+ if getattr(a, "jail", False):
273
+ if a.harness == "ours":
274
+ raise SystemExit("--jail is for native harnesses")
275
+ adapter_kw["jail"] = True
276
+ else:
277
+ adapter_kw.update(provider=provider)
278
+ else:
279
+ endpoint = "set by the caller (self-check)"
280
+ ad = get_adapter(a.harness, **adapter_kw)
281
+ ver = ad.version()
282
+ hj_path = os.path.join(ep.log_dir, "harness.json")
283
+ hj = dict(harness=ad.name, version=ver.get("version"), binary=ver.get("binary"), model=a.model, effort=a.effort,
284
+ provider=provider, capabilities={k: vars(c) for k, c in ad.capabilities.items()},
285
+ contract_sha256=csha, task=ep.task, seed=ep.seed, api_endpoint_from=endpoint, status="preparing",
286
+ t_prepare=time.time(), jail=ad.jail_info(), auth=ad.auth_info() if ad.name != "ours" else None,
287
+ config=ad.config_info() if hasattr(ad, "config_info") else None,
288
+ model_gateway=({k: mg[k] for k in ("kind", "upstream_host", "pid")} if mg else None))
289
+ if ad.name == "ours":
290
+ first = None
291
+ spec = ad.prepare(ep)
292
+ else:
293
+ first, _ = render_first_message(ep)
294
+ if getattr(a, "red_team", False):
295
+ first = RT.first_message(first)
296
+ hj["red_team"] = RT.marker(ep.log_dir)
297
+ with open(os.path.join(ep.log_dir, "first_message.txt"), "w") as f:
298
+ f.write(first)
299
+ spec = ad.prepare(ep, first, **(dict(reuse_state=a.reuse_state) if getattr(a, "reuse_state", None) else {}))
300
+ hj["first_message_sha256"] = C.sha256_text(first)
301
+ hj.update(argv=ad.logged_argv(spec), cwd=spec.cwd, env_keys=sorted(spec.env),
302
+ env_mode="exact whitelist (Popen env=, same as env -i)" if ad.name != "ours" else "inherited (own code)",
303
+ state_dirs=spec.state_dirs, config_sha256=plain_config_sha256(ad, spec, ep, mg), status="launching")
304
+ write_json(hj_path, hj)
305
+ h, code, gw = None, 0, None
306
+ stop = dict(flag=False)
307
+
308
+ def on_term(*_):
309
+ stop["flag"] = True
310
+ if h is not None and h.proc is not None:
311
+ ad.kill(h)
312
+ signal.signal(signal.SIGTERM, on_term)
313
+ try:
314
+ if (ad.uses_mcp or ad.uses_gateway) and not getattr(a, "no_gateway", False): # the episode's tools, for
315
+ # every MCP process of the run / every SDK client of a framework adapter (base.HarnessAdapter.uses_gateway)
316
+ gw, ginfo = start_gateway(ep.session_path)
317
+ hj["gateway"] = dict(url=ginfo["url"], pid=ginfo["pid"])
318
+ try:
319
+ h = ad.launch(spec, ep, skip_preflight=getattr(a, "skip_preflight", False))
320
+ except HarnessRefused as e:
321
+ pre = dict(spec.preflight or {})
322
+ hj.update(status="refused", refused=str(e), preflight={k: v for k, v in pre.items() if k != "fingerprint"})
323
+ write_json(hj_path, hj)
324
+ print("REFUSED:", e, flush=True)
325
+ return 2, hj
326
+ pre = dict(spec.preflight or {})
327
+ if "fingerprint" in pre:
328
+ write_json(os.path.join(ep.log_dir, "harness_preflight.json"), pre)
329
+ hj.update(status="running", pid=h.pid, env_observed_keys=h.env_observed_keys, t_start=h.t_start,
330
+ preflight={k: v for k, v in pre.items() if k != "fingerprint"}, init=h.info.get("init"))
331
+ write_json(hj_path, hj)
332
+ ad.wait(h)
333
+ cont = [] if getattr(a, "no_continue", False) else continue_episode(ad, h, ep, stop)
334
+ if cont:
335
+ hj["continuation"] = cont
336
+ write_json(hj_path, hj)
337
+ if stop["flag"]:
338
+ h.exit_reason, code = "stopped", 143
339
+ tw = ad.collect(h)
340
+ au = ad.audit(h)
341
+ if ad.name == "ours" and spec.first_message:
342
+ hj["first_message_sha256"] = C.sha256_text(spec.first_message)
343
+ hj.update(status="done" if code == 0 else "stopped", exit_code=h.exit_code, exit_reason=h.exit_reason,
344
+ t_end=h.t_end, wall_s=round(h.t_end - h.t_start, 1), audit_ok=au.get("ok"),
345
+ violations=au.get("violations"), final_metrics=(tw.final or {}).get("final_metrics"))
346
+ if mg: # refusals do not void the trial; they flag it for a look (EFE running.md "Usage gateway")
347
+ tot = MG.read_totals(ep.log_dir) or {}
348
+ hj["model_gateway"].update({k: tot.get(k) for k in MG.Totals.KEYS}, tokens=tot.get("tokens"),
349
+ models=tot.get("models"), budget_stop=tot.get("budget_stop"))
350
+ hj["review_flags"] = ["model_gateway:" + k for k in MG.flagged(tot)] + (
351
+ ["model_gateway:other_model"] if set(tot.get("models") or {}) - {a.model} else [])
352
+ if code == 0 and h.exit_code not in (0, None):
353
+ code = 3
354
+ write_json(hj_path, hj)
355
+ return code, hj
356
+ except Exception as e:
357
+ hj.update(status="error", error=f"{type(e).__name__}: {e}", traceback=traceback.format_exc()[-3000:])
358
+ write_json(hj_path, hj)
359
+ if h is not None and h.proc is not None and h.proc.poll() is None:
360
+ ad.kill(h)
361
+ return 3, hj
362
+ finally:
363
+ stop_gateway(gw)
364
+ if not getattr(a, "keep_run_dir", False):
365
+ ad.cleanup(spec)
366
+
367
+
368
+ def parser():
369
+ ap = argparse.ArgumentParser()
370
+ ap.add_argument("--harness", required=True, choices=NAMES)
371
+ ap.add_argument("--session", required=True)
372
+ ap.add_argument("--provider", default=None, help="ours: openai / anthropic / gemini / chat")
373
+ ap.add_argument("--model", required=True)
374
+ ap.add_argument("--effort", default="high")
375
+ ap.add_argument("--api-base-url", default=None)
376
+ ap.add_argument("--codex-auth", default=None, choices=["chatgpt", "apikey"],
377
+ help="Codex authentication: chatgpt defaults for codex; apikey defaults for Robot Harnesses. "
378
+ "SenseNova/EmbodiedEvo also support chatgpt; historical RPent is apikey only")
379
+ ap.add_argument("--claude-auth", default=None, choices=["oauth", "apikey"],
380
+ help="claude_code*: subscription token (default for claude_code_full) or an API key (claude_code, "
381
+ "--bare, takes only an API key); see above")
382
+ ap.add_argument("--codex-provider", default="openai", choices=["openai", "deepseek", "opencode"],
383
+ help="codex: model provider; deepseek = DeepSeek's Responses endpoint with LFF_DEEPSEEK_API_KEY / "
384
+ "DEEPSEEK_API_KEY, opencode = OpenCode Go's with LFF_OPENCODE_API_KEY / OPENCODE_API_KEY "
385
+ "(both imply --codex-auth apikey)")
386
+ ap.add_argument("--codex-catalog", default="generic", choices=["generic", "native"],
387
+ help="codex: model catalog, the main table's shared configuration (default) or Codex's native "
388
+ "one (control); see lffbench/harnesses/codex.py")
389
+ ap.add_argument("--max-budget-usd", type=float, default=None, help="claude_code*: --max-budget-usd")
390
+ ap.add_argument("--rpent-sessions", type=int, default=5,
391
+ help="rpent_codex: planner sessions per episode (RPent --explore-sessions; default 5 = k + 2 spare)")
392
+ ap.add_argument("--rpent-attempts-per-session", type=int, default=1,
393
+ help="rpent_codex: attempts one session may use (RPent --explore-attempts-per-session): 1 = "
394
+ "variant H, a fresh session with a handoff after each failed attempt (default); 0 = no limit")
395
+ ap.add_argument("--rpent-max-turns", type=int, default=100,
396
+ help="rpent_codex: model responses per session (RPent --max-turns)")
397
+ ap.add_argument("--timeout", type=float, default=10800)
398
+ ap.add_argument("--allow-unpinned", action="store_true",
399
+ help="launch even if no pin exists for this version / model / effort (the preflight still runs)")
400
+ ap.add_argument("--keep-run-dir", action="store_true", help="do not delete the one-time dirs (debugging)")
401
+ ap.add_argument("--no-gateway", action="store_true",
402
+ help="native harnesses: run the tools inside each MCP server process instead of the episode's "
403
+ "tool gateway (scripts/tool_gateway.py; same ToolCore, budget carried over via the transcript)")
404
+ ap.add_argument("--no-model-gateway", action="store_true",
405
+ help="native harnesses: call the model API directly instead of through the run's model gateway "
406
+ "(scripts/model_gateway.py: model calls only, provider-side tools refused, tokens counted)")
407
+ ap.add_argument("--token-budget-in", type=int, default=None,
408
+ help="model gateway: refuse further model calls once this many input tokens were used (cached "
409
+ "input counts in full)")
410
+ ap.add_argument("--token-budget-out", type=int, default=None,
411
+ help="model gateway: ... output tokens (reasoning included)")
412
+ ap.add_argument("--red-team", action="store_true",
413
+ help="adversarial acceptance run (lffbench/harnesses/redteam.py): the first message starts with the "
414
+ "red-team notice; own contract_sha256; read with scripts/redteam_report.py")
415
+ ap.add_argument("--no-continue", action="store_true",
416
+ help="do not resume a CLI that exited before the episode was over (self-check / debugging)")
417
+ ap.add_argument("--jail", action="store_true",
418
+ help="native harnesses: run the CLI in the native-harness jail (docs/15 §3.4): as uid 65534, no host "
419
+ "path visible, MCP server outside behind a socket relay")
420
+ return ap
421
+
422
+
423
+ def main():
424
+ code, hj = run(parser().parse_args())
425
+ print(json.dumps({k: hj.get(k) for k in ("harness", "status", "exit_reason", "audit_ok", "violations",
426
+ "contract_sha256", "final_metrics")}, default=str), flush=True)
427
+ sys.exit(code)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/headroom_parts_cart.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Incremental physical headroom evaluation of the composite prototype."""
2
+ import argparse,hashlib,json,time
3
+ from pathlib import Path
4
+ import numpy as np
5
+ from lffbench.tasks.lh_parts_cart import PartsCart
6
+
7
+ def clean(x):
8
+ if isinstance(x,np.ndarray):return x.tolist()
9
+ if isinstance(x,np.generic):return x.item()
10
+ raise TypeError(type(x).__name__)
11
+ p=argparse.ArgumentParser();p.add_argument('--kind',choices=['oracle','naive','adaptive','blind'],required=True);p.add_argument('--n',type=int,default=20);p.add_argument('--k',type=int,default=5);p.add_argument('--out',required=True);a=p.parse_args()
12
+ out=Path(a.out);out.parent.mkdir(parents=True,exist_ok=True);x=PartsCart();rows=[];start=time.time()
13
+ source=Path(__file__).parents[1]/'lffbench/tasks/lh_parts_cart.py';code_hash=hashlib.sha256(source.read_bytes()).hexdigest()
14
+ for seed in range(1000,1000+a.n):
15
+ i=x.sample_instance(seed);h=x.run_scripted(a.kind,i,k=a.k,seed=seed)
16
+ rows.append(dict(seed=seed,history=h));succ=sum(any(z['outcome']['success'] for z in row['history']) for row in rows)
17
+ out.write_text(json.dumps(dict(kind=a.kind,n_planned=a.n,n_complete=len(rows),k=a.k,successes=succ,rows=rows,seconds=time.time()-start,task_sha256=code_hash,status='complete' if len(rows)==a.n else 'running',note='scripted privileged-state headroom; fixed geometry, randomized inertia only'),indent=2,default=clean))
18
+ print(seed,a.kind,[z['outcome']['success'] for z in h], 'successes',succ,flush=True)
19
+ x.env.close()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/l6_controls.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """python scripts/l6_controls.py <l6_count_into_box|l6_sequence_resume> [n]
2
+
3
+ Extra controls for the two L6 tasks: thumbnails right after the interruption, extra scripted policies,
4
+ no-injection sanity check, analytic memoryless baselines. Writes results/<task>/controls.json."""
5
+ import sys, json, os, time
6
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+ sys.path.insert(0, ROOT)
8
+ import numpy as np, imageio
9
+ from lffbench import envs
10
+ import lffbench.tasks.l6_count, lffbench.tasks.l6_sequence # noqa
11
+ from lffbench.task_base import TASKS
12
+ name = sys.argv[1]
13
+ n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
14
+ out_dir = os.path.join(ROOT, "results", name)
15
+ os.makedirs(out_dir, exist_ok=True)
16
+ task = TASKS[name](cam_res=384)
17
+ extra = ["skip", "inc1"] if name == "l6_count_into_box" else ["skip"]
18
+ res = dict(task=name, n=n, seeds=list(range(1000, 1000 + n)), extra={}, no_inject={}, analytic={})
19
+ t0 = time.time()
20
+
21
+ # 1) frames right after the interruption (what the agent sees next), seeds 1000-1002, adaptive policy
22
+ def interrupted():
23
+ return (task.slip if name == "l6_count_into_box" else task.stop) is not None
24
+
25
+
26
+ for seed in range(1000, 1003):
27
+ inst = task.sample_instance(seed)
28
+ shot = {}
29
+ orig_step = task.env.step
30
+
31
+ def step(a, _o=orig_step):
32
+ r = _o(a)
33
+ if "f" not in shot and interrupted():
34
+ shot["cnt"] = shot.get("cnt", 0) + 1
35
+ if shot["cnt"] >= (4 if name == "l6_count_into_box" else 60): # count: 0.2 s; sequence: arm back home
36
+ shot["f"] = np.concatenate([envs.render(task.env, "agentview", 384),
37
+ envs.render(task.env, "robot0_eye_in_hand", 384)], 1)
38
+ return r
39
+ task.env.step = step
40
+ task.run_scripted("adaptive", inst, k=5, seed=seed)
41
+ task.env.step = orig_step
42
+ if "f" in shot:
43
+ imageio.imwrite(os.path.join(out_dir, f"interrupt_{seed}.png"), shot["f"])
44
+ print("thumbs", f"{time.time()-t0:.0f}s", flush=True)
45
+
46
+ # 2) extra scripted policies
47
+ for kind in extra:
48
+ fs = []
49
+ for i in range(n):
50
+ seed = 1000 + i
51
+ inst = task.sample_instance(seed)
52
+ h = task.run_scripted(kind, inst, k=5, seed=seed)
53
+ s = next((x["attempt"] for x in h if x["outcome"]["success"]), None)
54
+ fs.append(s)
55
+ res["extra"][kind] = dict(first_success=fs, succ_at_k=[float(np.mean([s is not None and s <= j for s in fs])) for j in range(1, 6)])
56
+ print(kind, res["extra"][kind]["succ_at_k"], f"{time.time()-t0:.0f}s", flush=True)
57
+
58
+ # 3) no-injection sanity (oracle + naive, first 10 seeds)
59
+ task.inject = False
60
+ for kind in ("adaptive", "naive"):
61
+ fs = []
62
+ for i in range(10):
63
+ seed = 1000 + i
64
+ inst = task.sample_instance(seed)
65
+ h = task.run_scripted(kind, inst, k=1, seed=seed)
66
+ fs.append(bool(h[0]["outcome"]["success"]))
67
+ res["no_inject"][kind] = float(np.mean(fs))
68
+ print("no inject", kind, res["no_inject"][kind], flush=True)
69
+ task.inject = True
70
+
71
+ # 4) analytic memoryless baselines over the same seeds (perfect execution assumed)
72
+ if name == "l6_count_into_box":
73
+ insts = [task.sample_instance(1000 + i) for i in range(n)]
74
+ res["analytic"]["uniform_guess_0..N-1@1"] = float(np.mean([1 / x["n_target"] for x in insts]))
75
+ best = max(range(0, 6), key=lambda g: np.mean([x["n_target"] - x["p"] == g for x in insts]))
76
+ res["analytic"]["best_fixed_number_to_add@1"] = dict(add=best, rate=float(np.mean([x["n_target"] - x["p"] == best for x in insts])))
77
+ res["analytic"]["p_hist"] = {str(v): int(sum(x["p"] == v for x in insts)) for v in range(1, 6)}
78
+ res["analytic"]["N_hist"] = {str(v): int(sum(x["n_target"] == v for x in insts)) for v in (4, 5)}
79
+ big = [task.sample_instance(5000 + i) for i in range(2000)]
80
+ res["analytic"]["uniform_guess@1_2000inst"] = float(np.mean([1 / x["n_target"] for x in big]))
81
+ res["analytic"]["best_fixed_add@1_2000inst"] = float(max(np.mean([x["n_target"] - x["p"] == g for x in big]) for g in range(1, 5)))
82
+ else:
83
+ insts = [task.sample_instance(1000 + i) for i in range(n)]
84
+ res["analytic"]["w_hist"] = {str(v): int(sum(x["stop_w"] == v for x in insts)) for v in range(1, 5)}
85
+ res["analytic"]["phase_hist"] = {p: int(sum(x["stop_phase"] == p for x in insts)) for p in "AB"}
86
+ res["analytic"]["uniform_guess_0..4@1"] = 0.2
87
+ big = [task.sample_instance(5000 + i) for i in range(2000)]
88
+ res["analytic"]["best_fixed_guess@1_2000inst"] = float(max(np.mean([x["stop_w"] == g for x in big]) for g in range(0, 5)))
89
+ res["analytic"]["skip_expected"] = float(np.mean([x["stop_phase"] == "B" or x["stop_w"] == 3 for x in big]))
90
+ res["seconds"] = time.time() - t0
91
+ json.dump(res, open(os.path.join(out_dir, "controls.json"), "w"), indent=1)
92
+ print(json.dumps(res["analytic"]))
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/ladder_plan.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-3 feedback ladder (user 2026-10-27; design docs/20). Same instances and records as the mismatched-history
2
+ control (scripts/mismatch_plan.py): the main-table attempt 1 of every Claude instance in the 9 twin tasks whose
3
+ attempt 1 failed. Fresh single-attempt agents (Claude Code B', jail, high, F1), README byte-identical to the Do arm;
4
+ only the Result section of history/README.md grows, one rung at a time:
5
+
6
+ F1 "The environment judged that attempt: failed." = the Do arm (do_<m>), not re-run
7
+ F2 + the measured error of that attempt (outcome.detail, axis labels stripped) batch lf2_<m>
8
+ hplus + "Cause: " the hidden variable (arm_specs reveal, as --arm hplus states it) batch lhp_<m>
9
+ fix + how to succeed (arm_specs fix, from the oracle parameters; results/_ladder/fix_validate.json) lfx_<m>
10
+
11
+ python scripts/ladder_plan.py build records -> runs/api/ladder_20261027/<m>/<rung>.json (+ tasks_<m>.txt)
12
+ python scripts/ladder_plan.py report per instance F1 / F2 / H+ / Fix, totals, adjacent paired counts
13
+ -> runs/api/ladder_20261027/report.json + markdown on stdout
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ SRC = os.path.join(API, "mismatch_20261027")
24
+ OUT = os.path.join(API, "ladder_20261027")
25
+ FIXV = os.path.join(ROOT, "results", "_ladder", "fix_validate.json")
26
+ MODELS = ("opus", "sonnet")
27
+ RUNGS = ("F2", "hplus", "fix")
28
+ BATCH = {"F1": "do", "F2": "lf2", "hplus": "lhp", "fix": "lfx"}
29
+ WITHIN = {"l2_turntable_restore"} # reported separately (docs/20 §2)
30
+
31
+
32
+ def events(log):
33
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip()]
34
+
35
+
36
+ def texts(src, fixes):
37
+ """rung -> result_extra for one record source (the logged attempt 1)"""
38
+ from lffbench import arm_specs
39
+ from lffbench.agent.robot_server import strip_axes
40
+ ev = events(src["log"])
41
+ start = next(e for e in ev if e["ev"] == "session_start")
42
+ done = next(e for e in ev if e["ev"] == "done" and e.get("attempt") == 1)
43
+ detail = strip_axes((done.get("outcome") or {}).get("detail") or "").strip()
44
+ if not detail:
45
+ raise SystemExit(f"{src['task']}:{src['seed']}: attempt 1 has no outcome detail for F2")
46
+ cause = "Cause: " + strip_axes(arm_specs.reveal(start["task"], start["inst"]).strip())
47
+ fx = fixes.get(f"{start['task']}:{start['seed']}")
48
+ if fx is None or not fx["ok"]:
49
+ raise SystemExit(f"{start['task']}:{start['seed']}: no validated fix text in {FIXV}")
50
+ return {"F2": detail, "hplus": detail + "\n\n" + cause, "fix": detail + "\n\n" + cause + "\n\n" + fx["fix"]}
51
+
52
+
53
+ def cmd_build():
54
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
55
+ for m in MODELS:
56
+ own = json.load(open(os.path.join(SRC, m, "own.json")))
57
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
58
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(own) + "\n")
59
+ out = {r: {} for r in RUNGS}
60
+ for key, d in own.items():
61
+ src = json.load(open(d + ".source.json"))
62
+ tx = texts(src, fixes)
63
+ for r in RUNGS:
64
+ dst = os.path.join(OUT, m, r, f"{src['task']}_s{src['seed']}")
65
+ if not os.path.isdir(dst):
66
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), src["log"],
67
+ dst, "--result-extra", tx[r]], check=True, capture_output=True)
68
+ out[r][key] = dst
69
+ for r in RUNGS:
70
+ json.dump(out[r], open(os.path.join(OUT, m, f"{r}.json"), "w"), indent=1)
71
+ print(m, len(own), "instances x", len(RUNGS), "rungs")
72
+
73
+
74
+ def single(batch):
75
+ """task:seed -> True / False (attempt 1 of the batch's done run)"""
76
+ out = {}
77
+ p = os.path.join(API, batch, "manifest.json")
78
+ if not os.path.exists(p):
79
+ return out
80
+ for r in json.load(open(p))["runs"]:
81
+ if r["status"] != "done":
82
+ continue
83
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
84
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
85
+ return out
86
+
87
+
88
+ def cmd_report():
89
+ rep, md = {}, []
90
+ order = ("F1", "F2", "hplus", "fix")
91
+ f = lambda v: "-" if v is None else ("S" if v else "F")
92
+ for m in MODELS:
93
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
94
+ res = {r: single(f"{BATCH[r]}_{m}") for r in order}
95
+ rows = [dict(inst=k, within=k.split(":")[0] in WITHIN, **{r: res[r].get(k) for r in order}) for k in want]
96
+ tot = {}
97
+ for part, sub in (("all", rows), ("cross", [r for r in rows if not r["within"]]),
98
+ ("within", [r for r in rows if r["within"]])):
99
+ tot[part] = {r: [sum(x[r] for x in sub if x[r] is not None), sum(x[r] is not None for x in sub)] for r in order}
100
+ steps = {}
101
+ cross = [r for r in rows if not r["within"]]
102
+ for lo, hi in zip(order, order[1:]):
103
+ both = [r for r in cross if r[lo] is not None and r[hi] is not None]
104
+ steps[f"{lo}->{hi}"] = dict(n=len(both), up=sum(r[hi] and not r[lo] for r in both),
105
+ down=sum(r[lo] and not r[hi] for r in both))
106
+ rep[m] = dict(rows=rows, totals=tot, steps=steps)
107
+ md += [f"### {m}", "", "| instance | F1 | F2 | H+ | Fix |", "|---|---|---|---|---|"]
108
+ md += [f"| {r['inst']}{' (within)' if r['within'] else ''} | " + " | ".join(f(r[x]) for x in order) + " |"
109
+ for r in rows]
110
+ for part in ("cross", "within"):
111
+ md.append(f"{part}: " + ", ".join(f"{x} {tot[part][x][0]}/{tot[part][x][1]}" for x in order))
112
+ md.append("adjacent (cross, paired): " + "; ".join(f"{k} n={v['n']} up {v['up']} down {v['down']}"
113
+ for k, v in steps.items()))
114
+ md.append("")
115
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
116
+ print("\n".join(md))
117
+
118
+
119
+ if __name__ == "__main__":
120
+ {"build": cmd_build, "report": cmd_report}[sys.argv[1]]()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/layer4_plan.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layer-4 minimal intervention (user 2026-10-30: 先用 opus; design reports/layer4_intervention_20261030/PLAN.md). Opus only, on the
2
+ two tasks whose every main-table instance failed all three attempts. Same protocol as the layer-3 ladder (a fresh
3
+ single-attempt agent, the instance's own failed attempt 1 in history/, F1), only the Result section differs:
4
+
5
+ f1 "The environment judged that attempt: failed."
6
+ v + a generic reminder to check the goal before ending; no cause
7
+ hp + "Cause: " the hidden variable (arm_specs reveal)
8
+ fx + cause + how to succeed (arm_specs fix, validated below)
9
+
10
+ python scripts/layer4_plan.py validate texts + oracle + LA push, debug and test seeds -> results/_layer4/fix_validate.json
11
+ python scripts/layer4_plan.py build debug records -> runs/api/layer4i_20261030/debug/<cond>.json + tasks.txt
12
+ python scripts/layer4_plan.py build test the same from the failed attempts of batch l4i_first (test seeds)
13
+ python scripts/layer4_plan.py report debug|test per instance per condition: outcome, process events, closing claim
14
+ """
15
+ import json
16
+ import os
17
+ import subprocess
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ sys.path.insert(0, ROOT)
22
+ API = os.path.join(ROOT, "runs", "api")
23
+ OUT = os.path.join(API, "layer4i_20261030")
24
+ FIXV = os.path.join(ROOT, "results", "_layer4", "fix_validate.json")
25
+ CONDS = ("f1", "v", "hp", "fx")
26
+ DEBUG = {"lh_clear_cover": {3000: "cc_opus1", 3001: "cc_opus_s2", 3003: "cc_opus_s3"},
27
+ "lh_tidy_stack": {3000: "cc_opus1", 3002: "cc_opus_s2", 3003: "cc_opus_s3"}}
28
+ # frozen before any test-seed run: first four seeds from 3100 with the trap active (clear_cover: covered, (seed * 7) % 20 < 10;
29
+ # tidy_stack: a soft box that is not on top of a nearest-first pile, (seed * 7) % 20 < 18 and % 4 != 3)
30
+ TEST = {"lh_clear_cover": [3100, 3101, 3103, 3104], "lh_tidy_stack": [3100, 3102, 3103, 3104]}
31
+ REMINDER = ("Before you end an attempt, use your observations to check whether every part of the goal is actually met; "
32
+ "if it is not, keep working.")
33
+
34
+
35
+ def events(log):
36
+ return [json.loads(line) for line in open(os.path.join(log, "events.jsonl")) if line.strip() and "\0" not in line]
37
+
38
+
39
+ def batch_log(batch, task, seed):
40
+ runs = json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
41
+ return next(r["log"] for r in runs if r["task"] == task and r["seed"] == seed and r.get("status") == "done"
42
+ and r.get("cond") == "harness")
43
+
44
+
45
+ def la_push(task, inst):
46
+ """the Fix text's lid push as LA commands; returns (z_push, sweep length, lid off?)"""
47
+ import numpy as np
48
+ from lffbench.agent.tools import ToolExecutor
49
+ from lffbench.tasks import lh_clear_cover as cc
50
+ from scripts.validate_ladder_fix import la_move
51
+ task.reset_instance(inst)
52
+ sim = task.env.sim
53
+ off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
54
+ ex = ToolExecutor(task, inst, image_res=64, cams=("agentview",))
55
+ cov = task.covering()
56
+ lp = task.lid_pos()
57
+ b = np.asarray(inst["boxes"][cov], float)
58
+ o = np.asarray(inst["boxes"][[c for c in cc.COLORS if c != cov][0]], float)
59
+ d = np.array((0.0, float(np.sign(b[1] - o[1]))))
60
+ back = cc.LID_HALF + 0.03
61
+ s = lp[:2] - d * back
62
+ z = lp[2] + cc.LID_T / 2 - cc.PUSH_DEPTH + cc.TIP
63
+ need = float((b - lp[:2]) @ d) + cc.BOX_OUT + back + 0.03
64
+ e = s + d * need
65
+ sb, eb, zb = s - off[:2], e - off[:2], z - off[2]
66
+ la_move(task, ex, off, gripper="close")
67
+ la_move(task, ex, off, x=sb[0], y=sb[1], z=zb + 0.08, yaw=0)
68
+ la_move(task, ex, off, x=sb[0], y=sb[1], z=zb)
69
+ la_move(task, ex, off, x=eb[0], y=eb[1], z=zb, speed=cc.PUSH_SPEED)
70
+ la_move(task, ex, off, z=zb + 0.10, speed=0.2)
71
+ return float(zb), float(need), task.covering() is None
72
+
73
+
74
+ def cmd_validate():
75
+ import importlib
76
+ import pkgutil
77
+ from lffbench import arm_specs
78
+ from lffbench import tasks as task_pkg
79
+ from lffbench.agent.robot_server import strip_axes
80
+ from lffbench.task_base import TASKS
81
+ for m in pkgutil.iter_modules(task_pkg.__path__):
82
+ importlib.import_module(f"lffbench.tasks.{m.name}")
83
+ rows = []
84
+ for name, seeds in ((t, sorted(DEBUG[t]) + TEST[t]) for t in DEBUG):
85
+ task = TASKS[name](cam_res=64)
86
+ for seed in seeds:
87
+ inst = task.sample_instance(seed)
88
+ clean = {k: v for k, v in inst.items() if not k.startswith("_")}
89
+ params = dict(task.oracle_params(inst))
90
+ row = dict(key=f"{name}:{seed}", hidden=clean.get("cover") or clean.get("soft_colour"))
91
+ row["oracle_success"] = bool(task.run_scripted("oracle", inst, k=1)[0]["outcome"]["success"])
92
+ row["naive_success"] = bool(task.run_scripted("naive", inst, k=1)[0]["outcome"]["success"])
93
+ if name == "lh_clear_cover":
94
+ params["z_push"], params["push_len"], row["la_lid_off"] = la_push(task, inst)
95
+ task.execute(inst, dict(plan="naive", check="side")) # the placing part, after the LA push
96
+ row["la_then_place_success"] = bool(task.outcome(inst)["success"])
97
+ cause, fx = arm_specs.reveal(name, clean), arm_specs.fix(name, clean, params)
98
+ row.update(cause=cause, fix=fx, no_axis_labels=strip_axes(cause + fx) == cause + fx)
99
+ row["ok"] = bool(row["oracle_success"] and not row["naive_success"] and row["hidden"] and row["no_axis_labels"]
100
+ and row.get("la_lid_off", True) and row.get("la_then_place_success", True))
101
+ rows.append(row)
102
+ print("OK " if row["ok"] else "BAD", json.dumps({k: v for k, v in row.items() if k not in ("cause", "fix")}), flush=True)
103
+ os.makedirs(os.path.dirname(FIXV), exist_ok=True)
104
+ json.dump(dict(rows=rows, n=len(rows), n_ok=sum(r["ok"] for r in rows)), open(FIXV, "w"), indent=1)
105
+ print(f"{sum(r['ok'] for r in rows)}/{len(rows)} ok -> {FIXV}")
106
+
107
+
108
+ def sources(stage):
109
+ if stage == "debug":
110
+ return [(t, s, batch_log(b, t, s)) for t, d in DEBUG.items() for s, b in sorted(d.items())]
111
+ out = []
112
+ for r in json.load(open(os.path.join(API, "l4i_first", "manifest.json")))["runs"]:
113
+ if r["status"] == "done":
114
+ d = next((e for e in events(r["log"]) if e["ev"] == "done" and e.get("attempt") == 1), None)
115
+ if d is not None and not d["success"]:
116
+ out.append((r["task"], r["seed"], r["log"]))
117
+ return out
118
+
119
+
120
+ def cmd_build(stage):
121
+ fixes = {r["key"]: r for r in json.load(open(FIXV))["rows"]}
122
+ base = os.path.join(OUT, stage)
123
+ os.makedirs(base, exist_ok=True)
124
+ maps, tasks = {c: {} for c in CONDS}, []
125
+ for task, seed, log in sources(stage):
126
+ key = f"{task}:{seed}"
127
+ if not fixes[key]["ok"]:
128
+ raise SystemExit(f"{key}: fix text not validated")
129
+ tasks.append(key)
130
+ cause = "Cause: " + fixes[key]["cause"]
131
+ extra = dict(f1="", v=REMINDER, hp=cause, fx=cause + "\n\n" + fixes[key]["fix"])
132
+ for c in CONDS:
133
+ dst = os.path.join(base, c, f"{task}_s{seed}")
134
+ if not os.path.isdir(dst):
135
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, dst,
136
+ "--result-extra", extra[c]], check=True, capture_output=True)
137
+ maps[c][key] = dst
138
+ for c in CONDS:
139
+ json.dump(maps[c], open(os.path.join(base, f"{c}.json"), "w"), indent=1)
140
+ open(os.path.join(base, "tasks.txt"), "w").write("\n".join(tasks) + "\n")
141
+ print(stage, len(tasks), "instances x", len(CONDS), "conditions")
142
+
143
+
144
+ def cmd_report(stage):
145
+ rows = {}
146
+ for c in CONDS:
147
+ p = os.path.join(API, f"l4i_{c}_{stage}", "manifest.json")
148
+ if not os.path.exists(p):
149
+ continue
150
+ for r in json.load(open(p))["runs"]:
151
+ key = f"{r['task']}:{r['seed']}"
152
+ cell = dict(status=r["status"])
153
+ if r["status"] == "done":
154
+ ev = events(r["log"])
155
+ d = next((e for e in ev if e["ev"] == "done"), {})
156
+ o = d.get("outcome") or {}
157
+ cell.update(success=bool(d.get("success")), calls=d.get("step"), reason=(d.get("reason") or "")[:300],
158
+ failure=o.get("failure"), detail=(o.get("detail") or "")[:300], log=r["log"],
159
+ events=[e.get("ev") for e in o.get("events", []) if isinstance(e, dict)][:40],
160
+ cover_removed=o.get("cover_removed"))
161
+ rows.setdefault(key, {})[c] = cell
162
+ print("| instance | " + " | ".join(CONDS) + " |")
163
+ print("|---|" + "---|" * len(CONDS))
164
+ f = lambda x: "-" if x is None else ("S" if x.get("success") else ("F" if x.get("status") == "done" else x.get("status")))
165
+ for k, v in sorted(rows.items()):
166
+ print(f"| {k} | " + " | ".join(f(v.get(c)) for c in CONDS) + " |")
167
+ for c in CONDS:
168
+ xs = [v[c] for v in rows.values() if c in v and v[c].get("status") == "done"]
169
+ print(c, f"{sum(x['success'] for x in xs)}/{len(xs)}")
170
+ json.dump(rows, open(os.path.join(OUT, f"report_{stage}.json"), "w"), indent=1)
171
+
172
+
173
+ if __name__ == "__main__":
174
+ {"validate": cmd_validate, "build": lambda: cmd_build(sys.argv[2]), "report": lambda: cmd_report(sys.argv[2])}[sys.argv[1]]()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/lerobot_export.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pack the recorded agent replays (scripts/lerobot_replay.py record) into one LeRobot v3.0 dataset plus LFF sidecars.
2
+
3
+ Runs in a Python with lerobot 0.4.x (it does not import lffbench / MuJoCo). Three steps, so that the video encoding
4
+ can run in parallel shards (contiguous episode ranges, merged in order, so episode indices follow the plan):
5
+
6
+ python scripts/lerobot_export.py plan --raw <raw_root>[,<raw_root2>] --runs-root <lffbench>/runs/api \
7
+ --paper <paper/latex> --task-set <lffbench>/sets/main_v2_1inst.txt --work <work_dir> [--batches ...] [--limit N]
8
+ python scripts/lerobot_export.py shard --work <work_dir> --shard i --nshards N
9
+ python scripts/lerobot_export.py merge --work <work_dir> --nshards N --out <dataset_root>
10
+
11
+ Only runs whose replay matched the log exactly are exported (replay.json: no code / instance difference, 0
12
+ mismatching reports or outcomes). Episodes without a judged attempt (the agent was stopped mid-attempt) are dropped.
13
+
14
+ LeRobot features (fps 20, one frame per robosuite control step; frame t = observation before action t, action t):
15
+ observation.images.image agentview RGB 256x256 (upright; LIBERO naming)
16
+ observation.images.wrist_image wrist (eye-in-hand) RGB 256x256
17
+ observation.state 8: eef xyz (world, m), eef axis-angle (3), gripper finger qpos (2) (LIBERO layout)
18
+ observation.joint_pos / joint_vel 7 arm joints (rad, rad/s)
19
+ observation.eef_quat 4: xyzw; observation.gripper_width 1 (m)
20
+ action 7: robosuite OSC_POSE input in [-1, 1]: dpos (x 0.1 m), drot axis-angle (x 0.5 rad),
21
+ gripper (-1 open, +1 close)
22
+ annotation.attempt_index attempt (1-based) the frame belongs to
23
+ annotation.command_index robot-command step within the attempt (-1: outcome check after `finish`)
24
+ annotation.phase 0 arm motion, 1 gripper open/close, 2 outcome check (not an agent action)
25
+ annotation.attempt_success 1 / 0 / -1 (succeeded / failed / not judged) for the frame's attempt
26
+ annotation.task_event number of task-monitor events (error / progress events) registered at this step
27
+ Sidecars under lff/: annotations/episode_*.json (full annotation), episodes.jsonl (flat per-episode table),
28
+ runs.jsonl (attempt chains), tasks.json (task metadata + paper description), sim_state/episode_*.npy (MuJoCo state
29
+ per frame), final/episode_* (observation after the last step = the state the outcome was judged in), code/.
30
+ """
31
+ import argparse
32
+ import glob
33
+ import json
34
+ import os
35
+ import re
36
+ import shutil
37
+ import time
38
+
39
+ import numpy as np
40
+
41
+ FPS = 20
42
+ RES = 256
43
+ BATCH_ORDER = ["cx_main1", "cc_main1", "cc_opus1", "cx_native1", "cx_pilot6c", "cx_pilot6b", "cx_pilot6", "cx_smoke",
44
+ "cc_smoke", "cc_opus_smoke"]
45
+ BATCH_NOTES = {
46
+ "cx_main1": "GPT main table: gpt-6-astra (high) in Codex 0.163, shared (generic) model catalog",
47
+ "cc_main1": "Claude main table: claude-sonnet-5-5 (high) in Claude Code 2.1.267",
48
+ "cc_opus1": "Claude main table: claude-opus-5-5 (high) in Claude Code 2.1.299",
49
+ "cx_native1": "control: gpt-6-astra in Codex with its native model catalog (code mode), 8 instances",
50
+ "cx_pilot6c": "pilot: gpt-6-astra in Codex, 3 history runs + memory-free retries (early-exit resume fixed)",
51
+ "cx_pilot6b": "pilot: gpt-6-astra in Codex; Codex sometimes exited early (before the resume fix), so the "
52
+ "with-history continuation of failed runs is incomplete",
53
+ "cx_pilot6": "pilot: gpt-6-astra in Codex, stopped early",
54
+ "cx_smoke": "smoke test: single attempt", "cc_smoke": "smoke test: single attempt",
55
+ "cc_opus_smoke": "smoke test: single attempt",
56
+ }
57
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
58
+ CAUSES = {"L1": "execution offset (the arm does not go exactly where commanded)",
59
+ "L2": "disturbed state to restore (incl. damage the agent causes)",
60
+ "L3": "infeasible manipulation strategy (grasp / contact / tool must change)",
61
+ "L4": "misjudged geometry (size, shape, fit, hidden structure)",
62
+ "L5": "misjudged physics (mass distribution, friction, dynamics)"}
63
+
64
+
65
+ def features():
66
+ vid = lambda: {"dtype": "video", "shape": (RES, RES, 3), "names": ["height", "width", "channels"]}
67
+ f32 = lambda n, names: {"dtype": "float32", "shape": (n,), "names": names}
68
+ i64 = lambda: {"dtype": "int64", "shape": (1,), "names": None}
69
+ return {
70
+ "observation.images.image": vid(),
71
+ "observation.images.wrist_image": vid(),
72
+ "observation.state": f32(8, ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z",
73
+ "finger_qpos_left", "finger_qpos_right"]),
74
+ "observation.joint_pos": f32(7, [f"joint{i}" for i in range(1, 8)]),
75
+ "observation.joint_vel": f32(7, [f"joint{i}" for i in range(1, 8)]),
76
+ "observation.eef_quat": f32(4, ["qx", "qy", "qz", "qw"]),
77
+ "observation.gripper_width": f32(1, ["width_m"]),
78
+ "action": f32(7, ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y",
79
+ "eef_delta_rot_aa_z", "gripper_close"]),
80
+ "annotation.attempt_index": i64(),
81
+ "annotation.command_index": i64(),
82
+ "annotation.phase": i64(),
83
+ "annotation.attempt_success": i64(),
84
+ "annotation.task_event": i64(),
85
+ }
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ paper metadata
89
+
90
+ def _clean_tex(s):
91
+ s = re.sub(r"%.*", "", s)
92
+ for a, b in [(r"\{\\times\}", "×"), (r"\\times", "×"), (r"\\,", " "), (r"\\mu", "μ"), (r"\^\\circ", "°"),
93
+ (r"\\pm", "±"), (r"\\leftrightarrow", "↔"), (r"\\geq", "≥"), (r"\\leq", "≤"), (r"\\%", "%"),
94
+ (r"\\_", "_"), (r"\\eg", "e.g."), (r"\\ie", "i.e."), (r"\\ding\{51\}", "yes"), (r"\\ding\{55\}", "no"),
95
+ (r"\\approx", "≈"), (r"\\to", "→"), (r"\\Delta", "Δ"), (r"\\theta", "θ"), (r"\\alpha", "α"),
96
+ (r"\\cdot", "·"), (r"\\ldots", "…"), (r"\\dots", "…"), (r"\\&", "&"), (r"\\textasciitilde", "~")]:
97
+ s = re.sub(a, b, s)
98
+ s = re.sub(r"\\(?:cref|ref|label|cite)\{[^}]*\}", "", s)
99
+ s = re.sub(r"\\(?:TODO|todo)\{[^}]*\}", "(to be written)", s)
100
+ for _ in range(3):
101
+ s = re.sub(r"\\(?:emph|texttt|textbf|textit|mathrm|text|mathit|mathbf)\{([^{}]*)\}", r"\1", s)
102
+ s = re.sub(r"\$([^$]*)\$", r"\1", s)
103
+ s = s.replace("``", '"').replace("''", '"').replace("---", "—").replace("--", "–").replace("~", " ")
104
+ s = re.sub(r"\{([^{}]*)\}", r"\1", s)
105
+ s = re.sub(r"\\[a-zA-Z]+\*?", "", s)
106
+ return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n", "\n\n", s)).strip()
107
+
108
+
109
+ def paper_tasks(paper_dir):
110
+ """{task: {name, cause, hidden_variable, repair_within_attempt, oracle_pct, naive_pct, description}} from the
111
+ paper's task table and task appendix (empty if the paper sources are not there)."""
112
+ out = {}
113
+ if not paper_dir:
114
+ return out
115
+ app = os.path.join(paper_dir, "sections", "appendix_tasks.tex")
116
+ tab = os.path.join(paper_dir, "sections", "tab_tasks.tex")
117
+ if os.path.exists(app):
118
+ txt = open(app).read()
119
+ parts = re.split(r"(\\paragraph\{|\\subsection\{|\\section\{)", txt)
120
+ for i in range(1, len(parts) - 1, 2):
121
+ if parts[i] != "\\paragraph{":
122
+ continue
123
+ body = parts[i + 1]
124
+ m = re.match(r"(.*?)\s*\(\\texttt\{([a-z0-9\\_]+)\};\s*([^)]*)\)\.\}", body, re.S)
125
+ if not m:
126
+ continue
127
+ name, code, cause = m.group(1).strip(), m.group(2).replace("\\_", "_"), m.group(3).strip()
128
+ desc = _clean_tex(body[m.end():])
129
+ out[code] = dict(name=name, cause=_clean_tex(cause), description=desc)
130
+ if os.path.exists(tab):
131
+ names = {v["name"].lower(): k for k, v in out.items()}
132
+ for line in open(tab):
133
+ cells = [c.strip() for c in line.split("&")]
134
+ if len(cells) != 6 or not cells[-1].endswith("\\\\"):
135
+ continue
136
+ nm = re.sub(r"\\contscene", "", cells[0]).strip().lower()
137
+ code = names.get(nm)
138
+ if not code:
139
+ continue
140
+ out[code].update(table_cause=_clean_tex(cells[1]), hidden_variable=_clean_tex(cells[2]),
141
+ repair_within_attempt=_clean_tex(cells[3]) == "yes",
142
+ oracle_first_attempt_pct=_clean_tex(cells[4]),
143
+ naive_first_attempt_pct=_clean_tex(cells[5].rstrip("\\").strip()))
144
+ return out
145
+
146
+
147
+ # ------------------------------------------------------------------------------------------------ collection
148
+
149
+ def manifest_status(runs_root, batch, run, cache={}):
150
+ if batch not in cache:
151
+ p = os.path.join(runs_root, batch, "manifest.json")
152
+ cache[batch] = json.load(open(p)) if os.path.exists(p) else {}
153
+ m = cache[batch]
154
+ for r in m.get("runs", []):
155
+ if r.get("run") == run:
156
+ return r.get("status", "?"), r
157
+ for r in m.get("superseded", []):
158
+ if r.get("run") == run:
159
+ return "superseded_" + str(r.get("status", "?")), r
160
+ return "not_in_manifest", {}
161
+
162
+
163
+ def collect(raw_roots, runs_root, batches, task_order):
164
+ """Verified episodes in dataset order. A run recorded under several raw roots is taken from the first root."""
165
+ eps, rejected, seen = [], [], set()
166
+ for root in raw_roots:
167
+ for rj in sorted(glob.glob(os.path.join(root, "*", "*", "replay.json"))):
168
+ rep = json.load(open(rj))
169
+ batch, run = rep.get("batch") or rj.split(os.sep)[-3], rep["run"]
170
+ if (batches and batch not in batches) or (batch, run) in seen:
171
+ continue
172
+ seen.add((batch, run))
173
+ ok = not rep.get("error") and rep.get("n_mismatch") == 0 and not rep.get("code_diff") and not rep.get("inst_diff")
174
+ status, entry = manifest_status(runs_root, batch, run)
175
+ if not ok:
176
+ never = rep.get("code_diff") == ["contract.json"] and not rep.get("n_checked")
177
+ rejected.append(dict(run=run, batch=batch, run_status=status,
178
+ reason="run never started (no contract, no robot command)" if never else
179
+ "replay does not reproduce the log (the log has gaps or the replay diverged)",
180
+ detail=rep.get("first_mismatches")))
181
+ continue
182
+ for ep in rep.get("episodes", []):
183
+ d = os.path.join(root, ep["dir"])
184
+ ann = json.load(open(os.path.join(d, "annotation.json")))
185
+ judged = [a for a in ann["attempts"] if a.get("success") is not None]
186
+ if not judged or ep["n_frames"] == 0:
187
+ rejected.append(dict(run=run, batch=batch, episode=ep["dir"],
188
+ reason="no judged attempt" if not judged else "no frames"))
189
+ continue
190
+ ann["source"]["run_status"] = status
191
+ ann["source"]["manifest_id"] = entry.get("id")
192
+ ann["source"]["replay"] = dict(n_reports_checked=rep["n_checked"], n_mismatch=rep["n_mismatch"],
193
+ max_eef_dev_m=rep["max_eef_dev_m"])
194
+ key = (BATCH_ORDER.index(batch) if batch in BATCH_ORDER else 99, task_order.get(ann["task"]["name"], 99),
195
+ {"with_history": 0, "memory_free_retry": 1}.get(ann["source"]["condition"], 2),
196
+ ann["source"].get("memory_free_rep") or 0, run, ann["source"]["episode_in_run"])
197
+ eps.append(dict(key=key, dir=d, n=int(ep["n_frames"]), ann=ann))
198
+ eps.sort(key=lambda x: x["key"])
199
+ return eps, rejected
200
+
201
+
202
+ # ------------------------------------------------------------------------------------------------ writing
203
+
204
+ def frames_of(path):
205
+ import av
206
+ with av.open(path) as c:
207
+ for fr in c.decode(video=0):
208
+ yield fr.to_ndarray(format="rgb24")
209
+
210
+
211
+ def flat_row(i, ann, n, idx0):
212
+ s, ag, t, ro = ann["source"], ann["agent"], ann["task"], ann["run_outcome"]
213
+ att = ann["attempts"]
214
+ a0 = att[0]
215
+ return dict(episode_index=i, dataset_from_index=idx0, dataset_to_index=idx0 + n, length=n,
216
+ batch=s["batch"], run=s["run"], run_status=s.get("run_status"), condition=s["condition"],
217
+ memory_free_rep=s.get("memory_free_rep"), memory_free_chain_of=s.get("memory_free_chain_of"),
218
+ episode_in_run=s["episode_in_run"], attempts=[a["attempt"] for a in att],
219
+ harness=ag.get("harness"), harness_version=ag.get("harness_version"), model=ag.get("model"),
220
+ effort=ag.get("effort"), codex_catalog=ag.get("codex_catalog"),
221
+ task=t["name"], level_code=t["level"], paper_cause=(t.get("paper") or {}).get("cause"),
222
+ category=t["category"], protocol=t["protocol"], seed=t["seed"], instruction=t["instruction"],
223
+ success=[a.get("success") for a in att], failure=[(a.get("outcome") or {}).get("failure") for a in att],
224
+ feedback_f2=[a.get("feedback_f2") for a in att], finish_reason=[a.get("finish_reason") for a in att],
225
+ auto_ended=[a.get("auto_ended") for a in att],
226
+ corrected_later_in_run=[a.get("corrected_later_in_run") for a in att],
227
+ error_event_in_attempt=[a.get("error_event_in_attempt") for a in att],
228
+ run_outcome_class=ro.get("outcome_class"), run_attempt_history=ro.get("attempt_history"),
229
+ n_commands=len(ann["commands"]), n_task_events=len(ann["task_events"]),
230
+ first_attempt_success=a0.get("success") if a0["attempt"] == 1 else None)
231
+
232
+
233
+ def cmd_plan(a):
234
+ task_order = {}
235
+ if a.task_set and os.path.exists(a.task_set):
236
+ for i, line in enumerate(l for l in open(a.task_set) if l.strip() and not l.startswith("#")):
237
+ task_order[line.split(":")[0].strip()] = i
238
+ batches = [b for b in a.batches.split(",") if b] if a.batches else None
239
+ eps, rejected = collect([r for r in a.raw.split(",") if r], a.runs_root, batches, task_order)
240
+ if a.limit:
241
+ eps = eps[:a.limit]
242
+ paper = paper_tasks(a.paper)
243
+ idx0 = 0
244
+ for i, e in enumerate(eps):
245
+ ann = e["ann"]
246
+ tname = ann["task"]["name"]
247
+ if tname in paper:
248
+ ann["task"]["paper"] = {k: v for k, v in paper[tname].items() if k != "description"}
249
+ ann["episode_index"] = i
250
+ ann["dataset_index_range"] = [idx0, idx0 + e["n"]]
251
+ e["index"], e["from"] = i, idx0
252
+ idx0 += e["n"]
253
+ del e["key"]
254
+ os.makedirs(a.work, exist_ok=True)
255
+ with open(os.path.join(a.work, "plan.json"), "w") as f:
256
+ json.dump(dict(episodes=eps, rejected=rejected, paper=paper, total_frames=idx0, repo_id=a.repo_id), f,
257
+ ensure_ascii=False)
258
+ print(f"plan: {len(eps)} episodes, {idx0} frames, {len(rejected)} rejected", flush=True)
259
+
260
+
261
+ def shard_range(n_eps, i, k):
262
+ return (n_eps * i) // k, (n_eps * (i + 1)) // k
263
+
264
+
265
+ def cmd_shard(a):
266
+ from lerobot.datasets.lerobot_dataset import LeRobotDataset
267
+ t0 = time.time()
268
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
269
+ eps = plan["episodes"]
270
+ lo, hi = shard_range(len(eps), a.shard, a.nshards)
271
+ out = os.path.join(a.work, "shards", f"shard_{a.shard:03d}")
272
+ if os.path.exists(os.path.join(out, "DONE")):
273
+ print(f"shard {a.shard}: done already", flush=True)
274
+ return
275
+ shutil.rmtree(out, ignore_errors=True)
276
+ ds = LeRobotDataset.create(repo_id=f"{plan['repo_id']}-shard{a.shard:03d}", fps=FPS, features=features(), root=out,
277
+ robot_type="franka_panda", use_videos=True, image_writer_threads=a.threads,
278
+ vcodec=a.vcodec)
279
+ nfr = 0
280
+ for e in eps[lo:hi]:
281
+ d, ann, n = e["dir"], e["ann"], e["n"]
282
+ fr = np.load(os.path.join(d, "frames.npz"))
283
+ assert len(fr["action"]) == n, d
284
+ succ = {x["attempt"]: (-1 if x.get("success") is None else int(bool(x["success"]))) for x in ann["attempts"]}
285
+ evc = np.zeros(n, np.int64)
286
+ for ev in ann["task_events"]:
287
+ if 0 <= ev["frame"] < n:
288
+ evc[ev["frame"]] += 1
289
+ state = np.concatenate([fr["eef_pos"], fr["eef_axis_angle"], fr["gripper_qpos"]], 1).astype(np.float32)
290
+ instr = ann["task"]["instruction"]
291
+ k = 0
292
+ for img, wr in zip(frames_of(os.path.join(d, "agentview.mp4")), frames_of(os.path.join(d, "wrist.mp4"))):
293
+ if k >= n:
294
+ break
295
+ ds.add_frame({
296
+ "observation.images.image": img, "observation.images.wrist_image": wr,
297
+ "observation.state": state[k],
298
+ "observation.joint_pos": fr["joint_pos"][k].astype(np.float32),
299
+ "observation.joint_vel": fr["joint_vel"][k].astype(np.float32),
300
+ "observation.eef_quat": fr["eef_quat_xyzw"][k].astype(np.float32),
301
+ "observation.gripper_width": np.array([fr["gripper_width"][k]], np.float32),
302
+ "action": fr["action"][k].astype(np.float32),
303
+ "annotation.attempt_index": np.array([fr["attempt"][k]], np.int64),
304
+ "annotation.command_index": np.array([fr["command"][k]], np.int64),
305
+ "annotation.phase": np.array([fr["phase"][k]], np.int64),
306
+ "annotation.attempt_success": np.array([succ.get(int(fr["attempt"][k]), -1)], np.int64),
307
+ "annotation.task_event": np.array([evc[k]], np.int64),
308
+ "task": instr,
309
+ })
310
+ k += 1
311
+ if k != n:
312
+ raise RuntimeError(f"{d}: {k} video frames for {n} numeric frames")
313
+ ds.save_episode()
314
+ nfr += n
315
+ ds.finalize()
316
+ shutil.rmtree(os.path.join(out, "images"), ignore_errors=True)
317
+ open(os.path.join(out, "DONE"), "w").write(f"{lo} {hi} {nfr}\n")
318
+ print(f"shard {a.shard}: episodes {lo}-{hi}, {nfr} frames, {time.time() - t0:.0f}s", flush=True)
319
+
320
+
321
+ def cmd_merge(a):
322
+ from pathlib import Path
323
+ from lerobot.datasets.aggregate import aggregate_datasets
324
+ t0 = time.time()
325
+ plan = json.load(open(os.path.join(a.work, "plan.json")))
326
+ eps = plan["episodes"]
327
+ roots, ids = [], []
328
+ for i in range(a.nshards):
329
+ lo, hi = shard_range(len(eps), i, a.nshards)
330
+ if hi <= lo:
331
+ continue
332
+ r = os.path.join(a.work, "shards", f"shard_{i:03d}")
333
+ if not os.path.exists(os.path.join(r, "DONE")):
334
+ raise SystemExit(f"shard {i} is not done")
335
+ roots.append(Path(r))
336
+ ids.append(f"{plan['repo_id']}-shard{i:03d}")
337
+ if os.path.exists(a.out):
338
+ raise SystemExit(f"{a.out} exists; refusing to overwrite")
339
+ aggregate_datasets(repo_ids=ids, aggr_repo_id=plan["repo_id"], roots=roots, aggr_root=Path(a.out))
340
+ print(f"aggregated {len(roots)} shards in {time.time() - t0:.0f}s", flush=True)
341
+ write_sidecars(a, plan)
342
+ print(f"merge done in {time.time() - t0:.0f}s", flush=True)
343
+
344
+
345
+ def write_sidecars(a, plan):
346
+ eps, paper = plan["episodes"], plan["paper"]
347
+ lff = os.path.join(a.out, "lff")
348
+ for sub in ("annotations", "sim_state", "final", "code"):
349
+ os.makedirs(os.path.join(lff, sub), exist_ok=True)
350
+ rows, runs, tasks = [], {}, {}
351
+ for e in eps:
352
+ i, d, ann, n = e["index"], e["dir"], e["ann"], e["n"]
353
+ name = f"episode_{i:06d}"
354
+ if os.path.exists(os.path.join(d, "sim_state.npy")):
355
+ shutil.copy(os.path.join(d, "sim_state.npy"), os.path.join(lff, "sim_state", name + ".npy"))
356
+ shutil.copy(os.path.join(d, "final.npz"), os.path.join(lff, "final", name + ".npz"))
357
+ for cam, key in (("agentview", "image"), ("wrist", "wrist_image")):
358
+ shutil.copy(os.path.join(d, f"final_{cam}.png"), os.path.join(lff, "final", f"{name}_{key}.png"))
359
+ with open(os.path.join(lff, "annotations", name + ".json"), "w") as f:
360
+ json.dump(ann, f, indent=1, ensure_ascii=False)
361
+ rows.append(flat_row(i, ann, n, e["from"]))
362
+ tname = ann["task"]["name"]
363
+ rk = (ann["source"]["batch"], ann["source"]["run"])
364
+ r = runs.setdefault(rk, dict(batch=rk[0], run=rk[1], manifest_id=ann["source"].get("manifest_id"),
365
+ run_status=ann["source"].get("run_status"), condition=ann["source"]["condition"],
366
+ memory_free_chain_of=ann["source"].get("memory_free_chain_of"),
367
+ memory_free_rep=ann["source"].get("memory_free_rep"), task=tname,
368
+ seed=ann["task"]["seed"], model=ann["agent"].get("model"),
369
+ harness=ann["agent"].get("harness"),
370
+ harness_version=ann["agent"].get("harness_version"),
371
+ codex_catalog=ann["agent"].get("codex_catalog"),
372
+ outcome_class=ann["run_outcome"].get("outcome_class"),
373
+ attempt_history=ann["run_outcome"].get("attempt_history"),
374
+ agent_final_report=ann["run_outcome"].get("agent_final_report"),
375
+ episodes=[]))
376
+ for x in ann["attempts"]:
377
+ r["episodes"].append(dict(attempt=x["attempt"], episode_index=i, success=x.get("success")))
378
+ if tname not in tasks:
379
+ tasks[tname] = {k: v for k, v in ann["task"].items() if k not in ("seed", "instance", "paper")}
380
+ if tname in paper:
381
+ tasks[tname]["paper"] = paper[tname]
382
+ tasks[tname]["instances"] = {}
383
+ tasks[tname]["instances"][str(ann["task"]["seed"])] = ann["task"]["instance"]
384
+ # memory-free retries <-> the history run whose first attempt they share (manifest "chain" = history run id)
385
+ by_id = {(r["batch"], r["manifest_id"]): rn for (b, rn), r in runs.items() if r.get("manifest_id")}
386
+ for r in runs.values():
387
+ if r.get("memory_free_chain_of"):
388
+ r["memory_free_chain_of_run"] = by_id.get((r["batch"], r["memory_free_chain_of"]))
389
+ for (b, rn), r in runs.items():
390
+ r["memory_free_retries"] = sorted((x["run"] for x in runs.values()
391
+ if x["batch"] == b and x.get("memory_free_chain_of_run") == rn),
392
+ key=lambda q: runs[(b, q)].get("memory_free_rep") or 0)
393
+ with open(os.path.join(lff, "episodes.jsonl"), "w") as f:
394
+ for row in rows:
395
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
396
+ with open(os.path.join(lff, "runs.jsonl"), "w") as f:
397
+ for r in runs.values():
398
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
399
+ with open(os.path.join(lff, "tasks.json"), "w") as f:
400
+ json.dump(dict(causes=CAUSES, phase_codes=PHASES, tasks=tasks), f, indent=1, ensure_ascii=False)
401
+ with open(os.path.join(lff, "batches.json"), "w") as f:
402
+ json.dump(BATCH_NOTES, f, indent=1)
403
+ with open(os.path.join(lff, "rejected.json"), "w") as f:
404
+ json.dump(plan["rejected"], f, indent=1)
405
+ here = os.path.dirname(os.path.abspath(__file__))
406
+ for s in ("lerobot_replay.py", "lerobot_export.py"):
407
+ shutil.copy(os.path.join(here, s), os.path.join(lff, "code", s))
408
+
409
+
410
+ def main():
411
+ ap = argparse.ArgumentParser()
412
+ ap.add_argument("step", choices=["plan", "shard", "merge"])
413
+ ap.add_argument("--work", required=True)
414
+ ap.add_argument("--raw", default="")
415
+ ap.add_argument("--runs-root", default="")
416
+ ap.add_argument("--out", default="")
417
+ ap.add_argument("--paper", default="")
418
+ ap.add_argument("--task-set", default="")
419
+ ap.add_argument("--repo-id", default="lffbench/agent-replays")
420
+ ap.add_argument("--batches", default="")
421
+ ap.add_argument("--limit", type=int, default=0)
422
+ ap.add_argument("--shard", type=int, default=0)
423
+ ap.add_argument("--nshards", type=int, default=1)
424
+ ap.add_argument("--threads", type=int, default=2)
425
+ ap.add_argument("--vcodec", default="libsvtav1")
426
+ a = ap.parse_args()
427
+ {"plan": cmd_plan, "shard": cmd_shard, "merge": cmd_merge}[a.step](a)
428
+
429
+
430
+ if __name__ == "__main__":
431
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/lerobot_replay.py ADDED
@@ -0,0 +1,744 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay logged LA-interface agent runs (Codex, Claude Code, the API driver) on the same task code, verify the replay
2
+ against the logged robot reports, and (record mode) write a dense 20 Hz trajectory with annotations, the input of the
3
+ LeRobot export (scripts/lerobot_export.py).
4
+
5
+ python scripts/lerobot_replay.py check <run_dir> [<run_dir> ...] [--json out.json] # replay only, print fidelity
6
+ python scripts/lerobot_replay.py record <run_dir> --out <raw_root> [--res 256]
7
+
8
+ Why an exact replay is possible: the robot server owns the simulator, and the agent changes it only through robot
9
+ commands, which events.jsonl logs with their arguments in order (`call` / `done`). MuJoCo is deterministic, robosuite
10
+ is built with initialization_noise=None, and the instance comes from the seed. The replay re-issues the commands exactly
11
+ like robot_server._handle_v2 / _done (same defaults, same rejection rules, same resets between attempts, the same
12
+ outcome() calls, which also step the simulator) and compares every logged report (eef position, yaw, gripper width,
13
+ ok, holding / touched flags) and every logged outcome dict with the replayed one. Only runs whose contract.json code
14
+ hashes equal the current files are expected to match (check_code()).
15
+
16
+ Record mode wraps env.step: before each control step it stores the observation of that step (agentview + wrist RGB,
17
+ proprioception, MuJoCo state) and the 7-D OSC action passed to env.step, i.e. frame t = (o_t, a_t). Episodes:
18
+ protocol "cross" -> one episode per attempt (the scene is reset between attempts); protocol "within" -> one episode
19
+ per run (the scene persists; attempts are segments of the episode). Rendering does not change the physics, and the
20
+ fidelity check runs in record mode too. Per episode the recorder writes <raw_root>/<batch>/<run>/epNN/:
21
+ agentview.mp4, wrist.mp4 lossless RGB H.264 (intermediate; the export re-encodes)
22
+ frames.npz per-frame numeric arrays (see Recorder.state) + labels attempt / command / phase
23
+ sim_state.npy MuJoCo state per frame (sim.get_state().flatten(): time, qpos, qvel)
24
+ final_*.png, final.npz observation after the last control step (the state the outcome was judged in)
25
+ annotation.json episode annotation (build_annotation)
26
+ and <raw_root>/<batch>/<run>/replay.json (fidelity) when the whole run is done.
27
+ """
28
+ import argparse
29
+ import ast
30
+ import hashlib
31
+ import importlib
32
+ import json
33
+ import math
34
+ import os
35
+ import pkgutil
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import time
40
+ from collections import defaultdict
41
+
42
+ import numpy as np
43
+
44
+ LFF_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
45
+ sys.path.insert(0, LFF_ROOT)
46
+
47
+ from lffbench import envs # noqa: E402
48
+ from lffbench import tasks as task_pkg # noqa: E402
49
+ from lffbench.agent import camera as C # noqa: E402
50
+ from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor, _json_default # noqa: E402
51
+ from lffbench.task_base import TASKS # noqa: E402
52
+
53
+ for _m in pkgutil.iter_modules(task_pkg.__path__):
54
+ importlib.import_module(f"lffbench.tasks.{_m.name}")
55
+
56
+ # per-frame phase label: move / gripper = inside an agent's move_eef command; judge = control steps run by the
57
+ # task's outcome() check after `finish` (the arm holds still; not an agent action)
58
+ PHASES = {"move": 0, "gripper": 1, "judge": 2}
59
+ FPS = 20
60
+ SCHEMA = "lff-replay-1"
61
+
62
+ # error events in the outcome dict (scripts/outcomes.py): an attempt-1 success with one of these is "IR"
63
+ ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
64
+ ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
65
+ "n_missed_strikes", "n_open_gripper_pushes")
66
+
67
+
68
+ def load_jsonl(p):
69
+ out = []
70
+ if not os.path.exists(p):
71
+ return out
72
+ with open(p) as f:
73
+ for line in f:
74
+ line = line.strip()
75
+ if line:
76
+ try:
77
+ out.append(json.loads(line))
78
+ except ValueError:
79
+ pass
80
+ return out
81
+
82
+
83
+ def norm_json(o):
84
+ return json.loads(json.dumps(o, default=_json_default))
85
+
86
+
87
+ def sha256(p):
88
+ with open(p, "rb") as f:
89
+ return hashlib.sha256(f.read()).hexdigest()
90
+
91
+
92
+ def check_code(run_dir):
93
+ """[(file, logged hash, current hash)] for the server code files whose hash differs from the run's contract."""
94
+ p = os.path.join(run_dir, "contract.json")
95
+ if not os.path.exists(p):
96
+ return [("contract.json", None, None)]
97
+ files = json.load(open(p))["contract"].get("server_code_files", {})
98
+ bad = []
99
+ for f, h in files.items():
100
+ q = os.path.join(LFF_ROOT, f)
101
+ cur = sha256(q) if os.path.exists(q) else None
102
+ if cur != h:
103
+ bad.append((f, h, cur))
104
+ return bad
105
+
106
+
107
+ def diff_json(a, b, path="", tol=0.0, out=None, limit=20):
108
+ """Differences between two JSON values (numbers compared with an absolute tolerance)."""
109
+ out = [] if out is None else out
110
+ if len(out) >= limit:
111
+ return out
112
+ if isinstance(a, dict) and isinstance(b, dict):
113
+ for k in sorted(set(a) | set(b)):
114
+ if k not in a or k not in b:
115
+ out.append((f"{path}.{k}", a.get(k, "<missing>"), b.get(k, "<missing>")))
116
+ else:
117
+ diff_json(a[k], b[k], f"{path}.{k}", tol, out, limit)
118
+ elif isinstance(a, list) and isinstance(b, list):
119
+ if len(a) != len(b):
120
+ out.append((path, f"len {len(a)}", f"len {len(b)}"))
121
+ else:
122
+ for i, (x, y) in enumerate(zip(a, b)):
123
+ diff_json(x, y, f"{path}[{i}]", tol, out, limit)
124
+ elif isinstance(a, bool) or isinstance(b, bool) or not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
125
+ if a != b:
126
+ out.append((path, a, b))
127
+ elif not (abs(float(a) - float(b)) <= tol or (math.isnan(float(a)) and math.isnan(float(b)))):
128
+ out.append((path, a, b))
129
+ return out
130
+
131
+
132
+ def error_event(o):
133
+ """True / False if the outcome dict says whether a mistake happened in the attempt, None if the task logs none."""
134
+ if not isinstance(o, dict):
135
+ return None
136
+ keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
137
+ if not keys:
138
+ return None
139
+ return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
140
+
141
+
142
+ # ====================================================================================================== logs -> notes
143
+
144
+ class RunLog:
145
+ """Everything about a run that comes from its logs alone (no simulator): commands with timing, the agent's
146
+ narration around every robot command (trajectory.jsonl), attempt outcomes, harness / model, batch condition."""
147
+
148
+ def __init__(self, run_dir, manifest=None):
149
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
150
+ self.run = os.path.basename(self.run_dir)
151
+ self.batch = os.path.basename(os.path.dirname(self.run_dir))
152
+ self.ev = load_jsonl(os.path.join(self.run_dir, "events.jsonl"))
153
+ self.start = next(e for e in self.ev if e["ev"] == "session_start")
154
+ self.calls, self.dones, self.harness_status = {}, [], []
155
+ last = None
156
+ for e in self.ev:
157
+ if e["ev"] == "call":
158
+ self.calls[(int(e["attempt"]), int(e["step"]))] = e
159
+ last = e
160
+ elif e["ev"] == "done":
161
+ self.dones.append(e)
162
+ last = e
163
+ elif e["ev"] == "http" and last is not None and "think_s" not in last:
164
+ ok = (last["ev"] == "call" and e.get("cmd") == last.get("cmd")) or \
165
+ (last["ev"] == "done" and e.get("cmd") in ("finish", "done", "move_eef", "observe"))
166
+ if ok:
167
+ last["think_s"], last["server_s"] = e.get("think_s"), e.get("server_s")
168
+ self.manifest = manifest or {}
169
+ self.entry = next((r for r in self.manifest.get("runs", []) if r.get("run") == self.run), {}) or {}
170
+ p = os.path.join(self.run_dir, "harness.json")
171
+ self.harness = json.load(open(p)) if os.path.exists(p) else {}
172
+ self.traj = load_jsonl(os.path.join(self.run_dir, "trajectory.jsonl"))
173
+ self._narration()
174
+
175
+ # ---------------------------------------------------------------- agent narration
176
+ def _narration(self):
177
+ """notes[(attempt, step)] = what the agent wrote / did since the previous robot command, up to this one;
178
+ finish_notes[attempt] likewise for the agent's finish call; final_report = its last message."""
179
+ self.notes, self.finish_notes, self.final_report, self.headers = {}, {}, "", []
180
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
181
+ attempt = 1
182
+
183
+ def take():
184
+ nonlocal buf
185
+ out = {k: v for k, v in buf.items() if v}
186
+ buf = dict(messages=[], reasoning=[], shell=[], viewed=[])
187
+ return out
188
+
189
+ last_msg = ""
190
+ for t in self.traj:
191
+ if t.get("kind") == "header":
192
+ self.headers.append(t.get("agent") or {})
193
+ continue
194
+ if t.get("kind") != "step":
195
+ continue
196
+ if (t.get("message") or "").strip():
197
+ buf["messages"].append(t["message"].strip())
198
+ last_msg = t["message"].strip()
199
+ if (t.get("reasoning_content") or "").strip():
200
+ buf["reasoning"].append(t["reasoning_content"].strip())
201
+ res = {r.get("source_call_id"): r for r in (t.get("observation") or {}).get("results", [])}
202
+ for c in t.get("tool_calls") or []:
203
+ fn, args = c.get("function_name"), c.get("arguments") or {}
204
+ if fn == "shell":
205
+ buf["shell"].append(str(args.get("command", ""))[:2000])
206
+ elif fn == "view_images":
207
+ buf["viewed"].extend(args.get("paths") or [])
208
+ elif fn == "robot":
209
+ cmd = str(args.get("command", "")).strip()
210
+ r = res.get(c.get("tool_call_id")) or {}
211
+ try:
212
+ rep = json.loads(r.get("content") or "{}")
213
+ except ValueError:
214
+ rep = {}
215
+ word = cmd.split()[0] if cmd else ""
216
+ m = re.search(r"a(\d+)_s(\d+)_state\.json", str(rep.get("state_file", "")))
217
+ if word in ("move_eef", "observe") and m:
218
+ a, s = int(m.group(1)), int(m.group(2))
219
+ n = take()
220
+ n["command"] = cmd
221
+ self.notes[(a, s)] = n
222
+ attempt = a
223
+ elif word in ("finish", "done"):
224
+ n = take()
225
+ n["command"] = cmd
226
+ n["reply"] = {k: rep.get(k) for k in ("feedback", "message") if rep.get(k)}
227
+ self.finish_notes.setdefault(attempt, n)
228
+ if rep.get("ended") and not rep.get("message", "").startswith("The episode is over"):
229
+ attempt += 1
230
+ # status / help / errors: their narration stays in the buffer for the next command
231
+ self.final_report = last_msg
232
+
233
+ # ---------------------------------------------------------------- run-level labels
234
+ def attempts(self):
235
+ out = []
236
+ for e in self.dones:
237
+ o = e.get("outcome") or {}
238
+ if isinstance(o, str):
239
+ try:
240
+ o = ast.literal_eval(o)
241
+ except (ValueError, SyntaxError):
242
+ o = {}
243
+ out.append(dict(attempt=int(e["attempt"]), success=e.get("success") in (True, "True"), outcome=o,
244
+ reason=e.get("reason") or ""))
245
+ return sorted(out, key=lambda x: x["attempt"])
246
+
247
+ def condition(self):
248
+ s, en = self.start, self.entry
249
+ mem = s.get("memory", en.get("mem"))
250
+ chain = en.get("chain")
251
+ if mem == "full":
252
+ cond = "with_history"
253
+ elif chain:
254
+ cond = "memory_free_retry"
255
+ else:
256
+ cond = "independent_single_attempt"
257
+ return cond, chain
258
+
259
+ def outcome_class(self):
260
+ """CS / IR / S? / XR / F for history runs (scripts/outcomes.py), else None."""
261
+ att = self.attempts()
262
+ if not att or self.start.get("memory") != "full":
263
+ return None, "".join("S" if a["success"] else "F" for a in att)
264
+ hist = "".join("S" if a["success"] else "F" for a in att)
265
+ if att[0]["success"]:
266
+ ev = error_event(att[0]["outcome"])
267
+ cls = "S?" if ev is None else ("IR" if ev else "CS")
268
+ else:
269
+ cls = "XR" if any(a["success"] for a in att) else "F"
270
+ return cls, hist
271
+
272
+ def agent_info(self):
273
+ h, en = self.harness, self.entry
274
+ hdr = self.headers[0] if self.headers else {}
275
+ return dict(harness=h.get("harness") or en.get("agent_harness") or hdr.get("name"),
276
+ harness_version=h.get("version") or hdr.get("version"),
277
+ harness_binary_sha256=(h.get("binary") or {}).get("sha256"),
278
+ model=h.get("model") or en.get("model") or hdr.get("model_name"),
279
+ effort=h.get("effort") or en.get("effort") or hdr.get("effort"),
280
+ provider=h.get("provider") or en.get("provider"),
281
+ codex_catalog=en.get("codex_catalog"), auth=en.get("codex_auth") or en.get("claude_auth"),
282
+ jail=en.get("jail"))
283
+
284
+
285
+ # ====================================================================================================== recording
286
+
287
+ class EpisodeSink:
288
+ """Streams one episode to disk: two lossless RGB videos while recording, numeric arrays when closed."""
289
+
290
+ def __init__(self, path):
291
+ self.path = path
292
+ os.makedirs(path, exist_ok=True)
293
+ self.w = None
294
+ self.num = defaultdict(list)
295
+ self.n = 0
296
+
297
+ def add(self, st, imgs):
298
+ import imageio
299
+ if self.w is None:
300
+ self.w = [imageio.get_writer(os.path.join(self.path, f"{k}.mp4"), fps=FPS, codec="libx264rgb",
301
+ pixelformat="rgb24", macro_block_size=1,
302
+ ffmpeg_params=["-crf", "0", "-preset", "veryfast", "-threads", "1"], ffmpeg_log_level="error")
303
+ for k in ("agentview", "wrist")]
304
+ for w, im in zip(self.w, imgs):
305
+ w.append_data(im)
306
+ for k, v in st.items():
307
+ self.num[k].append(v)
308
+ self.n += 1
309
+
310
+ def close(self, final_state, final_imgs):
311
+ from PIL import Image
312
+ if self.w is not None:
313
+ for w in self.w:
314
+ w.close()
315
+ arr = {k: np.asarray(v) for k, v in self.num.items() if k != "sim_state"}
316
+ np.savez(os.path.join(self.path, "frames.npz"), **arr)
317
+ if self.num.get("sim_state"):
318
+ np.save(os.path.join(self.path, "sim_state.npy"), np.asarray(self.num["sim_state"], np.float64))
319
+ np.savez(os.path.join(self.path, "final.npz"), **{k: np.asarray(v) for k, v in final_state.items()})
320
+ for k, im in zip(("agentview", "wrist"), final_imgs):
321
+ Image.fromarray(im).save(os.path.join(self.path, f"final_{k}.png"))
322
+
323
+
324
+ class Recorder:
325
+ """Captures (o_t, a_t) before every env.step while active and streams it into the current EpisodeSink."""
326
+
327
+ def __init__(self, rp, res):
328
+ self.rp, self.res = rp, int(res)
329
+ self.active = False
330
+ self.sink = None
331
+ self.cur = dict(attempt=1, command=-1, phase=PHASES["move"])
332
+ env = rp.task.env
333
+ self.env, self.rob = env, env.robots[0]
334
+ self.cams = (C.mj_cam("agentview"), C.mj_cam("wrist"))
335
+ orig = env.step
336
+
337
+ def step(a):
338
+ if self.active and self.sink is not None:
339
+ self.capture(np.asarray(a, np.float64))
340
+ out = orig(a)
341
+ if self.active and self.sink is not None:
342
+ self.rp.poll_events(self.sink.n - 1)
343
+ return out
344
+
345
+ env.step = step
346
+
347
+ @property
348
+ def n(self):
349
+ return self.sink.n if self.sink is not None else 0
350
+
351
+ def state(self):
352
+ import robosuite.utils.transform_utils as T
353
+ env, rob = self.env, self.rob
354
+ d = env.sim.data
355
+ eef = np.array(d.site_xpos[rob.eef_site_id], np.float64)
356
+ q_xyzw = T.convert_quat(np.array(d.get_body_xquat(rob.robot_model.eef_name), np.float64), to="xyzw")
357
+ gq = np.array([d.qpos[x] for x in rob._ref_gripper_joint_pos_indexes], np.float64)
358
+ try:
359
+ flat = np.asarray(env.sim.get_state().flatten(), np.float64)
360
+ except Exception:
361
+ flat = np.concatenate([[d.time], d.qpos, d.qvel]).astype(np.float64)
362
+ sk = self.rp.task.sk
363
+ return dict(eef_pos=eef, eef_quat_xyzw=q_xyzw, eef_axis_angle=np.asarray(T.quat2axisangle(q_xyzw), np.float64),
364
+ gripper_qpos=gq, joint_pos=np.array(d.qpos[rob._ref_joint_pos_indexes], np.float64),
365
+ joint_vel=np.array(d.qvel[rob._ref_joint_vel_indexes], np.float64),
366
+ gripper_width=np.float64(abs(gq[0] - gq[1])), eef_site_mat=np.array(d.site_xmat[rob.eef_site_id], np.float64),
367
+ eef_yaw_cmd=np.float64(getattr(sk, "yaw", 0.0)), gripper_cmd=np.float64(getattr(sk, "grip", -1.0)),
368
+ sim_time=np.float64(d.time), sim_state=flat)
369
+
370
+ def images(self):
371
+ return [envs.render(self.env, c, self.res) for c in self.cams]
372
+
373
+ def capture(self, a):
374
+ st = self.state()
375
+ st.update(action=a, attempt=np.int64(self.cur["attempt"]), command=np.int64(self.cur["command"]),
376
+ phase=np.int64(self.cur["phase"]))
377
+ self.sink.add(st, self.images())
378
+
379
+
380
+ class RunReplay:
381
+ def __init__(self, run_dir, record=False, res=256, out_root=None, manifest=None):
382
+ self.run_dir = os.path.abspath(run_dir.rstrip("/"))
383
+ self.run_name = os.path.basename(self.run_dir)
384
+ self.log = RunLog(self.run_dir, manifest)
385
+ self.ev = self.log.ev
386
+ self.start = self.log.start
387
+ cp = os.path.join(self.run_dir, "contract.json")
388
+ self.contract = json.load(open(cp))["contract"] if os.path.exists(cp) else {}
389
+ spec = self.contract.get("image_spec") or {}
390
+ self.image_res = int(spec.get("width", 512))
391
+ self.code_diff = check_code(self.run_dir)
392
+ s = self.start
393
+ self.task = TASKS[s["task"]](cam_res=self.image_res)
394
+ inst = self.task.sample_instance(s["seed"])
395
+ logged = s.get("inst") or {}
396
+ sampled = norm_json({k: v for k, v in inst.items() if not k.startswith("_")})
397
+ self.inst_diff = diff_json(sampled, logged, "inst")
398
+ if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
399
+ inst.update(logged) # controlled arms / nominal: the server overrode these instance fields
400
+ self.inst_diff = []
401
+ self.inst = inst
402
+ self.protocol = getattr(self.task, "protocol", "cross")
403
+ self.k = int(s.get("k") or self.task.max_attempts)
404
+ self.attempt = 1
405
+ self.mismatch = [] # (where, what, logged, replayed)
406
+ self.n_checked = 0
407
+ self.max_dev_m = 0.0
408
+ self.unfinished = None
409
+ self.rec = Recorder(self, res) if record else None
410
+ self.res = int(res)
411
+ self.out_root = out_root
412
+ self.n_mon = 0
413
+ self.events, self.spans, self.ep_attempts, self.ep_index = [], [], [], 0
414
+ self.episodes = [] # summaries of the written episodes
415
+ self.task.reset_instance(self.inst)
416
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
417
+ sim = self.task.env.sim
418
+ bid = sim.model.body_name2id("robot0_base")
419
+ self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
420
+ if self.rec:
421
+ self._open_episode()
422
+
423
+ # ------------------------------------------------------------------ episodes
424
+ def _ep_dir(self):
425
+ return os.path.join(self.out_root, self.log.batch, self.run_name, f"ep{self.ep_index:02d}")
426
+
427
+ def _open_episode(self):
428
+ self.rec.sink = EpisodeSink(self._ep_dir())
429
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
430
+ self.rec.active = True
431
+ self.events, self.spans, self.ep_attempts = [], [], []
432
+ self.ep_initial = self.rec.state() # state right after the reset (before frame 0)
433
+
434
+ def close_episode(self):
435
+ if not self.rec:
436
+ self.ep_attempts = []
437
+ return
438
+ sink = self.rec.sink
439
+ st = self.rec.state()
440
+ imgs = self.rec.images()
441
+ st.pop("sim_state", None)
442
+ sink.close(dict(st, sim_state=self.rec.state()["sim_state"]), imgs)
443
+ ann = build_annotation(self, sink)
444
+ with open(os.path.join(sink.path, "annotation.json"), "w") as f:
445
+ json.dump(ann, f, indent=1, default=_json_default)
446
+ self.episodes.append(dict(dir=os.path.relpath(sink.path, self.out_root), n_frames=sink.n,
447
+ attempts=[a["attempt"] for a in self.ep_attempts]))
448
+ self.rec.active = False
449
+ self.rec.sink = None
450
+ self.ep_index += 1
451
+
452
+ # ------------------------------------------------------------------ monitor events (task-side error events)
453
+ def poll_events(self, frame):
454
+ mon = getattr(self.task, "mon", None)
455
+ evs = mon.get("events") if isinstance(mon, dict) else None
456
+ if not isinstance(evs, list):
457
+ return
458
+ if len(evs) < self.n_mon: # monitor was rebuilt
459
+ self.n_mon = 0
460
+ for e in evs[self.n_mon:]:
461
+ self.events.append(dict(frame=int(frame), attempt=self.attempt,
462
+ event=norm_json(e) if isinstance(e, dict) else str(e)))
463
+ self.n_mon = len(evs)
464
+
465
+ # ------------------------------------------------------------------ state as the server reports it
466
+ def proprio_la(self):
467
+ p = self.ex.proprio()
468
+ pos = [round(float(v), 4) for v in np.asarray(p["eef_pos"], float) - self.base_off]
469
+ return dict(eef_pos=pos, eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
470
+
471
+ def compare(self, where, rep_logged, rep):
472
+ self.n_checked += 1
473
+ for k in ("eef_pos", "eef_yaw_deg", "gripper_width_m"):
474
+ if k not in rep_logged or k not in rep:
475
+ continue
476
+ a, b = rep_logged[k], rep[k]
477
+ if k == "eef_pos":
478
+ dev = float(np.max(np.abs(np.asarray(a, float) - np.asarray(b, float))))
479
+ self.max_dev_m = max(self.max_dev_m, dev)
480
+ if dev > 1.5e-4:
481
+ self.mismatch.append((where, k, a, b))
482
+ elif abs(float(a) - float(b)) > (0.11 if k == "eef_yaw_deg" else 1.5e-4):
483
+ self.mismatch.append((where, k, a, b))
484
+ if bool(rep_logged.get("ok", True)) != bool(rep.get("ok", True)):
485
+ self.mismatch.append((where, "ok", rep_logged.get("ok"), rep.get("ok")))
486
+
487
+ def _span(self, e, f0, kind):
488
+ if self.rec:
489
+ self.spans.append(dict(attempt=self.attempt, step=int(e.get("step", -1)), kind=kind, frame_start=f0,
490
+ frame_end=self.rec.n))
491
+
492
+ # ------------------------------------------------------------------ commands (robot_server._handle_v2)
493
+ def move_eef(self, e):
494
+ args = e.get("args") or {}
495
+ where = f"a{e['attempt']}s{e['step']}"
496
+ logged = e.get("report") or {}
497
+ f0 = self.rec.n if self.rec else 0
498
+ p = self.ex.proprio()
499
+ if set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}:
500
+ self._span(e, f0, "error")
501
+ return self.compare(where, logged, dict(ok=False))
502
+ off = self.base_off
503
+ try:
504
+ cur = np.asarray(p["eef_pos"], float) - off
505
+ tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
506
+ yaw = float(args.get("yaw", p["eef_yaw_deg"]))
507
+ speed = None if args.get("speed") in (None, "") else float(args["speed"])
508
+ except (TypeError, ValueError):
509
+ self._span(e, f0, "error")
510
+ return self.compare(where, logged, dict(ok=False))
511
+ grip = args.get("gripper")
512
+ if grip not in (None, "open", "close"):
513
+ self._span(e, f0, "error")
514
+ return self.compare(where, logged, dict(ok=False))
515
+ moving = any(k in args for k in ("x", "y", "z", "yaw"))
516
+ tgt_w = np.asarray(tgt) + off
517
+ if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
518
+ self._span(e, f0, "rejected")
519
+ return self.compare(where, logged, dict(ok=False, **self.proprio_la()))
520
+ raw = {}
521
+ if self.rec:
522
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["move"])
523
+ if moving:
524
+ mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
525
+ if speed is not None:
526
+ mv["speed"] = speed
527
+ raw.update(self.ex.call("move_to", mv).report)
528
+ if grip is not None:
529
+ if self.rec:
530
+ self.rec.cur = dict(attempt=self.attempt, command=int(e["step"]), phase=PHASES["gripper"])
531
+ raw.update(self.ex.call("open_gripper" if grip == "open" else "close_gripper", {}).report)
532
+ rep = dict(ok=bool(raw.get("ok", True)), **self.proprio_la())
533
+ self.compare(where, logged, rep)
534
+ lr = e.get("raw") or {}
535
+ for k in ("holding_object", "touched_object"):
536
+ if k in lr and k in raw and bool(lr[k]) != bool(raw[k]):
537
+ self.mismatch.append((where, "raw." + k, lr[k], raw[k]))
538
+ self._span(e, f0, "move_eef")
539
+
540
+ def observe(self, e):
541
+ f0 = self.rec.n if self.rec else 0
542
+ self._span(e, f0, "observe")
543
+
544
+ def done(self, e):
545
+ f0 = self.rec.n if self.rec else 0
546
+ if self.rec:
547
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["judge"])
548
+ out = self.task.outcome(self.inst)
549
+ succ = bool(out["success"])
550
+ where = f"a{e['attempt']}done"
551
+ if succ != bool(e.get("success") in (True, "True")):
552
+ self.mismatch.append((where, "success", e.get("success"), succ))
553
+ lo = e.get("outcome") or {}
554
+ ro = norm_json({k: v for k, v in out.items() if k != "feedback"})
555
+ if isinstance(lo, dict):
556
+ for d in diff_json(lo, ro, "outcome", tol=1e-6, limit=8):
557
+ self.mismatch.append((where,) + d)
558
+ info = dict(attempt=self.attempt, success=succ, outcome=ro, finish_reason=e.get("reason", ""),
559
+ feedback_shown=e.get("feedback", ""), auto_ended="(automatic)" in str(e.get("reason", "")),
560
+ think_s=e.get("think_s"))
561
+ try:
562
+ info["feedback_f2"] = self.task.feedback(self.inst, out, "F2")
563
+ except Exception as ex_:
564
+ info["feedback_f2"] = f"<unavailable: {type(ex_).__name__}>"
565
+ if self.rec:
566
+ info["judge_frames"] = [f0, self.rec.n]
567
+ self.ep_attempts.append(info)
568
+ last = self.attempt >= self.k or succ or bool(out.get("terminal"))
569
+ if self.protocol == "cross" or last:
570
+ self.close_episode()
571
+ if last:
572
+ return True
573
+ self.attempt += 1
574
+ if self.protocol == "cross":
575
+ self.task.reset_instance(self.inst)
576
+ self.n_mon = 0
577
+ if self.rec:
578
+ self._open_episode()
579
+ elif self.rec:
580
+ self.rec.cur = dict(attempt=self.attempt, command=-1, phase=PHASES["move"])
581
+ self.ex = ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=("agentview", "wrist"))
582
+ return False
583
+
584
+ def run(self):
585
+ t0 = time.time()
586
+ finished = False
587
+ for e in self.ev:
588
+ if e["ev"] == "call":
589
+ if e.get("cmd") == "move_eef":
590
+ self.move_eef(e)
591
+ elif e.get("cmd") == "observe":
592
+ self.observe(e)
593
+ else:
594
+ self.mismatch.append((f"a{e.get('attempt')}s{e.get('step')}", "unsupported command", e.get("cmd"), None))
595
+ elif e["ev"] == "done":
596
+ finished = self.done(e)
597
+ if finished:
598
+ break
599
+ self.unfinished = not finished
600
+ if not finished and self.rec and self.rec.sink is not None:
601
+ # the run ended without a final finish (agent stopped, harness died): keep it, outcome not judged
602
+ if self.rec.n or self.ep_attempts:
603
+ self.ep_attempts.append(dict(attempt=self.attempt, success=None, outcome=None, unjudged=True,
604
+ finish_reason="", feedback_shown="", auto_ended=False))
605
+ self.close_episode()
606
+ else:
607
+ shutil.rmtree(self.rec.sink.path, ignore_errors=True)
608
+ self.rec.sink = None
609
+ self.wall_s = time.time() - t0
610
+ return self
611
+
612
+ def summary(self):
613
+ return dict(run=self.run_name, batch=self.log.batch, task=self.start["task"], seed=self.start["seed"],
614
+ protocol=self.protocol, code_diff=[f for f, _, _ in self.code_diff], inst_diff=len(self.inst_diff),
615
+ n_checked=self.n_checked, n_mismatch=len(self.mismatch), max_eef_dev_m=round(self.max_dev_m, 6),
616
+ unfinished=self.unfinished, wall_s=round(getattr(self, "wall_s", 0.0), 1),
617
+ first_mismatches=[list(map(str, m)) for m in self.mismatch[:5]])
618
+
619
+
620
+ # ====================================================================================================== annotation
621
+
622
+ def task_info(task, inst):
623
+ cls = type(task)
624
+ return dict(name=cls.name, level=cls.level, family="long_horizon" if cls.name.startswith("lh_") else "hidden_variable",
625
+ category=cls.category, capabilities=list(cls.capabilities), protocol=getattr(cls, "protocol", "cross"),
626
+ max_attempts=cls.max_attempts, agent_max_steps=int(getattr(cls, "agent_max_steps", 40)),
627
+ instruction=cls.instruction)
628
+
629
+
630
+ def build_annotation(rp, sink):
631
+ """Episode annotation: provenance, agent, task + hidden variables, per-attempt outcome (incl. the privileged F2
632
+ failure description), run-level outcome class, every robot command with its frame span and the agent's narration,
633
+ task-side error events with frame indices."""
634
+ log = rp.log
635
+ s = rp.start
636
+ cond, chain = log.condition()
637
+ cls, hist = log.outcome_class()
638
+ att_all = log.attempts()
639
+ attempts = []
640
+ for a in rp.ep_attempts:
641
+ a = dict(a)
642
+ n = a["attempt"]
643
+ later = [x for x in att_all if x["attempt"] > n]
644
+ a["corrected_later_in_run"] = (None if a.get("success") is not False else any(x["success"] for x in later))
645
+ a["is_last_attempt_of_run"] = not later
646
+ fn = log.finish_notes.get(n)
647
+ if fn:
648
+ a["agent_finish"] = fn
649
+ a["error_event_in_attempt"] = error_event(a.get("outcome"))
650
+ attempts.append(a)
651
+ # post-failure reflection: what the agent wrote right after the failure feedback (before its next robot command)
652
+ for a in attempts:
653
+ nxt = sorted((k for k in log.notes if k[0] == a["attempt"] + 1), key=lambda k: k[1])
654
+ if a.get("success") is False and nxt:
655
+ note = log.notes[nxt[0]]
656
+ a["agent_reflection_after_feedback"] = {k: note[k] for k in ("messages", "reasoning") if k in note}
657
+ commands = []
658
+ for sp in rp.spans:
659
+ e = log.calls.get((sp["attempt"], sp["step"])) or {}
660
+ rep = e.get("report") or {}
661
+ c = dict(attempt=sp["attempt"], step=sp["step"], kind=sp["kind"], frame_start=sp["frame_start"],
662
+ frame_end=sp["frame_end"], command=" ".join([e.get("cmd", "")] + [f"{k}={v}" for k, v in (e.get("args") or {}).items()]),
663
+ args=e.get("args") or {}, ok=rep.get("ok"), error=rep.get("error"),
664
+ stopped_from_target=rep.get("stopped_from_target"), eef_pos_after=rep.get("eef_pos"),
665
+ gripper_width_after=rep.get("gripper_width_m"), holding_after=(e.get("raw") or {}).get("holding_object"),
666
+ touched_during=(e.get("raw") or {}).get("touched_object"), think_s=e.get("think_s"),
667
+ agent_obs_images=rep.get("images"))
668
+ note = log.notes.get((sp["attempt"], sp["step"]))
669
+ if note:
670
+ c["agent_note"] = {k: v for k, v in note.items() if k != "command"}
671
+ commands.append(c)
672
+ t_all = [x for x in (log.calls.get(k, {}).get("think_s") for k in log.calls) if x]
673
+ return dict(
674
+ schema=SCHEMA,
675
+ source=dict(batch=log.batch, run=log.run, attempts_in_episode=[a["attempt"] for a in attempts],
676
+ episode_in_run=rp.ep_index, condition=cond, memory_free_chain_of=chain,
677
+ memory_free_rep=(log.entry.get("rep") if cond == "memory_free_retry" else None),
678
+ feedback_level=s.get("feedback"), hide_k=s.get("k_shown", s.get("k")) != s.get("k"),
679
+ k=s.get("k"), perception=s.get("perception"), instruction_variant=s.get("instruction"),
680
+ contract_sha256=(json.load(open(os.path.join(rp.run_dir, "contract.json"))).get("contract_sha256")
681
+ if os.path.exists(os.path.join(rp.run_dir, "contract.json")) else None)),
682
+ agent=log.agent_info(),
683
+ task=dict(task_info(rp.task, rp.inst), seed=s.get("seed"),
684
+ instance={k: v for k, v in norm_json(rp.inst).items() if not str(k).startswith("_")}),
685
+ run_outcome=dict(outcome_class=cls, attempt_history=hist, n_attempts=len(att_all),
686
+ run_success=any(x["success"] for x in att_all) if att_all else None,
687
+ agent_final_report=log.final_report[:6000] or None,
688
+ mean_think_s=(round(float(np.mean(t_all)), 2) if t_all else None)),
689
+ attempts=attempts,
690
+ commands=commands,
691
+ task_events=rp.events,
692
+ frames=dict(n=sink.n, fps=FPS, image_res=rp.res,
693
+ phase_codes=PHASES, initial_state=dict(eef_pos=rp.ep_initial["eef_pos"],
694
+ joint_pos=rp.ep_initial["joint_pos"],
695
+ gripper_qpos=rp.ep_initial["gripper_qpos"])),
696
+ )
697
+
698
+
699
+ # ====================================================================================================== CLI
700
+
701
+ def load_manifest(run_dir):
702
+ p = os.path.join(os.path.dirname(os.path.abspath(run_dir.rstrip("/"))), "manifest.json")
703
+ return json.load(open(p)) if os.path.exists(p) else {}
704
+
705
+
706
+ def main():
707
+ ap = argparse.ArgumentParser()
708
+ ap.add_argument("mode", choices=["check", "record"])
709
+ ap.add_argument("runs", nargs="+")
710
+ ap.add_argument("--json", default="")
711
+ ap.add_argument("--out", default="")
712
+ ap.add_argument("--res", type=int, default=256)
713
+ ap.add_argument("--force", action="store_true", help="record again even if replay.json exists")
714
+ a = ap.parse_args()
715
+ rows = []
716
+ for r in a.runs:
717
+ r = r.rstrip("/")
718
+ try:
719
+ if a.mode == "check":
720
+ s = RunReplay(r, manifest=load_manifest(r)).run().summary()
721
+ else:
722
+ batch, name = os.path.basename(os.path.dirname(os.path.abspath(r))), os.path.basename(r)
723
+ rd = os.path.join(a.out, batch, name)
724
+ if os.path.exists(os.path.join(rd, "replay.json")) and not a.force:
725
+ print(json.dumps(dict(run=name, skipped="exists")), flush=True)
726
+ continue
727
+ shutil.rmtree(rd, ignore_errors=True)
728
+ rp = RunReplay(r, record=True, res=a.res, out_root=a.out, manifest=load_manifest(r)).run()
729
+ s = rp.summary()
730
+ s["episodes"] = rp.episodes
731
+ with open(os.path.join(rd, "replay.json"), "w") as f:
732
+ json.dump(s, f, indent=1)
733
+ except Exception:
734
+ import traceback
735
+ s = dict(run=os.path.basename(r), error=traceback.format_exc()[-2000:])
736
+ rows.append(s)
737
+ print(json.dumps(s), flush=True)
738
+ if a.json:
739
+ with open(a.json, "w") as f:
740
+ json.dump(rows, f, indent=1)
741
+
742
+
743
+ if __name__ == "__main__":
744
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/lerobot_sft_dataset.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build the training set for supervised fine-tuning (SFT) a VLA from the published agent replays.
3
+
4
+ Input: the unified LeRobot v3 release named by /mnt/cpfs/shared/datasets/lffbench_agent_replays/CURRENT.json, plus any
5
+ package it does not hold yet (--extra-source). Output: one LeRobot v2.1 dataset with the feature names of openpi's LIBERO
6
+ config (image, wrist_image, state, actions), one episode per successful attempt:
7
+
8
+ - only frames of attempts judged successful, without the evaluator's outcome check (annotation.phase == 2);
9
+ - a multi-attempt `within` episode gives one clip per successful attempt, so action chunks never cross attempts;
10
+ - the safety routine of l6_sequence_resume's emergency stop drives the arm without the agent, so it is cut out;
11
+ - one instance per task is held out by (task, seed) and written to a separate dataset, never to the training one;
12
+ - videos are remuxed packet by packet from the published files: the pixels are the validated ones, nothing is re-encoded.
13
+
14
+ python scripts/lerobot_sft_dataset.py build --out DIR --repo-id lff_sft_vX --holdout sets/main_v2_3inst.txt [--holdout-seed task:seed ...]
15
+ python scripts/lerobot_sft_dataset.py verify DIR/<repo-id> # in the OpenPI environment: reads through its LeRobot
16
+ python scripts/lerobot_sft_dataset.py norm DIR/<repo-id> --assets <assets_base_dir>/pi05_lff/<repo-id>
17
+
18
+ Run with an environment that has av and pyarrow (shared/envs/openpi-ppu20).
19
+ """
20
+ import argparse
21
+ import collections
22
+ import functools
23
+ import glob
24
+ import json
25
+ import multiprocessing
26
+ import os
27
+ import random
28
+ import time
29
+ from concurrent.futures import ProcessPoolExecutor
30
+
31
+ import av
32
+ import numpy as np
33
+ import pyarrow as pa
34
+ import pyarrow.parquet as pq
35
+
36
+ DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays"
37
+ FPS = 20
38
+ CAMERAS = {"image": "observation.images.image", "wrist_image": "observation.images.wrist_image"}
39
+ CHUNK = 1000
40
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
41
+
42
+
43
+ def sources(extra):
44
+ """The canonical release, which already merges the earlier packages, and what it does not hold yet."""
45
+ return [json.load(open(os.path.join(DATA, "CURRENT.json")))["dataset"]] + list(extra or [])
46
+
47
+
48
+ def read_holdout(path, extra):
49
+ out = {}
50
+ if path:
51
+ for line in open(path):
52
+ if line.strip() and not line.startswith("#"):
53
+ t, s = line.strip().split(":")
54
+ out[t] = {int(x) for x in s.split(",")}
55
+ for item in extra or []:
56
+ t, s = item.split(":")
57
+ out[t] = {int(x) for x in s.split(",")}
58
+ return out
59
+
60
+
61
+ def plan_source(name, only_task=None):
62
+ """Successful attempts of one published dataset, as frame ranges inside its episodes."""
63
+ p = os.path.join(DATA, name)
64
+ rows = {}
65
+ for line in open(os.path.join(p, "lff/episodes.jsonl")):
66
+ r = json.loads(line)
67
+ if any(r["success"]) and (not only_task or r["task"] in only_task):
68
+ rows[r["episode_index"]] = r
69
+ if not rows:
70
+ return [], collections.Counter()
71
+ meta = []
72
+ for f in sorted(glob.glob(os.path.join(p, "meta/episodes/chunk-*/file-*.parquet"))):
73
+ keep = ["episode_index", "length", "dataset_from_index"]
74
+ for key in CAMERAS.values():
75
+ keep += [f"videos/{key}/chunk_index", f"videos/{key}/file_index", f"videos/{key}/from_timestamp"]
76
+ meta += pq.read_table(f, columns=keep).to_pylist()
77
+ meta = {m["episode_index"]: m for m in meta}
78
+ cols = ["index", "episode_index", "frame_index", "annotation.attempt_index", "annotation.phase", "annotation.attempt_success",
79
+ "annotation.command_index", "action"]
80
+ keep, located, stops = {}, {}, {}
81
+ for f in sorted(glob.glob(os.path.join(p, "data/chunk-*/file-*.parquet"))):
82
+ t = pq.read_table(f, columns=cols)
83
+ ep = t["episode_index"].to_numpy().reshape(-1)
84
+ fr = t["frame_index"].to_numpy().reshape(-1)
85
+ att = t["annotation.attempt_index"].to_numpy().reshape(-1)
86
+ ph = t["annotation.phase"].to_numpy().reshape(-1)
87
+ su = t["annotation.attempt_success"].to_numpy().reshape(-1)
88
+ cmd = t["annotation.command_index"].to_numpy().reshape(-1)
89
+ grip = np.stack(t["action"].to_numpy(zero_copy_only=False))[:, 6]
90
+ first_index = int(t["index"][0].as_py())
91
+ for e in np.unique(ep):
92
+ if int(e) not in rows:
93
+ continue
94
+ located[int(e)] = (f, first_index)
95
+ m = (ep == e) & (su == 1) & (ph != 2)
96
+ for a in np.unique(att[m]):
97
+ ix = np.sort(fr[m & (att == a)])
98
+ keep[(int(e), int(a))] = ix
99
+ if rows[int(e)]["task"] == "l6_sequence_resume":
100
+ o = np.flatnonzero(ep == e)
101
+ o = o[np.argsort(fr[o])]
102
+ stops[int(e)] = emergency_stops(fr[o], att[o], cmd[o], ph[o], grip[o])
103
+ clips, stats = [], collections.Counter()
104
+ for (e, a), ix in sorted(keep.items()):
105
+ r = rows[e]
106
+ spans = [(int(ix[0]), int(ix[-1]) + 1)]
107
+ if not (np.diff(ix) == 1).all():
108
+ raise ValueError(f"{name} episode {e} attempt {a}: frames are not contiguous")
109
+ for s_att, cut0, cut1 in stops.get(e, []):
110
+ if s_att == a:
111
+ stats["emergency_frames_cut"] += cut1 - cut0
112
+ spans = [x for x in ((spans[0][0], cut0), (cut1, spans[0][1])) if x[1] > x[0]]
113
+ for s0, s1 in spans:
114
+ clips.append(dict(source=name, episode=e, attempt=a, start=s0, stop=s1, task=r["task"], seed=r["seed"], run=r["run"], batch=r["batch"],
115
+ model=r["model"], condition=r["condition"], protocol=r["protocol"], instruction=r["instruction"], cause=r["paper_cause"],
116
+ first_attempt=a == 1, run_outcome_class=r.get("run_outcome_class"),
117
+ videos={cam: dict(chunk=meta[e][f"videos/{key}/chunk_index"], file=meta[e][f"videos/{key}/file_index"],
118
+ t0=meta[e][f"videos/{key}/from_timestamp"]) for cam, key in CAMERAS.items()},
119
+ ep_from=meta[e]["dataset_from_index"], data_file=located[e][0], data_first_index=located[e][1]))
120
+ return clips, stats
121
+
122
+
123
+ def emergency_stops(frame, attempt, command, phase, grip):
124
+ """l6_sequence_resume's emergency stop opens the jaws in the middle of a move and then drives the arm home until that
125
+ command returns; an agent's move never changes the gripper while it moves. So the stop is where the gripper action
126
+ turns from close to open inside one motion command, and the routine is the rest of that command.
127
+ Returns [(attempt, first frame of the routine, end of the command)]."""
128
+ out = []
129
+ for i in range(1, len(frame)):
130
+ if phase[i] == 0 == phase[i - 1] and command[i] == command[i - 1] and attempt[i] == attempt[i - 1] \
131
+ and grip[i - 1] > 0 > grip[i]:
132
+ end = i
133
+ while end < len(frame) and command[end] == command[i] and attempt[end] == attempt[i]:
134
+ end += 1
135
+ out.append((int(attempt[i]), int(frame[i]), int(frame[end - 1]) + 1))
136
+ return out
137
+
138
+
139
+ def remux(src, dst, f0, n, t0):
140
+ """Copy n frames starting at file time t0 + f0/FPS without re-encoding. Returns (frames written, first frame kept):
141
+ a clip must start on a key frame, so a start between key frames moves to the next one."""
142
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
143
+ tmp = dst + ".tmp.mp4"
144
+ with av.open(src) as ic:
145
+ s = ic.streams.video[0]
146
+ tb = s.time_base
147
+ first = int(round((t0 + f0 / FPS) / tb))
148
+ frame_pts = int(round(1 / (FPS * tb)))
149
+ ic.seek(first, stream=s, backward=True, any_frame=False)
150
+ with av.open(tmp, "w", format="mp4") as oc:
151
+ o = oc.add_stream_from_template(s, opaque=True) # packets are copied, so no encoder is involved
152
+ base, written = None, 0
153
+ for pkt in ic.demux(s):
154
+ if pkt.pts is None or pkt.pts < first:
155
+ continue
156
+ idx = int(round((pkt.pts - first) / frame_pts))
157
+ if idx >= n:
158
+ break
159
+ if base is None:
160
+ if not pkt.is_keyframe:
161
+ continue
162
+ base, kept = pkt.pts, idx
163
+ pkt.pts = pkt.pts - base
164
+ pkt.dts = pkt.dts - base
165
+ pkt.stream = o
166
+ oc.mux(pkt)
167
+ written += 1
168
+ os.replace(tmp, dst)
169
+ return written, kept
170
+
171
+
172
+ @functools.lru_cache(maxsize=2)
173
+ def read_data_file(path):
174
+ return pq.read_table(path, columns=["observation.state", "action", "index", "episode_index", "annotation.attempt_success", "annotation.phase"])
175
+
176
+
177
+ def write_clip(job):
178
+ """One output episode: both videos, then the parquet of exactly the frames they hold."""
179
+ clip, ep, out = job
180
+ n = clip["stop"] - clip["start"]
181
+ chunk = ep // CHUNK
182
+ src = os.path.join(DATA, clip["source"])
183
+ results = {}
184
+ for cam, v in clip["videos"].items():
185
+ path = os.path.join(src, f"videos/{CAMERAS[cam]}/chunk-{v['chunk']:03d}/file-{v['file']:03d}.mp4")
186
+ results[cam] = remux(path, os.path.join(out, f"videos/chunk-{chunk:03d}/{cam}/episode_{ep:06d}.mp4"), clip["start"], n, v["t0"])
187
+ kept = {r[1] for r in results.values()}
188
+ if len(kept) != 1:
189
+ raise ValueError(f"cameras disagree on the first key frame: {results} ({clip['source']} {clip['episode']})")
190
+ skip = kept.pop()
191
+ length = results["image"][0]
192
+ if results["wrist_image"][0] != length or length != n - skip:
193
+ raise ValueError(f"frame count {results} != {n - skip} ({clip['source']} {clip['episode']})")
194
+ i0 = clip["ep_from"] + clip["start"] + skip
195
+ t = read_data_file(clip["data_file"]).slice(i0 - clip["data_first_index"], length)
196
+ if t.num_rows != length or int(t["index"][0].as_py()) != i0 or set(t["episode_index"].to_pylist()) != {clip["episode"]}:
197
+ raise ValueError(f"parquet slice mismatch ({clip['source']} {clip['episode']})")
198
+ if set(t["annotation.attempt_success"].to_pylist()) != {1} or 2 in set(t["annotation.phase"].to_pylist()):
199
+ raise ValueError(f"unexpected frame labels ({clip['source']} {clip['episode']})")
200
+ state = np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float32)
201
+ action = np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float32)
202
+ chunk_dir = os.path.join(out, f"videos/chunk-{chunk:03d}")
203
+ images = {cam: image_stats(os.path.join(chunk_dir, f"{cam}/episode_{ep:06d}.mp4"), length) for cam in CAMERAS}
204
+ return dict(ep=ep, length=length, skip=skip, state=state, action=action, image_stats=images)
205
+
206
+
207
+ def stats_of(a):
208
+ return dict(min=a.min(0).tolist(), max=a.max(0).tolist(), mean=a.mean(0).tolist(), std=a.std(0).tolist(), count=[len(a)])
209
+
210
+
211
+ def image_stats(path, length, n=5):
212
+ """Sampled image statistics for meta/episodes_stats.jsonl (LeRobot requires them, openpi does not use them)."""
213
+ frames = []
214
+ with av.open(path) as c:
215
+ s = c.streams.video[0]
216
+ for i in np.linspace(0, length - 1, min(n, length)).astype(int):
217
+ pts = int(round(i / FPS / s.time_base))
218
+ c.seek(pts, stream=s, backward=True)
219
+ for fr in c.decode(s):
220
+ if fr.pts >= pts:
221
+ frames.append(fr.to_ndarray(format="rgb24").astype(np.float32) / 255.0)
222
+ break
223
+ x = np.stack(frames).transpose(0, 3, 1, 2)
224
+ fmt = lambda v: [[[float(q)]] for q in v]
225
+ return dict(min=fmt(x.min((0, 2, 3))), max=fmt(x.max((0, 2, 3))), mean=fmt(x.mean((0, 2, 3))), std=fmt(x.std((0, 2, 3))), count=[len(frames)])
226
+
227
+
228
+ def pool(workers):
229
+ """Fresh interpreters: a forked worker inherits FFmpeg's state from a parent that decoded video and can deadlock."""
230
+ return ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn"))
231
+
232
+
233
+ def write_dataset(out, clips, workers):
234
+ os.makedirs(os.path.join(out, "meta"), exist_ok=True)
235
+ os.makedirs(os.path.join(out, "lff"), exist_ok=True)
236
+ tasks = sorted({c["instruction"] for c in clips})
237
+ task_index = {t: i for i, t in enumerate(tasks)}
238
+ clips = sorted(clips, key=lambda c: (c["task"], c["seed"], c["source"], c["episode"], c["start"]))
239
+ with pool(workers) as ex:
240
+ results = list(ex.map(write_clip, [(c, i, out) for i, c in enumerate(clips)], chunksize=4))
241
+ index, eps, ep_stats, prov = 0, [], [], []
242
+ for c, r in zip(clips, results):
243
+ ep, n = r["ep"], r["length"]
244
+ chunk = ep // CHUNK
245
+ ts = np.arange(n, dtype=np.float32) / FPS
246
+ table = pa.table({"state": list(r["state"]), "actions": list(r["action"]), "timestamp": ts, "frame_index": np.arange(n),
247
+ "episode_index": np.full(n, ep), "index": np.arange(index, index + n),
248
+ "task_index": np.full(n, task_index[c["instruction"]])})
249
+ p = os.path.join(out, f"data/chunk-{chunk:03d}/episode_{ep:06d}.parquet")
250
+ os.makedirs(os.path.dirname(p), exist_ok=True)
251
+ pq.write_table(table, p)
252
+ eps.append(dict(episode_index=ep, tasks=[c["instruction"]], length=n))
253
+ st = dict(state=stats_of(r["state"]), actions=stats_of(r["action"]),
254
+ timestamp=stats_of(ts[:, None]), frame_index=stats_of(np.arange(n)[:, None]),
255
+ episode_index=stats_of(np.full((n, 1), ep)), index=stats_of(np.arange(index, index + n)[:, None]),
256
+ task_index=stats_of(np.full((n, 1), task_index[c["instruction"]])))
257
+ st.update(r["image_stats"])
258
+ ep_stats.append(dict(episode_index=ep, stats=st))
259
+ prov.append(dict(episode_index=ep, index_from=index, length=n, source=c["source"], source_episode=c["episode"], attempt=c["attempt"],
260
+ source_frame_start=c["start"] + r["skip"], task=c["task"], seed=c["seed"], cause=c["cause"], model=c["model"],
261
+ run=c["run"], batch=c["batch"], condition=c["condition"], protocol=c["protocol"], first_attempt=c["first_attempt"],
262
+ run_outcome_class=c["run_outcome_class"]))
263
+ index += n
264
+ feat = lambda dtype, shape, names=None: dict(dtype=dtype, shape=shape, names=names)
265
+ video = dict(dtype="video", shape=[256, 256, 3], names=["height", "width", "channels"],
266
+ info={"video.height": 256, "video.width": 256, "video.codec": "av1", "video.pix_fmt": "yuv420p", "video.is_depth_map": False,
267
+ "video.fps": FPS, "video.channels": 3, "has_audio": False})
268
+ info = dict(codebase_version="v2.1", robot_type="franka_panda", total_episodes=len(clips), total_frames=index, total_tasks=len(tasks),
269
+ total_videos=2 * len(clips), total_chunks=(len(clips) - 1) // CHUNK + 1, chunks_size=CHUNK, fps=FPS, splits={"train": f"0:{len(clips)}"},
270
+ data_path="data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
271
+ video_path="videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
272
+ features=dict(image=video, wrist_image=video,
273
+ state=feat("float32", [8], ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", "finger_qpos_left", "finger_qpos_right"]),
274
+ actions=feat("float32", [7], ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", "eef_delta_rot_aa_z", "gripper_close"]),
275
+ timestamp=feat("float32", [1]), frame_index=feat("int64", [1]), episode_index=feat("int64", [1]), index=feat("int64", [1]),
276
+ task_index=feat("int64", [1])))
277
+ json.dump(info, open(os.path.join(out, "meta/info.json"), "w"), indent=1)
278
+ jsonl = lambda name, rows: open(os.path.join(out, name), "w").write("".join(json.dumps(r) + "\n" for r in rows))
279
+ jsonl("meta/tasks.jsonl", [dict(task_index=i, task=t) for i, t in enumerate(tasks)])
280
+ jsonl("meta/episodes.jsonl", eps)
281
+ jsonl("meta/episodes_stats.jsonl", ep_stats)
282
+ jsonl("lff/provenance.jsonl", prov)
283
+ return prov
284
+
285
+
286
+ def summarize(prov):
287
+ per = collections.defaultdict(lambda: dict(episodes=0, frames=0, seeds=set()))
288
+ for p in prov:
289
+ d = per[p["task"]]
290
+ d["episodes"] += 1
291
+ d["frames"] += p["length"]
292
+ d["seeds"].add(p["seed"])
293
+ return {t: dict(episodes=d["episodes"], frames=d["frames"], seeds=sorted(d["seeds"])) for t, d in sorted(per.items())}
294
+
295
+
296
+ def cmd_build(a):
297
+ holdout = read_holdout(a.holdout, a.holdout_seed)
298
+ names = sources(a.extra_source)
299
+ clips, stats = [], collections.Counter()
300
+ with pool(a.workers) as ex:
301
+ for c, s in ex.map(functools.partial(plan_source, only_task=a.only_task), names):
302
+ clips += c
303
+ stats.update(s)
304
+ seen =collections.Counter((c["run"], c["attempt"], c["start"]) for c in clips)
305
+ dups = [k for k, v in seen.items() if v > 1]
306
+ if dups:
307
+ raise SystemExit(f"{len(dups)} duplicate clips, e.g. {dups[:3]}")
308
+ no_holdout = sorted({c["task"] for c in clips} - set(holdout))
309
+ if no_holdout:
310
+ raise SystemExit(f"tasks without a held-out instance: {no_holdout}")
311
+ train = [c for c in clips if c["seed"] not in holdout[c["task"]]]
312
+ test = [c for c in clips if c["seed"] in holdout[c["task"]]]
313
+ report = dict(built_utc=time.strftime("%FT%TZ", time.gmtime()), sources=names, holdout={t: sorted(s) for t, s in holdout.items()},
314
+ emergency_frames_cut=stats["emergency_frames_cut"])
315
+ for split, group, repo in (("train", train, a.repo_id), ("heldout", test, a.repo_id + "_heldout")):
316
+ if split not in a.splits:
317
+ continue
318
+ out = os.path.join(a.out, repo)
319
+ if os.path.exists(os.path.join(out, "meta/info.json")):
320
+ raise SystemExit(f"{out} exists: datasets are not rewritten in place")
321
+ prov = write_dataset(out, group, a.workers)
322
+ report[split] = dict(repo_id=repo, episodes=len(prov), frames=sum(p["length"] for p in prov), tasks=len({p["task"] for p in prov}),
323
+ first_attempt=sum(p["first_attempt"] for p in prov), per_task=summarize(prov))
324
+ json.dump(report, open(os.path.join(out, "lff/build_report.json"), "w"), indent=1)
325
+ print(split, report[split]["episodes"], "episodes", report[split]["frames"], "frames", report[split]["tasks"], "tasks", flush=True)
326
+
327
+
328
+ @functools.lru_cache(maxsize=64)
329
+ def source_meta(src):
330
+ """Per episode metadata of one release, and (first index, path) of each of its data files."""
331
+ meta = {}
332
+ for mf in sorted(glob.glob(os.path.join(src, "meta/episodes/chunk-*/file-*.parquet"))):
333
+ keep = [c for c in pq.read_schema(mf).names if not c.startswith("stats/")]
334
+ for m in pq.read_table(mf, columns=keep).to_pylist():
335
+ meta[m["episode_index"]] = m
336
+ files = []
337
+ for df in sorted(glob.glob(os.path.join(src, "data/chunk-*/file-*.parquet"))):
338
+ files.append((int(pq.read_table(df, columns=["index"])["index"][0].as_py()), df))
339
+ return meta, files
340
+
341
+
342
+ def source_frame(prov, t):
343
+ """State, action and both camera frames of one output frame, read directly from the published release."""
344
+ src = os.path.join(DATA, prov["source"])
345
+ f = prov["source_frame_start"] + t
346
+ metas, files = source_meta(src)
347
+ meta = metas[prov["source_episode"]]
348
+ i = meta["dataset_from_index"] + f
349
+ first, df = [x for x in files if x[0] <= i][-1]
350
+ row = read_data_file(df).slice(i - first, 1).to_pylist()[0]
351
+ if row["index"] != i:
352
+ raise SystemExit(f"source row lookup failed: {prov['source']} {i}")
353
+ imgs = {}
354
+ for cam, key in CAMERAS.items():
355
+ path = os.path.join(src, f"videos/{key}/chunk-{meta[f'videos/{key}/chunk_index']:03d}/file-{meta[f'videos/{key}/file_index']:03d}.mp4")
356
+ ts = meta[f"videos/{key}/from_timestamp"] + f / FPS
357
+ with av.open(path) as c:
358
+ s = c.streams.video[0]
359
+ c.seek(int(ts / s.time_base), stream=s, backward=True)
360
+ for fr in c.decode(s):
361
+ if abs(float(fr.pts * s.time_base) - ts) < 1e-3:
362
+ imgs[cam] = fr.to_ndarray(format="rgb24")
363
+ break
364
+ return row, imgs
365
+
366
+
367
+ def cmd_verify(a):
368
+ """Reads the dataset through openpi's LeRobot exactly as training does and compares it with the published releases."""
369
+ import lerobot.common.datasets.lerobot_dataset as ld
370
+ out = a.dir.rstrip("/")
371
+ root, repo = os.path.dirname(out), os.path.basename(out)
372
+ prov = [json.loads(x) for x in open(os.path.join(out, "lff/provenance.jsonl"))]
373
+ report = json.load(open(os.path.join(out, "lff/build_report.json")))
374
+ meta = ld.LeRobotDatasetMetadata(repo, root=out)
375
+ H = 10
376
+ ds = ld.LeRobotDataset(repo, root=out, delta_timestamps={"actions": [t / meta.fps for t in range(H)]}, video_backend="pyav")
377
+ checks = dict(n_frames=len(ds), n_episodes=meta.total_episodes, fps=meta.fps)
378
+ if len(ds) != sum(p["length"] for p in prov):
379
+ raise SystemExit("frame count differs from the provenance")
380
+ holdout = {t: set(s) for t, s in report["holdout"].items()}
381
+ leaked = [p for p in prov if (p["seed"] in holdout.get(p["task"], ())) != repo.endswith("_heldout")]
382
+ checks["instances_in_wrong_split"] = len(leaked)
383
+ rng = random.Random(0)
384
+ by_task = collections.defaultdict(list)
385
+ for p in prov:
386
+ by_task[p["task"]].append(p)
387
+ samples = []
388
+ for t, ps in sorted(by_task.items()):
389
+ for j in range(a.per_task):
390
+ p = rng.choice(ps)
391
+ near_end = j % 2 == 1 and p["length"] > H # half of the samples test the chunks that reach the clip's end
392
+ samples.append((p, p["length"] - rng.randint(1, H - 1) if near_end else rng.randrange(p["length"])))
393
+ state_err, act_err, img_err, chunk_err, pad_bad, prompts = [], [], [], [], 0, set()
394
+ tasks = {t["task_index"]: t["task"] for t in (json.loads(x) for x in open(os.path.join(out, "meta/tasks.jsonl")))}
395
+ for p, t in samples:
396
+ item = ds[p["index_from"] + t]
397
+ row, imgs = source_frame(p, t)
398
+ state_err.append(float(np.abs(item["state"].numpy() - np.asarray(row["observation.state"])).max()))
399
+ chunk = item["actions"].numpy()
400
+ act_err.append(float(np.abs(chunk[0] - np.asarray(row["action"])).max()))
401
+ if row["annotation.attempt_success"] != 1 or row["annotation.phase"] == 2:
402
+ raise SystemExit(f"frame with the wrong label in the dataset: {p['source']} {p['source_episode']} {t}")
403
+ for j in range(1, H):
404
+ if t + j >= p["length"]: # past the clip's end the loader must repeat the last action, not read the next clip
405
+ last = ds.hf_dataset[p["index_from"] + p["length"] - 1]["actions"].numpy()
406
+ chunk_err.append(float(np.abs(chunk[j] - last).max()))
407
+ pad_bad += int(not item["actions_is_pad"][j])
408
+ for cam in CAMERAS:
409
+ got = (item[cam].numpy().transpose(1, 2, 0) * 255).round()
410
+ img_err.append(float(np.abs(got - imgs[cam].astype(float)).mean()))
411
+ prompts.add(tasks[int(item["task_index"])] == item["task"])
412
+ checks.update(samples=len(samples), max_state_err=max(state_err), max_action_err=max(act_err), max_image_mae=max(img_err),
413
+ chunk_end_checks=len(chunk_err), max_chunk_end_err=max(chunk_err or [0.0]), chunk_end_not_padded=pad_bad, prompts_ok=prompts == {True})
414
+ actions = np.concatenate([np.asarray(ds.hf_dataset[p["index_from"]]["actions"])[None] for p in prov[:50]])
415
+ checks["first_actions_range"] = [float(actions.min()), float(actions.max())]
416
+ checks["pass"] = bool(not leaked and max(state_err) < 1e-6 and max(act_err) < 1e-6 and max(img_err) < 1.0 and max(chunk_err or [0.0]) < 1e-6
417
+ and not pad_bad and prompts == {True})
418
+ json.dump(checks, open(os.path.join(out, "lff/verify_report.json"), "w"), indent=1)
419
+ print(json.dumps(checks, indent=1))
420
+ if not checks["pass"]:
421
+ raise SystemExit("VERIFY FAILED")
422
+
423
+
424
+ def cmd_norm(a):
425
+ """openpi's scripts/compute_norm_stats.py computes state and action-chunk statistics, decoding every video frame on
426
+ the way. This feeds the same RunningStats the same arrays from the parquet files, so it takes seconds."""
427
+ from openpi.shared import normalize
428
+ out = a.dir.rstrip("/")
429
+ stats = {key: normalize.RunningStats() for key in ("state", "actions")}
430
+ eps = [json.loads(x) for x in open(os.path.join(out, "meta/episodes.jsonl"))]
431
+ for e in eps:
432
+ i = e["episode_index"]
433
+ t = pq.read_table(os.path.join(out, f"data/chunk-{i // CHUNK:03d}/episode_{i:06d}.parquet"), columns=["state", "actions"])
434
+ state = np.stack(t["state"].to_numpy(zero_copy_only=False))
435
+ act = np.stack(t["actions"].to_numpy(zero_copy_only=False))
436
+ idx = np.minimum(np.arange(len(act))[:, None] + np.arange(a.horizon)[None, :], len(act) - 1) # the loader's clamping
437
+ stats["state"].update(state)
438
+ stats["actions"].update(act[idx])
439
+ norm = {key: s.get_statistics() for key, s in stats.items()}
440
+ normalize.save(a.assets, norm)
441
+ print(f"wrote {a.assets}/norm_stats.json from {len(eps)} episodes")
442
+ for key, n in norm.items():
443
+ print(key, "q01", np.round(n.q01, 4).tolist(), "q99", np.round(n.q99, 4).tolist())
444
+
445
+
446
+ def main():
447
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
448
+ sub = ap.add_subparsers(dest="cmd", required=True)
449
+ n = sub.add_parser("norm")
450
+ n.add_argument("dir")
451
+ n.add_argument("--assets", required=True, help="<assets_base_dir>/<config name>/<repo id>")
452
+ n.add_argument("--horizon", type=int, default=10)
453
+ n.set_defaults(fn=cmd_norm)
454
+ b = sub.add_parser("build")
455
+ b.add_argument("--out", required=True)
456
+ b.add_argument("--repo-id", required=True)
457
+ b.add_argument("--holdout", help="sets/ file naming the held-out instance of each task")
458
+ b.add_argument("--holdout-seed", nargs="*", help="task:seed items for tasks not in that file")
459
+ b.add_argument("--extra-source", nargs="*", help="packages not in the canonical release yet")
460
+ b.add_argument("--splits", nargs="*", default=["train", "heldout"])
461
+ b.add_argument("--only-task", nargs="*", help="keep only these tasks (development datasets)")
462
+ b.add_argument("--workers", type=int, default=6)
463
+ b.set_defaults(fn=cmd_build)
464
+ v = sub.add_parser("verify")
465
+ v.add_argument("dir")
466
+ v.add_argument("--per-task", type=int, default=3)
467
+ v.set_defaults(fn=cmd_verify)
468
+ a = ap.parse_args()
469
+ a.fn(a)
470
+
471
+
472
+ if __name__ == "__main__":
473
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/make_dossier.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the record of an earlier failed attempt for the full5 history arms (docs/14 §6).
2
+
3
+ python scripts/make_dossier.py <run log dir> <out dir> [--attempt 1] [--allow-success]
4
+
5
+ The record contains only what the agent of that attempt saw: the starting images, every robot command with the
6
+ robot's reply (as logged by robot_server), the images those commands produced, the agent's closing remark and the
7
+ F1 verdict ("failed"). No outcome codes, measurements or hidden variables. The same builder is used for the own-history
8
+ arm (record of a failed independent run on the same instance) and the mismatched arm (record of a failed run on the
9
+ twin instance: same layout, different hidden variable), so the two dossiers differ only in content.
10
+ """
11
+ import argparse
12
+ import json
13
+ import os
14
+ import shutil
15
+
16
+ DROP = ("state_file", "attempt_ended", "camera_file")
17
+
18
+
19
+ def shell_args(args):
20
+ out = []
21
+ for k, v in args.items():
22
+ v = json.dumps(v) if not isinstance(v, str) else v
23
+ out.append(f'{k}="{v}"' if (" " in v or not v) else f"{k}={v}")
24
+ return " ".join(out)
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("log")
30
+ ap.add_argument("out")
31
+ ap.add_argument("--attempt", type=int, default=1)
32
+ ap.add_argument("--allow-success", action="store_true")
33
+ ap.add_argument("--result-extra", default="",
34
+ help="layer-3 ladder (docs/20): text appended to the verdict in the Result section (paragraphs "
35
+ "separated by blank lines; the first one continues the verdict line). Empty = F1 record, "
36
+ "byte-identical to the record built without this option.")
37
+ a = ap.parse_args()
38
+ evs = [json.loads(line) for line in open(os.path.join(a.log, "events.jsonl")) if line.strip()]
39
+ start = next(e for e in evs if e["ev"] == "session_start")
40
+ if start.get("style", "la") not in ("la", None) and "style" in start:
41
+ raise SystemExit("only la-style runs are supported")
42
+ calls = [e for e in evs if e["ev"] == "call" and e.get("attempt") == a.attempt]
43
+ done = [e for e in evs if e["ev"] == "done" and e.get("attempt") == a.attempt]
44
+ if not done:
45
+ raise SystemExit(f"attempt {a.attempt} has no done event (run unfinished?)")
46
+ done = done[0]
47
+ if done["success"] and not a.allow_success:
48
+ raise SystemExit(f"attempt {a.attempt} succeeded; nothing to learn from (use --allow-success to force)")
49
+ imgs = os.path.join(a.log, "images")
50
+ # commands as that agent issued them: `./robot <cmd>` in a CLI workspace, the `robot` tool's argument otherwise
51
+ try:
52
+ iface = json.load(open(os.path.join(a.log, "agent_iface.json"))).get("agent_iface", "cli")
53
+ except OSError:
54
+ iface = "cli"
55
+ pre = "./robot " if iface == "cli" else ""
56
+ os.makedirs(os.path.join(a.out, "obs"), exist_ok=False)
57
+
58
+ def copy(rel):
59
+ base = os.path.basename(rel)
60
+ src = os.path.join(imgs, f"a{a.attempt}_{base}")
61
+ if not os.path.exists(src):
62
+ return None
63
+ shutil.copy(src, os.path.join(a.out, "obs", base))
64
+ return f"obs/{base}"
65
+
66
+ # starting images: the first images the agent saw (status at step 0)
67
+ first = sorted(f for f in os.listdir(imgs) if f.startswith(f"a{a.attempt}_") and "s000_" in f)
68
+ start_imgs = [copy(f.split("_", 1)[1]) for f in first]
69
+ lines = ["# Record of the earlier attempt", "",
70
+ "Starting scene: " + ", ".join(p for p in start_imgs if p), "",
71
+ "## Robot commands and replies", ""]
72
+ rec = []
73
+ for i, e in enumerate(calls, 1):
74
+ rep = {k: v for k, v in (e.get("report") or {}).items() if k not in DROP}
75
+ if "images" in rep:
76
+ rep["images"] = [p2 for p2 in (copy(p) for p in rep["images"]) if p2]
77
+ cmd = f"{pre}{e['cmd']} {shell_args(e.get('args') or {})}".strip()
78
+ lines += [f"{i}. `{cmd}`", " reply: `" + json.dumps(rep) + "`", ""]
79
+ rec.append(dict(n=i, command=cmd, reply=rep))
80
+ lines += [f"{len(calls) + 1}. `{pre}finish reason=\"{done.get('reason', '')}\"`", "",
81
+ "## Closing remark of that attempt", "", str(done.get("reason", "")), "",
82
+ "## Result", ""]
83
+ verdict = "The environment judged that attempt: " + ("succeeded." if done["success"] else "failed.")
84
+ extra = [x.strip() for x in a.result_extra.split("\n\n") if x.strip()]
85
+ if extra:
86
+ verdict += " " + extra[0]
87
+ lines += [verdict, ""]
88
+ for x in extra[1:]:
89
+ lines += [x, ""]
90
+ with open(os.path.join(a.out, "README.md"), "w") as f:
91
+ f.write("\n".join(lines))
92
+ with open(os.path.join(a.out, "record.jsonl"), "w") as f:
93
+ for r in rec:
94
+ f.write(json.dumps(r) + "\n")
95
+ with open(os.path.join(os.path.dirname(os.path.abspath(a.out)), os.path.basename(a.out) + ".source.json"), "w") as f:
96
+ json.dump(dict(log=os.path.abspath(a.log), attempt=a.attempt, task=start.get("task"), seed=start.get("seed"),
97
+ arm=start.get("arm", "none"), n_commands=len(calls), success=done["success"],
98
+ result_extra=a.result_extra), f)
99
+ print(json.dumps(dict(out=a.out, n_commands=len(calls), n_images=len(os.listdir(os.path.join(a.out, "obs"))))))
100
+
101
+
102
+ if __name__ == "__main__":
103
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/make_video.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Record a scripted rollout of a task as an mp4 (agentview | wrist), with title cards between attempts.
2
+
3
+ python scripts/make_video.py --task l1_bias_place --kind adaptive --seed 1000
4
+ """
5
+ import argparse
6
+ import importlib
7
+ import os
8
+ import pkgutil
9
+ import sys
10
+ import textwrap
11
+
12
+ import numpy as np
13
+
14
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
+ sys.path.insert(0, ROOT)
16
+
17
+ import imageio # noqa: E402
18
+ from PIL import Image, ImageDraw, ImageFont # noqa: E402
19
+
20
+ import lffbench.tasks as task_pkg # noqa: E402
21
+ from lffbench import envs # noqa: E402
22
+ from lffbench.task_base import TASKS # noqa: E402
23
+
24
+ for m in pkgutil.iter_modules(task_pkg.__path__):
25
+ importlib.import_module(f"lffbench.tasks.{m.name}")
26
+
27
+ RES = 320
28
+ FPS = 15
29
+
30
+
31
+ def font(size):
32
+ try:
33
+ return ImageFont.load_default(size=size)
34
+ except TypeError:
35
+ return ImageFont.load_default()
36
+
37
+
38
+ def header(img, lines):
39
+ im = Image.fromarray(img)
40
+ d = ImageDraw.Draw(im)
41
+ d.rectangle([0, 0, im.width, 18 * len(lines) + 6], fill=(0, 0, 0))
42
+ for i, s in enumerate(lines):
43
+ d.text((6, 3 + 18 * i), s, fill=(255, 255, 255), font=font(15))
44
+ return np.asarray(im)
45
+
46
+
47
+ def card(lines, w, h, color=(20, 20, 20)):
48
+ im = Image.new("RGB", (w, h), color)
49
+ d = ImageDraw.Draw(im)
50
+ y = 20
51
+ for s in lines:
52
+ for part in textwrap.wrap(s, 70) or [""]:
53
+ d.text((20, y), part, fill=(255, 255, 255), font=font(18))
54
+ y += 24
55
+ y += 6
56
+ return np.asarray(im)
57
+
58
+
59
+ def main():
60
+ ap = argparse.ArgumentParser()
61
+ ap.add_argument("--task", required=True)
62
+ ap.add_argument("--kind", default="adaptive")
63
+ ap.add_argument("--seed", type=int, default=1000)
64
+ ap.add_argument("--k", type=int, default=5)
65
+ ap.add_argument("--every", type=int, default=3, help="record one frame every N control steps")
66
+ ap.add_argument("--out", default=None)
67
+ args = ap.parse_args()
68
+
69
+ task = TASKS[args.task]()
70
+ env = task.env
71
+ inst = task.sample_instance(args.seed)
72
+ frames = []
73
+ state = dict(n=0, attempt=1)
74
+ W = 2 * RES
75
+
76
+ def grab():
77
+ a = envs.render(env, "agentview", RES)
78
+ w = envs.render(env, "robot0_eye_in_hand", RES)
79
+ img = np.concatenate([a, w], axis=1)
80
+ return header(img, [f"{args.task} [{task.level}] policy={args.kind} seed={args.seed}",
81
+ f"attempt {state['attempt']} t={state['n'] * 0.05:5.1f}s (sim) left: agentview right: wrist"])
82
+
83
+ orig_step = env.step
84
+
85
+ def step(a):
86
+ out = orig_step(a)
87
+ state["n"] += 1
88
+ if state["n"] % args.every == 0:
89
+ frames.append(grab())
90
+ return out
91
+
92
+ env.step = step
93
+
94
+ def on_attempt(a, params, out):
95
+ txt = [f"Attempt {a + 1}: {'SUCCESS' if out['success'] else 'FAILED'}"]
96
+ if out.get("detail"):
97
+ txt.append("Feedback (F2): " + out["detail"])
98
+ p = {k: (round(v, 3) if isinstance(v, float) else v) for k, v in (params or {}).items()
99
+ if not isinstance(v, (list, dict)) or len(str(v)) < 120}
100
+ if p:
101
+ txt.append(f"params: {p}")
102
+ if not out["success"]:
103
+ txt.append(f"-> attempt {a + 2}")
104
+ frames.extend([card(txt, W, RES, (40, 20, 20) if not out["success"] else (20, 50, 20))] * (FPS * 3))
105
+ state["attempt"] = a + 2
106
+
107
+ intro = card([f"Task: {args.task} (level {task.level}; capabilities: {', '.join(task.capabilities)})",
108
+ f"Instruction: {task.instruction}",
109
+ f"Policy: {args.kind} (scripted reference)",
110
+ "Hidden variables are not visible to the policy."], W, RES)
111
+ frames.extend([intro] * (FPS * 3))
112
+ task.reset_instance(inst)
113
+ frames.append(grab())
114
+ n_cards_before = len(frames)
115
+ hist = task.run_scripted(args.kind, inst, k=args.k, seed=args.seed, on_attempt=on_attempt)
116
+ # tasks whose run_scripted does not call on_attempt: summarise at the end
117
+ if not any(f is not None and f.shape[0] == RES and (f[5, 5] == np.array([40, 20, 20])).all() for f in frames[n_cards_before:]) \
118
+ and not any((f[5, 5] == np.array([20, 50, 20])).all() for f in frames[n_cards_before:]):
119
+ lines = []
120
+ for h in hist:
121
+ o = h["outcome"]
122
+ lines.append(f"Attempt {h['attempt']}: {'SUCCESS' if o['success'] else 'FAILED'} — {o.get('detail', '')}")
123
+ frames.extend([card(lines[-6:], W, RES)] * (FPS * 4))
124
+ out = args.out or os.path.join(ROOT, "videos", f"{args.task}_{args.kind}_s{args.seed}.mp4")
125
+ os.makedirs(os.path.dirname(out), exist_ok=True)
126
+ imageio.mimwrite(out, frames, fps=FPS, quality=7, macro_block_size=8)
127
+ first = next((h["attempt"] for h in hist if h["outcome"]["success"]), None)
128
+ print(f"wrote {out} frames={len(frames)} attempts={len(hist)} first_success={first}")
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_deepseek/lff/source_closure/scripts/mismatch_plan.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mismatched-history control for layer 2 (user 2026-10-27: "错配历史的做一下"; design docs/14 §6 Do / Dm, current protocol).
2
+
3
+ Instances: the 9 hidden-variable tasks that have a twin (l7_key_turn has none), every Claude main-table instance
4
+ (Sonnet 5.5: cc_main1 / cc_sonnet_s2 / cc_sonnet_s3; Opus 5.5: cc_opus1 / cc_opus_s2 / cc_opus_s3) whose attempt 1 failed.
5
+ Arms, all fresh single-attempt agents (= the memory-free retries of the main table) with the same model and CLI:
6
+ tw_<m> twin instance (--arm twin: same layout, the hidden variable takes another value); its failed run is the
7
+ mismatched record. If the twin attempt succeeds there is no record: one more twin run (tw2_<m>), then give up.
8
+ do_<m> own record: history/ = attempt 1 of the instance's main-table history run (scripts/make_dossier.py)
9
+ dm_<m> mismatched record: history/ = the failed twin run. README byte-identical to do_<m>; only history/ differs.
10
+
11
+ python3 scripts/mismatch_plan.py own build own records + write <OUT>/<m>/own.json and tasks_<m>.txt
12
+ python3 scripts/mismatch_plan.py twin <m> build twin records from tw_<m> (+ tw2_<m>) -> <OUT>/<m>/twin.json;
13
+ prints the instances still without a failed twin run
14
+ python3 scripts/mismatch_plan.py report per instance: main-table attempt 2 with history (H2) and first
15
+ memory-free retry (N2), Do, Dm, twin; totals and paired counts
16
+ -> <OUT>/report.json + markdown on stdout
17
+ """
18
+ import json
19
+ import os
20
+ import subprocess
21
+ import sys
22
+
23
+ ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
+ API = os.path.join(ROOT, "runs", "api")
25
+ OUT = os.path.join(API, "mismatch_20261027")
26
+ TWIN_TASKS = ["l7_offcenter_push", "l5_slide_to_target", "l5_tablecloth_pull", "l3_wall_flush", "l3_under_table_tool",
27
+ "l4_fit_container", "l2_turntable_restore", "l3_card_shelf", "l5_loaded_beam"]
28
+ MAIN = {"opus": ["cc_opus1", "cc_opus_s2", "cc_opus_s3"], "sonnet": ["cc_main1", "cc_sonnet_s2", "cc_sonnet_s3"]}
29
+
30
+
31
+ def runs(batch):
32
+ return json.load(open(os.path.join(API, batch, "manifest.json")))["runs"]
33
+
34
+
35
+ def attempt1(log):
36
+ for line in open(os.path.join(log, "events.jsonl")):
37
+ e = json.loads(line)
38
+ if e.get("ev") == "done" and e.get("attempt") == 1:
39
+ return e
40
+ return None
41
+
42
+
43
+ def dossier(log, out):
44
+ if not os.path.isdir(out):
45
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "make_dossier.py"), log, out], check=True,
46
+ capture_output=True)
47
+ return out
48
+
49
+
50
+ def cmd_own():
51
+ for m, batches in MAIN.items():
52
+ own, tasks = {}, []
53
+ for b in batches:
54
+ for r in runs(b):
55
+ if r["cond"] != "harness" or r["task"] not in TWIN_TASKS or r["status"] != "done":
56
+ continue
57
+ d = attempt1(r["log"])
58
+ if d is None or d["success"]:
59
+ continue
60
+ key = f"{r['task']}:{r['seed']}"
61
+ own[key] = dossier(r["log"], os.path.join(OUT, m, "own", f"{r['task']}_s{r['seed']}"))
62
+ tasks.append(key)
63
+ os.makedirs(os.path.join(OUT, m), exist_ok=True)
64
+ json.dump(own, open(os.path.join(OUT, m, "own.json"), "w"), indent=1)
65
+ open(os.path.join(OUT, m, f"tasks_{m}.txt"), "w").write("\n".join(tasks) + "\n")
66
+ print(m, len(tasks))
67
+
68
+
69
+ def cmd_twin(m):
70
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
71
+ twin = {}
72
+ for b in (f"tw_{m}", f"tw2_{m}"):
73
+ if not os.path.exists(os.path.join(API, b, "manifest.json")):
74
+ continue
75
+ for r in runs(b):
76
+ key = f"{r['task']}:{r['seed']}"
77
+ if key in twin or r["status"] != "done":
78
+ continue
79
+ d = attempt1(r["log"])
80
+ if d is not None and not d["success"]:
81
+ twin[key] = dossier(r["log"], os.path.join(OUT, m, "twin", f"{r['task']}_s{r['seed']}"))
82
+ json.dump(twin, open(os.path.join(OUT, m, "twin.json"), "w"), indent=1)
83
+ print(json.dumps(dict(model=m, with_record=len(twin), missing=[k for k in want if k not in twin])))
84
+
85
+
86
+ # twin oracle also solves the original instance (docs/14 §6.4, 10-12 validation): mismatch is weak there
87
+ WEAK = {"l3_wall_flush", "l3_under_table_tool"}
88
+
89
+
90
+ def single(batch):
91
+ """task:seed -> True / False (attempt 1 of the batch's done run), None if not run or not finished."""
92
+ out = {}
93
+ if not os.path.exists(os.path.join(API, batch, "manifest.json")):
94
+ return out
95
+ for r in runs(batch):
96
+ if r["status"] == "done":
97
+ d = attempt1(r["log"])
98
+ out[f"{r['task']}:{r['seed']}"] = None if d is None else bool(d["success"])
99
+ return out
100
+
101
+
102
+ def main_rows(batches):
103
+ rows = {}
104
+ for b in batches:
105
+ tmp = os.path.join(OUT, f".oc_{b}.json")
106
+ subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "outcomes.py"), "--batch", b, "--json", tmp],
107
+ check=True, capture_output=True)
108
+ for r in json.load(open(tmp))["rows"]:
109
+ rows[f"{r['task']}:{r['seed']}"] = dict(batch=b, history=r["history"], memfree=r["memfree"])
110
+ os.remove(tmp)
111
+ return rows
112
+
113
+
114
+ def cmd_report():
115
+ rep, md = {}, []
116
+ for m, batches in MAIN.items():
117
+ want = [l.strip() for l in open(os.path.join(OUT, m, f"tasks_{m}.txt")) if l.strip()]
118
+ main = main_rows(batches)
119
+ do, dm = single(f"do_{m}"), single(f"dm_{m}")
120
+ t1, t2 = single(f"tw_{m}"), single(f"tw2_{m}") # "twin" = F if some twin run failed (a record exists)
121
+ tw = {k: (False if False in (t1.get(k), t2.get(k)) else t1.get(k)) for k in set(t1) | set(t2)}
122
+ rows = []
123
+ for k in want:
124
+ h, mf = main[k]["history"] or "", main[k]["memfree"] or ""
125
+ rows.append(dict(inst=k, task=k.split(":")[0], weak=k.split(":")[0] in WEAK,
126
+ H2=(h[1] == "S") if len(h) > 1 else None, N2=(mf[1] == "S") if len(mf) > 1 and mf[1] in "SF" else None,
127
+ Do=do.get(k), Dm=dm.get(k), twin=tw.get(k)))
128
+ def rate(key, sub):
129
+ v = [r[key] for r in sub if r[key] is not None]
130
+ return f"{sum(v)}/{len(v)}" if v else "-"
131
+ both = [r for r in rows if r["Do"] is not None and r["Dm"] is not None]
132
+ pairs = dict(n=len(both), do_only=sum(r["Do"] and not r["Dm"] for r in both),
133
+ dm_only=sum(r["Dm"] and not r["Do"] for r in both), both=sum(r["Do"] and r["Dm"] for r in both))
134
+ rep[m] = dict(rows=rows, pairs=pairs)
135
+ md += [f"### {m}", "", "| instance | twin run | H2 (history, main) | N2 (memory-free, main) | Do (own record) | Dm (twin record) |",
136
+ "|---|---|---|---|---|---|"]
137
+ f = lambda v: "-" if v is None else ("S" if v else "F")
138
+ for r in rows:
139
+ md.append(f"| {r['inst']}{' (weak)' if r['weak'] else ''} | {f(r['twin'])} | {f(r['H2'])} | {f(r['N2'])} | {f(r['Do'])} | {f(r['Dm'])} |")
140
+ strong = [r for r in rows if not r["weak"]]
141
+ md += ["", f"all: H2 {rate('H2', rows)}, N2 {rate('N2', rows)}, Do {rate('Do', rows)}, Dm {rate('Dm', rows)}; "
142
+ f"strong mismatch only: Do {rate('Do', strong)}, Dm {rate('Dm', strong)}; "
143
+ f"paired Do/Dm n={pairs['n']}: Do only {pairs['do_only']}, Dm only {pairs['dm_only']}, both {pairs['both']}", ""]
144
+ json.dump(rep, open(os.path.join(OUT, "report.json"), "w"), indent=1)
145
+ print("\n".join(md))
146
+
147
+
148
+ if __name__ == "__main__":
149
+ {"own": lambda: cmd_own(), "twin": lambda: cmd_twin(sys.argv[2]), "report": lambda: cmd_report()}[sys.argv[1]]()