File size: 60,708 Bytes
1e71a55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
"""Observation-only GraspGen-style PCA/AABB controller for ATEC Task E.

This is an experimental submit-style policy: it uses only proprioception plus
the fixed external RGB-D camera observation to estimate object centres, then
drives a calibrated Piper pick/place primitive with local kinematics.
"""

from __future__ import annotations

import os
from dataclasses import dataclass

import numpy as np
import torch

try:
    import pinocchio as pin
except Exception:  # pragma: no cover - handled at runtime by the judge/server
    pin = None


TABLE_CENTER_X = 1.00
TABLE_CENTER_Y = 0.00
TABLE_DIMS_AT_0P008 = (0.6468062441005529, 0.9084968693231588, 0.6613141183247961)
TABLE_SCALE = 0.01
TABLE_DIMS = tuple(dim * (TABLE_SCALE / 0.008) for dim in TABLE_DIMS_AT_0P008)
TABLE_HALF_X = TABLE_DIMS[0] * 0.5
TABLE_TOP_Z = TABLE_DIMS[2]
BASKET_CENTER_X = TABLE_CENTER_X + 0.08
BASKET_CENTER_Y = TABLE_CENTER_Y - 0.30

DEFAULT_Q = np.array([0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035], dtype=np.float64)
HOME_Q = np.array([-0.000033, 0.924525, -1.514983, 0.000011, 1.219900, -0.000033, 0.035, -0.035], dtype=np.float64)
ACTION_SCALE = 0.5
GRIP_OPEN = np.array([0.035, -0.035], dtype=np.float64)
GRIP_HALF = np.array([0.018, -0.018], dtype=np.float64)
GRIP_CLOSE = np.array([0.0, 0.0], dtype=np.float64)
OBJ1_HOLD_GAP = 0.0415
OBJ3_HOLD_GAP = float(os.environ.get("ATEC_PCA_OBJ3_HOLD_GAP", "0.0675"))
OBJ3_CLOSE_MIN_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_CLOSE_MIN_STEPS", "160"))
OBJ3_LOW_HOLD_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_LOW_HOLD_STEPS", "0"))
OBJ3_LIFT_CLEARANCE = float(os.environ.get("ATEC_PCA_OBJ3_LIFT_CLEARANCE", "0.12"))
OBJ3_CARRY_CLEARANCE = float(os.environ.get("ATEC_PCA_OBJ3_CARRY_CLEARANCE", "0.145"))
OBJ3_OBJECT_SERVO_GAIN = float(os.environ.get("ATEC_PCA_OBJ3_OBJECT_SERVO_GAIN", "1.0"))
OBJ3_OBJECT_SERVO_MAX_XY = float(os.environ.get("ATEC_PCA_OBJ3_OBJECT_SERVO_MAX_XY", "0.300"))
OBJ3_FINGER_SERVO_MAX_XY = float(os.environ.get("ATEC_PCA_OBJ3_FINGER_SERVO_MAX_XY", "0.240"))
OBJ3_APPROACH_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_APPROACH_FINGER_Z", str(TABLE_TOP_Z + 0.090)))
OBJ3_CLOSE_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_CLOSE_FINGER_Z", str(TABLE_TOP_Z + 0.000)))
OBJ3_LIFT_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_LIFT_FINGER_Z", str(TABLE_TOP_Z + 0.045)))
OBJ3_ENABLE_INSERT = os.environ.get("ATEC_PCA_OBJ3_ENABLE_INSERT", "0") != "0"
OBJ3_PREGRASP_OFFSET = np.array(
    [
        float(os.environ.get("ATEC_PCA_OBJ3_PREGRASP_X_OFFSET", "0.000")),
        float(os.environ.get("ATEC_PCA_OBJ3_PREGRASP_Y_OFFSET", "0.080")),
    ],
    dtype=np.float64,
)
OBJ3_SIDE_APPROACH_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_SIDE_APPROACH_STEPS", "160"))
OBJ3_SIDE_LOW_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_SIDE_LOW_STEPS", "140"))
OBJ3_INSERT_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_INSERT_STEPS", "220"))
OBJ3_PREGRASP_LOW_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_PREGRASP_LOW_FINGER_Z", str(TABLE_TOP_Z + 0.024)))
OBJ3_FALLBACK_DRAG_Z = float(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_DRAG_Z", str(TABLE_TOP_Z + 0.035)))
OBJ3_FALLBACK_START_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_START_STEPS", "60"))
OBJ3_FALLBACK_MID_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_MID_STEPS", "260"))
OBJ3_FALLBACK_END_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_END_STEPS", "260"))
OBJ3_FALLBACK_OPEN_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_OPEN_STEPS", "100"))
OBJ3_DRAG_START_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_START_STEPS", "80"))
OBJ3_DRAG_MID_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_MID_STEPS", "360"))
OBJ3_DRAG_END_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_END_STEPS", "360"))
OBJ3_DRAG_SETTLE_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_SETTLE_STEPS", "120"))
PCA_DLS_MAX_DELTA = float(os.environ.get("ATEC_PCA_DLS_MAX_DELTA", "0.18"))
PCA_FINGER_IK_MAX_DELTA = float(os.environ.get("ATEC_PCA_FINGER_IK_MAX_DELTA", "0.18"))
OBJ3_GRIPPER_MAX_DELTA = float(os.environ.get("ATEC_PCA_OBJ3_GRIPPER_MAX_DELTA", "0.003"))
OBJ3_HOLD_GRIP_DEFAULT = np.array(
    [
        float(os.environ.get("ATEC_PCA_OBJ3_HOLD_Q_POS", "0.0000")),
        float(os.environ.get("ATEC_PCA_OBJ3_HOLD_Q_NEG", "0.0000")),
    ],
    dtype=np.float64,
)

BASE_POS_W = np.array([TABLE_CENTER_X + TABLE_HALF_X, TABLE_CENTER_Y, TABLE_TOP_Z], dtype=np.float64)
R_W_B = np.diag([-1.0, -1.0, 1.0])
K_VIDEO = np.array([[732.99927, 0.0, 320.0], [0.0, 732.99927, 240.0], [0.0, 0.0, 1.0]], dtype=np.float64)
CAM_POS_W = np.array([-0.2, 0.0, 1.6266427], dtype=np.float64)
CAM_QUAT_WXYZ = np.array([-0.33350849, 0.62351596, -0.62351584, 0.33350849], dtype=np.float64)

OBJ_Y_BANDS = {
    1: (TABLE_CENTER_Y + 0.25, TABLE_CENTER_Y + 0.29),
    2: (TABLE_CENTER_Y + 0.14, TABLE_CENTER_Y + 0.20),
    3: (TABLE_CENTER_Y + 0.03, TABLE_CENTER_Y + 0.09),
}
OBJ_Z_LIMITS = {
    1: (TABLE_TOP_Z + 0.035, TABLE_TOP_Z + 0.130),
    2: (TABLE_TOP_Z + 0.020, TABLE_TOP_Z + 0.190),
    3: (TABLE_TOP_Z + 0.012, TABLE_TOP_Z + 0.095),
}
OBJ_GRASP_CENTER_OFFSETS = {
    1: np.array([0.0, 0.0], dtype=np.float64),
    2: np.array([0.060, 0.0], dtype=np.float64),
    3: np.array([float(os.environ.get("ATEC_PCA_OBJ3_X_OFFSET", "0.0")), 0.0], dtype=np.float64),
}
OBJ_CENTER_COMPLETION_OFFSETS = {
    # The fixed camera sees object_1 from the lower-y side when it is near the
    # top band edge; RGB-D AABB/median centres land on the visible side instead
    # of the root/contact centre.  This completes the centre before applying
    # the Piper finger offset below.
    1: np.array([0.020, 0.0], dtype=np.float64),
    2: np.array([0.0, 0.0], dtype=np.float64),
    3: np.array(
        [
            0.0,
            float(os.environ.get("ATEC_PCA_OBJ3_CENTER_Y_OFFSET", "0.000")),
        ],
        dtype=np.float64,
    ),
}
OBJ_TCP_Z = {1: 0.140, 2: 0.040, 3: 0.090}
OBJ_CLOSE_Z_OFFSETS = {1: 0.020, 2: 0.020, 3: float(os.environ.get("ATEC_PCA_OBJ3_CLOSE_Z_OFFSET", "-0.005"))}
OBJ_CLOSE_Z = {
    1: TABLE_TOP_Z + 0.030,  # low close plane; compensate submit IK's high-contact bias
    2: TABLE_TOP_Z + 0.030,
    3: TABLE_TOP_Z + 0.030,
}
OBJ_ROOT_Z_EST = {
    1: TABLE_TOP_Z + 0.045,
    2: TABLE_TOP_Z + 0.055,
    3: TABLE_TOP_Z + 0.035,
}
OBJ_PRECLOSE_INSERT_OFFSETS = {
    1: np.array([0.0, 0.0], dtype=np.float64),
}
OBJ_FINGER_XY_OFFSETS = {
    # Calibrated from successful 2026-05-20 scripted traces.  Banana succeeds
    # when the actual link7/link8 centre is slightly on the -X side of the
    # object root, cradling the curve instead of pushing from the +X side.
    3: np.array(
        [
            float(os.environ.get("ATEC_PCA_OBJ3_FINGER_X_OFFSET", "-0.010")),
            float(os.environ.get("ATEC_PCA_OBJ3_FINGER_Y_OFFSET", "0.000")),
        ],
        dtype=np.float64,
    ),
}
OBJ_FINGER_TARGET_REL_Z = {
    1: -0.025,
    3: float(os.environ.get("ATEC_PCA_OBJ3_FINGER_REL_Z", "0.027")),
}
OBJ_FINGER_SERVO_MAX_Z = {1: 0.050, 3: 0.040}
OBJ_REACH_STEPS = {1: 200, 2: 200, 3: 200}
OBJ_CLOSE_STEPS = {1: 220, 2: 180, 3: int(os.environ.get("ATEC_PCA_OBJ3_CLOSE_STEPS", "90"))}
OBJ_LIFT_STEPS = {1: 300, 2: 200, 3: int(os.environ.get("ATEC_PCA_OBJ3_LIFT_STEPS", "35"))}
OBJ_TRANSPORT_STEPS = {1: 1400, 2: 1400, 3: int(os.environ.get("ATEC_PCA_OBJ3_TRANSPORT_STEPS", "440"))}
OBJ_PLACE_STEPS = {1: 260, 2: 260, 3: 220}
OBJ_OPEN_STEPS = {1: 260, 2: 260, 3: 220}
OBJ_PLACE_XY_OFFSETS = {
    1: np.array([0.0, 0.0], dtype=np.float64),
    3: np.array(
        [
            float(os.environ.get("ATEC_PCA_OBJ3_PLACE_X_OFFSET", "0.0")),
            float(os.environ.get("ATEC_PCA_OBJ3_PLACE_Y_OFFSET", "0.0")),
        ],
        dtype=np.float64,
    ),
}


def _quat_wxyz_to_rot(q: np.ndarray) -> np.ndarray:
    q = np.asarray(q, dtype=np.float64)
    q = q / max(np.linalg.norm(q), 1e-12)
    w, x, y, z = q
    return np.array(
        [
            [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
            [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
            [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
        ],
        dtype=np.float64,
    )


def _rot_error(current: np.ndarray, target: np.ndarray) -> np.ndarray:
    err = target @ current.T
    return 0.5 * np.array(
        [err[2, 1] - err[1, 2], err[0, 2] - err[2, 0], err[1, 0] - err[0, 1]],
        dtype=np.float64,
    )


def _world_to_base_pos(pos_w: np.ndarray) -> np.ndarray:
    return R_W_B.T @ (np.asarray(pos_w, dtype=np.float64) - BASE_POS_W)


def _world_to_base_rot(rot_w: np.ndarray) -> np.ndarray:
    return R_W_B.T @ rot_w


@dataclass
class PoseTarget:
    pos_w: np.ndarray
    rot_w: np.ndarray
    grip: np.ndarray
    steps: int
    finger_xy: np.ndarray | None = None
    finger_z: float | None = None
    servo_obj_z: float | None = None
    servo_target_rel_z: float | None = None
    freeze_arm: bool = False
    label: str = ""


class _PiperIK:
    def __init__(self):
        if pin is None:
            raise RuntimeError("pinocchio is required for solution_pca.py")
        root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        urdf = os.path.join(root, "third_party", "Agilex-College", "piper", "handpose_det", "models", "modified_piper_without_camera.urdf")
        if not os.path.exists(urdf):
            urdf = os.environ.get("ATEC_PIPER_URDF", urdf)
        self.model = pin.buildModelFromUrdf(urdf)
        self.data = self.model.createData()
        self.frame_id = self.model.getFrameId("gripper_base")
        self.link7_id = self.model.getFrameId("link7")
        self.link8_id = self.model.getFrameId("link8")
        self._last_q = HOME_Q[:6].copy()

    def fk_base(self, q6: np.ndarray):
        q = np.concatenate([np.asarray(q6, dtype=np.float64), GRIP_OPEN])
        pin.forwardKinematics(self.model, self.data, q)
        pin.updateFramePlacements(self.model, self.data)
        M = self.data.oMf[self.frame_id]
        return M.translation.copy(), M.rotation.copy()

    def solve(self, q_current8: np.ndarray, pos_w: np.ndarray, rot_w: np.ndarray) -> np.ndarray:
        target_pos_b = _world_to_base_pos(pos_w)
        target_rot_b = _world_to_base_rot(rot_w)
        q6 = np.asarray(q_current8[:6], dtype=np.float64).copy()
        if not np.all(np.isfinite(q6)):
            q6 = self._last_q.copy()
        for _ in range(35):
            pos_b, rot_b = self.fk_base(q6)
            err = np.concatenate([target_pos_b - pos_b, _rot_error(rot_b, target_rot_b)])
            if np.linalg.norm(err[:3]) < 0.003 and np.linalg.norm(err[3:]) < 0.03:
                break
            J = pin.computeFrameJacobian(
                self.model,
                self.data,
                np.concatenate([q6, GRIP_OPEN]),
                self.frame_id,
                pin.ReferenceFrame.LOCAL_WORLD_ALIGNED,
            )[:, :6]
            damping = 0.020
            dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(6), err)
            dq = np.clip(dq, -0.20, 0.20)
            q6 = np.clip(q6 + dq, [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944])
        # Near contact, being centimetres high is worse than a small wrist
        # orientation error.  The successful simulator runner effectively
        # servos the link7/link8 centre every step; this position-only cleanup
        # gives the submit-style IK the same priority.
        for _ in range(20):
            pos_b, _ = self.fk_base(q6)
            pos_err = target_pos_b - pos_b
            if np.linalg.norm(pos_err) < 0.002:
                break
            J = pin.computeFrameJacobian(
                self.model,
                self.data,
                np.concatenate([q6, GRIP_OPEN]),
                self.frame_id,
                pin.ReferenceFrame.LOCAL_WORLD_ALIGNED,
            )[:3, :6]
            damping = 0.012
            dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(3), pos_err)
            dq = np.clip(dq, -0.18, 0.18)
            q6 = np.clip(q6 + dq, [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944])
        self._last_q = q6.copy()
        return q6

    def step_dls(
        self,
        q_current8: np.ndarray,
        pos_w: np.ndarray,
        rot_w: np.ndarray,
        *,
        lambda_val: float = 0.05,
        max_joint_delta: float = PCA_DLS_MAX_DELTA,
        position_only: bool = False,
    ) -> np.ndarray:
        """One DifferentialIK-style DLS update from the current joint state.

        The successful simulator runner uses IsaacLab's CartesianController,
        which computes a small damped least-squares update from the current
        PhysX state on every frame.  This mirrors that behavior more closely
        than solving a full IK target and then clipping the final joint target.
        """
        target_pos_b = _world_to_base_pos(pos_w)
        target_rot_b = _world_to_base_rot(rot_w)
        q6 = np.asarray(q_current8[:6], dtype=np.float64).copy()
        if not np.all(np.isfinite(q6)):
            q6 = self._last_q.copy()
        q8 = np.concatenate([q6, GRIP_OPEN])
        pos_b, rot_b = self.fk_base(q6)
        J_full = pin.computeFrameJacobian(
            self.model,
            self.data,
            q8,
            self.frame_id,
            pin.ReferenceFrame.LOCAL_WORLD_ALIGNED,
        )[:, :6]
        if position_only:
            err = target_pos_b - pos_b
            J = J_full[:3, :]
        else:
            err = np.concatenate([target_pos_b - pos_b, _rot_error(rot_b, target_rot_b)])
            J = J_full
        damping = float(lambda_val)
        dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(J.shape[0]), err)
        dq = np.clip(dq, -max_joint_delta, max_joint_delta)
        q6 = np.clip(
            q6 + dq,
            [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944],
            [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944],
        )
        self._last_q = q6.copy()
        return q6

    def finger_center_world(self, q_current8: np.ndarray) -> np.ndarray:
        q = np.asarray(q_current8, dtype=np.float64).copy()
        pin.forwardKinematics(self.model, self.data, q)
        pin.updateFramePlacements(self.model, self.data)
        p7 = self.data.oMf[self.link7_id].translation
        p8 = self.data.oMf[self.link8_id].translation
        center_b = 0.5 * (p7 + p8)
        return BASE_POS_W + R_W_B @ center_b

    def finger_gap(self, q_current8: np.ndarray) -> float:
        q = np.asarray(q_current8, dtype=np.float64).copy()
        pin.forwardKinematics(self.model, self.data, q)
        pin.updateFramePlacements(self.model, self.data)
        p7 = self.data.oMf[self.link7_id].translation
        p8 = self.data.oMf[self.link8_id].translation
        return float(np.linalg.norm(p7 - p8))

    def solve_finger(self, q_current8: np.ndarray, finger_w: np.ndarray, rot_w: np.ndarray) -> np.ndarray:
        """IK on the actual link7/link8 centre, not the gripper_base proxy."""
        target_pos_b = _world_to_base_pos(finger_w)
        target_rot_b = _world_to_base_rot(rot_w)
        q_current8 = np.asarray(q_current8, dtype=np.float64).copy()
        q6 = q_current8[:6].copy()
        grip = q_current8[6:8].copy()
        if not np.all(np.isfinite(q6)):
            q6 = self._last_q.copy()
        for _ in range(40):
            q8 = np.concatenate([q6, grip])
            pin.forwardKinematics(self.model, self.data, q8)
            pin.updateFramePlacements(self.model, self.data)
            p7 = self.data.oMf[self.link7_id].translation
            p8 = self.data.oMf[self.link8_id].translation
            center_b = 0.5 * (p7 + p8)
            gb_rot = self.data.oMf[self.frame_id].rotation
            pos_err = target_pos_b - center_b
            rot_err = _rot_error(gb_rot, target_rot_b)
            if np.linalg.norm(pos_err) < 0.002 and np.linalg.norm(rot_err) < 0.05:
                break
            J7 = pin.computeFrameJacobian(self.model, self.data, q8, self.link7_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)[:3, :6]
            J8 = pin.computeFrameJacobian(self.model, self.data, q8, self.link8_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)[:3, :6]
            Jpos = 0.5 * (J7 + J8)
            Jrot = pin.computeFrameJacobian(self.model, self.data, q8, self.frame_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)[3:, :6]
            rot_wt = 0.05
            J = np.vstack([Jpos, rot_wt * Jrot])
            err = np.concatenate([pos_err, rot_wt * rot_err])
            damping = 0.018
            dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(6), err)
            dq = np.clip(dq, -PCA_FINGER_IK_MAX_DELTA, PCA_FINGER_IK_MAX_DELTA)
            q6 = np.clip(q6 + dq, [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944])
        self._last_q = q6.copy()
        return q6


class AlgSolution:
    def __init__(self):
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
        self.ik = _PiperIK()
        self.reset()

    def reset(self, **_kwargs):
        self.t = 0
        self.home_count = 0
        self.plan: list[PoseTarget] = []
        self.plan_idx = 0
        self.step_in_target = 0
        self.detected = False
        self.fallback_done = False
        self.objects: tuple[int, ...] = ()
        self._last_action = np.zeros(8, dtype=np.float64)
        self._obj1_hold_grip: np.ndarray | None = None
        self._obj3_hold_grip: np.ndarray | None = None
        self._obj3_carry_offset_xy: np.ndarray | None = None
        self._detected_centers: dict[int, np.ndarray] = {}

    def reset_episode(self):
        self.reset()

    def _obs_qpos(self, obs: dict) -> np.ndarray:
        proprio = obs["proprio"]
        if isinstance(proprio, torch.Tensor):
            p = proprio.detach().cpu().numpy()[0]
        else:
            p = np.asarray(proprio)[0]
        return p[:8].astype(np.float64) + DEFAULT_Q

    def _video_rgb_depth(self, obs: dict) -> tuple[np.ndarray, np.ndarray]:
        rgb = obs["image"]["video_rgb"]
        if isinstance(rgb, torch.Tensor):
            rgb_arr = rgb.detach().cpu().numpy()[0]
        else:
            rgb_arr = np.asarray(rgb)[0]
        if rgb_arr.ndim == 3 and rgb_arr.shape[0] in (3, 4):
            rgb_arr = np.transpose(rgb_arr[:3], (1, 2, 0))
        if rgb_arr.shape[-1] == 4:
            rgb_arr = rgb_arr[..., :3]
        if np.issubdtype(rgb_arr.dtype, np.floating):
            rgb_arr = (rgb_arr * 255.0).clip(0, 255).astype(np.uint8)

        depth = obs["image"]["video_depth"]
        if isinstance(depth, torch.Tensor):
            arr = depth.detach().cpu().numpy()[0]
        else:
            arr = np.asarray(depth)[0]
        if arr.ndim == 3:
            arr = arr[..., 0]
        return rgb_arr.astype(np.uint8, copy=False), arr.astype(np.float64)

    def _points_for_object(
        self,
        rgb: np.ndarray,
        depth: np.ndarray,
        obj_idx: int,
        *,
        wide: bool = False,
        fill_holes: bool = True,
    ) -> np.ndarray:
        h, w = depth.shape
        ys, xs = np.where(np.isfinite(depth) & (depth > 0.0) & (depth < 6.0))
        if len(xs) == 0:
            return np.zeros((0, 3), dtype=np.float64)
        z = depth[ys, xs]
        x = (xs.astype(np.float64) - K_VIDEO[0, 2]) / K_VIDEO[0, 0] * z
        y = (ys.astype(np.float64) - K_VIDEO[1, 2]) / K_VIDEO[1, 1] * z
        pts_cam = np.stack([x, y, z], axis=1)
        rot_w_cam = _quat_wxyz_to_rot(CAM_QUAT_WXYZ)
        pts = (rot_w_cam @ pts_cam.T).T + CAM_POS_W
        y0, y1 = OBJ_Y_BANDS[obj_idx]
        if wide:
            y0 = BASKET_CENTER_Y - 0.10
            y1 = OBJ_Y_BANDS[obj_idx][1] + (0.045 if obj_idx == 3 else 0.10)
        z0, z1 = OBJ_Z_LIMITS[obj_idx]
        if wide:
            z0 = TABLE_TOP_Z + 0.005
            if obj_idx == 3:
                z1 = TABLE_TOP_Z + 0.220
        rgb_pts = rgb[ys, xs].astype(np.float32)
        maxc = rgb_pts.max(axis=1)
        minc = rgb_pts.min(axis=1)
        non_gray = ((maxc - minc) > 18.0) | (maxc > 170.0)
        if obj_idx == 3:
            # Use the banana's yellow appearance for dynamic tracking.  The broad
            # world band can include the pink basket, white gripper, and mustard;
            # a simple color gate is more reliable than generic non-gray there.
            r, g, b = rgb_pts[:, 0], rgb_pts[:, 1], rgb_pts[:, 2]
            non_gray = (r > 105.0) & (g > 75.0) & (b < 130.0) & ((r - b) > 35.0)
        keep = (
            (pts[:, 0] >= TABLE_CENTER_X - 0.18)
            & (pts[:, 0] <= TABLE_CENTER_X + 0.18)
            & (pts[:, 1] >= y0 - 0.035)
            & (pts[:, 1] <= y1 + 0.035)
            & (pts[:, 2] >= z0)
            & (pts[:, 2] <= z1)
            & non_gray
        )
        if np.count_nonzero(keep) == 0:
            return pts[keep]
        if not fill_holes:
            return pts[keep]
        # Mirror rgbd_band_object_mask(): fill shallow holes inside the detected
        # component ROI, still constrained by the legal world band and z gate.
        yy = ys[keep]
        xx = xs[keep]
        x1, x2 = int(xx.min()), int(xx.max())
        y1p, y2p = int(yy.min()), int(yy.max())
        in_roi = (xs >= x1) & (xs <= x2) & (ys >= y1p) & (ys <= y2p)
        fill_keep = (
            in_roi
            & (pts[:, 0] >= TABLE_CENTER_X - 0.18)
            & (pts[:, 0] <= TABLE_CENTER_X + 0.18)
            & (pts[:, 1] >= y0 - 0.035)
            & (pts[:, 1] <= y1 + 0.035)
            & (pts[:, 2] >= z0)
            & (pts[:, 2] <= z1)
        )
        return pts[fill_keep]

    def _estimate_grasp(self, rgb: np.ndarray, depth: np.ndarray, obj_idx: int, *, wide: bool = False) -> tuple[np.ndarray, np.ndarray]:
        pts = self._points_for_object(rgb, depth, obj_idx, wide=wide, fill_holes=(obj_idx != 1))
        if len(pts) < 64:
            # Spawn-band fallback keeps the controller alive if one frame is bad.
            y0, y1 = OBJ_Y_BANDS[obj_idx]
            center = np.array([TABLE_CENTER_X, 0.5 * (y0 + y1), TABLE_TOP_Z + 0.06], dtype=np.float64)
            return center, _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64))
        center = pts.mean(axis=0)
        world_aabb_center = 0.5 * (pts.min(axis=0) + pts.max(axis=0))
        cov = (pts - center).T @ (pts - center) / max(len(pts) - 1, 1)
        vals, vecs = np.linalg.eigh(cov)
        order = np.argsort(vals)[::-1]
        axes = vecs[:, order]
        if np.linalg.det(axes) < 0:
            axes[:, 2] *= -1
        local = (axes.T @ (pts - center).T).T
        mn, mx = local.min(axis=0), local.max(axis=0)
        aabb_center = axes @ ((mn + mx) * 0.5) + center
        extents = mx - mn
        if obj_idx == 3:
            exec_center = aabb_center.copy()
            # The banana is curved; when the visible PCA/AABB centre drifts
            # toward the far end of the crescent, the calibrated -X finger
            # offset is cancelled and the gripper closes on the outside.  In
            # that case the RGB-D point mean is a better proxy for the contact
            # root used by the successful runner traces.
            if abs(float(aabb_center[0] - center[0])) > float(os.environ.get("ATEC_PCA_OBJ3_AABB_MEAN_X_SWITCH", "0.025")):
                exec_center[0] = center[0] + float(os.environ.get("ATEC_PCA_OBJ3_MEAN_X_BIAS", "0.005"))
        else:
            upper = pts[pts[:, 2] >= np.percentile(pts[:, 2], 70)]
            # Object 1/2 visible-surface medians can be biased toward the
            # camera-facing side by 2+ cm.  Use the world AABB centre for XY
            # completion, while keeping a high visible-surface z for approach.
            exec_center = world_aabb_center.copy()
            z_src = upper if len(upper) else pts
            exec_center[2] = float(np.percentile(z_src[:, 2], 85))
        if os.environ.get("ATEC_PCA_DEBUG_TARGET"):
            upper = pts[pts[:, 2] >= np.percentile(pts[:, 2], 70)]
            upper_med = np.median(upper if len(upper) else pts, axis=0)
            print(
                f"[PCA_EST] obj={obj_idx} n={len(pts)} "
                f"mean=({center[0]:.3f},{center[1]:.3f},{center[2]:.3f}) "
                f"world_aabb=({world_aabb_center[0]:.3f},{world_aabb_center[1]:.3f},{world_aabb_center[2]:.3f}) "
                f"upper_med=({upper_med[0]:.3f},{upper_med[1]:.3f},{upper_med[2]:.3f}) "
                f"exec=({exec_center[0]:.3f},{exec_center[1]:.3f},{exec_center[2]:.3f})",
                flush=True,
            )

        grasp_axis = int(np.argmin(extents))
        if grasp_axis == 0:
            jaw_hint_w = axes[:, 1]
        else:
            jaw_hint_w = axes[:, 0]
        jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64)
        if np.linalg.norm(jaw_xy) < 1e-6:
            jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64)
        jaw_xy /= np.linalg.norm(jaw_xy)
        grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64)
        align_x = np.cross(jaw_xy, grip_z)
        align_x /= max(np.linalg.norm(align_x), 1e-6)
        jaw_y = np.cross(grip_z, align_x)
        jaw_y /= max(np.linalg.norm(jaw_y), 1e-6)
        rot_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1)
        return exec_center.astype(np.float64), rot_w_tool.astype(np.float64)

    def _estimate_object3_current_center(self, obs: dict) -> np.ndarray | None:
        rgb, depth = self._video_rgb_depth(obs)
        pts = self._points_for_object(rgb, depth, 3, wide=True, fill_holes=True)
        if len(pts) < 64:
            return None
        center = 0.5 * (pts.min(axis=0) + pts.max(axis=0))
        # Track the table-near/lifted banana body, not high gripper occluders.
        center[2] = float(np.percentile(pts[:, 2], 65))
        center[:2] += OBJ_CENTER_COMPLETION_OFFSETS[3]
        if not np.all(np.isfinite(center)):
            return None
        if not (TABLE_CENTER_X - 0.22 <= center[0] <= TABLE_CENTER_X + 0.22):
            return None
        if not (BASKET_CENTER_Y - 0.14 <= center[1] <= OBJ_Y_BANDS[3][1] + 0.10):
            return None
        return center.astype(np.float64)

    def _build_object3_drag_fallback(self, obs: dict) -> bool:
        topdown = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64))
        # Re-localize the banana at fallback time.  Use the same narrow
        # closed-drag recovery that succeeded in run_graspnet_pick.py: keep the
        # gripper closed and drag from the current object centre to the basket
        # centre in two smooth segments.
        drag_z = OBJ3_FALLBACK_DRAG_Z
        c_live = self._estimate_object3_current_center(obs)
        c0 = c_live if c_live is not None else self._detected_centers.get(
            3, np.array([TABLE_CENTER_X, OBJ_Y_BANDS[3][0], TABLE_TOP_Z], dtype=np.float64)
        )
        start = np.array([c0[0], c0[1], drag_z], dtype=np.float64)
        mid = np.array([BASKET_CENTER_X, 0.5 * (c0[1] + BASKET_CENTER_Y), drag_z], dtype=np.float64)
        end = np.array([BASKET_CENTER_X, BASKET_CENTER_Y, drag_z], dtype=np.float64)
        print(
            f"[PCA_FALLBACK] object_3 closed_drag cur=({c0[0]:.3f},{c0[1]:.3f},{c0[2]:.3f}) "
            f"mid=({mid[0]:.3f},{mid[1]:.3f},{mid[2]:.3f}) "
            f"end=({end[0]:.3f},{end[1]:.3f},{end[2]:.3f})",
            flush=True,
        )
        self.plan = []
        self.plan_idx = 0
        self.step_in_target = 0
        hold_grip = self._obj3_hold_grip.copy() if self._obj3_hold_grip is not None else OBJ3_HOLD_GRIP_DEFAULT.copy()
        finger_offset = OBJ_FINGER_XY_OFFSETS[3]
        start_finger = start[:2] + finger_offset
        mid_finger = mid[:2] + finger_offset
        end_finger = end[:2] + finger_offset
        self._add_pose([start_finger[0], start_finger[1], drag_z], topdown, hold_grip, OBJ3_FALLBACK_START_STEPS, finger_xy=start_finger, finger_z=drag_z, label="fallback_closed_drag_start")
        self._add_pose([mid_finger[0], mid_finger[1], drag_z], topdown, hold_grip, OBJ3_FALLBACK_MID_STEPS, finger_xy=mid_finger, finger_z=drag_z, label="fallback_closed_drag_mid")
        self._add_pose([end_finger[0], end_finger[1], drag_z], topdown, hold_grip, OBJ3_FALLBACK_END_STEPS, finger_xy=end_finger, finger_z=drag_z, label="fallback_closed_drag_end")
        self._add_pose([end_finger[0], end_finger[1], drag_z], topdown, GRIP_OPEN, OBJ3_FALLBACK_OPEN_STEPS, finger_xy=end_finger, finger_z=drag_z, label="fallback_closed_drag_open")
        self._add_pose([BASKET_CENTER_X, BASKET_CENTER_Y, TABLE_TOP_Z + 0.18], topdown, GRIP_OPEN, 120, label="fallback_retract")
        return True

    def _build_object1_drag_rescue(self, obs: dict) -> bool:
        rgb, depth = self._video_rgb_depth(obs)
        pts = self._points_for_object(rgb, depth, 1, wide=True, fill_holes=False)
        if len(pts) < 64:
            print(f"[PCA_RESCUE] skip object_1 drag: only {len(pts)} points", flush=True)
            return False
        # After transport failures object_1 is usually back on the table.  The
        # high visible points can be the gripper/finger occluder or a lifted
        # face, so estimate the rescue push centre from table-near points only.
        low = pts[(pts[:, 2] >= TABLE_TOP_Z + 0.030) & (pts[:, 2] <= TABLE_TOP_Z + 0.110)]
        if len(low) >= 32:
            c = 0.5 * (low.min(axis=0) + low.max(axis=0))
            c[2] = float(np.median(low[:, 2]))
        else:
            c, _ = self._estimate_grasp(rgb, depth, 1, wide=True)
        if not np.all(np.isfinite(c)):
            return False
        topdown = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64))
        drag_z = TABLE_TOP_Z + 0.055
        # Push from the object's positive-y side toward the basket.  A fixed
        # start_y misses the cube after ACT/hybrid rollouts because object_1
        # often remains around y=0.26..0.34.
        lanes_x = [
            float(np.clip(c[0] - 0.045, TABLE_CENTER_X - 0.16, TABLE_CENTER_X + 0.22)),
            float(np.clip(c[0], TABLE_CENTER_X - 0.16, TABLE_CENTER_X + 0.22)),
            float(np.clip(c[0] + 0.045, TABLE_CENTER_X - 0.16, TABLE_CENTER_X + 0.22)),
        ]
        start_y = float(np.clip(c[1] + 0.085, TABLE_CENTER_Y + 0.085, TABLE_CENTER_Y + 0.46))
        end_y = BASKET_CENTER_Y
        print(
            f"[PCA_RESCUE] object_1 drag c=({c[0]:.3f},{c[1]:.3f},{c[2]:.3f}) "
            f"low_n={len(low)} "
            f"lanes={','.join(f'{x:.2f}' for x in lanes_x)} y=({start_y:.3f}->{end_y:.3f})",
            flush=True,
        )
        self.objects = (1,)
        self.plan = []
        self.plan_idx = 0
        self.step_in_target = 0
        for i, lane_x in enumerate(lanes_x):
            start = np.array([lane_x, start_y, drag_z], dtype=np.float64)
            end = np.array([lane_x, end_y, drag_z], dtype=np.float64)
            self._add_pose([lane_x, start_y, TABLE_TOP_Z + 0.20], topdown, GRIP_OPEN, 70, label=f"obj1_rescue_lane{i}_pre")
            self._add_pose(start, topdown, GRIP_OPEN, 100, finger_xy=start[:2], finger_z=drag_z, label=f"obj1_rescue_lane{i}_start")
            self._add_pose(end, topdown, GRIP_OPEN, 520, finger_xy=end[:2], finger_z=drag_z, label=f"obj1_rescue_lane{i}_mid")
        self._add_pose([BASKET_CENTER_X, BASKET_CENTER_Y, TABLE_TOP_Z + 0.15], topdown, GRIP_OPEN, 160, label="obj1_rescue_open")
        self._add_pose([RETRACT_X, RETRACT_Y, TABLE_TOP_Z + 0.40], topdown, GRIP_OPEN, 80, label="obj1_rescue_retract")
        return True

    def _build_plan(self, obs: dict):
        rgb, depth = self._video_rgb_depth(obs)
        topdown = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64))
        self.plan = []
        objects = tuple(int(x) for x in os.environ.get("ATEC_PCA_OBJECTS", "3,2,1").replace(" ", ",").split(",") if x)
        self.objects = objects
        for obj_idx in objects:
            c, grasp_rot = self._estimate_grasp(rgb, depth, obj_idx)
            if obj_idx == 1:
                grasp_rot = _quat_wxyz_to_rot(np.array([0.0, 0.709, 0.705, 0.0], dtype=np.float64))
            # The submit-style RGB-D PCA estimate is biased toward the visible
            # left crescent of the banana.  Keep GraspGen/PCA for its centre,
            # but use the task-calibrated top-down wrist pose that the runner
            # already validated for object_3.
            if obj_idx == 3 and os.environ.get("ATEC_PCA_OBJ3_USE_PCA_ROT") != "1":
                grasp_rot = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.004, 0.0], dtype=np.float64))
            c[:2] += OBJ_CENTER_COMPLETION_OFFSETS[obj_idx]
            self._detected_centers[obj_idx] = c.copy()
            pick_xy = c[:2] + OBJ_GRASP_CENTER_OFFSETS[obj_idx]
            yaw = float(np.arctan2(grasp_rot[1, 1], grasp_rot[0, 1]))
            print(
                f"[PCA_PLAN] obj={obj_idx} center=({c[0]:.3f},{c[1]:.3f},{c[2]:.3f}) "
                f"pick=({pick_xy[0]:.3f},{pick_xy[1]:.3f}) jaw_yaw={yaw:+.2f}",
                flush=True,
            )
            reach_z = max(float(c[2] + OBJ_TCP_Z[obj_idx]), TABLE_TOP_Z + 0.055)
            # The PCA point cloud z is a visible-surface estimate, not the USD
            # object root z used by the validated runner.  Closing from
            # c[2]+offset is too high for object_1 and makes the gripper miss
            # the cube.  Use the calibrated task close plane instead.
            root_z_est = OBJ_ROOT_Z_EST.get(obj_idx, TABLE_TOP_Z + 0.045)
            close_z = max(root_z_est + OBJ_CLOSE_Z_OFFSETS.get(obj_idx, 0.020), TABLE_TOP_Z + 0.030)
            lift_z = TABLE_TOP_Z + (OBJ3_LIFT_CLEARANCE if obj_idx == 3 else 0.30)
            release_z = TABLE_TOP_Z + (OBJ3_CARRY_CLEARANCE if obj_idx == 3 else (0.32 if obj_idx == 1 else 0.24))
            open_z = TABLE_TOP_Z + (OBJ3_CARRY_CLEARANCE if obj_idx == 3 else (0.24 if obj_idx == 1 else 0.15))
            place_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y]) + OBJ_PLACE_XY_OFFSETS.get(
                obj_idx, np.zeros(2, dtype=np.float64)
            )
            # Keep the calibrated top-down task quaternion for all objects.  The
            # PCA/AABB centre supplies translation; Task-E contact tuning supplies
            # the wrist orientation and release heights.
            finger_xy = pick_xy.copy() + OBJ_FINGER_XY_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64)) if obj_idx in (1, 2, 3) else None
            close_finger_xy = (
                pick_xy
                + OBJ_PRECLOSE_INSERT_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64))
                + OBJ_FINGER_XY_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64))
            )
            closed_grip = OBJ3_HOLD_GRIP_DEFAULT.copy() if obj_idx == 3 else GRIP_CLOSE
            finger_z = reach_z if obj_idx in (1, 2) else None
            place_rot = grasp_rot if obj_idx in (1, 2) else topdown
            self._add_pose([pick_xy[0], pick_xy[1], TABLE_TOP_Z + 0.30], grasp_rot, GRIP_OPEN, 90, label=f"obj{obj_idx}_pre")
            servo_rel_z = OBJ_FINGER_TARGET_REL_Z.get(obj_idx)
            if obj_idx == 3 and OBJ3_ENABLE_INSERT:
                # Diagnostic-only guarded side approach.  Local tests showed
                # low open-finger insertion can shove the banana laterally, so
                # the default path below matches the successful GraspNet runner:
                # reach the calibrated contact point first, then close there.
                side_finger_xy = close_finger_xy + OBJ3_PREGRASP_OFFSET
                self._add_pose(
                    [side_finger_xy[0], side_finger_xy[1], reach_z],
                    grasp_rot,
                    GRIP_OPEN,
                    OBJ3_SIDE_APPROACH_STEPS,
                    finger_xy=side_finger_xy,
                    finger_z=OBJ3_APPROACH_FINGER_Z,
                    servo_obj_z=root_z_est,
                    servo_target_rel_z=None,
                    label=f"obj{obj_idx}_side_pre",
                )
                self._add_pose(
                    [side_finger_xy[0], side_finger_xy[1], close_z],
                    grasp_rot,
                    GRIP_OPEN,
                    OBJ3_SIDE_LOW_STEPS,
                    finger_xy=side_finger_xy,
                    finger_z=OBJ3_PREGRASP_LOW_FINGER_Z,
                    servo_obj_z=root_z_est,
                    servo_target_rel_z=None,
                    label=f"obj{obj_idx}_side_low",
                )
                self._add_pose(
                    [close_finger_xy[0], close_finger_xy[1], close_z],
                    grasp_rot,
                    GRIP_OPEN,
                    OBJ3_INSERT_STEPS,
                    finger_xy=close_finger_xy,
                    finger_z=OBJ3_PREGRASP_LOW_FINGER_Z,
                    servo_obj_z=root_z_est,
                    servo_target_rel_z=None,
                    label=f"obj{obj_idx}_insert",
                )
            else:
                self._add_pose(
                    [pick_xy[0], pick_xy[1], reach_z],
                    grasp_rot,
                    GRIP_OPEN,
                    OBJ_REACH_STEPS[obj_idx],
                    finger_xy=finger_xy,
                    finger_z=None,
                    servo_obj_z=root_z_est,
                    servo_target_rel_z=None,
                    label=f"obj{obj_idx}_reach",
                )
            if obj_idx != 3 and np.linalg.norm(OBJ_PRECLOSE_INSERT_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64))) > 1e-6:
                self._add_pose(
                    [close_finger_xy[0], close_finger_xy[1], close_z],
                    grasp_rot,
                    GRIP_OPEN,
                    180,
                    finger_xy=close_finger_xy,
                    finger_z=None,
                    servo_obj_z=root_z_est,
                    servo_target_rel_z=servo_rel_z,
                    label=f"obj{obj_idx}_insert",
                )
            obj3_finger_z = OBJ3_CLOSE_FINGER_Z if obj_idx == 3 else None
            self._add_pose(
                [close_finger_xy[0], close_finger_xy[1], close_z],
                grasp_rot,
                closed_grip,
                OBJ_CLOSE_STEPS[obj_idx],
                finger_xy=close_finger_xy,
                finger_z=obj3_finger_z,
                servo_obj_z=root_z_est,
                servo_target_rel_z=None if obj_idx == 3 else servo_rel_z,
                label=f"obj{obj_idx}_close",
            )
            if obj_idx == 3:
                self._add_pose(
                    [close_finger_xy[0], close_finger_xy[1], close_z],
                    grasp_rot,
                    closed_grip,
                    OBJ3_LOW_HOLD_STEPS,
                    finger_xy=close_finger_xy,
                    finger_z=OBJ3_CLOSE_FINGER_Z,
                    servo_obj_z=root_z_est,
                    servo_target_rel_z=None,
                    label=f"obj{obj_idx}_low_hold",
                )
            if obj_idx == 1:
                self._add_pose(
                    [close_finger_xy[0], close_finger_xy[1], close_z],
                    grasp_rot,
                    GRIP_CLOSE,
                    160,
                    finger_xy=None,
                    finger_z=None,
                    freeze_arm=True,
                    label=f"obj{obj_idx}_squeeze",
                )
            self._add_pose(
                [close_finger_xy[0], close_finger_xy[1], lift_z],
                grasp_rot,
                closed_grip,
                OBJ_LIFT_STEPS[obj_idx],
                finger_xy=close_finger_xy,
                finger_z=OBJ3_LIFT_FINGER_Z if obj_idx == 3 else None,
                servo_obj_z=None if obj_idx == 3 else root_z_est,
                servo_target_rel_z=None if obj_idx == 3 else servo_rel_z,
                label=f"obj{obj_idx}_lift",
            )
            if obj_idx == 3:
                # After a short lift confirms contact, do not keep a high-air
                # friction grasp.  Banana is contact-sensitive in official
                # physics; a low closed-drag/cradle path preserves contact and
                # avoids the DLS high-transport singularity seen in videos.
                drag_z = OBJ3_FALLBACK_DRAG_Z
                drag_start_finger = close_finger_xy.copy()
                drag_mid_obj = np.array([BASKET_CENTER_X, 0.5 * (pick_xy[1] + BASKET_CENTER_Y)], dtype=np.float64)
                drag_end_obj = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64)
                drag_mid_finger = drag_mid_obj + OBJ_FINGER_XY_OFFSETS[3]
                drag_end_finger = drag_end_obj + OBJ_FINGER_XY_OFFSETS[3]
                self._add_pose(
                    [drag_start_finger[0], drag_start_finger[1], drag_z],
                    topdown,
                    closed_grip,
                    OBJ3_DRAG_START_STEPS,
                    finger_xy=drag_start_finger,
                    finger_z=drag_z,
                    label=f"obj{obj_idx}_drag_start",
                )
                self._add_pose(
                    [drag_mid_finger[0], drag_mid_finger[1], drag_z],
                    topdown,
                    closed_grip,
                    OBJ3_DRAG_MID_STEPS,
                    finger_xy=drag_mid_finger,
                    finger_z=drag_z,
                    label=f"obj{obj_idx}_drag_mid",
                )
                self._add_pose(
                    [drag_end_finger[0], drag_end_finger[1], drag_z],
                    topdown,
                    closed_grip,
                    OBJ3_DRAG_END_STEPS,
                    finger_xy=drag_end_finger,
                    finger_z=drag_z,
                    label=f"obj{obj_idx}_drag_end",
                )
                self._add_pose(
                    [drag_end_finger[0], drag_end_finger[1], drag_z],
                    topdown,
                    closed_grip,
                    OBJ3_DRAG_SETTLE_STEPS,
                    finger_xy=drag_end_finger,
                    finger_z=drag_z,
                    label=f"obj{obj_idx}_drag_settle",
                )
                self._add_pose(
                    [drag_end_finger[0], drag_end_finger[1], drag_z],
                    topdown,
                    GRIP_OPEN,
                    OBJ_OPEN_STEPS[obj_idx],
                    finger_xy=drag_end_finger,
                    finger_z=drag_z,
                    label=f"obj{obj_idx}_drag_open",
                )
                self._add_pose([RETRACT_X, RETRACT_Y, TABLE_TOP_Z + 0.40], topdown, GRIP_OPEN, 80, label=f"obj{obj_idx}_retract")
                continue
            mid = np.array([(close_finger_xy[0] + place_xy[0]) * 0.5, (close_finger_xy[1] + place_xy[1]) * 0.5, release_z])
            if obj_idx == 3:
                carry_mid_finger = mid[:2] + OBJ_FINGER_XY_OFFSETS[3]
                release_finger = place_xy + OBJ_FINGER_XY_OFFSETS[3]
            else:
                carry_mid_finger = mid[:2] if obj_idx in (1, 2) else None
                release_finger = place_xy if obj_idx in (1, 2) else None
            carry_finger_z = OBJ3_LIFT_FINGER_Z if obj_idx == 3 else None
            self._add_pose(
                mid,
                place_rot,
                closed_grip,
                max(OBJ_TRANSPORT_STEPS[obj_idx] // 2, 1),
                finger_xy=carry_mid_finger,
                finger_z=carry_finger_z,
                label=f"obj{obj_idx}_mid",
            )
            if obj_idx == 1:
                self._add_pose(
                    mid,
                    place_rot,
                    GRIP_CLOSE,
                    140,
                    freeze_arm=True,
                    label=f"obj{obj_idx}_mid_squeeze",
                )
            self._add_pose(
                [place_xy[0], place_xy[1], release_z],
                place_rot,
                closed_grip,
                max(OBJ_TRANSPORT_STEPS[obj_idx] - OBJ_TRANSPORT_STEPS[obj_idx] // 2, 1),
                finger_xy=release_finger,
                finger_z=carry_finger_z,
                label=f"obj{obj_idx}_release",
            )
            if obj_idx == 3:
                # Match the runner's basket-hold phase: keep the gripper closed
                # above the release pose while the object centre is servoed into
                # the real basket centre before opening.
                self._add_pose(
                    [place_xy[0], place_xy[1], release_z],
                    place_rot,
                    closed_grip,
                    420,
                    finger_xy=release_finger,
                    finger_z=carry_finger_z,
                    label=f"obj{obj_idx}_basket_hold",
                )
            if obj_idx == 1 and os.environ.get("ATEC_PCA_ENABLE_OBJ1_RESCUE") == "1":
                self._add_pose([place_xy[0], place_xy[1], release_z], place_rot, GRIP_CLOSE, 1, label="obj1_relocalize_drag")
            settle_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64) if obj_idx == 1 else place_xy
            settle_finger = release_finger if obj_idx == 3 else (settle_xy if obj_idx in (1, 2) else None)
            self._add_pose([settle_xy[0], settle_xy[1], open_z], place_rot, closed_grip, 80 if obj_idx != 3 else 120, finger_xy=settle_finger, label=f"obj{obj_idx}_settle")
            self._add_pose([settle_xy[0], settle_xy[1], open_z], place_rot, GRIP_OPEN, OBJ_OPEN_STEPS[obj_idx], label=f"obj{obj_idx}_open")
            self._add_pose([RETRACT_X, RETRACT_Y, TABLE_TOP_Z + 0.40], topdown, GRIP_OPEN, 80, label=f"obj{obj_idx}_retract")
        self.detected = True

    def _add_pose(
        self,
        pos,
        rot,
        grip,
        steps,
        finger_xy=None,
        finger_z=None,
        servo_obj_z=None,
        servo_target_rel_z=None,
        freeze_arm=False,
        label="",
    ):
        if int(steps) <= 0:
            return
        self.plan.append(
            PoseTarget(
                np.asarray(pos, dtype=np.float64),
                np.asarray(rot, dtype=np.float64),
                np.asarray(grip, dtype=np.float64),
                int(steps),
                None if finger_xy is None else np.asarray(finger_xy, dtype=np.float64),
                None if finger_z is None else float(finger_z),
                None if servo_obj_z is None else float(servo_obj_z),
                None if servo_target_rel_z is None else float(servo_target_rel_z),
                bool(freeze_arm),
                str(label),
            )
        )

    def predicts(self, obs, current_score):
        qpos = self._obs_qpos(obs)
        if self.t < 25:
            self.t += 1
            return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False}
        if self.home_count < 80:
            self.home_count += 1
            action = np.clip((HOME_Q - DEFAULT_Q) / ACTION_SCALE, -3.0, 3.0)
            return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False}
        if not self.detected:
            if (
                os.environ.get("ATEC_PCA_OBJ1_DIRECT_RESCUE") == "1"
                and tuple(int(x) for x in os.environ.get("ATEC_PCA_OBJECTS", "3,2,1").replace(" ", ",").split(",") if x) == (1,)
                and self._build_object1_drag_rescue(obs)
            ):
                self.detected = True
            else:
                self._build_plan(obs)
        if self.plan_idx >= len(self.plan):
            if (
                not self.fallback_done
                and 3 in self.objects
                and os.environ.get("ATEC_PCA_ENABLE_FALLBACK") == "1"
            ):
                self.fallback_done = True
                if self._build_object3_drag_fallback(obs):
                    target = self.plan[self.plan_idx]
                    pos_w = target.pos_w.copy()
                else:
                    action = np.clip((HOME_Q - DEFAULT_Q) / ACTION_SCALE, -3.0, 3.0)
                    return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False}
            else:
                action = np.clip((HOME_Q - DEFAULT_Q) / ACTION_SCALE, -3.0, 3.0)
                return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False}
        else:
            target = self.plan[self.plan_idx]
            pos_w = target.pos_w.copy()
        if target.label == "obj1_relocalize_drag":
            if self._build_object1_drag_rescue(obs):
                target = self.plan[self.plan_idx]
                pos_w = target.pos_w.copy()
            else:
                self.plan_idx += 1
                return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False}
        raw_pos_w = pos_w.copy()
        dynamic_finger_xy = None
        finger_target_w = None
        if target.label in ("obj3_basket_hold", "obj3_settle") and os.environ.get(
            "ATEC_PCA_OBJ3_OBJECT_SERVO", "1"
        ) != "0":
            c_now = self._estimate_object3_current_center(obs)
            if c_now is not None:
                if self._obj3_carry_offset_xy is None:
                    finger_now = self.ik.finger_center_world(qpos)
                    observed_offset = finger_now[:2] - c_now[:2]
                    # Preserve the actual contact relation reached at lift,
                    # but bound it so a bad visual frame cannot launch the arm.
                    observed_offset = np.clip(observed_offset, [-0.055, -0.055], [0.055, 0.055])
                    if np.all(np.isfinite(observed_offset)):
                        self._obj3_carry_offset_xy = observed_offset.astype(np.float64)
                carry_offset = (
                    self._obj3_carry_offset_xy
                    if self._obj3_carry_offset_xy is not None
                    else OBJ_FINGER_XY_OFFSETS[3]
                )
                object_target_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64)
                correction = np.zeros(2, dtype=np.float64)
                correction = (object_target_xy - c_now[:2]) * OBJ3_OBJECT_SERVO_GAIN
                corr_norm = float(np.linalg.norm(correction))
                max_corr = OBJ3_OBJECT_SERVO_MAX_XY
                if corr_norm > max_corr:
                    correction = correction / max(corr_norm, 1e-6) * max_corr
                pos_w[:2] = raw_pos_w[:2] + correction
                raw_pos_w = pos_w.copy()
                # Keep the same finger-to-object contact relation while
                # servoing the object centre into the basket.  Pointing the
                # finger target at c_now pins the hand near the old table pose
                # and fights the basket correction.
                dynamic_finger_xy = object_target_xy + carry_offset
                if (
                    os.environ.get("ATEC_PCA_ENABLE_FALLBACK") == "1"
                    and
                    os.environ.get("ATEC_PCA_OBJ3_DYNAMIC_FALLBACK", "1") != "0"
                    and not self.fallback_done
                    and target.label in ("obj3_mid", "obj3_release", "obj3_basket_hold")
                    and c_now[1] > BASKET_CENTER_Y + 0.16
                    and c_now[2] < TABLE_TOP_Z + 0.045
                    and self.step_in_target > 80
                ):
                    self.fallback_done = True
                    print(
                        f"[PCA_FALLBACK_TRIGGER] object_3 stalled c=({c_now[0]:.3f},{c_now[1]:.3f},{c_now[2]:.3f}) "
                        f"target={target.label} step={self.step_in_target}",
                        flush=True,
                    )
                    if self._build_object3_drag_fallback(obs):
                        target = self.plan[self.plan_idx]
                        pos_w = target.pos_w.copy()
                        raw_pos_w = pos_w.copy()
                        dynamic_finger_xy = None
                if os.environ.get("ATEC_PCA_DEBUG_TARGET") and self.step_in_target % 25 == 0:
                    print(
                        f"[PCA_OBJ_SERVO] {target.label} c=({c_now[0]:.3f},{c_now[1]:.3f}) "
                        f"target=({object_target_xy[0]:.3f},{object_target_xy[1]:.3f}) "
                        f"corr=({correction[0]:+.3f},{correction[1]:+.3f})",
                        flush=True,
                    )
        if target.finger_xy is not None:
            finger = self.ik.finger_center_world(qpos)
            gb_b, _ = self.ik.fk_base(qpos[:6])
            gb_w = BASE_POS_W + R_W_B @ gb_b
            finger_from_gb = finger - gb_w
            desired_finger_xy = target.finger_xy if dynamic_finger_xy is None else dynamic_finger_xy
            finger_target_z = target.finger_z if target.finger_z is not None else finger[2]
            finger_target_w = np.array([desired_finger_xy[0], desired_finger_xy[1], finger_target_z], dtype=np.float64)
            xy_error = finger[:2] - desired_finger_xy
            correction = -xy_error
            corr_norm = float(np.linalg.norm(correction))
            max_xy = 0.12
            if target.label.startswith("obj3_") and (
                ("_mid" in target.label)
                or ("_release" in target.label)
                or ("_basket_hold" in target.label)
                or ("_settle" in target.label)
                or ("_drag" in target.label)
            ):
                max_xy = OBJ3_FINGER_SERVO_MAX_XY
            elif ("_mid" in target.label) or ("_release" in target.label) or ("_settle" in target.label):
                max_xy = 0.32
            if corr_norm > max_xy:
                correction = correction / max(corr_norm, 1e-6) * max_xy
            pos_w[:2] = raw_pos_w[:2] + correction
            if target.finger_z is not None:
                pos_w[2] = float(target.finger_z - finger_from_gb[2])
            elif target.servo_obj_z is not None and target.servo_target_rel_z is not None:
                rel_z = float(finger[2] - target.servo_obj_z)
                z_error = float(target.servo_target_rel_z - rel_z)
                obj_for_label = 3 if target.label.startswith("obj3_") else 1
                max_z = OBJ_FINGER_SERVO_MAX_Z.get(obj_for_label, 0.050)
                if obj_for_label == 3:
                    z_correction = float(np.clip(z_error, -max_z, max_z))
                else:
                    z_correction = min(0.0, max(-max_z, z_error))
                pos_w[2] = float(raw_pos_w[2] + z_correction)
            if os.environ.get("ATEC_PCA_DEBUG_TARGET") and self.step_in_target % 25 == 0:
                print(
                    f"[PCA_TARGET] plan={self.plan_idx} step={self.step_in_target} "
                    f"raw=({raw_pos_w[0]:.3f},{raw_pos_w[1]:.3f},{raw_pos_w[2]:.3f}) "
                    f"gb=({gb_w[0]:.3f},{gb_w[1]:.3f},{gb_w[2]:.3f}) "
                    f"finger=({finger[0]:.3f},{finger[1]:.3f},{finger[2]:.3f}) "
                    f"desired=({desired_finger_xy[0]:.3f},{desired_finger_xy[1]:.3f}) "
                    f"pos=({pos_w[0]:.3f},{pos_w[1]:.3f},{pos_w[2]:.3f})",
                    flush=True,
                )
        # Use a submit-side equivalent of the runner's CartesianController:
        # one DLS update from the current qpos per simulator step.  Close/reach
        # phases prioritize position because centimetres of z error are enough
        # to miss the object, while a small wrist error is tolerable.
        position_only = (
            ("_reach" in target.label)
            or ("_side_pre" in target.label)
            or ("_side_low" in target.label)
            or ("_insert" in target.label)
            or ("_close" in target.label)
            or ("_low_hold" in target.label)
            or (target.label.startswith("obj3_") and any(key in target.label for key in ("drag", "mid", "release", "basket_hold", "settle")))
        )
        if target.freeze_arm:
            q6 = qpos[:6].copy()
        elif (
            finger_target_w is not None
            and (
                (
                    target.label.startswith("fallback_")
                    and os.environ.get("ATEC_PCA_FALLBACK_FINGER_IK", "0") != "0"
                )
                or (
                    target.label.startswith("obj3_")
                    and os.environ.get("ATEC_PCA_OBJ3_USE_FINGER_IK", "0") == "1"
                    and any(key in target.label for key in ("mid", "release", "basket_hold", "settle"))
                )
            )
        ):
            q6 = self.ik.solve_finger(qpos, finger_target_w, target.rot_w)
        elif os.environ.get("ATEC_PCA_USE_FULL_IK") == "1":
            q6 = self.ik.solve(qpos, pos_w, target.rot_w)
        else:
            q6 = self.ik.step_dls(qpos, pos_w, target.rot_w, position_only=position_only)
        q_target = np.concatenate([q6, target.grip])
        if target.label.startswith("obj1_"):
            gap = self.ik.finger_gap(qpos)
            if (
                self._obj1_hold_grip is None
                and
                target.label in ("obj1_close", "obj1_lift", "obj1_mid")
                and gap <= OBJ1_HOLD_GAP
                and self.step_in_target > 10
            ):
                self._obj1_hold_grip = qpos[6:8].copy()
            if self._obj1_hold_grip is not None and any(
                key in target.label for key in ("close", "squeeze", "lift", "mid", "release", "settle")
            ):
                q_target[6:8] = self._obj1_hold_grip
        if target.label.startswith("obj3_"):
            gap = self.ik.finger_gap(qpos)
            if (
                self._obj3_hold_grip is None
                and target.label == "obj3_lift"
                and gap <= OBJ3_HOLD_GAP
                and self.step_in_target >= int(os.environ.get("ATEC_PCA_OBJ3_LIFT_LATCH_STEP", "20"))
            ):
                self._obj3_hold_grip = qpos[6:8].copy()
            if self._obj3_hold_grip is not None and any(
                key in target.label for key in ("close", "low_hold", "lift", "mid", "release", "basket_hold", "settle", "drag")
            ):
                q_target[6:8] = self._obj3_hold_grip
        # Match IsaacLab CartesianController's per-step clamp; gripper fingers
        # still close gradually so they do not shove the object sideways.
        gripper_max_delta = 0.010
        if target.label.startswith("obj3_") and self._obj3_hold_grip is None and any(
            key in target.label for key in ("close", "low_hold")
        ):
            gripper_max_delta = OBJ3_GRIPPER_MAX_DELTA
        max_delta = np.array(
            [0.18, 0.18, 0.18, 0.18, 0.18, 0.18, gripper_max_delta, gripper_max_delta],
            dtype=np.float64,
        )
        q_target = qpos + np.clip(q_target - qpos, -max_delta, max_delta)
        action = np.clip((q_target - DEFAULT_Q) / ACTION_SCALE, -5.0, 5.0)
        self.step_in_target += 1
        advance = self.step_in_target >= target.steps
        if target.label == "obj1_close" and self._obj1_hold_grip is not None:
            advance = True
        if (
            target.label == "obj3_close"
            and self._obj3_hold_grip is not None
            and self.step_in_target >= OBJ3_CLOSE_MIN_STEPS
        ):
            advance = True
        if "_squeeze" in target.label:
            gap = self.ik.finger_gap(qpos)
            if self._obj1_hold_grip is not None and target.label.startswith("obj1_"):
                advance = self.step_in_target >= 20
            elif gap > OBJ1_HOLD_GAP and self.step_in_target < 420:
                advance = False
            if os.environ.get("ATEC_PCA_DEBUG_TARGET") and self.step_in_target % 25 == 0:
                print(f"[PCA_SQUEEZE] step={self.step_in_target} gap={gap:.4f} advance={advance}", flush=True)
        if advance:
            if os.environ.get("ATEC_PCA_DEBUG_TARGET") and target.label.startswith("obj3_"):
                c_dbg = self._estimate_object3_current_center(obs)
                f_dbg = self.ik.finger_center_world(qpos)
                gap_dbg = self.ik.finger_gap(qpos)
                c_msg = "none"
                if c_dbg is not None:
                    c_msg = f"({c_dbg[0]:.3f},{c_dbg[1]:.3f},{c_dbg[2]:.3f})"
                print(
                    f"[PCA_STAGE_END] {target.label} c={c_msg} "
                    f"finger=({f_dbg[0]:.3f},{f_dbg[1]:.3f},{f_dbg[2]:.3f}) "
                    f"gap={gap_dbg:.4f} hold="
                    f"{None if self._obj3_hold_grip is None else [float(v) for v in self._obj3_hold_grip]}",
                    flush=True,
                )
            self.step_in_target = 0
            self.plan_idx += 1
        return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False}


RETRACT_X = TABLE_CENTER_X + TABLE_HALF_X - 0.05
RETRACT_Y = TABLE_CENTER_Y