File size: 73,449 Bytes
a8d2eb5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
"""Reference controller for drawer-cabinet kitting cell KT-4 (Franka Panda).

Staged loop (iteration skill); every stage is closed on the joint readings or the fixture/part tracker:
  1. Commissioning touch-offs: the closed fingertips are lowered onto both ends of the kit-tray base until the
     measured tool speed stalls. The two heights give the mount height error and lean, which are applied to every
     world target (targets are commanded in the frame of the commanded joint angles, so joint sag and offsets near
     the work areas are absorbed too).
  2. Per drawer on the kit card (one drawer out at a time, as the interlock demands; the interlock lamp must be
     lit before a drawer is opened): grasp the round handle bar firmly (hand pitched, the bar height touched off with the
     upper finger first), break the detent, pull at up to 0.12 m/s and stop short of the end stop, release.
  3. Per kit line in that drawer: find the part in the named compartment (drawer frame from the averaged cabinet
     pose and the measured pull), grasp across its width (yaw and tilt chosen so that the pick, the carry and the
     place pose are reachable and collision-free in the cell model), check the finger opening against the
     catalogue width, lift, leave the drawer through a portal in front of it, carry on straight lines at a gentle
     speed (fast carries let the part creep along the pads), hover over the pocket, correct the hand from averaged
     tracker readings of the held part, lower until the part lands, release, check the pocket from the tracker,
     re-pick if it was knocked out.
  4. Close the drawer: push the front panel beside the handle with the closed fingertips, slowly for the last
     30 mm, in 1.5 mm steps from 3 mm short of shut until the soft-close detent latches it; after each step back
     off and read the interlock lamp.
  Every joint move is checked against the cell model (drawers at their current extension, the held part as a box)
  and never executed when it would sweep through the cabinet.
  Faults: a gripper command echo that differs from the command (dead gripper); a tracker stamp that stops, or
  readings that repeat exactly once noise has been seen (frozen tracker) end in an abort.
"""
from __future__ import annotations

import math
import os

import mujoco
import numpy as np

APP = os.path.dirname(os.path.abspath(__file__))

# ---- cell data sheet ----
DRAWER_FLOOR_Z = {"A": 0.490, "B": 0.390}
TRAVEL = 0.20
HANDLE_X, HANDLE_Z, BAR_R = -0.054, 0.040, 0.006
ROW_X = (0.060,)
COL_Y = (0.18, 0.0, -0.18)
COMP_HALF = (0.058, 0.087)
CAB_TOP_Z = 0.600
PARTS = {"JB-40": (0.040, 0.020, 0.012), "JB-44": (0.044, 0.020, 0.012), "LK-52": (0.052, 0.016, 0.010),
         "LK-58": (0.058, 0.016, 0.010), "GB-34": (0.034, 0.024, 0.014), "GB-38": (0.038, 0.024, 0.014)}
TRAY_TOP = 0.012
TRAY_BASE_HALF = (0.150, 0.115)
POCKETS = {f"K{i * 3 + j + 1}": ((j - 1) * 0.09, (0.5 - i) * 0.10) for i in range(2) for j in range(3)}
OPEN = 0.04
TIP = 0.0089              # fingertips reach this far past the tool point
HOME_Q = np.array([0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785])
PULL_STOP = TRAVEL - 0.006
FRONT_T = 0.018
PITCH = math.radians(10.0)
CARRY_V = 0.22          # m/s, straight-line carry of a held part (accelerations kept at 0.5 m/s2)
FAST_Q = 1.1            # rad/s, joint moves well clear of the cell
JOINT_V_MAX = 1.8       # rad/s, most any joint command may change in a straight-line move
PUSH_LEAD = 0.0055        # closed fingertips, hand pitched 10 deg: the upper finger corner leads the tip point


class Abort(Exception):
  def __init__(self, fault):
    super().__init__(fault)
    self.fault = fault


class Retry(Exception):
  pass


def wrap(a):
  return (a + math.pi) % (2 * math.pi) - math.pi


def yaw_of(q):
  return math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] ** 2 + q[3] ** 2))


def rot_topdown(a):
  y = np.array([math.cos(a), math.sin(a), 0.0])
  z = np.array([0.0, 0.0, -1.0])
  return np.column_stack([np.cross(y, z), y, z])


def rot_tilt(a, p):
  """Top-down hand with closing axis at yaw a, tilted by p about the closing axis (the approach axis leans
  towards the hand's +x side for p > 0). Turning it about the vertical keeps the held part's relation."""
  c, s = math.cos(p), math.sin(p)
  return rot_topdown(a) @ np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])


def rot_pitched(yaw, pitch):
  z = np.array([math.cos(pitch) * math.cos(yaw), math.cos(pitch) * math.sin(yaw), -math.sin(pitch)])
  y = np.array([math.sin(pitch) * math.cos(yaw), math.sin(pitch) * math.sin(yaw), math.cos(pitch)])
  return np.column_stack([np.cross(y, z), y, z])


def rot_err(R, Rc):
  qe = np.zeros(4)
  mujoco.mju_mat2Quat(qe, (R @ Rc.T).reshape(-1))
  return 2 * qe[1:] * (1.0 if qe[0] >= 0 else -1.0)


EYE6 = np.eye(6)


class Kin:
  """Kinematics of the arm on a private copy of the cell model."""

  ARM = [f"robot/joint{i}" for i in range(1, 8)]

  def __init__(self, xml):
    self.m = mujoco.MjModel.from_xml_path(xml)
    self.m.opt.enableflags &= ~int(mujoco.mjtEnableBit.mjENBL_SLEEP)   # kinematics only: keep every body live
    self.d = mujoco.MjData(self.m)
    m = self.m
    self.jid = [m.joint(n).id for n in self.ARM]
    self.qadr = np.array([m.jnt_qposadr[j] for j in self.jid])
    self.vadr = np.array([m.jnt_dofadr[j] for j in self.jid])
    self.lo = np.array([m.jnt_range[j, 0] for j in self.jid])
    self.hi = np.array([m.jnt_range[j, 1] for j in self.jid])
    self.site = m.site("robot/tcp").id
    self.kp = np.array([m.actuator_gainprm[m.actuator(f"robot/actuator{i}").id, 0] for i in range(1, 8)])
    # kinematics (IK, FK, Jacobians) on the bare arm model: the same chain mounted at the origin, much cheaper
    # than updating the whole cell for every IK iteration
    arm_xml = os.path.join(os.path.dirname(os.path.abspath(xml)), "robot", "panda.xml")
    self.mi = mujoco.MjModel.from_xml_path(arm_xml)
    self.di = mujoco.MjData(self.mi)
    self.qadr_i = np.array([self.mi.jnt_qposadr[self.mi.joint(n.split("/", 1)[1]).id] for n in self.ARM])
    self.vadr_i = np.array([self.mi.jnt_dofadr[self.mi.joint(n.split("/", 1)[1]).id] for n in self.ARM])
    self.site_i = self.mi.site("tcp").id
    self.jp = np.zeros((3, self.mi.nv)); self.jr = np.zeros((3, self.mi.nv))
    self.fq = [m.jnt_qposadr[m.joint(f).id] for f in ("robot/finger_joint1", "robot/finger_joint2")]
    self.dq = {dr: m.jnt_qposadr[m.joint(f"drawer_{dr}_slide").id] for dr in DRAWER_FLOOR_Z}
    self.robot_body = np.array([(m.body(b).name or "").startswith("robot/") for b in range(m.nbody)])
    self.part_body = np.array([(m.body(b).name or "").startswith("part_") for b in range(m.nbody)])
    # arm links whose contact with each other is a self-collision (the hand and fingers touch by design)
    self.arm_link = np.array([(m.body(b).name or "") in {f"robot/link{i}" for i in range(8)} for b in range(m.nbody)])
    self.set_fingers(OPEN)
    self.held = None
    self.last_hit = ""
    # collision checks see fixtures 10 mm early, so swept paths can keep a clearance
    for g in range(m.ngeom):
      if not self.robot_body[m.geom_bodyid[g]]:
        m.geom_margin[g] = 0.010

  def hold(self, body=None, dims=None):
    """Carry a box of the held part's size in the hand for collision checks (None: empty hand)."""
    self.held = None
    if body is None:
      return
    b = self.m.body(body).id
    self.held = (b, self.m.jnt_qposadr[self.m.body_jntadr[b]], np.array(dims, float))
    for g in range(self.m.ngeom):
      if self.m.geom_bodyid[g] == b:
        self.m.geom_size[g] = [dims[0] / 2 + 0.003, dims[1] / 2 + 0.003, dims[2] / 2 + 0.003]
        self.m.geom_pos[g] = [0, 0, 0]
    self.m.geom_rbound[:] = np.where(self.m.geom_bodyid == b, np.linalg.norm(dims) / 2 + 0.01,
                                     self.m.geom_rbound)

  def set_fingers(self, w):
    for a in self.fq:
      self.d.qpos[a] = w

  def set_cabinet(self, pos, yaw, ext):
    b = self.m.body("cabinet").id
    self.m.body_pos[b] = pos
    self.m.body_quat[b] = [math.cos(yaw / 2), 0, 0, math.sin(yaw / 2)]
    for dr, e in ext.items():
      self.d.qpos[self.dq[dr]] = e

  def set_tray(self, pos, yaw):
    b = self.m.body("kit_tray").id
    self.m.body_pos[b] = pos
    self.m.body_quat[b] = [math.cos(yaw / 2), 0, 0, math.sin(yaw / 2)]

  def fk(self, q):
    self.di.qpos[self.qadr_i] = q
    mujoco.mj_kinematics(self.mi, self.di)
    mujoco.mj_comPos(self.mi, self.di)
    return self.di.site_xpos[self.site_i].copy(), self.di.site_xmat[self.site_i].reshape(3, 3).copy()

  def jac(self, q):
    self.fk(q)
    mujoco.mj_jacSite(self.mi, self.di, self.jp, self.jr, self.site_i)
    return self.jp[:, self.vadr_i].copy(), self.jr[:, self.vadr_i].copy()

  def step(self, q, pos, R, iters=3, lam=1e-4, wrot=0.6, rest=None, nsw=0.0):
    q = np.array(q, float)
    for _ in range(iters):
      p, Rc = self.fk(q)
      e = np.concatenate([pos - p, wrot * rot_err(R, Rc)])
      mujoco.mj_jacSite(self.mi, self.di, self.jp, self.jr, self.site_i)
      J = np.empty((6, 7))
      J[:3] = self.jp[:, self.vadr_i]
      J[3:] = wrot * self.jr[:, self.vadr_i]
      Jp = J.T @ np.linalg.solve(J @ J.T + lam * EYE6, EYE6)
      dq = Jp @ e
      if rest is not None and nsw > 0:
        r = nsw * (rest - q)
        dq += r - Jp @ (J @ r)
      mx = np.max(np.abs(dq))
      if iters > 4 and mx < (2e-4 if not nsw else 3e-3) and float(np.max(np.abs(e))) < 1e-5:     # converged
        break
      if mx > 0.3:
        dq *= 0.3 / mx
      q = np.clip(q + dq, self.lo + 0.01, self.hi - 0.01)
    p, Rc = self.fk(q)
    return q, float(np.linalg.norm(pos - p)), float(np.linalg.norm(rot_err(R, Rc)))

  def ik(self, pos, R, seeds, rest=None):
    best = None
    for s in seeds:
      q, ep, er = self.step(s, pos, R, iters=150, lam=1e-3, rest=rest if rest is not None else s, nsw=0.02)
      if ep < 5e-4 and er < 3e-3:
        marg = float(np.min(np.minimum(q - self.lo, self.hi - q)))
        if best is None or marg > best[1] + 0.05:
          best = (q, marg)
    return None if best is None else best[0]

  def sag(self, q):
    """Joint offset the position servos need to hold q against gravity (feed-forward)."""
    m, d = self.m, self.d
    d.qpos[self.qadr] = q
    d.qvel[:] = 0
    mujoco.mj_forward(m, d)
    return d.qfrc_bias[self.vadr] / self.kp

  def self_clear(self, q, fingers=OPEN, need=0.0):
    """True if no two arm links come closer than `need` (links that are not neighbours)."""
    self.d.qpos[self.qadr] = q
    self.set_fingers(fingers)
    m, d = self.m, self.d
    mujoco.mj_forward(m, d)
    for i in range(d.ncon):
      c = d.contact[i]
      b1, b2 = m.geom_bodyid[c.geom1], m.geom_bodyid[c.geom2]
      if self.robot_body[b1] and self.robot_body[b2] and (self.arm_link[b1] or self.arm_link[b2]) and c.dist < need:
        self.last_hit = f"self/{m.body(b1).name}/{m.body(b2).name}/{c.dist:.4f}"
        return False
    return True

  def collides(self, q, fingers=OPEN, ignore_parts=True, tol=-0.001):
    self.d.qpos[self.qadr] = q
    self.set_fingers(fingers)
    m, d = self.m, self.d
    hb = -1
    if self.held is not None:
      hb, adr, dims = self.held
      mujoco.mj_kinematics(m, d)
      p, R = d.site_xpos[self.site], d.site_xmat[self.site].reshape(3, 3)
      d.qpos[adr:adr + 3] = p + R[:, 2] * (TIP - dims[2] / 2)
      qq = np.zeros(4); mujoco.mju_mat2Quat(qq, R.reshape(-1))
      d.qpos[adr + 3:adr + 7] = qq
    mujoco.mj_forward(self.m, self.d)
    for i in range(d.ncon):
      c = d.contact[i]
      if c.dist > tol:
        continue
      b1, b2 = m.geom_bodyid[c.geom1], m.geom_bodyid[c.geom2]
      if b1 == hb or b2 == hb:
        if self.robot_body[b1] or self.robot_body[b2] or self.part_body[b1] and self.part_body[b2]:
          continue
        self.last_hit = f"held/{m.body(b1).name}/{m.body(b2).name}"
        return self.last_hit
      if self.robot_body[b1] and self.robot_body[b2]:
        if (self.arm_link[b1] or self.arm_link[b2]) and c.dist < -0.002:
          self.last_hit = f"self/{m.body(b1).name}/{m.body(b2).name}/{c.dist:.4f}"
          return self.last_hit
        continue
      if not self.robot_body[b1] and not self.robot_body[b2]:
        continue
      if ignore_parts and (self.part_body[b1] or self.part_body[b2]):
        continue
      self.last_hit = f"{m.geom(c.geom1).name or m.body(b1).name}/{m.geom(c.geom2).name or m.body(b2).name}/{c.dist:.4f}"
      return self.last_hit
    return ""


class Track:
  """Running average of one body's tracked pose (restarted when the body moves)."""

  def __init__(self):
    self.n = 0
    self.sum = np.zeros(3)
    self.last = None
    self.quat = None
    self.seen = -1.0

  def reset(self):
    self.n, self.sum, self.out = 0, np.zeros(3), []

  def add(self, pose, t, jump):
    """A reading far from the running mean is held back as an outlier (tracker noise); three in a row mean the
    body really moved, and the average restarts from them."""
    p = np.asarray(pose[:3], float)
    self.last = p
    self.quat = np.asarray(pose[3:7], float)
    self.seen = t
    if self.n and np.linalg.norm(p - self.sum / self.n) > jump:
      self.out = getattr(self, "out", []) + [p]
      if len(self.out) < 3:
        return
      self.n, self.sum = len(self.out) - 1, np.sum(self.out[:-1], axis=0)
    self.out = []
    self.n = min(self.n + 1, 40)
    if self.n == 40:
      self.sum = self.sum * (39 / 40)
    self.sum += p

  @property
  def mean(self):
    return self.sum / max(1, self.n)


class Controller:
  def __init__(self, model_info: dict):
    self.info = model_info
    self.dt = float(model_info["control_dt_s"])
    xml = model_info.get("scene_xml") or os.path.join(APP, "scene.xml")
    if not os.path.exists(xml):
      xml = os.path.join(APP, "scene.xml")
    self.k = Kin(xml)
    self.lo = np.array(model_info["ctrl_low"], float)
    self.hi = np.array(model_info["ctrl_high"], float)
    self.max_step = float(model_info.get("max_command_step_frac", 0.25)) * (self.hi - self.lo)

  # ================================================================ interface
  def reset(self, obs):
    self.obs = obs
    self.t = float(obs["time"])
    self.q = np.array(obs["ctrl"][:7], float)            # commanded arm joints
    self.grip = float(obs["ctrl"][7])
    self.sent = None
    self.aborting = None
    self.tracks: dict[str, Track] = {}
    self.cab_hist = []
    self.sigma = 0.0015      # tracker noise (per axis), estimated from the cabinet's readings
    self.stamp = None
    self.stamp_t = self.t
    self.noise_seen = False
    self.same = 0
    self.prev_vals = None
    self.phi = 0.0          # mount lean about y (world = Ry(phi) model - dz)
    self.dz = 0.0
    self.zfix = []          # local z residuals [(x, residual)] from touch-offs
    self.ext = {dr: 0.0 for dr in DRAWER_FLOOR_Z}
    self.handle_at = {}     # drawer -> commanded tcp (model frame) where the handle was held when closed
    self.finger_bias = 0.0
    self.fb = []
    self.fq = []          # last finger readings: the reading is noisy tick to tick, so checks use a short mean
    self.card = obs.get("io", {}).get("kit_card", [])
    self.log = []
    self.stage = "start"
    self.clear_z = None
    self.gen = self._run()

  def act(self, obs):
    self.obs = obs
    self.t = float(obs["time"])
    if getattr(self, "aborting", None) is not None:
      fault, left = self.aborting
      if left <= 0:
        return {"status": "abort", "fault": fault}
      self.aborting = (fault, left - 1)
      return self._relax()
    if self.sent is not None and abs(float(obs["ctrl"][7]) - float(self.sent[7])) > 1e-7:
      self.aborting = ("dead_gripper", 40)
      return self._relax()
    try:
      self._ingest(obs)
      cmd = next(self.gen)
    except StopIteration:
      return {"status": "done"}
    except Abort as a:
      # stop pressing on whatever the hand touches (the cell holds the last command after an abort), then report
      self.aborting = (a.fault, 40)
      return self._relax()
    cmd = np.clip(cmd, self.lo, self.hi)
    if self.sent is not None:
      cmd = np.clip(cmd, self.sent - self.max_step, self.sent + self.max_step)
    self.sent = cmd.copy()
    return cmd

  def _relax(self):
    """Before an abort is reported: get the hand clear of whatever it touches, since after an abort the cell holds
    the arm at its measured joints and it sags a few millimetres. Over 40 ticks: open the fingers if they hold a
    drawer handle (and the gripper still works), back off / lift 1.5 mm a tick for 15 ticks, then hold."""
    fault, left = self.aborting
    k = 40 - left                       # ticks into the relax
    cmd = self.sent.copy() if self.sent is not None else np.array(self.obs["ctrl"], float)
    on_handle = str(self.stage).startswith(("open", "close"))
    if on_handle and fault != "dead_gripper" and k < 12:
      cmd[7] = OPEN                     # let go of the bar first
    elif k < 30:
      try:
        p, Rc = self.tcp()
        d = (-Rc[:, 2] * 0.0015) if on_handle else np.array([0.0, 0.0, 0.0015])
        self.q, _, _ = self.k.step(self.q, p + d, Rc, iters=3)
        cmd[:7] = self.q
      except Exception:
        pass
    cmd = np.clip(cmd, self.lo, self.hi)
    if self.sent is not None:
      cmd = np.clip(cmd, self.sent - self.max_step, self.sent + self.max_step)
    self.sent = cmd.copy()
    return cmd

  # ================================================================ perception
  def _ingest(self, obs):
    st = obs.get("objects_stamp")
    objs = obs.get("objects", {})
    if st is not None and st != self.stamp:
      self.stamp, self.stamp_t = st, self.t
      vals = np.concatenate([objs[k][:3] for k in ("cabinet", "kit_tray") if k in objs])
      if self.prev_vals is not None and len(vals) == len(self.prev_vals):
        if np.array_equal(vals, self.prev_vals):
          self.same += 1
        else:
          self.same = 0
          if np.max(np.abs(vals - self.prev_vals)) > 1e-7:
            self.noise_seen = True
      self.prev_vals = vals
      if "cabinet" in objs:     # the cabinet stands still: its readings give the tracker noise
        self.cab_hist = (getattr(self, "cab_hist", []) + [np.asarray(objs["cabinet"][:3], float)])[-40:]
        if len(self.cab_hist) >= 10:
          h = np.array(self.cab_hist)
          self.sigma = float(np.median(np.abs(h - np.median(h, axis=0)))) * 1.4826
      sg = getattr(self, "sigma", 0.0015)
      for k, v in objs.items():
        tr = self.tracks.setdefault(k, Track())
        tr.add(v, self.t, max(0.006, 4.5 * sg) if k.startswith("part_") else max(0.02, 6 * sg))
    if self.t - self.stamp_t > 0.45:
      raise Abort("perception_freeze")
    if self.noise_seen and self.same >= 4:
      raise Abort("perception_freeze")
    self.fq = (self.fq + [float(obs["qpos"][7])])[-8:]
    if self.grip >= OPEN - 1e-9 and abs(float(obs["qvel"][7])) < 1e-3 and len(self.fb) < 400:
      self.fb.append(float(obs["qpos"][7]) - OPEN)
      self.finger_bias = float(np.mean(self.fb))

  def finger(self):
    return float(np.mean(self.fq)) - self.finger_bias

  def _cmd(self):
    return np.concatenate([self.q + self.k.sag(self.q), [self.grip]])

  def _hold(self, s):
    for _ in range(max(1, round(s / self.dt))):
      yield self._cmd()

  def n_avg(self, base=5):
    """Tracker readings to average for a position check: more when the tracker is noisy."""
    sg = getattr(self, "sigma", 0.0015)
    return base if sg < 0.002 else int(round(base * 2.4))

  def _fresh(self, n=1):
    """Waits for n new tracker readings."""
    st0, got = self.stamp, 0
    while got < n:
      yield self._cmd()
      if self.stamp != st0:
        st0, got = self.stamp, got + 1

  # ================================================================ frames
  def to_model_raw(self, p):
    """World point -> commanded-joint (model) frame, from the mount height and lean only."""
    p = np.asarray(p, float) + np.array([0.0, 0.0, self.dz])
    c, s = math.cos(self.phi), math.sin(self.phi)
    x, y, z = p
    return np.array([c * x - s * z, y, s * x + c * z])

  def to_model(self, p):
    """World point -> commanded-joint (model) frame, with the local height corrections from touch-offs."""
    out = self.to_model_raw(p)
    return out + np.array([0.0, 0.0, self._zlocal(out[0])])

  def to_world(self, p):
    p = np.asarray(p, float) - np.array([0.0, 0.0, self._zlocal(p[0])])
    c, s = math.cos(self.phi), math.sin(self.phi)
    x, y, z = p
    return np.array([c * x + s * z, y, -s * x + c * z]) - np.array([0.0, 0.0, self.dz])

  def _zlocal(self, x):
    if not self.zfix:
      return 0.0
    w = np.array([math.exp(-((x - xx) / 0.10) ** 2) for xx, _ in self.zfix]) + 1e-9
    r = np.array([rr for _, rr in self.zfix])
    return float((w * r).sum() / (w.sum() + 0.05))

  def cab(self):
    tr = self.tracks["cabinet"]
    return tr.mean, yaw_of(tr.quat)

  def tray(self):
    tr = self.tracks["kit_tray"]
    return tr.mean, yaw_of(tr.quat)

  def cab_point(self, loc):
    """Cabinet-frame point -> world."""
    o, yaw = self.cab()
    c, s = math.cos(yaw), math.sin(yaw)
    return np.array([o[0] + c * loc[0] - s * loc[1], o[1] + s * loc[0] + c * loc[1], o[2] + loc[2]])

  def tray_point(self, loc):
    o, yaw = self.tray()
    c, s = math.cos(yaw), math.sin(yaw)
    return np.array([o[0] + c * loc[0] - s * loc[1], o[1] + s * loc[0] + c * loc[1], o[2] + loc[2]])

  def to_cab(self, p):
    o, yaw = self.cab()
    c, s = math.cos(yaw), math.sin(yaw)
    dx, dy = p[0] - o[0], p[1] - o[1]
    return np.array([c * dx + s * dy, -s * dx + c * dy, p[2] - o[2]])

  def sync_model(self):
    o, yaw = self.cab()
    self.k.set_cabinet(self.to_model_raw(o), yaw, self.ext)
    to, tyaw = self.tray()
    self.k.set_tray(self.to_model_raw(to), tyaw)

  # ================================================================ motion
  def tcp(self, q=None):
    return self.k.fk(self.q if q is None else q)

  def _seeds(self, pos):
    j1 = math.atan2(pos[1], pos[0])
    out = [self.q.copy()]
    for base in ((-0.3, -2.2, 2.0), (0.1, -1.7, 1.8), (0.4, -1.3, 1.7)):
      for j7 in (-2.2, -0.8, 0.785, 2.2):
        out.append(np.array([j1, base[0], 0.0, base[1], 0.0, base[2], j7]))
    return out

  def solve(self, pos, R, a=None, check=True, fingers=OPEN, sym=False):
    """IK for a model-frame tool pose. With sym=True a top-down pose may also be taken with the hand turned
    half a turn (empty hand)."""
    targets = [R]
    if sym:
      targets.append(R @ np.diag([-1.0, -1.0, 1.0]))
    best = None
    seeds = self._seeds(pos)
    for Rt in targets:
      for s in seeds:
        q, ep, er = self.k.step(s, pos, Rt, iters=25, lam=1e-3, rest=s, nsw=0.02)
        if ep > 0.08:
          continue
        q, ep, er = self.k.step(q, pos, Rt, iters=35, lam=1e-3, rest=s, nsw=0.02)
        if ep > 0.02:
          continue
        q, ep, er = self.k.step(q, pos, Rt, iters=60, lam=1e-4, rest=s, nsw=0.02)
        if ep > 5e-4 or er > 3e-3:
          continue
        marg = float(np.min(np.minimum(q - self.k.lo, self.k.hi - q)))
        cost = -min(marg, 0.4) + 0.1 * float(np.linalg.norm(q - self.q))
        if best is not None and cost >= best[1]:
          continue
        if check and self.k.collides(q, fingers):
          continue
        best = (q, cost)
    return None if best is None else best[0]

  def move_q(self, q_goal, vmax=0.9, settle=0.1, fingers=None, fast=None):
    """Quintic joint move. With `fingers` given, a move that keeps 25 mm clear of the cell (servo lag grows with
    speed) runs at up to 1.1 rad/s."""
    q0 = self.q.copy()
    fast = FAST_Q if fast is None else fast
    if self.k.held is not None:
      fast = min(fast, 0.7)
    if fingers is not None and vmax < fast and self.safe_q_path(q_goal, fingers, clear=0.025):
      vmax = fast
    dist = float(np.max(np.abs(q_goal - q0)))
    T = max(0.3, 1.875 * dist / vmax)
    n = max(1, round(T / self.dt))
    for i in range(1, n + 1):
      s = i / n
      s = 10 * s ** 3 - 15 * s ** 4 + 6 * s ** 5
      self.q = q0 + (q_goal - q0) * s
      yield self._cmd()
    yield from self._hold(settle)

  def safe_q_path(self, q_goal, fingers=OPEN, n=24, start=None, clear=0.004):
    """True if the joint-space path to q_goal keeps `clear` (4 mm) from fixtures in the model (sampled every
    0.02 rad)."""
    q0 = self.q if start is None else start
    n = max(n, int(math.ceil(float(np.max(np.abs(q_goal - q0))) / 0.02)))
    for i in range(1, n + 1):
      c = self.k.collides(q0 + (q_goal - q0) * i / n, fingers, tol=clear if 3 <= i <= n - 3 else -0.001)
      if c:
        self.last_col = (i, c)
        return False
    return True

  def hubs(self, q_goal):
    """Intermediate arm poses for joint moves that would sweep through the cabinet."""
    out = []
    for j1 in (0.5 * (self.q[0] + q_goal[0]), 0.0, self.q[0], q_goal[0]):
      h = HOME_Q.copy(); h[0] = j1; h[6] = 0.5 * (self.q[6] + q_goal[6])
      out.append(h)
    # high hand-down poses between the bench work areas and the cabinet front (clear of an open drawer)
    for v in ((0.20, 0.0, 0.70), (0.22, -0.20, 0.62), (0.18, 0.18, 0.66), (0.30, -0.30, 0.45)):
      pos = np.array(v)
      q = self.solve(pos, rot_topdown(math.atan2(v[1], v[0]) + math.pi / 2), check=True, sym=True)
      if q is not None:
        out.append(q)
    return out

  def line(self, pos, R, vmax=0.15, amax=0.6, settle=0.05, guard=None, backoff=0.004):
    """Straight tool-point line (model frame) with a trapezoidal speed profile; rotation is slerped along.
    guard = (min_progress_m, stall_ratio): stops as soon as the measured tool speed along the line falls below
    stall_ratio x the commanded speed, and backs the command off to where the tool stopped; returns True then."""
    p0, R0 = self.tcp()
    d = np.asarray(pos, float) - p0
    L = float(np.linalg.norm(d))
    ang = float(np.linalg.norm(rot_err(R, R0)))
    ta = vmax / amax
    if L < vmax * ta:                       # triangle profile
      ta = math.sqrt(max(L, 1e-9) / amax)
      vpk = amax * ta
    else:
      vpk = vmax
    T = max(2 * ta + max(0.0, L - vpk * ta) / vpk, ang / 0.8, 0.06)
    n = max(1, round(T / self.dt))
    T = n * self.dt
    q0 = np.zeros(4); mujoco.mju_mat2Quat(q0, R0.reshape(-1))
    q1 = np.zeros(4); mujoco.mju_mat2Quat(q1, np.ascontiguousarray(R).reshape(-1))
    if np.dot(q0, q1) < 0:
      q1 = -q1
    u = d / L if L > 1e-9 else np.zeros(3)
    ta = min(ta, T / 2)
    acc = vpk / ta if ta > 0 else amax
    hist = []
    for i in range(1, n + 1):
      t = i * self.dt
      if t < ta:
        s, v = 0.5 * acc * t * t, acc * t
      elif t > T - ta:
        s, v = L - 0.5 * acc * (T - t) ** 2, acc * (T - t)
      else:
        s, v = 0.5 * acc * ta * ta + vpk * (t - ta), vpk
      s = min(L, max(0.0, s)) if L > 1e-9 else 0.0
      f = (s / L) if L > 1e-9 else i / n
      qq = (1 - f) * q0 + f * q1
      qq /= np.linalg.norm(qq)
      Rt = np.zeros(9); mujoco.mju_quat2Mat(Rt, qq)
      q_prev = self.q
      q_new, ep, er = self.k.step(self.q, p0 + u * s, Rt.reshape(3, 3), iters=2)
      # near a singularity the arm can need a fast swing for a small tool step: spread it over more ticks
      k_ext = int(math.ceil(float(np.max(np.abs(q_new - q_prev))) / (JOINT_V_MAX * self.dt)))
      for kk in range(1, k_ext):
        self.q = q_prev + (q_new - q_prev) * kk / k_ext
        yield self._cmd()
      self.q = q_new
      yield self._cmd()
      if guard is not None:
        hist.append(v)
        if s > guard[0] and len(hist) >= 3:
          vm = float(self.tool_speed() @ u)
          vc = hist[-2]                    # the servo follows the command about one tick late
          if vc > 0.25 * vpk and vm < guard[1] * vc:
            self.hit_p = p0 + u * s
            back = max(0.0, s - backoff)
            self.q, _, _ = self.k.step(self.q, p0 + u * back, Rt.reshape(3, 3), iters=3)
            yield self._cmd()
            return True
    if guard is not None:
      return False
    yield from self._hold(settle)
    return False

  def line_ok(self, pos, R, fingers=OPEN, n=20, q_start=None, margin=0.05, tol=-0.001):
    """True if the straight tool line to pos (rotation slerped) tracks in IK and is collision free (with
    q_start: from that arm pose, and the end pose is returned instead of True)."""
    p0, R0 = self.tcp(q_start)
    q0 = np.zeros(4); mujoco.mju_mat2Quat(q0, R0.reshape(-1))
    q1 = np.zeros(4); mujoco.mju_mat2Quat(q1, np.ascontiguousarray(R).reshape(-1))
    if np.dot(q0, q1) < 0:
      q1 = -q1
    q = (self.q if q_start is None else q_start).copy()
    for i in range(1, n + 1):
      f = i / n
      qq = (1 - f) * q0 + f * q1
      qq /= np.linalg.norm(qq)
      Rt = np.zeros(9); mujoco.mju_quat2Mat(Rt, qq)
      q, ep, er = self.k.step(q, p0 + (pos - p0) * f, Rt.reshape(3, 3), iters=8)
      if ep > 0.003 or er > 0.02 or float(np.min(np.minimum(q - self.k.lo, self.k.hi - q))) < margin:
        self.k.last_hit = f'track {ep:.4f} {er:.3f}'
        return False
      if self.k.collides(q, fingers, tol=tol):
        return False
    return True if q_start is None else q

  def tool_speed(self):
    qm = np.array(self.obs["qpos"][:7], float)
    Jp, _ = self.k.jac(qm)
    return Jp @ np.array(self.obs["qvel"][:7], float)

  def gripper(self, w, wait=0.4):
    self.grip = float(np.clip(w, 0.0, OPEN))
    yield from self._hold(wait)

  def touch(self, R, direction, travel, speed=0.012):
    """Guarded move along `direction` (model frame); returns the commanded tool point at contact or None."""
    p0, _ = self.tcp()
    u = np.asarray(direction, float) / np.linalg.norm(direction)
    hit = yield from self.line(p0 + u * travel, R, vmax=speed, amax=0.1, guard=(0.002, 0.5), backoff=0.002)
    if not hit:
      return None
    yield from self._hold(0.04)
    return self.hit_p.copy()

  # ================================================================ calibration
  def _calibrate(self):
    """Touch the kit-tray base strip at both ends with the closed fingertips."""
    self.stage = "calibrate"
    yield from self.gripper(0.0, 0.3)
    pts = []
    for name, wpt in (("tray-", self.tray_point(np.array([-0.133, -0.03, TRAY_TOP]))),
                      ("tray+", self.tray_point(np.array([0.133, -0.03, TRAY_TOP])))):
      R = rot_topdown(self.tray()[1] + math.pi / 2)
      above = self.to_model(wpt) + np.array([0, 0, 0.040 + TIP])     # bench height error up to 20 mm, plus lean
      yield from self.go(above, R, high=0.08, sym=True)
      _, R = self.tcp()
      p = yield from self.touch(R, [0, 0, -1], 0.08, speed=0.012)
      if p is None:
        self.log.append((round(self.t, 2), "no touch", name))
        raise Retry()
      pts.append((float(p[0]), float(p[2] - TIP - wpt[2]), wpt))
      self.log.append(("touch", name, [round(float(x), 4) for x in p], [round(float(x), 4) for x in wpt]))
      yield from self.line(p + np.array([0, 0, 0.05]), R, vmax=0.2, amax=1.0, settle=0.0)
    (x1, r1, w1), (x2, r2, w2) = pts
    # model z - world z = -(world z - model z); with world = Ry(phi) model - dz: z_m - z_w ~= phi * x + dz
    phi = (r1 - r2) / (x1 - x2)
    dz = r1 - phi * x1
    if abs(phi) > 0.045 or abs(dz) > 0.035:     # beyond any bench lean or height error the cell allows
      self.log.append((round(self.t, 2), "calib rejected", round(phi, 4), round(dz, 4)))
      raise Retry()
    self.phi, self.dz = phi, dz
    self.log.append(("calib", round(self.phi, 4), round(self.dz, 4)))

  # ================================================================ moves between work areas
  def go(self, pos, R, high=0.12, a=None, fingers=OPEN, vmax=0.6, sym=False, climb_to=None, q_goal=None):
    """Move to a model-frame pose: straight up (to climb_to, or to the goal's approach height if that is higher),
    joint move to a pose `high` above the goal, straight down."""
    p, Rc = self.tcp()
    climb = max(p[2], pos[2] + high, climb_to if climb_to is not None else -1.0)
    if climb > p[2] + 0.005:
      up = p.copy(); up[2] = climb
      # the climb must keep 12 mm from the cell (the forearm passes close to an open drawer front, the servos lag
      # the line and the model's drawer and mount are a few millimetres off): climb only as far as it does, and
      # leave the rest to the checked joint move
      for frac in (1.0, 0.75, 0.5, 0.25):
        tgt = p.copy(); tgt[2] = p[2] + frac * (climb - p[2])
        if self.line_ok(tgt, Rc, fingers=fingers, tol=0.012):
          yield from self.line(tgt, Rc, vmax=0.25, amax=1.0, settle=0.0)
          break
    above = pos.copy(); above[2] = pos[2] + high
    if q_goal is not None:      # a planned arm pose at pos (its straight-line follow-ups were checked from it)
      q = np.array(q_goal, float)
    else:
      q = self.solve(above, R, a, check=True, fingers=fingers, sym=sym)
    if q is None:
      q = self.solve(above, R, a, check=False, fingers=fingers, sym=sym)
    if q is None:
      self.log.append((round(self.t, 2), "no ik", [round(float(x), 3) for x in above]))
      raise Retry()
    for attempt in range(2):
      if self.safe_q_path(q, fingers):
        break
      hub_ok = False
      hubs = self.hubs(q)
      reach = [h for h in hubs if self.safe_q_path(h, fingers)]
      for hub in reach:
        if self.safe_q_path(q, fingers, start=hub):
          yield from self.move_q(hub, vmax=vmax, settle=0.0, fingers=fingers)
          hub_ok = True
          break
      if not hub_ok:          # two hubs
        for h1 in reach:
          for h2 in hubs:
            if h2 is h1:
              continue
            if self.safe_q_path(h2, fingers, start=h1) and self.safe_q_path(q, fingers, start=h2):
              yield from self.move_q(h1, vmax=vmax, settle=0.0, fingers=fingers)
              yield from self.move_q(h2, vmax=vmax, settle=0.0, fingers=fingers)
              hub_ok = True
              break
          if hub_ok:
            break
      if not hub_ok:          # straight-line legs through the open corridor in front of the cabinet
        p_now, R_now = self.tcp()
        for via in ((0.30, -0.25, 0.35), (0.24, -0.18, 0.45), (0.22, -0.05, 0.50), (0.25, 0.0, 0.45),
                    (0.20, 0.0, 0.62)):
          v = np.array(via)
          v[2] = max(v[2], p_now[2])
          for Rv in (R_now, R):
            qv = self.line_ok(v, Rv, fingers=fingers, q_start=self.q.copy())
            if qv is False:
              continue
            if self.safe_q_path(q, fingers, start=qv):
              yield from self.line(v, Rv, vmax=0.2, amax=0.6, settle=0.0)
              hub_ok = True
              break
            for hub in hubs:
              if self.safe_q_path(hub, fingers, start=qv) and self.safe_q_path(q, fingers, start=hub):
                yield from self.line(v, Rv, vmax=0.2, amax=0.6, settle=0.0)
                yield from self.move_q(hub, vmax=vmax, settle=0.0, fingers=fingers)
                hub_ok = True
                break
            if hub_ok:
              break
          if hub_ok:
            break
      if hub_ok:
        break
      self.log.append((round(self.t, 2), "no safe path", self.stage, getattr(self, "last_col", None),
                       [round(float(x), 3) for x in self.tcp()[0]], [round(float(x), 3) for x in pos]))
      if attempt == 0:        # step out of a tight corner (straight up, or away from the cabinet / toward the base)
        p, Rc = self.tcp()
        _, yaw = self.cab()
        u = np.array([math.cos(yaw), math.sin(yaw), 0.0])
        rb = -np.array([p[0], p[1], 0.0]); rb /= max(float(np.linalg.norm(rb)), 1e-6)
        esc = [np.array([p[0], p[1], max(p[2], 0.62)])]
        for dv in (-u, rb, -u + np.array([0, 0, 1.0])):
          for sc in (0.06, 0.12):
            esc.append(p + dv * sc)
        moved = False
        for e in esc:
          if np.linalg.norm(e - p) < 0.01 or e[2] > 0.80:
            continue
          qe = self.line_ok(e, Rc, fingers=fingers, q_start=self.q.copy())
          if qe is False:
            continue
          legs = [e]
          e2 = e.copy(); e2[2] = max(e[2], 0.62)
          if e2[2] > e[2] + 0.01 and self.line_ok(e2, Rc, fingers=fingers, q_start=qe) is not False:
            legs.append(e2)
          for e_ in legs:
            yield from self.line(e_, Rc, vmax=0.2, amax=0.8, settle=0.0)
          self.log.append((round(self.t, 2), "step out", [round(float(x), 3) for x in legs[-1]]))
          moved = True
          break
        if moved:
          continue
      raise Retry()
    yield from self.move_q(q, vmax=vmax, fingers=fingers)
    _, Rq = self.tcp()
    yield from self.line(pos, Rq, vmax=0.2, amax=1.0, settle=0.05)

  # ================================================================ drawers
  def handle_world(self, dr, ext):
    return self.cab_point(np.array([HANDLE_X - ext, 0.0, DRAWER_FLOOR_Z[dr] + HANDLE_Z]))

  def grasp_handle(self, dr, ext):
    o, yaw = self.cab()
    R = rot_pitched(yaw, PITCH)
    hraw = self.to_model_raw(self.handle_world(dr, ext))
    hw = self.to_model(self.handle_world(dr, ext))
    ax = R[:, 2]
    # start with the bar between the open fingers, nearer the upper finger, 3 mm in from the pad centre
    start = hw + ax * 0.003 + np.array([0, 0, -0.016])
    back = start - ax * 0.07
    yield from self.gripper(OPEN, 0.05)
    Rf = R @ np.diag([-1.0, -1.0, 1.0])     # the hand turned half a turn about its axis: the same grip on the bar
    if self.solve(back + np.array([0, 0, 0.03]), R, check=False) is None and \
        self.solve(back + np.array([0, 0, 0.03]), Rf, check=False) is not None:
      self.log.append((round(self.t, 2), "handle: hand turned", dr))
      R = Rf
    yield from self.go(back, R, high=0.03)
    # the arm configuration must also carry the pull (a folded arm meets itself near the base)
    o_, yaw_ = self.cab()
    u_ = -np.array([math.cos(yaw_), math.sin(yaw_), 0.0])
    pull_end = start + u_ * (PULL_STOP - ext)

    def pull_frac(q0, Rx):
      f1, q1 = self._pull_track(q0, back, start, Rx, n=20)
      if f1 < 1.0:
        return 0.0
      f2, _ = self._pull_track(q1, start, pull_end, Rx, n=40, fingers=BAR_R - 0.004)
      return f2

    if ext == 0.0:
      f_now = pull_frac(self.q, R)
      if f_now < 1.0:
        # another arm configuration (or the hand turned half a turn about its axis, the same grip on the bar)
        # may follow the pull further
        best = None
        for Rx in (R, R @ np.diag([-1.0, -1.0, 1.0])):
          seeds = self._seeds(back)
          seeds += [sd + np.array([0, 0, j3, 0, -j3, 0, 0]) for sd in seeds[1:] for j3 in (-0.6, 0.6)]
          for sd in seeds:
            qa = self._ik_at(back, Rx, sd)
            if qa is None or self.k.collides(qa):
              continue
            f = pull_frac(qa, Rx)
            if (best is None or f > best[0] + 1e-6) and f > f_now + 0.02 and self.safe_q_path(qa):
              best = (f, qa, Rx)
            if best is not None and best[0] >= 1.0:
              break
          if best is not None and best[0] >= 1.0:
            break
        self.log.append((round(self.t, 2), "handle: re-configure", dr, round(f_now, 3),
                         None if best is None else round(best[0], 3)))
        if best is not None:
          yield from self.move_q(best[1], vmax=0.4, settle=0.1)
          R = best[2]
    yield from self.line(start, R, vmax=0.15, amax=0.8, settle=0.05)
    p = yield from self.touch(R, [0, 0, -1], 0.05, speed=0.015)
    if p is None:
      self.log.append((round(self.t, 2), "bar: no touch", dr, [round(float(x), 3) for x in self.tcp()[0]],
                       [round(float(x), 3) for x in hw]))
      raise Retry()
    # contact: upper pad face on the bar top; pad face is 40 mm above the tool point along the hand y axis
    zbar = p[2] + OPEN / math.cos(PITCH) - BAR_R
    self.log.append(("bar touch", dr, round(float(p[2] - hw[2]), 4), round(float(zbar - hw[2]), 4)))
    self.zfix.append((float(p[0]), float(zbar - hraw[2])))
    self.zfix = self.zfix[-8:]
    target = p.copy(); target[2] = zbar
    yield from self.line(p + np.array([0, 0, 0.002]), R, vmax=0.01, amax=0.1, settle=0.0)
    yield from self.line(target, R, vmax=0.02, amax=0.2, settle=0.05)
    yield from self.gripper(BAR_R - 0.008, 0.35)   # about 25 N per finger: the bar must not slide out under the detent
    self.log.append(("bar grip", dr, round(self.finger(), 4)))
    if abs(self.finger() - BAR_R) > 0.0035:
      raise Retry()
    return target, R

  def open_drawer(self, dr):
    self.stage = f"open {dr}"
    yield from self.clear_cabinet()
    p0, R = yield from self.grasp_handle(dr, 0.0)
    self.handle_at[dr] = p0.copy()
    o, yaw = self.cab()
    u = -np.array([math.cos(yaw), math.sin(yaw), 0.0])
    # break the detent gently, then pull
    # pull as far as the arm can follow cleanly (near the base the lower drawer's handle folds the arm)
    f, _ = self._pull_track(self.q, p0, p0 + u * PULL_STOP, R, n=40, fingers=BAR_R - 0.004)
    pull = max(0.02, f * PULL_STOP - 0.004) if f < 1.0 else PULL_STOP
    if pull < PULL_STOP - 0.009:
      self.log.append((round(self.t, 2), "pull: short", dr, round(pull, 4), self.k.last_hit))
    yield from self.line(p0 + u * 0.008, R, vmax=0.02, amax=0.2, settle=0.0)
    yield from self.line(p0 + u * pull, R, vmax=0.12, amax=0.25, settle=0.15)
    pe, _ = self.tcp()
    self.ext[dr] = float((pe - p0) @ u)
    self.log.append((round(self.t, 2), "pull done", dr, round(pull, 4), round(self.ext[dr], 4),
                     round(float((self.k.fk(np.array(self.obs["qpos"][:7], float))[0] - p0) @ u), 4)))
    yield from self.gripper(OPEN, 0.3)
    self.sync_model()
    # off the bar: back and up, but backing off folds the arm further when the pull already ended near the base
    for off in (np.array([0, 0, 0.02]) - R[:, 2] * 0.06, np.array([0, 0, 0.03]) - R[:, 2] * 0.03,
                np.array([0, 0, 0.04]) - R[:, 2] * 0.01):
      qe = self.line_ok(pe + off, R, margin=0.03, q_start=self.q)
      if qe is not False and self.k.self_clear(qe, OPEN, 0.002):
        break
    yield from self.line(pe + off, R, vmax=0.12, settle=0.0)
    # the parts in this drawer were tracked while it moved: start their averages afresh now it is at rest
    for k, tr in self.tracks.items():
      if k.startswith("part_"):
        tr.reset()
    yield from self._fresh(4)

  def _ik_at(self, pos, R, seed):
    q, ep, er = self.k.step(seed, pos, R, iters=25, lam=1e-3, rest=seed, nsw=0.02)
    if ep > 0.08:
      return None
    q, ep, er = self.k.step(q, pos, R, iters=35, lam=1e-3, rest=seed, nsw=0.02)
    q, ep, er = self.k.step(q, pos, R, iters=60, lam=1e-4, rest=seed, nsw=0.02)
    return q if ep < 5e-4 and er < 3e-3 else None

  def _push_ok(self, q0, start, end, R):
    qs = self.line_ok(start, R, fingers=0.0, q_start=q0, margin=0.015)
    if qs is False:
      self.push_why = ("to start", self.k.last_hit)
      return False
    if not self.k.self_clear(qs, 0.0, need=0.004) or not self.k.self_clear(q0, 0.0, need=0.004):
      self.push_why = ("start self", self.k.last_hit)
      return False
    # the line to the start can fold the arm onto itself between its ends (lower drawer, cabinet far out)
    pa, _ = self.tcp(q0)
    q = np.array(q0, float).copy()
    for i in range(1, 11):
      q, _, _ = self.k.step(q, pa + (start - pa) * i / 10, R, iters=8)
      if not self.k.self_clear(q, 0.0, need=0.004):
        self.push_why = ("to start self", i, self.k.last_hit)
        return False
    # the end of the push is in contact with the panel in the model (drawer at its pulled extension): check
    # tracking only, not collisions
    p0, _ = self.tcp(qs)
    q = qs.copy()
    for i in range(1, 21):
      q, ep, er = self.k.step(q, p0 + (end - p0) * i / 20, R, iters=8)
      mg = float(np.min(np.minimum(q - self.k.lo, self.k.hi - q)))
      if ep > 0.003 or er > 0.02 or mg < 0.015:
        self.push_why = ("push", i, round(ep, 4), round(er, 4), round(mg, 3), int(np.argmin(np.minimum(q - self.k.lo, self.k.hi - q))))
        return False
      if (i % 4 == 0 or i == 20) and not self.k.self_clear(q, 0.0, need=0.004):   # a folded arm meets itself
        self.push_why = ("push self", i, self.k.last_hit)
        return False
    return True

  def _pull_track(self, q0, a_, b_, R, n=30, fingers=OPEN):
    """Fraction of the straight tool line a_ -> b_ that the arm, starting at q0, follows with margin to its
    joint limits and without folding onto itself (2 mm clearance between links, every third step)."""
    q = np.array(q0, float)
    for i in range(1, n + 1):
      q, ep, er = self.k.step(q, a_ + (b_ - a_) * i / n, R, iters=8)
      if ep > 0.002 or er > 0.01 or float(np.min(np.minimum(q - self.k.lo, self.k.hi - q))) < 0.05 or \
          q[3] < -2.96 or (i % 3 == 0 or i == n) and not self.k.self_clear(q, fingers, need=0.004):
        self.k.last_hit = f"pull {i}/{n} {ep:.4f} {er:.3f} q4 {q[3]:.3f} {self.k.last_hit}"
        return (i - 1) / n, q
    return 1.0, q

  def _pull_ok(self, q0, back, start, end, R):
    """The arm at q0 (tool at `back`) can follow back -> start -> end without folding onto itself."""
    f, q = self._pull_track(q0, back, start, R, n=20)
    if f < 1.0:
      return False
    f, q = self._pull_track(q, start, end, R, n=30, fingers=BAR_R - 0.004)
    return f >= 1.0

  def close_drawer(self, dr):
    """Push the drawer shut with the closed fingertips on its front panel, beside the handle."""
    self.stage = f"close {dr}"
    self.sync_model()
    ext = self.ext[dr]
    o, yaw = self.cab()
    u = np.array([math.cos(yaw), math.sin(yaw), 0.0])
    # where to push the panel and with which hand: the first candidate whose push the arm can follow from a
    # collision-free start (the right-hand side of the lower drawer needs the hand turned half a turn)
    first = 0.15 if self.cab_point(np.zeros(3))[1] < 0 else -0.125
    cands = [(first, False), (first, True), (0.15, False), (-0.15, True), (0.2, False), (-0.2, True)]
    plan = None
    for side, flip in cands:
      R = rot_pitched(yaw, PITCH) @ (np.diag([-1.0, -1.0, 1.0]) if flip else np.eye(3))
      ax = R[:, 2]
      face = self.to_model(self.cab_point(np.array([-ext - FRONT_T, side, DRAWER_FLOOR_Z[dr] + 0.050])))
      closed_face = self.to_model(self.cab_point(np.array([-FRONT_T, side, DRAWER_FLOOR_Z[dr] + 0.050])))
      start = face - u * 0.025 - ax * TIP
      pre = start - u * 0.10 + np.array([0, 0, 0.10])
      end = closed_face - u * (PUSH_LEAD - 0.006) - ax * TIP
      for sd in self._seeds(pre):
        qa = self._ik_at(pre, R, sd)
        if qa is not None and not self.k.collides(qa, 0.0) and self._push_ok(qa, start, end, R):
          plan = (side, flip, R, ax, face, closed_face, start, pre, end)
          break
      if plan is not None:
        break
    if plan is None:
      self.log.append((round(self.t, 2), "close: no push plan", dr))
      raise Retry()
    side, flip, R, ax, face, closed_face, start, pre, end = plan
    self.log.append(("close plan", dr, side, flip))
    yield from self.gripper(0.0, 0.05)
    yield from self.go(pre, R, high=0.02, fingers=0.0)
    # the push must be trackable from here (an arm pose near its joint limits cannot follow it): otherwise
    # change to another arm configuration at the same pre-pose that can
    if not self._push_ok(self.q, start, end, R):
      alt = None
      for sd in self._seeds(pre):
        qa = self._ik_at(pre, R, sd)
        if qa is None or self.k.collides(qa, 0.0) or not self._push_ok(qa, start, end, R):
          continue
        if self.safe_q_path(qa, 0.0):
          alt = qa
          break
      self.log.append((round(self.t, 2), "close: push not trackable", dr, alt is not None, getattr(self, "push_why", None)))
      if alt is None:
        raise Retry()
      yield from self.move_q(alt, vmax=0.5, settle=0.1)
    yield from self.line(start, R, vmax=0.2, amax=0.8, settle=0.05)
    yield from self.gripper(0.0, 0.2)
    p, _ = self.tcp()
    dist = float((closed_face - face) @ u)
    yield from self.line(p + u * 0.030, R, vmax=0.03, amax=0.3, settle=0.0)       # meet the panel slowly
    p, _ = self.tcp()
    # push to 2.5 mm short of closed (inside the soft-close detent, which pulls the drawer into its latch);
    # the interlock lamp tells whether it latched, otherwise push 1 mm further and look again
    hit = False
    for k, short in enumerate((0.003, 0.0015, 0.0, -0.0015, -0.003, -0.0045, -0.006)):
      tgt = closed_face - u * (short + PUSH_LEAD) - ax * TIP
      p, _ = self.tcp()
      if float((tgt - p) @ u) > 0.03:
        yield from self.line(tgt - u * 0.015, R, vmax=0.12, amax=0.25, settle=0.0)
      # stall-guarded: the closed-face estimate can be some millimetres off, and a drawer at its back stop must
      # not be pushed harder
      stalled = yield from self.line(tgt, R, vmax=0.012, amax=0.15, settle=0.05, guard=(0.003, 0.5))
      if stalled:
        yield from self._hold(0.05)
      yield from self.line(self.tcp()[0] - u * 0.008, R, vmax=0.03, amax=0.3, settle=0.3)
      yield from self._fresh(2)
      hit = bool(self.obs.get("io", {}).get("cabinet", {}).get("all_latched"))
      self.log.append(("close push", dr, k, hit))
      if hit:
        break
    # off the panel: straight back unless that folds the arm onto itself (lower drawer, cabinet near the arm),
    # then more up than back
    p0, _ = self.tcp()
    for off in (-u * 0.10, -u * 0.05 + np.array([0, 0, 0.06]), -u * 0.02 + np.array([0, 0, 0.08])):
      qe = self.line_ok(p0 + off, R, fingers=0.0, q_start=self.q, margin=0.02)
      if qe is not False and self.k.self_clear(qe, 0.0, need=0.004):
        break
      self.log.append((round(self.t, 2), "close: back-off", [round(float(x), 3) for x in off], self.k.last_hit))
    yield from self.line(p0 + off, R, vmax=0.1, amax=0.5, settle=0.0)
    p, _ = self.tcp()
    if self.line_ok(p + np.array([0, 0, 0.08]), R, fingers=0.0):
      yield from self.line(p + np.array([0, 0, 0.08]), R, vmax=0.1, amax=0.5, settle=0.0)
    if not hit:
      raise Retry()
    self.ext[dr] = 0.0
    self.sync_model()
    return hit

  # ================================================================ parts
  def find_part(self, ln):
    """The tracked part lying in the line's compartment (drawer frame from the measured pull)."""
    dr, c = ln["drawer"], ln["compartment"]
    ctr = np.array([ROW_X[(c - 1) // 3] - self.ext[dr], COL_Y[(c - 1) % 3]])
    best = None
    for k, tr in self.tracks.items():
      if not k.startswith("part_") or self.t - tr.seen > 0.25:
        continue
      loc = self.to_cab(tr.mean)
      if abs(loc[2] - DRAWER_FLOOR_Z[dr]) > 0.02:
        continue
      rel = loc[:2] - ctr
      if abs(rel[0]) < COMP_HALF[0] + 0.01 and abs(rel[1]) < COMP_HALF[1] + 0.01:
        dd = float(np.linalg.norm(rel))
        if best is None or dd < best[1]:
          best = (k, dd)
    return None if best is None else best[0]

  def place_yaw(self, ln):
    """World yaw the part's +x axis must have in its pocket."""
    _, tyaw = self.tray()
    return tyaw + (math.pi / 2 if ln["orientation"] == "tab to notch" else -math.pi / 2)

  def plan_grasp(self, body, ln, in_drawer=True):
    """Hand yaw and tilt for the grasp so that pick, hover and place poses are all reachable (the far
    compartments of the upper drawers are out of reach with the hand straight down: the hand then leans
    away from the arm base about its closing axis). Returns (a_pick, a_place, tilt)."""
    tr = self.tracks[body]
    pyaw = yaw_of(tr.quat)
    L, W, H = PARTS[ln["part"]]
    g = self.to_model(tr.mean) + np.array([0, 0, 0.005])
    if in_drawer:   # the part lies on the drawer floor: trust the floor height over a noisy reading
      fl = self.to_model(self.cab_point(np.array([0.0, 0.0, DRAWER_FLOOR_Z[ln["drawer"]]])))[2]
      g[2] = fl + 0.005
    pk = POCKETS[ln["pocket"]]
    gp = self.to_model(self.tray_point(np.array([pk[0], pk[1], TRAY_TOP]))) + np.array([0, 0, 0.006])
    fails = []
    for tilt_deg in (0, 20, 30, 40):
      best = None
      for off in (math.pi / 2, -math.pi / 2):
        a_pick = pyaw + off
        a_place = self.place_yaw(ln) + off
        x0 = rot_topdown(a_pick)[:, 0]
        sg = 1.0 if x0[0] * g[0] + x0[1] * g[1] >= 0 else -1.0
        tilt = sg * math.radians(tilt_deg)
        Rp, Rl = rot_tilt(a_pick, tilt), rot_tilt(a_place, tilt)
        qs = []
        for pos, R, a, chk, fw in ((g - Rp[:, 2] * TIP, Rp, a_pick, True, W / 2 + 0.008),
                                   (g + np.array([0, 0, H + 0.04]) - Rp[:, 2] * TIP, Rp, a_pick, True, W / 2 + 0.010),
                                   (gp - Rl[:, 2] * TIP, Rl, a_place, False, W / 2),
                                   (gp + np.array([0, 0, 0.02]) - Rl[:, 2] * TIP, Rl, a_place, True, W / 2)):
          q = self.solve(pos, R, a, check=chk, fingers=fw)
          if q is None:
            fails.append((tilt_deg, round(off, 2), len(qs), self.k.last_hit if chk else "ik"))
            break
          qs.append(q)
        if len(qs) < 4:
          continue
        if in_drawer and not self._drawer_path_ok(tr.mean, g, Rp, a_pick, ln, body, gp, Rl, a_place):
          fails.append((tilt_deg, round(off, 2), 4, self.k.last_hit))
          continue
        marg = min(float(np.min(np.minimum(q - self.k.lo, self.k.hi - q))) for q in qs)
        if best is None or marg > best[2]:
          best = (a_pick, a_place, marg, tilt, getattr(self, "portal_q", None) if in_drawer else None)
      if best is not None and best[2] > 0.08:
        break
    if best is None:
      self.log.append(("no grasp", body, fails[:4]))
      raise Retry()
    self.portal_q = best[4]
    return best[0], best[1], best[3]

  def _drawer_path_ok(self, pw, g, R, a, ln, body=None, gp=None, Rl=None, a_place=None):
    """The in-drawer approach (portal, over the part, down) and the exit (up, portal) as the straight lines pick
    runs them, checked from the arm pose at the portal: they must track and stay clear of the cell and of the
    arm itself."""
    L, W, H = PARTS[ln["part"]]
    dr, ax, open_w = ln["drawer"], R[:, 2], W / 2 + 0.010
    ycab = float(self.to_cab(pw)[1])
    pts = self.portal(dr, ycab)
    q = self.solve(pts[1], R, a, check=True, fingers=open_w)
    if q is None:
      self.k.last_hit = "portal ik"
      return False
    self.portal_q = q.copy()
    hover = self.to_model(pw) + np.array([0, 0, H + 0.035]) - ax * TIP
    top_in = hover.copy(); top_in[2] = pts[0][2]
    grasp = g - ax * TIP
    up = self.to_model(self.cab_point(np.array([self.to_cab(pw)[0], ycab, DRAWER_FLOOR_Z[dr] + 0.105])))
    for target, fw, tol in ((pts[0], open_w, 0.003), (top_in, open_w, 0.003), (hover, open_w, 0.003),
                            (grasp, open_w, -0.001), (grasp + np.array([0, 0, 0.03]), W / 2, -0.001)):
      q = self.line_ok(target, R, fingers=fw, q_start=q, margin=0.02, tol=tol)
      if q is False:
        return False
    if body is None:
      return True
    # with the part in the hand: up, out through the portal and the carry to over the pocket
    self.k.hold(body, (L, W, H))
    try:
      for target in (up, pts[0], pts[1]):
        q = self.line_ok(target, R, fingers=W / 2, q_start=q, margin=0.02, tol=0.002)
        if q is False:
          return False
      above = gp + np.array([0, 0, 0.0105 + 0.06]) - Rl[:, 2] * TIP
      if self._carry_route(above, Rl, a_place, W, q0=q) is None and \
          self._carry_route(above, Rl, a_place, W, q0=q, margin=0.025) is None:
        self.k.last_hit = ("carry", getattr(self, "carry_why", None))
        return False
      return True
    finally:
      self.k.hold(None)

  def portal(self, dr, ycab):
    """Way points (model frame, tool point) from over the open drawer's front out to the arm's side."""
    fl = DRAWER_FLOOR_Z[dr]
    return [self.to_model(self.cab_point(np.array([-self.ext[dr] - 0.11, ycab, fl + 0.135]))),
            self.to_model(self.cab_point(np.array([-self.ext[dr] - 0.21, 0.5 * ycab, fl + 0.135])))]

  def pick(self, body, ln, in_drawer=True):
    self.stage = f"pick {ln['line']} {body}"
    L, W, H = PARTS[ln["part"]]
    yield from self._fresh(3)
    tr = self.tracks[body]
    a_pick, a_place, tilt = self.plan_grasp(body, ln, in_drawer)
    R = rot_tilt(a_pick, tilt)
    ax = R[:, 2]
    self.log.append(("grasp plan", body, round(math.degrees(tilt))))
    pw = tr.mean.copy()
    pm = self.to_model(pw)
    open_w = W / 2 + 0.010
    yield from self.gripper(open_w, 0.05)
    hover = pm + np.array([0, 0, H + 0.035]) - ax * TIP
    if in_drawer:   # in over the drawer front, then down
      dr = ln["drawer"]
      ycab = float(self.to_cab(pw)[1])
      pts = self.portal(dr, ycab)[::-1]
      yield from self.go(pts[0], R, high=0.0 if self.portal_q is not None else 0.04, a=a_pick, fingers=open_w,
                         q_goal=self.portal_q)
      yield from self.line(pts[1], R, vmax=0.15, amax=0.5, settle=0.0)
      top_in = hover.copy(); top_in[2] = pts[1][2]
      yield from self.line(top_in, R, vmax=0.15, amax=0.5, settle=0.0)
      yield from self.line(hover, R, vmax=0.12, amax=0.5, settle=0.1)
    else:
      yield from self.go(hover, R, high=0.06, a=a_pick, fingers=open_w)
    # look again: the part may have been pushed
    tr = self.tracks[body]
    for look in range(3):
      tr.reset()
      yield from self._fresh(8)
      shift = float(np.linalg.norm(tr.mean[:2] - pw[:2]))
      yaw_off = min(abs(wrap(yaw_of(tr.quat) - (a_pick - math.pi / 2))), abs(wrap(yaw_of(tr.quat) - (a_pick + math.pi / 2))))
      if shift <= 0.006 and yaw_off <= 0.25:
        break
      if look == 2 or shift > 0.03 or yaw_off > 0.35:
        self.log.append((round(self.t, 2), "part moved", body, round(shift, 4), round(yaw_off, 3)))
        raise Retry()
      # a small shift (or reading noise): hover over the new estimate and look again
      pw = tr.mean.copy()
      hover = self.to_model(pw) + np.array([0, 0, H + 0.035]) - ax * TIP
      yield from self.line(hover, R, vmax=0.05, amax=0.4, settle=0.05)
    # touch the part's top with the open fingertips? no: touch beside it is risky; touch the top with the palm gap
    # closed would push it. Use the tracked height of the part instead, corrected by local touch-offs.
    top = self.to_model(tr.mean + np.array([0, 0, H]))
    yield from self.line(top + np.array([0, 0, 0.012]) - ax * TIP, R, vmax=0.12, amax=0.8, settle=0.0)
    hit = yield from self.line(top + np.array([0, 0, -H + 0.0025]) - ax * TIP, R, vmax=0.015, amax=0.2,
                               guard=(0.003, 0.5))
    p, _ = self.tcp()
    if hit:   # fingertips found the floor (or the part): back up 1.5 mm
      yield from self.line(p + np.array([0, 0, 0.0015]), R, vmax=0.01, amax=0.1, settle=0.05)
    else:
      yield from self._hold(0.05)
    yield from self.gripper(W / 2 - 0.004, 0.45)
    w = self.finger()
    if abs(w - W / 2) > 0.003:
      self.log.append((round(self.t, 2), "grip width", body, round(w, 4), W / 2))
      yield from self.gripper(open_w, 0.3)
      yield from self.line(self.tcp()[0] + np.array([0, 0, 0.04]), R, vmax=0.1)
      raise Retry()
    p, _ = self.tcp()
    yield from self.line(p + np.array([0, 0, 0.03]), R, vmax=0.06, amax=0.4, settle=0.1)
    self.k.hold(body, (L, W, H))
    self.exit_pts = []
    if in_drawer:   # out of the drawer: up clear of the walls, then over the drawer front towards the arm
      dr = ln["drawer"]
      loc = self.to_cab(self.to_world(p))
      fl = DRAWER_FLOOR_Z[dr]
      # up until the held part's underside clears the drawer front (83 mm above the floor) with margin
      up = None
      for zz in (0.115, 0.105, 0.095):
        cand = self.to_model(self.cab_point(np.array([loc[0], loc[1], fl + zz])))
        if self.line_ok(cand, R, fingers=W / 2):
          up = cand
          break
      if up is None:
        up = self.to_model(self.cab_point(np.array([loc[0], loc[1], fl + 0.095])))
      self.exit_pts = [up] + self.portal(dr, loc[1])
    yield from self._fresh(3)
    tr = self.tracks[body]
    hw = self.to_world(self.tcp()[0] + ax * TIP)
    if tr.last is None or abs(tr.last[2] - (hw[2] - 0.002)) > 0.012:
      self.log.append((round(self.t, 2), "not lifted", body, None if tr.last is None else round(float(tr.last[2] - hw[2]), 4)))
      yield from self.gripper(open_w, 0.3)
      raise Retry()
    return a_place, tilt

  def place(self, body, ln, a_place, tilt=0.0):
    self.stage = f"place {ln['line']}"
    L, W, H = PARTS[ln["part"]]
    pk = POCKETS[ln["pocket"]]
    target_w = self.tray_point(np.array([pk[0], pk[1], TRAY_TOP]))
    R = rot_tilt(a_place, tilt)
    p, Rc = self.tcp()
    # rise above the drawer front, then over to the pocket
    hover_m = self.to_model(target_w) + np.array([0, 0, 0.014 + 0.0025]) - R[:, 2] * TIP
    for e in getattr(self, "exit_pts", []):
      _, Rc = self.tcp()
      yield from self.line(e, Rc, vmax=CARRY_V, amax=0.5, settle=0.0)
    self.exit_pts = []
    above = hover_m + np.array([0, 0, 0.06])
    # a held part creeps in the pads under fast wrist turns: carry it on straight lines, through a via point
    # in front of the cabinet when the direct line is blocked
    route = None
    for lift in range(2):
      if lift:      # nothing found from here: straight up first (clear of the open drawer's front), then again
        p0, R0 = self.tcp()
        up = np.array([p0[0], p0[1], max(p0[2] + 0.06, 0.60)])
        if not self.line_ok(up, R0, fingers=W / 2):
          break
        self.log.append((round(self.t, 2), "carry: lift first", ln["line"]))
        yield from self.line(up, R0, vmax=CARRY_V, amax=0.5, settle=0.0)
      route = self._carry_route(above, R, a_place, W) or self._carry_route(above, R, a_place, W, margin=0.025)
      if route is not None:
        break
    if route is not None:
      for kind, wp, Rw in route:
        if kind == "line":
          yield from self.line(wp, Rw, vmax=CARRY_V, amax=0.5, settle=0.0)
        else:
          yield from self.move_q(wp, vmax=0.4, settle=0.1, fingers=W / 2, fast=0.7)
      yield from self.line(hover_m, R, vmax=0.12, amax=0.5, settle=0.05)
    else:
      self.log.append((round(self.t, 2), "carry by joint move", ln["line"]))
      yield from self.go(hover_m, R, high=0.06, a=a_place, fingers=W / 2, vmax=0.5)
    return (yield from self._place_down(body, ln, target_w, W, L, H, tilt))

  def _carry_route(self, above, R, a_place, W, q0=None, margin=0.05):
    """Straight carry lines to over the pocket, through a via point when the direct line is blocked (from the arm
    pose q0, default the commanded one)."""
    route = None
    planning = q0 is not None
    q0 = self.q.copy() if q0 is None else np.array(q0, float)
    if self.line_ok(above, R, fingers=W / 2, q_start=q0, margin=margin) is not False:
      route = [("line", above, R)]
    else:
      why = [self.k.last_hit]
      p0, R0 = self.tcp(q0)
      for via in (np.array([0.24, -0.18, max(0.45, above[2])]), np.array([0.22, -0.05, max(0.50, p0[2])]),
                  np.array([0.20, -0.40, max(0.50, p0[2])]), np.array([0.18, -0.32, 0.60]),
                  np.array([0.30, -0.25, 0.35]), np.array([0.25, 0.0, 0.45])):
        q1 = self.line_ok(via, R0, fingers=W / 2, q_start=q0, margin=margin)
        if q1 is False:
          why.append(("to via", self.k.last_hit))
          continue
        q2 = self.line_ok(above, R, fingers=W / 2, q_start=q1, margin=margin)
        if q2 is False:
          why.append(("from via", self.k.last_hit))
        if q2 is not False:
          route = [("line", via, R0), ("line", above, R)]
          break
        qv = self.solve(via, R, a_place, check=True, fingers=W / 2)
        if qv is None:
          why.append(("via ik", self.k.last_hit))
          continue
        if not self.safe_q_path(qv, W / 2, start=q1):
          why.append(("via turn", getattr(self, "last_col", None)))
          continue
        if self.line_ok(above, R, fingers=W / 2, q_start=qv, margin=margin) is not False:
          route = [("line", via, R0), ("joint", qv, None), ("line", above, R)]
          break
        why.append(("via down", self.k.last_hit))
      self.carry_why = why[:4]
      if route is None and not planning:
        self.log.append((round(self.t, 2), "carry blocked", why[:8]))
    return route

  def _place_down(self, body, ln, target_w, W, L, H, tilt):
    # correct the hand from the tracked part (held), two passes
    for _ in range(3):
      yield from self._hold(0.25)
      self.tracks[body].reset()
      yield from self._fresh(self.n_avg())
      tr = self.tracks[body]
      ph, _ = self.tcp()
      lost = float(np.linalg.norm(tr.mean[:2] - self.to_world(ph)[:2])) > 0.03 or self.finger() < W / 2 - 0.004
      if lost:      # the part is not in the hand: let go and pick it up again from where it is
        self.log.append((round(self.t, 2), "part lost in carry", ln["line"], round(self.finger(), 4)))
        yield from self.gripper(OPEN, 0.3)
        self.k.hold(None)
        raise Retry()
      err = target_w[:2] - tr.mean[:2]
      yerr = wrap(self.place_yaw(ln) - yaw_of(tr.quat))
      if np.linalg.norm(err) > 0.02:
        err = err * (0.02 / float(np.linalg.norm(err)))
      yerr = max(-0.3, min(0.3, yerr))
      self.log.append(("place corr", ln["line"], round(self.t, 2), [round(float(x), 4) for x in err], round(yerr, 3)))
      if np.linalg.norm(err) < 0.0012 and abs(yerr) < 0.02:
        break
      p, Rc = self.tcp()
      Rn = rot_tilt(math.atan2(Rc[1, 1], Rc[0, 1]) + yerr, tilt)
      # rotating about the tool point moves the part if it is held off-centre: rotate about the part instead
      off = tr.mean[:2] - self.to_world(p)[:2]
      c, s = math.cos(yerr), math.sin(yerr)
      off_new = np.array([c * off[0] - s * off[1], s * off[0] + c * off[1]])
      dp = np.array([err[0] + off[0] - off_new[0], err[1] + off[1] - off_new[1], 0.0])
      yield from self.line(p + dp, Rn, vmax=0.03, amax=0.3, settle=0.05)
    # lower until the part's underside is 1.5 mm above the tray (tracked height of the held part), then let go
    tr = self.tracks[body]
    ph, Rh = self.tcp()
    self.log.append(("hold off", ln["line"], [round(float(x), 4) for x in Rh.T @ (tr.mean[:3] - self.to_world(ph))],
                     round(self.finger(), 4)))
    drop = float(tr.mean[2] - (target_w[2] + 0.0015))
    off_len = abs(float((Rh.T @ (tr.mean[:3] - self.to_world(ph)))[0]))
    if off_len > 0.006:
      # held off-centre along its length: the fingers miss the relief gap in the pocket's long walls, so the
      # fingertips stay above the wall tops and the part is let go a little higher
      room = float(self.to_world(ph)[2] - (target_w[2] + 0.008 + TIP + 0.0035))
      if room < drop:
        self.log.append(("high release", ln["line"], round(off_len, 4), round(drop - max(room, 0.0), 4)))
        drop = max(room, 0.0)
    p, Rc = self.tcp()
    if drop > 0.012:
      yield from self.line(p + np.array([0, 0, -(drop - 0.006)]), Rc, vmax=0.03, amax=0.3, settle=0.0)
      p, _ = self.tcp()
      drop = 0.006
    hit = yield from self.line(p + np.array([0, 0, -max(0.0, drop)]), Rc, vmax=0.008, amax=0.1, guard=(0.001, 0.5))
    yield from self._hold(0.1)
    # let go with a small opening first: the fingertips are below the pocket walls (30 mm pocket, wide parts)
    yield from self.gripper(W / 2 + 0.0025, 0.3)
    self.k.hold(None)
    p, _ = self.tcp()
    yield from self.line(p + np.array([0, 0, 0.015]), Rc, vmax=0.03, amax=0.3, settle=0.0)
    yield from self.gripper(W / 2 + 0.008, 0.2)
    p, _ = self.tcp()
    yield from self.line(p + np.array([0, 0, 0.035]), Rc, vmax=0.15, amax=0.8, settle=0.0)
    # check the pocket
    yield from self._hold(0.3)
    self.tracks[body].reset()
    yield from self._fresh(self.n_avg())
    ok = self.in_pocket(body, ln)
    self.log.append(("placed", ln["line"], round(self.t, 2), ok, bool(hit), [round(float(x), 4) for x in self.tracks[body].mean]))
    return ok

  def in_pocket(self, body, ln):
    tr = self.tracks[body]
    L, W, H = PARTS[ln["part"]]
    pk = POCKETS[ln["pocket"]]
    to, tyaw = self.tray()
    c, s = math.cos(tyaw), math.sin(tyaw)
    d = tr.mean[:2] - to[:2]
    loc = np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1]])
    yerr = abs(wrap(self.place_yaw(ln) - yaw_of(tr.quat)))
    # the part's own room in the pocket across and along it (30 x 64 mm), but never stricter than 3 / 4 mm
    tol_x = max(0.003, min(0.006, (0.030 - W) / 2))
    tol_y = max(0.004, min(0.008, (0.064 - L) / 2))
    return (abs(loc[0] - pk[0]) < tol_x and abs(loc[1] - pk[1]) < tol_y and yerr < 0.12
            and abs(tr.mean[2] - (to[2] + TRAY_TOP)) < 0.004)

  # ================================================================ main
  def _run(self):
    yield from self._hold(0.6)
    yield from self._fresh(6)
    self.sync_model()
    for _ in range(2):
      try:
        yield from self._calibrate()
        break
      except Retry:
        self.log.append((round(self.t, 2), 'retry', self.stage))
        continue
    self.sync_model()
    order = []
    for ln in self.card:
      if ln["drawer"] not in order:
        order.append(ln["drawer"])
    for dr in order:
      lines = [ln for ln in self.card if ln["drawer"] == dr]
      yield from self._fresh(2)
      if not self.obs.get("io", {}).get("cabinet", {}).get("all_latched", True):
        self.log.append((round(self.t, 2), "cabinet not latched: no further drawers", dr))
        break                     # the interlock would hold the next drawer: stop rather than force it
      opened = False
      for attempt in range(3):
        try:
          yield from self.open_drawer(dr)
          opened = True
          break
        except Retry:
          self.log.append((round(self.t, 2), 'retry', self.stage))
          yield from self.gripper(OPEN, 0.3)
          yield from self.retreat()
          yield from self.clear_cabinet()
      if not opened:
        self.log.append((round(self.t, 2), "drawer not opened: its lines skipped", dr))
        continue
      for ln in lines:
        yield from self.do_line(ln)
      for attempt in range(3):
        try:
          yield from self.close_drawer(dr)
          break
        except Retry:
          self.log.append((round(self.t, 2), 'retry', self.stage))
          yield from self.gripper(OPEN, 0.3)
          yield from self.retreat()
    yield from self.park()
    # last checks before reporting done: gripper echo and fresh tracker readings
    yield from self.gripper(OPEN - 0.001, 0.1)
    yield from self.gripper(OPEN, 0.1)
    yield from self._fresh(5)

  def do_line(self, ln):
    body = None
    for attempt in range(4):
      try:
        yield from self._fresh(2)
        if body is None or self.t - self.tracks[body].seen > 0.3:
          body = self.find_part(ln) if attempt == 0 or body is None else body
        if body is None:
          return
        in_drawer = self.to_cab(self.tracks[body].mean)[0] > -TRAVEL - 0.06 and \
            self.tracks[body].mean[2] > self.cab()[0][2] + 0.3
        a_place, tilt = yield from self.pick(body, ln, in_drawer)
        ok = yield from self.place(body, ln, a_place, tilt)
        if ok:
          return
      except Retry:
        self.log.append((round(self.t, 2), 'retry', self.stage))
        self.k.hold(None)
        yield from self.gripper(OPEN, 0.2)
        yield from self.retreat(up=0.05, back=0.0)

  def retreat(self, up=0.04, back=0.04):
    """Back the hand off after a failed step: along -approach and up if the cell model says it is clear, else
    straight back, else straight up, else stay."""
    self.sync_model()
    p, R = self.tcp()
    for d in (np.array([0, 0, up]) - R[:, 2] * back, -R[:, 2] * max(back, 0.03), np.array([0, 0, max(up, 0.03)])):
      if p[2] + d[2] > 0.80 or not np.any(d):
        continue
      if self.line_ok(p + d, R):
        yield from self.line(p + d, R, vmax=0.1, settle=0.0)
        return
    self.log.append((round(self.t, 2), "retreat blocked"))

  def clear_cabinet(self):
    """Straight back from the cabinet front when the hand is close to it (the servo lags a fast joint move by
    centimetres, so joint moves start clear of the drawers)."""
    self.sync_model()
    p, R = self.tcp()
    o, yaw = self.cab()
    u = np.array([math.cos(yaw), math.sin(yaw), 0.0])
    if float(self.to_cab(self.to_world(p))[0]) > -0.35 and p[2] > 0.25:
      for back in (0.12, 0.08, 0.04):
        tgt = p - u * back
        if self.line_ok(tgt, R, fingers=self.grip):
          yield from self.line(tgt, R, vmax=0.15, settle=0.0)
          return

  def park(self):
    """Back to the tucked pose, only along a path the cell model says is clear (otherwise stay put)."""
    self.stage = "park"
    self.sync_model()
    yield from self.clear_cabinet()
    p, R = self.tcp()
    if p[2] < 0.5:
      up = np.array([p[0], p[1], 0.5])
      if self.line_ok(up, R):
        yield from self.line(up, R, vmax=0.2, settle=0.0)
    if self.safe_q_path(HOME_Q):
      yield from self.move_q(HOME_Q, vmax=0.5, settle=0.2, fingers=OPEN)
      return
    for hub in self.hubs(HOME_Q):
      if self.safe_q_path(hub) and self.safe_q_path(HOME_Q, start=hub):
        yield from self.move_q(hub, vmax=0.5, settle=0.0, fingers=OPEN)
        yield from self.move_q(HOME_Q, vmax=0.5, settle=0.2, fingers=OPEN)
        return
    self.log.append((round(self.t, 2), "park: no safe path, staying"))