File size: 60,644 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
"""Matched single-environment evaluation of frozen reactive and planned keyposes."""

import hashlib
import inspect
import json
import time
from pathlib import Path
from types import SimpleNamespace
from typing import Literal

import gymnasium as gym
import mani_skill.envs  # noqa: F401
import numpy as np
import torch
from mani_skill.utils.wrappers import CPUGymWrapper
from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    NonNegativeInt,
    PositiveInt,
    model_validator,
)
from pydantic_settings import CliApp

from lim.act_policy import build_policy
from lim.chunk_coordinates import chunk_relative_to_world
from lim.chunk_endpoint import check_endpoint_controller, dense_chunk_endpoint
from lim.gripper_feedback import (
    FeedbackReaderConfig,
    GripperCompletionConfig,
    PandaGripperFeedback,
)
from lim.keypose_control import KeyposeControlConfig, keypose_command
from lim.keypose_diagnostics import (
    FirstTargetXYZConfig,
    TrainingFirstTargetXYZ,
    TrainingResetConfig,
    TrainingSceneReset,
    first_target_intervention,
    nearest_cube_intervention,
    predict_action_chunk,
    predict_keypose,
)
from lim.keypose_phase import KEYPOSE_PHASE_NAMES, read_phase_logits
from lim.keypose_stop import read_stop_logits
from lim.planned_keypose import (
    MplibKeyposePlanner,
    PlannedExecutorConfig,
    PlannedKeyposeExecutor,
    PlannerConfig,
)
from lim.policy_video import PolicyVideo, PolicyVideoConfig
from lim.reference_act import (
    AuditConfig,
    ReferenceConfig,
    ReleasedSupportAudit,
    check_policy_checkpoint,
    load_checkpoint,
    load_official,
    source_provenance,
)


class EvaluationConfig(BaseModel, frozen=True):
    model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True)
    reference: Path = Path("round9/specs/eval-keypose-main.json")
    """Frozen model and sensor contract; checked against its trained action semantics."""
    target_source: Literal[
        "keypose", "dense_chunk_endpoint", "chunk_relative_endpoint"
    ] = "keypose"
    """Direct query-zero keypose, or nominal endpoint composed from a dense delta chunk."""
    mode: Literal["reactive", "planned"]
    """Fresh prediction each step, or full planned path before each prediction."""
    reactive_gripper_gate: bool = True
    """Reactive only: false directly executes predicted gripper, changing no motion command."""
    output_dir: Path
    """New directory containing every episode, command, prediction and plan."""
    episodes: PositiveInt = 60
    """Consecutive original ID scenes; no selection or retries."""
    seed_start: int = 54000
    """First paired scene seed."""
    max_steps: PositiveInt = 200
    """Physical control steps per scene; non-200 budgets are horizon diagnostics."""
    video_seeds: tuple[int, ...] = (54000, 54017)
    """Selected recordings; the model does not see the observer camera."""
    gripper_completion: GripperCompletionConfig = GripperCompletionConfig()
    """Finger encoder/contact feedback criteria for planned execution completion."""
    resume_after_incomplete: bool = False
    """Keep querying after an unmet gripper command instead of freezing the episode.

    The original contract has no path back from gripper_timeout: the 27 stalled
    chunk_relative endpoint episodes spent 2,314 further steps (42.9% of their
    budget) without a single new query. Default false preserves scored runs.
    """
    carry_gripper_feedback: bool = False
    """Reuse fresh motion-time gripper stability for an exactly unchanged command."""
    phase_gripper_events: bool = False
    """Use predicted close/open classes to hold the arm and execute the predicted
    continuous gripper immediately; other classes retain full planned motion."""
    motion_replan_steps: NonNegativeInt = 0
    """Refresh the target after N actual motion steps; zero executes full paths."""
    first_close_hold: bool = False
    """On the first requested open-to-close transition, hold measured arm joints
    and execute only the predicted gripper. Context retains the raw request,
    whose arm pose was bypassed, after gripper feedback completion."""
    hold_after_first_release: bool = False
    """After the first predicted negative-to-nonnegative gripper transition
    completes its original path and feedback, hold its final command to horizon."""
    honor_predicted_stop: bool = False
    """Consume the checkpoint's stop-after-target prediction only after full
    execution and feedback; false logs the same logits but continues querying."""
    terminal_gripper_event: bool = False
    """For a predicted terminal target with nonnegative gripper, bypass its arm
    pose and hold measured joints during the original gripper feedback."""
    training_dataset: Path | None = None
    """Diagnostic only: restore saved training states selected by episode seed."""
    first_target_xyz_alpha: float | None = Field(
        default=None, ge=0, le=1, allow_inf_nan=False
    )
    """Training-scene oracle only: first XYZ = expert + alpha * model residual.
    None preserves the original path; alpha=1 is an exact identity diagnostic.
    Rotation, gripper and all later predictions remain the model's outputs.
    """
    first_target_xy: Literal["predicted", "cube_center"] = "predicted"
    """Diagnostic only: replace first target XY, retaining all other predictions."""
    every_target_xy: Literal["predicted", "nearest_cube_center"] = "predicted"
    """Diagnostic only: replace EVERY target XY with the nearest cube center.

    Isolates localization precision from phase advancement: height, orientation,
    continuous gripper and the decision of when to advance remain the model's.
    """

    @property
    def diagnostic_xy(self):
        """Number of active privileged-XY interventions; zero for a scored run."""
        return int(self.first_target_xy != "predicted") + int(
            self.every_target_xy != "predicted"
        )

    @model_validator(mode="after")
    def check_single_intervention(self):
        if self.terminal_gripper_event and not self.honor_predicted_stop:
            raise ValueError("Terminal gripper events require predicted-stop execution")
        if self.honor_predicted_stop and (
            self.mode != "planned"
            or self.target_source != "keypose"
            or self.hold_after_first_release
            or self.first_close_hold
            or self.motion_replan_steps
            or self.carry_gripper_feedback
            or self.resume_after_incomplete
            or self.phase_gripper_events
            or self.diagnostic_xy
            or self.first_target_xyz_alpha is not None
            or not self.reactive_gripper_gate
        ):
            raise ValueError("Predicted stop requires an isolated planned context lane")
        if self.hold_after_first_release and (
            self.mode != "planned"
            or self.target_source != "keypose"
            or self.first_close_hold
            or self.motion_replan_steps
            or self.carry_gripper_feedback
            or self.resume_after_incomplete
            or self.phase_gripper_events
            or self.diagnostic_xy
            or self.first_target_xyz_alpha is not None
            or not self.reactive_gripper_gate
        ):
            raise ValueError("Release hold requires an isolated planned context lane")
        if self.first_close_hold and (
            self.mode != "planned"
            or self.target_source != "keypose"
            or self.motion_replan_steps
            or self.carry_gripper_feedback
            or self.resume_after_incomplete
            or self.phase_gripper_events
            or self.diagnostic_xy
            or self.first_target_xyz_alpha is not None
            or not self.reactive_gripper_gate
        ):
            raise ValueError("First-close hold requires an isolated planned lane")
        if self.motion_replan_steps and (
            self.mode != "planned"
            or self.target_source != "keypose"
            or self.carry_gripper_feedback
            or self.resume_after_incomplete
            or self.phase_gripper_events
            or self.diagnostic_xy
            or self.first_target_xyz_alpha is not None
            or not self.reactive_gripper_gate
        ):
            raise ValueError("Motion replanning requires an isolated planned lane")
        if self.phase_gripper_events and (
            self.mode != "planned"
            or self.target_source != "keypose"
            or self.carry_gripper_feedback
            or self.resume_after_incomplete
            or self.diagnostic_xy
            or self.first_target_xyz_alpha is not None
        ):
            raise ValueError(
                "Phase gripper events require an isolated planned keypose lane"
            )
        if not self.reactive_gripper_gate and self.mode != "reactive":
            raise ValueError("Disabling the gripper gate requires reactive execution")
        if self.carry_gripper_feedback and self.mode != "planned":
            raise ValueError("Motion feedback carry requires planned execution")
        if self.diagnostic_xy > 1:
            raise ValueError(
                "Choose one XY intervention; combining them confounds the diagnostic"
            )
        if self.first_target_xyz_alpha is not None:
            if (
                self.mode != "planned"
                or self.target_source != "keypose"
                or self.training_dataset is None
            ):
                raise ValueError(
                    "First XYZ residual diagnostic requires planned keypose and training_dataset"
                )
            if self.diagnostic_xy:
                raise ValueError(
                    "First XYZ residual diagnostic cannot combine with XY interventions"
                )
        if self.target_source != "keypose" and (
            self.mode != "planned"
            or self.diagnostic_xy
            or self.training_dataset is not None
        ):
            raise ValueError(
                "Dense endpoint diagnostic uses planned execution without privileged interventions"
            )
        return self


def reactive_action(current, target, previous_gripper, control, *, gripper_gate=True):
    """Apply the original TCP controller, optionally replacing its gripper only."""
    command, reached, position_error, rotation_error = keypose_command(
        current, target, previous_gripper, control
    )
    gated = command[..., -1].clone()
    requested = target[..., -1].clamp(-1, 1)
    would_change = bool((gated != requested).item())
    if not gripper_gate:
        command[..., -1] = requested
    return command, {
        "phase": "reactive",
        "reached": bool(reached.item()),
        "position_error_m": position_error.item(),
        "rotation_error_rad": rotation_error.item(),
        "requested_gripper": requested.item(),
        "gated_gripper": gated.item(),
        "gate_would_change_gripper": would_change,
        "gripper_gate_blocked": bool(gripper_gate and would_change),
        "reactive_gripper_gate": gripper_gate,
    }


def phase_prediction_details(agent):
    """Read only the latest batch-one prior forward; no environment phase input."""
    logits = read_phase_logits(agent).detach().cpu()
    if (
        logits.shape != (1, len(KEYPOSE_PHASE_NAMES))
        or not torch.isfinite(logits).all()
    ):
        raise ValueError("Expected finite batch-one six-class prior phase logits")
    return {
        "phase_logits_prior": logits[0].tolist(),
        "predicted_phase": int(logits[0].argmax().item()),
    }


def is_gripper_phase(details):
    """Only the current model argmax selects an event; no ordering or sign rule."""
    index = details["predicted_phase"]
    if index not in range(len(KEYPOSE_PHASE_NAMES)):
        raise ValueError("Invalid predicted phase")
    return KEYPOSE_PHASE_NAMES[index] in ("close_gripper", "open_gripper")


def with_completed_target(observation, previous):
    """Encode the prior feedback-completed request; no expert phase is supplied.

    Normally its arm path executed. The explicit first-close-hold intervention
    preserves the requested pose despite bypassing it and logs that exception.
    """
    context = np.zeros(11, dtype=np.float32)
    if previous is not None:
        value = np.asarray(previous, dtype=np.float32)
        if value.shape != (10,) or not np.isfinite(value).all():
            raise ValueError("Expected a finite completed world keypose10")
        context[:10], context[10] = value, 1
    return {**observation, "completed_target": context}


def should_hold_first_close(predicted, executed_gripper, *, already_held):
    """First closing request after an actual nonnegative actuator command."""
    target = torch.as_tensor(predicted)
    if target.shape != (10,) or not torch.isfinite(target).all():
        raise ValueError("Expected finite raw predicted world keypose10")
    if executed_gripper is not None and not np.isfinite(executed_gripper):
        raise ValueError("Expected a finite previously executed gripper command")
    return bool(
        not already_held
        and executed_gripper is not None
        and executed_gripper >= 0
        and target[-1] < 0
    )


def is_first_release_request(predicted, executed_gripper, *, already_requested):
    """A predicted opening follows an actual negative actuator command."""
    target = torch.as_tensor(predicted)
    if target.shape != (10,) or not torch.isfinite(target).all():
        raise ValueError("Expected finite raw predicted world keypose10")
    if executed_gripper is not None and not np.isfinite(executed_gripper):
        raise ValueError("Expected a finite previously executed gripper command")
    return bool(
        not already_requested
        and executed_gripper is not None
        and executed_gripper < 0
        and target[-1] >= 0
    )


def completed_target_hold_command(command, feedback, *, query, hold_query):
    """Latch only a physically executed command after the selected feedback completes."""
    if (
        hold_query is None
        or query != hold_query
        or feedback.get("status") != "complete"
    ):
        return None
    result = np.asarray(command, dtype=np.float32).copy()
    if result.shape != (8,) or not np.isfinite(result).all():
        raise ValueError("Expected the finite executed joint/gripper command8")
    return result


def stop_prediction_details(agent):
    """Read the latest prior forward without another model call or oracle input."""
    logits = read_stop_logits(agent).detach().cpu().clone()
    if logits.shape != (1,) or not torch.isfinite(logits).all():
        raise ValueError("Expected one finite stop-after-target logit")
    return {
        "stop_logit": float(logits[0]),
        "stop_probability": float(logits[0].sigmoid()),
        "stop_after_target": bool(logits[0] >= 0),
    }


def is_terminal_gripper_event(predicted, stop_after_target):
    """Use only the model's terminal intent and original gripper request."""
    target = torch.as_tensor(predicted)
    if target.shape != (10,) or not torch.isfinite(target).all():
        raise ValueError("Expected finite raw predicted world keypose10")
    return bool(stop_after_target and target[-1] >= 0)


def planning_state(base):
    """Read physical state without rendering or taking a simulation step."""
    return {
        "qpos": base.agent.robot.get_qpos().detach().cpu().numpy().copy(),
        "qvel": base.agent.robot.get_qvel().detach().cpu().numpy().copy(),
        "tcp": base.agent.tcp.pose.raw_pose.detach().cpu().numpy().copy(),
        "elapsed_steps": torch.as_tensor(base.elapsed_steps).cpu().numpy().copy(),
    }


def verify_planning_unchanged(before, after):
    if before.keys() != after.keys():
        raise ValueError("Planning state fields differ")
    for key in before:
        if not np.array_equal(before[key], after[key]):
            raise RuntimeError(f"Planner dry-run changed physical {key}")
    return True


def executor_trace(executor):
    """Log active execution separately from the latest (possibly rejected) query."""
    return {
        "goal_id": executor.goal_id,
        "path_revision": executor.path_revision,
        "active_target_query": executor.active_query,
        "completed_target_from_query": executor.completed_target_query,
        "completed_target": None
        if executor.completed_target is None
        else executor.completed_target.tolist(),
        "completed_goals": executor.completed_goals,
        "motion_steps_since_attempt": executor.motion_steps_since_attempt,
        "goal_motion_steps": executor.goal_motion_steps,
        "total_motion_steps": executor.total_motion_steps,
        "goal_replan_attempts": executor.goal_replan_attempts,
    }


def run(config: EvaluationConfig):
    torch.set_num_threads(4)
    torch.manual_seed(0)
    np.random.seed(0)
    config.output_dir.mkdir(parents=True, exist_ok=False)
    (config.output_dir / "plans").mkdir()
    if config.motion_replan_steps:
        (config.output_dir / "query_observations").mkdir()
    reference = ReferenceConfig.model_validate_json(config.reference.read_text())
    context_enabled = reference.policy.keypose_context != "none"
    stop_enabled = reference.policy.keypose_stop_head
    if config.honor_predicted_stop and not stop_enabled:
        raise ValueError(
            "Predicted stop requires a checkpoint trained with a stop head"
        )
    if stop_enabled and (
        config.hold_after_first_release
        or config.first_close_hold
        or config.motion_replan_steps
    ):
        raise ValueError("Stop-head evaluation cannot combine execution interventions")
    if config.hold_after_first_release and not context_enabled:
        raise ValueError("Release hold requires a context-enabled keypose checkpoint")
    if context_enabled and (
        config.mode != "planned"
        or config.target_source != "keypose"
        or config.diagnostic_xy
        or config.first_target_xyz_alpha is not None
        or config.phase_gripper_events
        or config.carry_gripper_feedback
        or config.resume_after_incomplete
    ):
        raise ValueError(
            "Completed goal conditioning requires an isolated planned lane"
        )
    if config.phase_gripper_events and reference.policy.keypose_phase_weight <= 0:
        raise ValueError(
            "Phase gripper events require a checkpoint trained with phase outputs"
        )
    dense_endpoint = config.target_source == "dense_chunk_endpoint"
    relative_endpoint = config.target_source == "chunk_relative_endpoint"
    if dense_endpoint or relative_endpoint:
        if not (
            reference.policy.keypose is None
            and reference.policy.method
            == ("chunk_relative" if relative_endpoint else "cvae")
            and reference.policy.action_encoding == "rotation6d"
            and reference.control_mode == "pd_ee_delta_pose"
            and reference.num_queries == 30
            and not reference.gripper_execution.active
        ):
            raise ValueError("Expected frozen 30-query dense CVAE pose6D model")
    elif reference.policy.keypose is None:
        raise ValueError("Direct keypose evaluation requires a trained keypose model")
    control = reference.policy.keypose or KeyposeControlConfig()
    module = load_official(reference)
    checkpoint, provenance = load_checkpoint(reference.checkpoint)
    check_policy_checkpoint(checkpoint, reference)
    first_xyz_oracle = (
        TrainingFirstTargetXYZ(
            FirstTargetXYZConfig(
                dataset=config.training_dataset, alpha=config.first_target_xyz_alpha
            )
        )
        if config.first_target_xyz_alpha is not None
        else None
    )
    metadata = json.loads(reference.demonstration_metadata.read_text())
    sensor = metadata["env_info"]["env_kwargs"]["sensor_configs"]
    control_mode = "pd_joint_pos" if config.mode == "planned" else "pd_ee_delta_pose"
    raw = gym.make(
        "StackCube-v1",
        obs_mode="rgb",
        control_mode=control_mode,
        reward_mode="sparse",
        render_mode="rgb_array",
        sim_backend="physx_cpu",
        reconfiguration_freq=1,
        max_episode_steps=config.max_steps,
        sensor_configs=sensor,
    )
    if config.training_dataset is not None:
        raw = TrainingSceneReset(
            TrainingResetConfig(env=raw, dataset=config.training_dataset)
        )
    env = ReleasedSupportAudit(
        AuditConfig(
            env=raw,
            snapshots=config.output_dir / "raw_observations",
            stride=10,
            seed_start=config.seed_start,
        )
    )
    env = PolicyVideo(
        PolicyVideoConfig(
            env=env,
            output_dir=config.output_dir / "videos",
            seeds=config.video_seeds,
            label=f"{config.target_source}-{config.mode}",
            max_steps=config.max_steps,
        )
    )
    env = module.FlattenRGBDObservationWrapper(env, depth=False)
    env = CPUGymWrapper(env, ignore_terminations=True, record_metrics=True)
    # Build against the checkpoint's original pose controller7, independent of
    # physical joint ABI8. The policy config distinguishes world poses from deltas.
    spaces = SimpleNamespace(
        single_observation_space=env.observation_space,
        single_action_space=gym.spaces.Box(-1, 1, (7,), dtype=np.float32),
    )
    episodes = []
    started = time.time()
    try:
        agent = (
            build_policy(
                module,
                spaces,
                module.args,
                reference.policy,
                checkpoint.get("normalization"),
            )
            .cuda()
            .eval()
        )
        agent.load_state_dict(checkpoint["ema_agent"])
        with (
            (config.output_dir / "steps.jsonl").open("x") as trace,
            (config.output_dir / "predictions.jsonl").open("x") as predictions,
        ):
            for seed in range(config.seed_start, config.seed_start + config.episodes):
                obs, _ = env.reset(seed=seed)
                base = env.unwrapped
                if dense_endpoint or relative_endpoint:
                    check_endpoint_controller(
                        base.agent._controller_configs["pd_ee_delta_pose"]["arm"]
                    )
                if relative_endpoint:
                    np.testing.assert_allclose(
                        base.agent.robot.pose.raw_pose[0, 3:].cpu().numpy(),
                        [1, 0, 0, 0],
                        atol=1e-5,
                    )
                torch.save(
                    {
                        "observation": obs,
                        "cubeA_pose": base.cubeA.pose.raw_pose.cpu(),
                        "cubeB_pose": base.cubeB.pose.raw_pose.cpu(),
                    },
                    config.output_dir / f"initial-{seed}.pt",
                )
                grip = torch.tensor(
                    [np.clip((obs["state"][7:9].mean() + 0.01) / 0.05 * 2 - 1, -1, 1)],
                    dtype=torch.float32,
                )
                planner = (
                    MplibKeyposePlanner(PlannerConfig(env=env))
                    if config.mode == "planned"
                    else None
                )
                executor = PlannedKeyposeExecutor(
                    PlannedExecutorConfig(
                        control=control,
                        gripper_completion=config.gripper_completion,
                        initial_gripper=float(grip.item()),
                        resume_after_incomplete=config.resume_after_incomplete,
                        carry_gripper_feedback=config.carry_gripper_feedback,
                        motion_replan_steps=config.motion_replan_steps,
                    )
                )
                feedback_reader = (
                    PandaGripperFeedback(
                        FeedbackReaderConfig(
                            env=env, completion=config.gripper_completion
                        )
                    )
                    if planner is not None
                    else None
                )
                calls, failures, plans_completed, gripper_events = 0, 0, 0, 0
                previous_command = None
                first_close_hold_query = None
                release_query, release_request_step = None, None
                release_feedback_complete_step, hold_started_step = None, None
                stop_query, stop_request_step, stop_feedback_complete_step = (
                    None,
                    None,
                    None,
                )
                terminal_command = None
                terminal_event_query = None
                terminal_hold_steps = 0
                for step in range(config.max_steps):
                    before = obs["state"].copy()
                    replan = executor.needs_motion_replan
                    if terminal_command is None and (
                        config.mode == "reactive" or executor.needs_prediction or replan
                    ):
                        if (
                            config.mode == "planned"
                            and calls
                            and not config.motion_replan_steps
                        ):
                            plans_completed += 1
                        query_state_before = (
                            executor_trace(executor)
                            if config.motion_replan_steps
                            else {}
                        )
                        inference_start = (
                            time.monotonic() if config.motion_replan_steps else None
                        )
                        endpoint_details = {}
                        if dense_endpoint:
                            chunk = predict_action_chunk(agent, obs)
                            if chunk.shape != (reference.num_queries, 10):
                                raise ValueError(
                                    "Dense checkpoint returned unexpected chunk shape"
                                )
                            root_pose = base.agent.robot.pose.raw_pose[0].cpu()
                            predicted, decoded = dense_chunk_endpoint(
                                chunk, before[18:25], root_pose
                            )
                            endpoint_details = {
                                "dense_chunk": chunk.tolist(),
                                "decoded_commands": decoded.tolist(),
                                "robot_root_pose": root_pose.tolist(),
                                "model_target_semantics": "nominal composed endpoint; raw model output is dense_chunk",
                            }
                        elif relative_endpoint:
                            chunk = predict_action_chunk(agent, obs)
                            if chunk.shape != (reference.num_queries, 10):
                                raise ValueError(
                                    "Expected a 30x10 fixed-reference chunk"
                                )
                            anchor = torch.tensor(before[18:25])
                            predicted = chunk_relative_to_world(chunk[-1], anchor)
                            endpoint_details = {
                                "relative_chunk": chunk.tolist(),
                                "chunk_start_tcp": anchor.tolist(),
                                "selected_query_index": len(chunk) - 1,
                                "model_target_semantics": "query29 restored from its fixed chunk-start TCP; no delta accumulation",
                            }
                        else:
                            model_obs = (
                                with_completed_target(obs, executor.completed_target)
                                if context_enabled
                                else obs
                            )
                            predicted = predict_keypose(agent, model_obs)
                            if context_enabled:
                                endpoint_details = {
                                    "completed_target_input": model_obs[
                                        "completed_target"
                                    ].tolist(),
                                    "completed_target_from_query": executor.completed_target_query,
                                    "context_mode": reference.policy.keypose_context,
                                }
                                if config.first_close_hold:
                                    endpoint_details.update(
                                        requested_target_context=model_obs[
                                            "completed_target"
                                        ].tolist(),
                                        context_semantics="historical_requested_target_after_feedback",
                                        context_arm_pose_executed=None
                                        if executor.completed_target_query is None
                                        else executor.completed_target_query
                                        != first_close_hold_query,
                                    )
                            if reference.policy.keypose_phase_weight > 0:
                                endpoint_details = phase_prediction_details(agent)
                            if stop_enabled:
                                endpoint_details.update(stop_prediction_details(agent))
                        if config.motion_replan_steps:
                            inference_wall_s = time.monotonic() - inference_start
                            observation_path = (
                                config.output_dir
                                / f"query_observations/seed{seed}-query{calls + 1}.npz"
                            )
                            np.savez_compressed(observation_path, **model_obs)
                        target = first_target_intervention(
                            predicted,
                            query=calls + 1,
                            cube_xy=base.cubeA.pose.p[0, :2].cpu()
                            if config.first_target_xy == "cube_center" and calls == 0
                            else None,
                        )
                        nearest = None
                        if config.every_target_xy == "nearest_cube_center":
                            # Live poses: a perfect localizer would read current state.
                            target, nearest = nearest_cube_intervention(
                                predicted,
                                cubes={
                                    "cubeA": base.cubeA.pose.p[0, :2].cpu(),
                                    "cubeB": base.cubeB.pose.p[0, :2].cpu(),
                                },
                            )
                        xyz_intervention = None
                        if first_xyz_oracle is not None:
                            target, xyz_intervention = first_xyz_oracle.apply(
                                predicted, query=calls + 1, seed=seed
                            )
                        calls += 1
                        prediction = {
                            "seed": seed,
                            "step": step,
                            "query": calls,
                            "target": target.tolist(),
                            "model_target": predicted.tolist(),
                            "first_xy_overridden": config.first_target_xy
                            == "cube_center"
                            and calls == 1,
                            "every_xy_overridden": nearest is not None,
                            "state_before": before.tolist(),
                            **(
                                {"nearest_cube": nearest} if nearest is not None else {}
                            ),
                            **(
                                {"first_xyz_intervention": xyz_intervention}
                                if xyz_intervention is not None
                                else {}
                            ),
                            **endpoint_details,
                        }
                        if stop_enabled:
                            if stop_query is None and prediction["stop_after_target"]:
                                stop_query, stop_request_step = calls, step
                            prediction.update(
                                stop_query=stop_query,
                                stop_request_step=stop_request_step,
                                honor_predicted_stop=config.honor_predicted_stop,
                            )
                        event = config.phase_gripper_events and is_gripper_phase(
                            endpoint_details
                        )
                        hold_close = (
                            config.first_close_hold
                            and should_hold_first_close(
                                predicted,
                                None
                                if previous_command is None
                                else float(previous_command[-1]),
                                already_held=first_close_hold_query is not None,
                            )
                        )
                        hold_terminal = (
                            config.terminal_gripper_event
                            and is_terminal_gripper_event(
                                predicted, prediction["stop_after_target"]
                            )
                        )
                        if config.terminal_gripper_event:
                            prediction.update(
                                terminal_gripper_event=hold_terminal,
                                arm_pose_executed=False if hold_terminal else None,
                            )
                        if config.hold_after_first_release:
                            release_requested = is_first_release_request(
                                predicted,
                                None
                                if previous_command is None
                                else float(previous_command[-1]),
                                already_requested=release_query is not None,
                            )
                            if release_requested:
                                release_query, release_request_step = calls, step
                            prediction.update(
                                release_requested=release_requested,
                                release_query=release_query,
                                release_request_step=release_request_step,
                                previous_executed_gripper=None
                                if previous_command is None
                                else float(previous_command[-1]),
                            )
                        if config.first_close_hold:
                            prediction.update(
                                first_close_hold_triggered=hold_close,
                                previous_executed_gripper=None
                                if previous_command is None
                                else float(previous_command[-1]),
                                arm_pose_executed=False if hold_close else None,
                            )
                        if event or hold_close or hold_terminal:
                            executor.begin_gripper(
                                target, before[:9], source_query=calls
                            )
                            if hold_close:
                                first_close_hold_query = calls
                            elif hold_terminal:
                                terminal_event_query = calls
                            else:
                                gripper_events += 1
                            prediction.update(
                                planning_status="first_close_hold"
                                if hold_close
                                else "terminal_gripper_event"
                                if hold_terminal
                                else "gripper_event",
                                planning_wall_s=0.0,
                                path_steps=0,
                                hold_arm_qpos=before[:7].tolist(),
                            )
                        elif planner is not None:
                            physical_before_plan = (
                                planning_state(base)
                                if config.motion_replan_steps
                                else None
                            )
                            start = time.monotonic()
                            plan = planner.plan(target)
                            prediction["planning_wall_s"] = time.monotonic() - start
                            prediction["planning_status"] = planner.last_status
                            failures += int(plan is None)
                            if config.motion_replan_steps:
                                unchanged = verify_planning_unchanged(
                                    physical_before_plan, planning_state(base)
                                )
                            if plan is not None:
                                np.savez_compressed(
                                    config.output_dir
                                    / f"plans/seed{seed}-query{calls}.npz",
                                    position=plan["position"],
                                    velocity=plan["velocity"],
                                    time=plan["time"],
                                )
                                prediction["path_steps"] = len(plan["position"])
                            if replan:
                                accepted = executor.replace_motion_plan(
                                    target,
                                    None if plan is None else plan["position"],
                                    source_query=calls,
                                )
                            else:
                                executor.begin(
                                    target,
                                    None if plan is None else plan["position"],
                                    before[:9],
                                    source_query=calls,
                                )
                                accepted = plan is not None
                            if config.motion_replan_steps:
                                prediction.update(
                                    query_kind="motion_replan"
                                    if replan
                                    else "goal_start",
                                    candidate_target=target.tolist(),
                                    accepted=accepted,
                                    active_target=executor.target.tolist(),
                                    query_state_before=query_state_before,
                                    **executor_trace(executor),
                                    candidate_path_steps=0
                                    if plan is None
                                    else len(plan["position"]),
                                    dry_run_state_unchanged=unchanged,
                                    inference_wall_s=inference_wall_s,
                                    inference_planning_wall_s=inference_wall_s
                                    + prediction["planning_wall_s"],
                                    deadline_50ms_exceeded=inference_wall_s
                                    + prediction["planning_wall_s"]
                                    > 0.05,
                                    deadline_200ms_exceeded=inference_wall_s
                                    + prediction["planning_wall_s"]
                                    > 0.2,
                                    observation_file=str(
                                        observation_path.relative_to(config.output_dir)
                                    ),
                                    observation_sha256=hashlib.sha256(
                                        observation_path.read_bytes()
                                    ).hexdigest(),
                                )
                                if accepted:
                                    prediction["first_command_minus_qpos"] = (
                                        executor.path[0] - before[:7]
                                    ).tolist()
                                    prediction["first_command_minus_previous"] = (
                                        None
                                        if previous_command is None
                                        else (
                                            executor.path[0] - previous_command[:7]
                                        ).tolist()
                                    )
                                # A failed candidate must never become the executed target.
                                target = executor.target.clone()
                        predictions.write(json.dumps(prediction) + "\n")
                    phase_before = executor.phase
                    if terminal_command is not None:
                        command = terminal_command.copy()
                        if hold_started_step is None:
                            hold_started_step = step
                        terminal_hold_steps += 1
                        details = {
                            "phase": "terminal_hold",
                            "held_command": command.tolist(),
                        }
                    elif planner is None:
                        command_tensor, details = reactive_action(
                            torch.tensor(before[18:25])[None],
                            target[None],
                            grip,
                            control,
                            gripper_gate=config.reactive_gripper_gate,
                        )
                        command = command_tensor[0].numpy()
                        grip = command_tensor[:, -1].clone()
                    else:
                        command, details = executor.command(before[18:25])
                    obs, _, terminated, truncated, info = env.step(command)
                    if config.motion_replan_steps and details["phase"] == "trajectory":
                        executor.observe_motion_step()
                    measured_gripper = (
                        feedback_reader.read(
                            float(command[-1])
                            if config.carry_gripper_feedback
                            else executor.gripper
                        )
                        if planner is not None and details["phase"] != "terminal_hold"
                        else None
                    )
                    if planner is not None and details["phase"] == "gripper":
                        details["gripper_feedback"] = executor.observe_gripper(
                            measured_gripper
                        )
                    elif (
                        planner is not None
                        and config.carry_gripper_feedback
                        and details["phase"] == "trajectory"
                    ):
                        details["motion_gripper_feedback"] = (
                            executor.observe_motion_gripper(measured_gripper)
                        )
                    if config.motion_replan_steps:
                        details.update(
                            **executor_trace(executor),
                            phase_before=phase_before,
                            phase_after=executor.phase,
                            qpos_before=before[:9].tolist(),
                            qvel_before=before[9:18].tolist(),
                            qvel_after=obs["state"][9:18].tolist(),
                            completion_published=details.get(
                                "gripper_feedback", {}
                            ).get("status")
                            == "complete",
                        )
                        previous_command = command.copy()
                    if config.first_close_hold:
                        completed_now = (
                            details.get("gripper_feedback", {}).get("status")
                            == "complete"
                        )
                        details.update(
                            first_close_hold_query=first_close_hold_query,
                            first_close_hold_active=calls == first_close_hold_query,
                            arm_pose_executed=False
                            if calls == first_close_hold_query
                            else (True if completed_now else None),
                            request_feedback_completed=completed_now,
                            completed_target_from_query=executor.completed_target_query,
                            completed_target_arm_pose_executed=None
                            if executor.completed_target_query is None
                            else executor.completed_target_query
                            != first_close_hold_query,
                        )
                        previous_command = command.copy()
                    if config.hold_after_first_release:
                        if terminal_command is None:
                            terminal_command = completed_target_hold_command(
                                command,
                                details.get("gripper_feedback", {}),
                                query=calls,
                                hold_query=release_query,
                            )
                            if terminal_command is not None:
                                release_feedback_complete_step = step
                        details.update(
                            release_query=release_query,
                            release_request_step=release_request_step,
                            release_feedback_complete_step=release_feedback_complete_step,
                            hold_started_step=hold_started_step,
                            terminal_hold_steps=terminal_hold_steps,
                        )
                        previous_command = command.copy()
                    if stop_enabled:
                        if stop_feedback_complete_step is None:
                            completed_command = completed_target_hold_command(
                                command,
                                details.get("gripper_feedback", {}),
                                query=calls,
                                hold_query=stop_query,
                            )
                            if completed_command is not None:
                                stop_feedback_complete_step = step
                                if config.honor_predicted_stop:
                                    terminal_command = completed_command
                        details.update(
                            stop_query=stop_query,
                            stop_request_step=stop_request_step,
                            stop_feedback_complete_step=stop_feedback_complete_step,
                            hold_started_step=hold_started_step,
                            terminal_hold_steps=terminal_hold_steps,
                        )
                    if config.terminal_gripper_event:
                        details.update(
                            terminal_event_query=terminal_event_query,
                            terminal_gripper_event_active=calls == terminal_event_query,
                            arm_pose_executed=False
                            if calls == terminal_event_query
                            else None,
                        )
                    assert not terminated and bool(truncated) == (
                        step == config.max_steps - 1
                    )
                    trace.write(
                        json.dumps(
                            {
                                "seed": seed,
                                "step": step,
                                "query": calls,
                                "target": target.tolist(),
                                "command": command.tolist(),
                                "tcp_before": before[18:25].tolist(),
                                "tcp_after": obs["state"][18:25].tolist(),
                                "qpos_after": obs["state"][:9].tolist(),
                                "success": bool(info["success"]),
                                **details,
                            }
                        )
                        + "\n"
                    )
                row = {k: np.asarray(v).item() for k, v in info["episode"].items()}
                row.update(
                    seed=seed,
                    audit_release_once=bool(info["audit_release_once"]),
                    audit_release_at_end=bool(info["audit_release_at_end"]),
                    steps=config.max_steps,
                    policy_calls=calls,
                    planning_failures=failures,
                    completed_plans=executor.completed_goals
                    if config.motion_replan_steps
                    else plans_completed
                    + int(planner is not None and executor.needs_prediction),
                    last_phase="terminal_hold"
                    if terminal_hold_steps
                    else executor.phase
                    if planner
                    else "reactive",
                    # Cumulative: resuming clears the phase that used to record it.
                    # With resume disabled a timeout is terminal, so this still
                    # equals the previous 0/1 indicator on every scored run.
                    gripper_timeouts=executor.gripper_timeouts if planner else 0,
                    gripper_arrests=executor.gripper_arrests if planner else 0,
                )
                if config.carry_gripper_feedback:
                    row["gripper_feedback_carried"] = executor.gripper_feedback_carried
                if config.phase_gripper_events:
                    row["gripper_event_queries"] = gripper_events
                if config.first_close_hold:
                    row.update(
                        first_close_hold_queries=int(
                            first_close_hold_query is not None
                        ),
                        first_close_hold_query=first_close_hold_query,
                    )
                if config.hold_after_first_release:
                    row.update(
                        release_query=release_query,
                        release_request_step=release_request_step,
                        release_feedback_complete_step=release_feedback_complete_step,
                        hold_started_step=hold_started_step,
                        terminal_hold_steps=terminal_hold_steps,
                        held_command=None
                        if terminal_command is None
                        else terminal_command.tolist(),
                    )
                if stop_enabled:
                    row.update(
                        stop_query=stop_query,
                        stop_request_step=stop_request_step,
                        stop_feedback_complete_step=stop_feedback_complete_step,
                        honor_predicted_stop=config.honor_predicted_stop,
                        hold_started_step=hold_started_step,
                        terminal_hold_steps=terminal_hold_steps,
                        held_command=None
                        if terminal_command is None
                        else terminal_command.tolist(),
                    )
                if config.terminal_gripper_event:
                    row["terminal_event_query"] = terminal_event_query
                if config.motion_replan_steps:
                    row.update(
                        completed_goals=executor.completed_goals,
                        accepted_paths=executor.accepted_paths,
                        replan_attempts=executor.replan_attempts,
                        replan_failures=executor.replan_failures,
                        total_motion_steps=executor.total_motion_steps,
                        unfinished_path_steps=len(executor.path) - executor.index
                        if executor.phase == "trajectory"
                        else 0,
                    )
                episodes.append(row)
                with (config.output_dir / "episodes.jsonl").open("a") as stream:
                    stream.write(json.dumps(row) + "\n")
                predictions.flush()
                trace.flush()
                print("EPISODE_COMPLETE", json.dumps(row), flush=True)
    finally:
        env.close()
    from mani_skill.examples.motionplanning.base_motionplanner import motionplanner

    result = {
        "config": config.model_dump(mode="json"),
        "provenance": provenance | source_provenance(reference),
        "policy": reference.policy.model_dump(mode="json"),
        "sensor_configs": sensor,
        "control_mode": control_mode,
        "control_hz": 20,
        "diagnostic": config.training_dataset is not None
        or config.first_target_xyz_alpha is not None
        or config.first_target_xy != "predicted"
        or config.every_target_xy != "predicted"
        or config.max_steps != 200
        or not config.reactive_gripper_gate
        or dense_endpoint
        or relative_endpoint,
        "pose_control_diagnostics": control.model_dump(mode="json"),
        "target_semantics": (
            "Compose all 30 decoded deltas assuming perfect tracking; only final gripper is retained. "
            "Intermediate motion and gripper events are discarded, then re-planned by the unchanged executor."
            if dense_endpoint
            else (
                "Last predicted relative target restored from the fixed chunk-start TCP; only final gripper retained."
                if relative_endpoint
                else "Latest query-zero world keypose"
            )
        ),
        "episodes": len(episodes),
        "counts": {
            k: sum(r[k] for r in episodes)
            for k in (
                "success_once",
                "success_at_end",
                "audit_release_once",
                "audit_release_at_end",
            )
        },
        "policy_calls": sum(r["policy_calls"] for r in episodes),
        "planning_failures": sum(r["planning_failures"] for r in episodes),
        "started_epoch": started,
        "ended_epoch": time.time(),
        "planner_source_sha256": hashlib.sha256(
            Path(inspect.getfile(motionplanner)).read_bytes()
        ).hexdigest(),
        "scope": f"Frozen final EMA ({config.target_source}); {config.max_steps} physical steps per scene. Planned: full joint trajectory then measured finger position/velocity or bilateral contact stability. Contact feedback only in executor, no task labels in model inputs or model updates. Timeout holds without replanning; TCP errors diagnostic only. Control20Hz is not fresh-observation policy20Hz."
        + (
            f" Motion-only target updates after {config.motion_replan_steps} actual path steps; latest accepted path completes before gripper feedback. Failed replan retains old target/path/index. Completed context changes only on real feedback completion; unexecuted targets never enter it. No temporal ensemble. Additional inference/planning cost is logged; no continuity or realtime guarantee."
            if config.motion_replan_steps
            else ""
        )
        + (
            " Historical requested-target context retains the previous raw model request after feedback completion; initially invalid. The first-close-hold request bypasses its arm pose, so that context does not claim the pose executed or was reached. No expert target or phase is supplied."
            if context_enabled and config.first_close_hold
            else " Completed-target context comes only from the previous model target after executor completion; initially invalid. The zero-context control masks this input inside its model. No expert target or phase is supplied."
            if context_enabled
            else ""
        )
        + (
            " First-close hold is an actuator intervention: the first negative gripper request following an actual nonnegative gripper command holds measured joints and applies the unchanged continuous gripper request with native clipping/feedback. The raw requested pose is bypassed, not corrected. Trigger uses no query number, expert phase or task geometry. completed_plans includes this feedback-completed request and does not certify all poses executed."
            if config.first_close_hold
            else ""
        )
        + (
            " First predicted release after an actual negative gripper command executes its original full path and gripper feedback, then holds the last executed command through the unchanged horizon without further queries. This heuristic does not use task success, certify release, or implement a learned stop. Failure/timeout never enters terminal hold."
            if config.hold_after_first_release
            else ""
        )
        + (
            " Stop-after-target logits are read from the same zero-latent forward, with fixed probability threshold 0.5. Enabled execution holds the last actual command only after the selected request's declared execution and gripper feedback complete, through the unchanged horizon. Ignored execution records the same prediction without changing commands or queries. Task success, expert phase, and gripper sign never substitute for predicted terminal intent."
            if stop_enabled
            else ""
        )
        + (
            " A predicted terminal target with a nonnegative gripper request bypasses its arm pose: measured joints are held while the original continuous gripper request is completed by feedback, then the existing stop holds its last command to horizon. This request's raw world pose was not executed, and is never passed into a subsequent query. Completion counts refer to the gripper event, not reaching the bypassed world pose."
            if config.terminal_gripper_event
            else ""
        )
        + (
            " Privileged first-query XYZ = saved training approach XYZ + alpha * model residual. Rotation, gripper and all subsequent targets remain predicted. Every alpha, including the alpha=1 identity control, is an oracle diagnostic, not learned-policy performance."
            if first_xyz_oracle is not None
            else ""
        )
        + (
            " Motion-time stable feedback can complete an unchanged gripper command at the final path step; changed commands still require post-path feedback."
            if config.carry_gripper_feedback
            else ""
        )
        + (
            " Reactive gripper gate disabled: only the gripper scalar is replaced by the clipped model request; arm motion commands are unchanged."
            if not config.reactive_gripper_gate
            else ""
        )
        + (
            " The current prior-mode phase argmax selects arm hold for close/open events; continuous gripper is still the model prediction. No expert phase, forced stage order, or forced gripper sign. completed_plans counts completed action targets including gripper events."
            if config.phase_gripper_events
            else " Phase logits and argmax are diagnostic outputs from the current prior-mode policy forward only; no environment phase labels, target changes or phase-based execution decisions."
            if reference.policy.keypose_phase_weight > 0
            else ""
        ),
    }
    (config.output_dir / "result.json").write_text(json.dumps(result, indent=2) + "\n")
    print("PLANNED_COMPARISON_COMPLETE", json.dumps(result), flush=True)


if __name__ == "__main__":
    run(CliApp.run(EvaluationConfig))