File size: 32,662 Bytes
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#!/usr/bin/env python3
"""Check a recorded demo against its task's BDDL goal, from the dataset alone.

    python tools/bddl_eval.py datasets/round_peg_hole                  # every listed episode
    python tools/bddl_eval.py DATASET --episodes 0 3 --control          # + the truncation control

As BEHAVIOR and LIBERO use it, a BDDL goal is EXECUTABLE: the simulator grounds each predicate
in its own state and the goal decides success. This is that grounding for these datasets. The
predicate NAMES are LIBERO's (`Up`, `In`, `Open`); what they MEAN here is the criterion the demos
were graded by at record time -- the same `pipeline` class, built by the same
`tools/task_spec.make_success` from the dataset's own meta/task.json -- replayed over the
recorded frames:

    (Up X)                      X's root z >= its z on the first frame + success.height_m
    (In X Y_insertion_region)   X's head within success.clearance_m of Y's axis and past
                                success.depth_m along it (pipeline.InsertSuccess)
    (Open X)                    X's graded joint turned success.min_deg (joint_angle) or moved
                                success.fraction of its travel (joint_open; for the hammer only
                                travel delivered while the tool moves >= min_tool_speed_mps)

each held for success_hold_s continuously. The goal is satisfied when every atom's hold
completes within the episode. A task with ``success.no_carry`` (pivot_box_against_wall) is
graded with it too -- the object never airborne past the limit (pipeline.StaySupported) -- a
rule over the whole episode that the goal cannot state, so its BDDL says it in the
``; success as graded:`` line.

The composite criteria of 2026-09-28 are grounded the same way, by the task's own criterion
over the recorded frames, and their goal must be exactly the one tools/task_bddl.py writes
for the recorded task file:

    (Not (In X Y_insertion_region))   `separate`: X's head >= success.min_m from its seat
                                      on Y, any direction (pipeline.SeparateSuccess)
    (And (In A Y_...) (In B Y_...))   `count`: every named part in one of Y's holes
                                      (pipeline.CountSuccess; `(true)` when fewer are needed)
    several literals, one per part    `all`: every sub-criterion holding on the same frame
                                      (pipeline.AllSuccess); `(On X table_X_goal_region)` for
                                      a place on the table, `(true)` for an orientation,
                                      which LIBERO has no predicate for
    (true)                            `reorient_face`: the cube rolled onto the named (or a
                                      neighbouring) face and resting (pipeline.FaceNeighborSuccess)
    (true)                            `handover`: lifted, then with one hand's thumb tip and then
                                      the other's (pipeline.HandoverSuccess; the tip is Thumb3's
                                      recorded pose + meta/rig/<side>/rig.json's tip offset)
    (true)                            `joint_sequence`: the named joints moved in ORDER
                                      (pipeline.JointSequenceSuccess; coordinates and limits from
                                      bodies.json) The values come from the recording: the target's root pose
(observation.object_pose), the graded joint (observation.object_joint_pos), every other part's
pose through bodies.json and observation.state, the tool's speed from observation.velocity.

A goal atom must name what the task file grades -- `(Up cube_1)` on a task whose success lifts
the cube -- or the episode is refused rather than graded by a rule the BDDL does not state.

`--control` also replays each episode CUT one frame short. The hold completes on the last
recorded frame (recording stops at success), so the cut episode must NOT satisfy the goal: an
evaluator that passes everything would pass it too.

Exit status: 0 when every episode's goal agrees with its recorded `success` (and every control
fails), 1 otherwise. Needs numpy and pandas; runs from the repository or a package root.
"""

from __future__ import annotations

import argparse
import json
import os
import sys

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
for _p in (ROOT, HERE):
    if _p not in sys.path:
        sys.path.insert(0, _p)

import pipeline  # noqa: E402
from tools import contact_io, scene_assets, task_bddl, task_spec  # noqa: E402

GROUNDED = {"up": "lift", "in": "insert", "screwed": "insert",
            "open": ("joint_angle", "joint_open")}
#: Graded by one criterion over several parts' poses, or by a rule no LIBERO predicate names
#: (`(true)` + the rule in the comment); either way the goal is checked whole.
COMPOSITE = ("separate", "count", "all", "pose_target", "axis_upright", "reorient_face",
             "handover", "joint_sequence", "turn")


def _lit(a) -> str:
    """One goal literal back as text: ["in", "x", "y"] -> (in x y), ["not", [...]] -> (not (...))."""
    return "(" + " ".join(_lit(x) if isinstance(x, list) else x for x in a) + ")"


def _inst(name: str) -> str:
    return task_bddl._ident(name) + "_1"


def check_goal(spec: dict, atoms: list) -> None:
    """Refuse a goal whose atoms do not name what `success` grades."""
    s = spec["success"]
    target = task_spec.target(spec)["name"]
    if s["type"] in COMPOSITE or (s["type"] == "lift" and s.get("objects")):
        # One criterion over several parts: the goal must be the one the task file's own
        # criterion maps to, literal for literal, so no part is graded by a rule the goal
        # does not state and no stated part goes ungraded.
        want = task_bddl.goal_atoms(task_bddl.parse(task_bddl.to_bddl(spec))["goal"])
        if atoms != want:
            raise ValueError(f"goal {atoms} but the task's {s['type']!r} criterion maps to {want}")
        return
    if len(atoms) != 1:
        raise ValueError(f"{len(atoms)} goal atoms; these tasks grade one criterion")
    pred, *args = atoms[0]
    want = GROUNDED.get(pred)
    if want is None:
        raise ValueError(f"predicate {pred!r} has no grounding here (known: {sorted(GROUNDED)})")
    if s["type"] not in ((want,) if isinstance(want, str) else want):
        raise ValueError(f"({pred} ...) but the task grades {s['type']!r}")
    if pred == "up" and args != [_inst(target)]:
        raise ValueError(f"(Up {' '.join(args)}) but the task lifts {_inst(target)}")
    if pred in ("in", "screwed") and args != [_inst(target), _inst(s["into"]) + "_insertion_region"]:
        raise ValueError(f"({pred.title()} {' '.join(args)}) but the task inserts "
                         f"{_inst(target)} into {_inst(s['into'])}")
    # Screwed IS a threaded insert, and In is NOT: a part pushed straight down
    # satisfies In and fails the thread rule, so the two may not stand in for
    # each other either way.
    if pred == "screwed" and "thread" not in s:
        raise ValueError("(Screwed ...) but the task's insert has no thread block")
    if pred == "in" and "thread" in s:
        raise ValueError("(In ...) but the task grades a THREADED insert -- the goal must be "
                         "(Screwed ...); regenerate meta/task.bddl with tools/task_bddl.py")
    if pred == "open" and args != [_inst(s.get("of", target))]:
        raise ValueError(f"(Open {' '.join(args)}) but the task grades "
                         f"{_inst(s.get('of', target))}'s joint")


def _dof_start(bodies: list, body: dict) -> int:
    """Where a body's joint velocities start in observation.velocity (Newton joint_qd): the
    coordinates are in joint order and a FREE joint's 7 coordinates are 6 velocities, a BALL's
    4 are 3."""
    order = sorted((b for b in bodies if b.get("joint")), key=lambda b: b["joint"]["state_slice"][0])
    d = 0
    for b in order:
        if b["index"] == body["index"]:
            return d
        n = b["joint"]["state_slice"][1] - b["joint"]["state_slice"][0]
        d += {7: 6, 4: 3}.get(n, n)
    raise KeyError(body["label"])


def _group_root(bodies: list, group: str) -> dict:
    """The root body of `/World/envs/env_0/<group>`: the one whose parent is outside it."""
    inside = [b for b in bodies if b["label"].split("env_0/")[-1].split("/")[0] == group]
    ids = {b["index"] for b in inside}
    roots = [b for b in inside if b.get("parent") not in ids]
    if len(roots) != 1:
        raise ValueError(f"{group}: {len(roots)} root bodies")
    return roots[0]


def _groups_of_shapes(root: str) -> tuple[dict, list, list]:
    """(shape index -> its body-group name, bodies, shapes) from meta/assets."""
    bodies_doc, shapes_doc = scene_assets.load(os.path.join(root, "meta", "assets"))
    group = {}
    for sh in shapes_doc["shapes"]:
        lab = sh.get("label") or ""
        group[sh["index"]] = (lab.split("env_0/")[-1].split("/")[0] if "/envs/" in lab else None)
    return group, bodies_doc["bodies"], shapes_doc["shapes"]


def contact_flags(root: str, spec: dict, episode: int, n_frames: int) -> list:
    """Per frame, (tool touching the driven body, embodiment touching it) -- the contact half of
    a require_tool_contact criterion, read from the recording's sidecars.

    tool     = every shape of the target (the `Object` group: the hammer)
    driven   = the shapes of the graded joint's CHILD body (the nail, not its board)
    embodiment = every shape that is not a task object, the table or the ground: a MANO hand, a
               gripper or a robot hand alike, so a retargeted replay is judged by the same rule
    Both the pressure patch (`_shape_pair`) and the solver's contacts (`_mj_pair`) count, from
    contacts/hand_obj/ and contacts/obj_obj/. A contact within one frame of
    the step counts: live sidecars sit one step from a compiled one."""
    group, bodies, shapes = _groups_of_shapes(root)
    g = task_spec.graded(spec)
    jname = (g.get("joint") or {}).get("name")
    ggroup = "Object" if g["name"] == task_spec.target(spec)["name"] else f"Prop_{g['name']}"
    child = [b["index"] for b in bodies if b.get("joint")
             and b["label"].split("env_0/")[-1].split("/")[0] == ggroup
             and (jname is None or b["joint"]["label"].endswith("/" + jname))]
    if len(child) != 1:
        raise ValueError(f"{len(child)} bodies carry {ggroup}/{jname}; cannot tell what is driven")
    driven = {sh["index"] for sh in shapes if sh["body"] == child[0]}
    tool = {i for i, gr in group.items() if gr == "Object"} - driven
    embodiment = {i for i, gr in group.items()
                  if gr is not None and gr != "Object" and not gr.startswith("Prop_") and gr != "Table"}
    tool_on, hand_on = np.zeros(n_frames, bool), np.zeros(n_frames, bool)
    found = False
    for cls in contact_io.PAIRS:
        p = contact_io.sidecar_path(root, episode, cls)
        if not os.path.exists(p):
            continue
        found = True
        z = np.load(p)
        for k in z.files:
            if not (k.endswith("_shape_pair") or k.endswith("_mj_pair")):
                continue
            f = int(k.split("_", 1)[0])
            if not 0 <= f < n_frames:
                continue
            pairs = z[k].reshape(-1, 2)
            a, b = pairs[:, 0], pairs[:, 1]
            on_driven_a, on_driven_b = np.isin(a, list(driven)), np.isin(b, list(driven))
            if ((on_driven_a & np.isin(b, list(tool))) | (on_driven_b & np.isin(a, list(tool)))).any():
                tool_on[f] = True
            if ((on_driven_a & np.isin(b, list(embodiment))) |
                    (on_driven_b & np.isin(a, list(embodiment)))).any():
                hand_on[f] = True
    if not found:
        raise ValueError("require_tool_contact needs the contact sidecars "
                         "(contacts/hand_obj/, contacts/obj_obj/), which this "
                         "recording does not have")
    def widen(x):                  # a contact one frame either side of the step counts
        w = x.copy()
        w[1:] |= x[:-1]
        w[:-1] |= x[1:]
        return w
    return list(zip(widen(tool_on), widen(hand_on)))


class _AsZs:
    """A zs_hands criterion seen as the plain zs it extends, to rebuild its heights."""
    VALUE = "zs"

    def __init__(self, crit):
        self.names = crit.names


def hands_on_objects(root: str, names: list, spec: dict, episode: int, n_frames: int) -> list:
    """Per frame, how many hands touch any of the named objects -- the contact half of a lift
    with success.max_hands_touching, read from the recording's sidecars (collect_env counts it
    off the live hydroelastic surface). A hand is a HandLeft/HandRight group; both the pressure
    patch and the solver's contacts count. No widening: an extra hand on one frame resets the
    hold live, so it does here."""
    group, _, _ = _groups_of_shapes(root)
    tname = task_spec.target(spec)["name"]
    want = {"Object" if n == tname else f"Prop_{n}" for n in names}
    graded = [i for i, gr in group.items() if gr in want]
    hands = {side: [i for i, gr in group.items() if gr == f"Hand{side.title()}"]
             for side in task_spec.SIDES}
    on = {side: np.zeros(n_frames, bool) for side in hands}
    found = False
    for cls in contact_io.PAIRS:
        p = contact_io.sidecar_path(root, episode, cls)
        if not os.path.exists(p):
            continue
        found = True
        z = np.load(p)
        for k in z.files:
            if not (k.endswith("_shape_pair") or k.endswith("_mj_pair")):
                continue
            f = int(k.split("_", 1)[0])
            if not 0 <= f < n_frames:
                continue
            pairs = z[k].reshape(-1, 2)
            ga, gb = np.isin(pairs[:, 0], graded), np.isin(pairs[:, 1], graded)
            for side, shp in hands.items():
                if ((ga & np.isin(pairs[:, 1], shp)) | (gb & np.isin(pairs[:, 0], shp))).any():
                    on[side][f] = True
    if not found:
        raise ValueError("success.max_hands_touching needs the contact sidecars "
                         "(contacts/hand_obj/), which this recording does not have")
    return list(sum(v.astype(int) for v in on.values()))


def episode_values(root: str, crit, spec: dict, df, ep_meta: dict | None = None) -> list:
    """What the criterion was fed each step, rebuilt from the recorded frames.

    ``ep_meta`` (the episode's line in meta/episodes.jsonl) puts welded fixtures at the anchor
    THAT episode drew: a fixed joint has no coordinates, so without it a _fixed task's socket or
    holder sits where the scene was built (battery_spring_holder_fixed, 2026-10-03: 0/10
    graded until it did)."""
    def _doc():
        d = scene_assets.load(os.path.join(root, "meta", "assets"))[0]
        return (scene_assets.weld_anchored(d, ep_meta, os.path.join(root, "meta"))
                if ep_meta is not None else d)
    op = np.stack(df["observation.object_pose"].to_numpy()).astype(float)
    want = crit.VALUE
    if want == "joint" and getattr(crit, "min_tool_speed", None) is not None:
        want = "joint_tool"
    if want == "z":
        return list(op[:, 2])
    if want in ("joint", "joint_tool"):
        jp = np.stack(df["observation.object_joint_pos"].to_numpy()).astype(float)
        if jp.shape[1] > 1:
            # object_joint_pos is EVERY joint of the graded object (a nut's spin and advance, a
            # padlock's key cylinder and shackle); collect_env graded only the named ones
            # (success.joints, else the object's joint.name). Their columns, by name, from
            # observation.state -- the same numbers, measured equal on nut_thread and the padlock.
            g = task_spec.graded(spec)
            names = list(spec["success"].get("joints") or [(g.get("joint") or {}).get("name")])
            bodies = _doc()["bodies"]
            state = np.stack(df["observation.state"].to_numpy()).astype(float)
            jp = state[:, [_recorded_joint(bodies, spec, g["name"], n)["state_slice"][0]
                           for n in names]]
        if want == "joint":
            return list(jp[:, 0]) if jp.shape[1] == 1 else list(jp)
        if "observation.velocity" not in df.columns:
            raise ValueError("the tool-speed criterion needs observation.velocity, which this "
                             "recording predates")
        bodies = _doc()["bodies"]
        d0 = _dof_start(bodies, _group_root(bodies, "Object"))
        vel = np.stack(df["observation.velocity"].to_numpy()).astype(float)
        speed = np.linalg.norm(vel[:, d0:d0 + 3], axis=1)
        if getattr(crit, "require_tool_contact", False):
            flags = contact_flags(root, spec, int(df["episode_index"].iloc[0]), len(df))
            return list(zip(jp[:, 0], speed, flags))
        return list(zip(jp[:, 0], speed))
    if want == "pose":
        return list(op[:, :7])
    if want == "zs_hands":
        zs = episode_values(root, _AsZs(crit), spec, df, ep_meta)
        hands = hands_on_objects(root, crit.names, spec, int(df["episode_index"].iloc[0]), len(df))
        return list(zip(zs, hands))
    if want == "zs":
        # every named object's root height, in crit.names order (collect_env: root_pos_w z of each)
        doc = _doc()
        tname = task_spec.target(spec)["name"]
        idx = {n: _group_root(doc["bodies"], "Prop_" + n)["index"] for n in crit.names if n != tname}
        state = np.stack(df["observation.state"].to_numpy()).astype(float)
        out = []
        for i in range(len(state)):
            bp = scene_assets.body_poses(doc, state[i]) if idx else None
            out.append([float(op[i, 2]) if n == tname else float(bp[idx[n]][2]) for n in crit.names])
        return out
    if want == "joints":
        # {step label: coordinate}, as collect_env read each step's joint (joint_pos = joint_q)
        bodies = _doc()["bodies"]
        state = np.stack(df["observation.state"].to_numpy()).astype(float)
        cols = {task_spec.step_label(st):
                _recorded_joint(bodies, spec, st["of"], st.get("joint"))["state_slice"][0]
                for st in spec["success"]["steps"]}
        return [{k: float(state[i, c]) for k, c in cols.items()} for i in range(len(state))]
    if want == "handover":
        # (object z, object position, {side: thumb tip}): the tip rides Thumb3 at the rig's
        # tips_rest.thumb - joints_rest.Thumb3, in Thumb3's frame (collect_env.Hand.thumb_tip)
        doc = _doc()
        state = np.stack(df["observation.state"].to_numpy()).astype(float)
        thumbs = {}
        for side in ("left", "right"):
            rp = os.path.join(root, "meta", "rig", side, "rig.json")
            body = [b for b in doc["bodies"] if b["label"].endswith("/Thumb3")
                    and b["label"].split("env_0/")[-1].split("/")[0] == f"Hand{side.title()}"]
            if not body:
                continue
            if not os.path.exists(rp):
                raise ValueError(f"a handover is graded at the thumb tips, and meta/rig/{side}/rig.json "
                                 f"(where the tip is) is not in this dataset")
            with open(rp) as fh:
                rj = json.load(fh)
            thumbs[side] = (body[0]["index"], np.asarray(rj["tips_rest"]["thumb"], float)
                            - np.asarray(rj["joints_rest"]["Thumb3"], float))
        out = []
        for i in range(len(state)):
            bp = scene_assets.body_poses(doc, state[i])
            tips = {s: np.asarray(bp[k][:3], float) + np.asarray(pipeline._qrot(bp[k][3:7], loc))
                    for s, (k, loc) in thumbs.items()}
            out.append((float(op[i, 2]), op[i, :3], {s: tips.get(s) for s in ("left", "right")}))
        return out
    if want == "named_poses":
        # {part: pose} per frame, as collect_env handed it over (success.pose_names): the
        # target from its recorded root pose, every other part through bodies.json.
        doc = _doc()
        tname = task_spec.target(spec)["name"]
        names = list(crit.pose_names)
        idx = {n: _group_root(doc["bodies"], "Prop_" + n)["index"] for n in names if n != tname}
        state = np.stack(df["observation.state"].to_numpy()).astype(float)
        out = []
        for i in range(len(state)):
            bp = scene_assets.body_poses(doc, state[i]) if idx else None
            out.append({n: (op[i, :7] if n == tname else np.asarray(bp[idx[n]], float))
                        for n in names})
        return out
    if want == "poses":
        doc = _doc()
        into = _group_root(doc["bodies"], "Prop_" + spec["success"]["into"])
        state = np.stack(df["observation.state"].to_numpy()).astype(float)
        return [(op[i, :7], np.asarray(scene_assets.body_poses(doc, state[i])[into["index"]],
                                       float)) for i in range(len(state))]
    raise ValueError(f"criterion value {want!r} has no replay here")


def _recorded_joint(bodies: list, spec: dict, obj_name: str, name: str | None) -> dict:
    """The one joint of object `obj_name` (named `name`, or its only limited joint) in
    meta/assets/bodies.json."""
    group = "Object" if obj_name == task_spec.target(spec)["name"] else f"Prop_{obj_name}"
    hits = [b["joint"] for b in bodies
            if b.get("joint") and b["label"].split("env_0/")[-1].split("/")[0] == group
            and (b["joint"].get("limit") if name is None
                 else b["joint"]["label"].endswith("/" + name))]
    if len(hits) != 1:
        raise ValueError(f"{len(hits)} recorded joints match {group}/{name}; cannot read its limits")
    return hits[0]


def _limits(joint: dict) -> tuple:
    lo, hi = joint["limit"]
    return float(lo), float(hi), ("prismatic" if "PRISMATIC" in joint["type"].upper() else "revolute")


def recorded_joint_limits(root: str, spec: dict):
    """(lo, hi, kind) of the graded joint as the PHYSICS had it: meta/assets/bodies.json, the
    model's own joint_limit_lower/upper; for a joint_sequence {step label: (lo, hi, kind)}.
    None when the task grades no joint."""
    s = spec["success"]
    if s["type"] not in ("joint_open", "joint_sequence"):
        return None
    bodies = scene_assets.load(os.path.join(root, "meta", "assets"))[0]["bodies"]
    if s["type"] == "joint_sequence":
        return {task_spec.step_label(st): _limits(_recorded_joint(bodies, spec, st["of"], st.get("joint")))
                for st in s["steps"]}
    g = task_spec.graded(spec)
    return _limits(_recorded_joint(bodies, spec, g["name"], (g.get("joint") or {}).get("name")))


def replay(crit, values) -> int | None:
    """Arm on the first frame (as the recorder did when the demo started) and step: the frame
    at which the hold completed, or None."""
    crit.arm(values[0])
    for i, v in enumerate(values):
        if crit.update(v):
            return i
    return None


def evaluate(root: str, episodes=None, control: bool = False, log=print,
             spec: dict | None = None) -> dict:
    """{episode: result} for the listed episodes (default: every one in episodes.jsonl).
    `spec` grades by another task definition than the recorded meta/task.json (--regrade)."""
    import pandas as pd  # noqa: PLC0415
    own = spec is None
    if own:
        with open(os.path.join(root, "meta", "task.json")) as fh:
            spec = json.load(fh)
    bddl_path = os.path.join(root, "meta", "task.bddl")
    text = (open(bddl_path).read() if own and os.path.exists(bddl_path)
            else task_bddl.to_bddl(spec))
    atoms = task_bddl.goal_atoms(task_bddl.parse(text)["goal"])
    check_goal(spec, atoms)
    with open(os.path.join(root, "meta", "info.json")) as fh:
        hz = float((json.load(fh).get("collection_config") or {}).get("physics_hz") or 250.0)
    rows = [json.loads(line) for line in open(os.path.join(root, "meta", "episodes.jsonl"))
            if line.strip()]
    if episodes is not None:
        rows = [r for r in rows if r["episode_index"] in set(episodes)]
    limits = recorded_joint_limits(root, spec)
    out = {}
    for r in rows:
        ep = r["episode_index"]
        hold = int(round(float((r.get("success_terms") or {}).get("success_hold_s", 2.0)) * hz))
        crit, _, _ = task_spec.make_success(spec, hold, pipeline, joint_limits=limits)
        df = pd.read_parquet(os.path.join(root, "data", f"episode_{ep:06d}.parquet"))
        vals = episode_values(root, crit, spec, df, r)
        at = replay(crit, vals)
        res = {"goal": " ".join(_lit(a) for a in atoms), "satisfied": at is not None,
               "at_frame": at, "frames": len(vals), "recorded_success": bool(r.get("success")),
               "terms": crit.terms()}
        # the recomputed numbers against the ones the recorder wrote
        rec = r.get("success_terms") or {}
        # A criterion credited through the contact sidecars matches its contacts within one frame
        # (contact_flags), so a few frames of travel can be credited differently: hammer_nail,
        # 2026-09-30, 0-9 um on ~70 mm (<= 1.3e-4); pry_lid_screwdriver ep1 63 um on 12.2 mm
        # (0.5 %) -- each with its verdict on the exact frame. Those terms get 1 %; every other
        # term, and every verdict and frame, stays exact.
        rtol = 1e-2 if getattr(crit, "require_tool_contact", False) else 0.0
        res["terms_mismatch"] = sorted(
            k for k, v in res["terms"].items()
            if isinstance(v, (int, float)) and not isinstance(v, bool) and k in rec
            and isinstance(rec[k], (int, float)) and not np.isclose(v, rec[k], rtol=rtol, atol=1e-4))
        if control:
            c2, _, _ = task_spec.make_success(spec, hold, pipeline, joint_limits=limits)
            res["control_satisfied"] = replay(c2, vals[:-1]) is not None
        res["agrees"] = (res["satisfied"] == res["recorded_success"] and not res["terms_mismatch"]
                         and not res.get("control_satisfied", False))
        out[ep] = res
    return out


def regrade(root: str, task_file: str, log=print) -> bool:
    """Re-grade a dataset under a CHANGED success rule, when nothing but the rule changed.

    The success rule is a label on the recording, not part of the physics, so demos recorded
    under an old rule can be graded under a new one from their frames. Refused unless:
      * the recorded meta/task.json and `task_file` differ ONLY in `success` (the scene the
        demos were recorded in has not moved), and
      * under the new rule every recorded-successful episode completes its hold on exactly its
        LAST frame (the recording stops at success, so it still ends at the moment the new rule
        is met) and fails one frame short.
    Then meta/task.json becomes `task_file`, each row's success_terms the new rule's, with the
    old ones kept as `success_terms_recorded` and a `regraded` stamp; the two originals are
    copied to meta/regrade_backup/<timestamp>/ first. Returns True when written.
    """
    import datetime  # noqa: PLC0415
    import shutil  # noqa: PLC0415
    from tools.task_status import _strip  # noqa: PLC0415
    meta = os.path.join(root, "meta")
    with open(os.path.join(meta, "task.json")) as fh:
        was = json.load(fh)
    with open(task_file) as fh:
        now = json.load(fh)
    a, b = _strip(was), _strip(now)
    for x in (a, b):
        x.pop("hands", None)
    moved = sorted(k for k in set(a) | set(b) if a.get(k) != b.get(k) and k != "success")
    if moved:
        log(f"❌ {root}: refused -- the task changed in {moved}, not only in `success`; "
            f"re-grading cannot stand in for a scene that moved")
        return False
    if a.get("success") == b.get("success"):
        log(f"   {root}: success rule unchanged, nothing to re-grade")
        return False
    res = evaluate(root, control=True, spec=now)
    rows = [json.loads(line) for line in open(os.path.join(meta, "episodes.jsonl")) if line.strip()]
    bad = [ep for ep, r in res.items()
           if r["recorded_success"] and not (r["satisfied"] and r["at_frame"] == r["frames"] - 1
                                             and not r["control_satisfied"])]
    if bad:
        log(f"❌ {root}: refused -- under the new rule {len(bad)} successful episode(s) do not "
            f"complete their hold on their last frame: {bad[:10]}")
        return False
    stamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
    bdir = os.path.join(meta, "regrade_backup", stamp)
    os.makedirs(bdir)
    for f in ("task.json", "episodes.jsonl"):
        shutil.copy2(os.path.join(meta, f), os.path.join(bdir, f))
    old_rule = next((r.get("success_terms", {}).get("criterion") for r in rows), None)
    for r in rows:
        new = res.get(r["episode_index"])
        if new is None:
            continue
        keep = {k: r["success_terms"][k] for k in ("success_hold_s", "post_success_s",
                                                   "criterion_held_at_end")
                if k in r.get("success_terms", {})}
        r["success_terms_recorded"] = r.get("success_terms")
        r["success_terms"] = {**new["terms"], **keep}
        r["success"] = bool(new["satisfied"])
        r["regraded"] = {"when": stamp, "by": "tools/bddl_eval.py --regrade",
                         "was": old_rule, "backup": os.path.relpath(bdir, root)}
    with open(os.path.join(meta, "episodes.jsonl"), "w") as fh:
        for r in rows:
            fh.write(json.dumps(r) + "\n")
    shutil.copy2(task_file, os.path.join(meta, "task.json"))
    log(f"✅ {root}: {len(res)} episodes re-graded under the new rule, every success on its last "
        f"frame; originals in {os.path.relpath(bdir, root)}")
    return True


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("roots", nargs="+", help="dataset roots (the directory holding data/ and meta/)")
    ap.add_argument("--episodes", type=int, nargs="+", help="only these episode indices")
    ap.add_argument("--control", action="store_true",
                    help="also replay each episode one frame short; it must NOT satisfy the goal")
    ap.add_argument("--quiet", action="store_true", help="one line per dataset")
    ap.add_argument("--regrade", metavar="TASK.json",
                    help="re-grade the (one) dataset under this task file's success rule and "
                         "write it, when nothing else changed (see regrade())")
    a = ap.parse_args()
    if a.regrade:
        if len(a.roots) != 1:
            ap.error("--regrade takes exactly one dataset root")
        return 0 if regrade(a.roots[0], a.regrade) else 1
    bad = 0
    for root in a.roots:
        name = os.path.basename(os.path.normpath(root))
        try:
            res = evaluate(root, a.episodes, a.control)
        except Exception as exc:                          # noqa: BLE001
            print(f"❌ {name}: {exc}")
            bad += 1
            continue
        n_ok = sum(r["agrees"] for r in res.values())
        goal = next(iter(res.values()))["goal"] if res else "-"
        if not a.quiet:
            for ep, r in res.items():
                if not r["agrees"] or len(res) <= 5:
                    print(f"  {name} episode {ep}: goal {'SATISFIED' if r['satisfied'] else 'not satisfied'}"
                          f" (hold complete at frame {r['at_frame']} of {r['frames']}), recorded "
                          f"success {r['recorded_success']}"
                          + (f", terms differ: {r['terms_mismatch']}" if r["terms_mismatch"] else "")
                          + (f", cut-short control {'PASSED (wrong)' if r['control_satisfied'] else 'fails (right)'}"
                             if "control_satisfied" in r else ""))
        print(f"{'✅' if n_ok == len(res) else '❌'} {name}: {goal} -- {n_ok}/{len(res)} episodes "
              f"agree with their recorded success"
              + (" (and fail the cut-short control)" if a.control else ""))
        bad += n_ok != len(res)
    return 1 if bad else 0


if __name__ == "__main__":
    code = main()
    # Exit without native teardown: with many of these running at once (package_dataset.py
    # --check runs one per task), a library's worker thread was occasionally torn down while
    # joinable -- "terminate called without an active exception", SIGABRT -- AFTER the verdict
    # was printed, failing a check that had passed (1 run in 65, a different task each time).
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(code or 0)