File size: 62,577 Bytes
69df7c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reference controller for cafe service cell CS-3 (Franka Panda): fill and serve a drinks ticket.

Staged loop (iteration skill), every stage closed on the overhead RGB-D camera, the fixture tracker or the
dispenser lamps:
  1. Camera check: the tray's footprint in the depth image is aligned with the tracker's tray pose (soft-mask
     fit). The tracker is noisy per reading, so the correction is re-derived as more readings are averaged. Cups
     are found in depth + colour; a cup cut off by the image border is located by a known-radius rim fit.
  2. Hand-eye check per work area (staging, dispenser front, tray side): the robot model is ray-cast at the
     commanded joint angles and registered to the measured depth (ICP: translation, then a small rigid fit). The
     offset absorbs mount height and lean, joint offsets and sag, so targets are commanded as world target minus
     offset.
  3. Per ticket line: pick a clean cup of the right size (yaw that keeps the hand clear of taller neighbours,
     force-limited close, opening checked against the cup size), carry it over the other staging cups, seat it
     under the nozzle (lowered until the cup lamp comes on; a search across the jaws if not), re-measure where
     the cup sits in the hand, hold still through the pour (easing the cup back if it creeps off the fill
     point), draw out gently (minimum-jerk, bounded acceleration), carry upright round the customer zone, enter
     it slowly from the best side (every stroke of the carry dry-run first), set the cup down slowly on its
     slot, release and back out.  A line that cannot be served ends the ticket (the dispenser pours in order),
     and so does running out of time, always with an empty hand.
  4. Check every served cup on the tray from the camera; a knocked cup is picked up again and re-seated.
  Faults: a gripper echo that differs from the command (dead gripper), a camera stamp that stops or frames that
  repeat while sensor noise has been seen (frozen camera) end in an abort.
"""
from __future__ import annotations

import math
import os
import sys

import mujoco
import numpy as np

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

# ---- cell sheet ----
CAM_POS = np.array([0.26, 0.0, 1.45])
CAM_R = np.array([[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])   # columns: camera x, y, z in world
CUPS = {"espresso": (0.028, 0.062), "flat_white": (0.031, 0.080), "takeaway": (0.034, 0.100)}
PLATE_H, TRAY_H = 0.015, 0.012
CYCLE_END_S = 150.0            # the cell is judged as it stands at this time
TRAY_HALF = (0.145, 0.225)
SLOT_POS = {f"{row}{j + 1}": ((-0.5 + i) * 0.13, (1 - j) * 0.14) for i, row in enumerate("AB") for j in range(3)}
ZONE_MARGIN = 0.03 + 0.03     # zone edge (30 mm) plus our own margin
OPEN = 0.04
SQUEEZE = 0.0030              # paper cup, past contact: about 7.5 N per pad measured (limit 10 N)
SQUEEZE_CERAMIC = 0.0085      # ceramic cups: about 15 N per pad, well under the 35 N squeeze limit


def squeeze_for(r):
  return SQUEEZE if r > 0.033 else SQUEEZE_CERAMIC
GRASP_BELOW_RIM = 0.021       # tool point this far below the rim: pads cover 12.5-29.5 mm below it
HOME_Q = np.array([0.0, -1.0, 0.0, -2.9, 0.0, 1.95, 0.785])
VIEW_Q = HOME_Q
HUB = np.array([0.42, 0.10])  # world xy of the transit point between the work areas


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


class Retry(Exception):
  pass


def _hsv(img):
  x = img.astype(np.float32) / 255.0
  r, g, b = x[..., 0], x[..., 1], x[..., 2]
  mx = x.max(-1)
  c = mx - x.min(-1)
  hue = np.zeros_like(mx)
  m = c > 1e-6
  rr = m & (mx == r)
  gg = m & (mx == g) & ~rr
  bb = m & ~rr & ~gg
  hue[rr] = (60 * ((g - b)[rr] / c[rr])) % 360
  hue[gg] = 60 * ((b - r)[gg] / c[gg]) + 120
  hue[bb] = 60 * ((r - g)[bb] / c[bb]) + 240
  sat = np.where(mx > 1e-6, c / np.maximum(mx, 1e-6), 0)
  return hue, sat, mx


def _rot_log(r):
  q = np.zeros(4)
  mujoco.mju_mat2Quat(q, np.ascontiguousarray(r).reshape(9))
  v = np.zeros(3)
  mujoco.mju_quat2Vel(v, q, 1.0)
  return v


def topdown(yaw):
  """Tool frame for a top-down grasp with the closing axis at `yaw` (approach straight down)."""
  c, s = math.cos(yaw), math.sin(yaw)
  return np.array([[-s, c, 0.0], [c, s, 0.0], [0.0, 0.0, -1.0]])


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


def _components(mask):
  """4-connected components of a boolean image: list of (rows, cols) arrays."""
  h, w = mask.shape
  lab = np.zeros((h, w), np.int32)
  out = []
  ys, xs = np.nonzero(mask)
  for y0, x0 in zip(ys, xs):
    if lab[y0, x0]:
      continue
    k = len(out) + 1
    stack = [(y0, x0)]
    lab[y0, x0] = k
    pts = []
    while stack:
      y, x = stack.pop()
      pts.append((y, x))
      for yy, xx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
        if 0 <= yy < h and 0 <= xx < w and mask[yy, xx] and not lab[yy, xx]:
          lab[yy, xx] = k
          stack.append((yy, xx))
    a = np.array(pts)
    out.append((a[:, 0], a[:, 1]))
  return out


def grasp_yaw_ok(xy, h, neighbours, yaw, margin=0.012):
  """Hand clearance for a top-down grasp (same rule as the integrator's note in task.py)."""
  u = np.array([math.cos(yaw), math.sin(yaw)])
  v = np.array([-u[1], u[0]])
  for nxy, nr, nh in neighbours:
    rel = np.asarray(nxy) - np.asarray(xy)
    a, c = abs(float(rel @ u)), abs(float(rel @ v))
    if a < 0.0663 + nr + margin and c < 0.0105 + nr + margin:
      return False
    if nh > h + 0.012 and a < 0.104 + nr + margin and c < 0.032 + nr + margin:
      return False
  return True


def _nn(a, b):
  """Nearest point of b for every point of a: (index, distance)."""
  d2 = (a * a).sum(1)[:, None] + (b * b).sum(1)[None, :] - 2.0 * (a @ b.T)
  j = np.argmin(d2, 1)
  return j, np.sqrt(np.maximum(d2[np.arange(len(a)), j], 0.0))


class Frame:
  """One RGB-D frame; the point cloud and colour channels are computed on first use."""

  def __init__(self, obs, K, cam_off):
    self.stamp = float(obs["camera_stamp"])
    self.img = obs["images"]["overhead"]
    self.depth = obs["depth"]["overhead"]
    self.K = K
    self.cam_off = np.array(cam_off, float)

  def __getattr__(self, name):
    if name in ("P", "valid"):
      fx, fy, cx, cy = self.K
      h, w = self.depth.shape
      u = np.arange(w)[None, :] + 0.5
      v = np.arange(h)[:, None] + 0.5
      d = self.depth
      pc = np.stack([(u - cx) / fx * d, -(v - cy) / fy * d, -d], -1)
      self.P = pc @ CAM_R.T + CAM_POS
      self.P[..., :2] -= self.cam_off
      self.valid = (d > 0.3) & (d < 1.6)
      return getattr(self, name)
    if name in ("hue", "sat", "val"):
      self.hue, self.sat, self.val = _hsv(self.img)
      return getattr(self, name)
    raise AttributeError(name)


class Controller:
  def __init__(self, model_info):
    self.info = model_info
    self.dt = float(model_info["control_dt_s"])
    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)
    cam = model_info["cameras"][0]
    f = 0.5 * cam["height"] / math.tan(math.radians(cam["fovy_deg"]) / 2)
    self.K = (f, f, cam["width"] / 2.0, cam["height"] / 2.0)
    self.cam_period = 1.0 / float(model_info.get("perception_hz", 2.0))
    app = os.path.dirname(model_info["scene_xml"])
    self.rm = mujoco.MjModel.from_xml_path(os.path.join(app, "robot", "panda.xml"))
    self.rd = mujoco.MjData(self.rm)
    self.tcp = self.rm.site("tcp").id
    self.jlo = self.rm.jnt_range[:7, 0].copy()
    self.jhi = self.rm.jnt_range[:7, 1].copy()
    names = {"hand", "left_finger", "right_finger", "link7", "link6"}
    self.cal_bodies = np.array([self.rm.body(b).name in names for b in range(self.rm.nbody)])
    sys.path.insert(0, os.path.join(app, "skills", "motion-planning", "scripts"))
    try:
      import motion_planner as mp
      self.planner = mp.RobotArmPlanner(mjcf_path=os.path.join(app, "robot", "panda.xml"))
    except Exception:  # noqa: BLE001
      self.planner = None

  # ================================================================ gauntlet interface
  def reset(self, obs):
    self.obs = obs
    self.t = float(obs["time"])
    self.qcmd = np.array(obs["ctrl"][:7], float)
    self.grip = OPEN
    self.sent = None
    self.bias_sum, self.bias_n, self.open_ticks, self.finger_bias = 0.0, 0, 21, 0.0
    self.frames = []
    self.last_stamp = None
    self.last_stamp_time = self.t
    self.same_count = 0
    self.noise_seen = False
    self.cam_off = np.zeros(2)
    self.cam_tray = None
    self.offs = []           # [(belief tcp position, offset)]
    self.hand_off = 0.0      # held cup axis minus tool point, along the hand x axis
    self.log = []
    self.ticket = [dict(x) for x in obs["io"]["ticket"]]
    self.fix = {}
    self._ingest(obs)
    self.gen = self._run()

  def act(self, obs):
    self.obs = obs
    self.t = float(obs["time"])
    if self.sent is not None and abs(float(obs["ctrl"][7]) - float(self.sent[7])) > 1e-7:
      return {"status": "abort", "fault": "dead_gripper"}
    if self.sent is None or float(self.sent[7]) >= OPEN - 1e-9:
      self.open_ticks += 1
      if self.open_ticks > 20 and abs(float(obs["qvel"][7])) < 0.01:
        self.bias_sum += float(obs["qpos"][7]) - OPEN
        self.bias_n += 1
        self.finger_bias = self.bias_sum / self.bias_n
    else:
      self.open_ticks = 0
    try:
      self._ingest(obs)
      cmd = next(self.gen)
    except StopIteration:
      return {"status": "done"}
    except Abort as a:
      return {"status": "abort", "fault": a.fault}
    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 bookkeeping
  def _ingest(self, obs):
    for name, pose in obs.get("objects", {}).items():
      pose = np.array(pose, float)
      hist = self.fix.setdefault(name, [])
      if not hist or not np.array_equal(hist[-1], pose):     # fixtures are static: average every new reading
        hist.append(pose)
        del hist[:-400]
    st = obs.get("camera_stamp")
    if st is None or "overhead" not in obs.get("depth", {}):
      return
    if self.last_stamp is None or st != self.last_stamp:
      fr = Frame(obs, self.K, self.cam_off)
      if self.frames:
        prev = self.frames[-1]
        same = np.array_equal(prev.depth, fr.depth)
        if not same and not np.array_equal(prev.depth[:16, :16], fr.depth[:16, :16]):
          self.noise_seen = True
        self.same_count = self.same_count + 1 if same else 0
        if self.same_count >= 2 and self.noise_seen:
          raise Abort("perception_freeze")
      self.frames = (self.frames + [fr])[-3:]
      self.last_stamp = st
      self.last_stamp_time = self.t
    elif self.t - self.last_stamp_time > 3.2 * self.cam_period:
      raise Abort("perception_freeze")

  def _fresh(self, after, timeout=2.5):
    """Holds the arm until a camera frame rendered after `after` arrives; returns it."""
    t0 = self.t
    while True:
      if self.frames and self.frames[-1].stamp >= after - 1e-9:
        return self.frames[-1]
      if self.t - t0 > timeout:
        raise Abort("perception_freeze")
      yield self._cmd()

  def _fixture(self, name):
    return np.mean(np.array(self.fix[name]), axis=0)

  # ================================================================ kinematics
  def _cmd(self):
    return np.concatenate([self.qcmd, [self.grip]])

  def _fk(self, q, fingers=OPEN):
    self.rd.qpos[:7] = q
    self.rd.qpos[7:9] = fingers
    mujoco.mj_kinematics(self.rm, self.rd)
    return self.rd.site_xpos[self.tcp].copy(), self.rd.site_xmat[self.tcp].reshape(3, 3).copy()

  def _ik_local(self, q, pos, rot, iters=4, lam=0.02):
    q = np.array(q, float)
    jp = np.zeros((3, self.rm.nv))
    jr = np.zeros((3, self.rm.nv))
    for _ in range(iters):
      p, r = self._fk(q)
      e = np.concatenate([pos - p, r @ _rot_log(r.T @ rot)])
      if np.linalg.norm(e[:3]) < 2e-5 and np.linalg.norm(e[3:]) < 2e-4:
        break
      mujoco.mj_comPos(self.rm, self.rd)
      mujoco.mj_jacSite(self.rm, self.rd, jp, jr, self.tcp)
      j = np.vstack([jp[:, :7], jr[:, :7]])
      dq = j.T @ np.linalg.solve(j @ j.T + lam ** 2 * np.eye(6), e)
      n = float(np.linalg.norm(dq))
      if n > 0.4:
        dq *= 0.4 / n
      q = np.clip(q + dq, self.jlo + 0.01, self.jhi - 0.01)
    p, r = self._fk(q)
    err = float(np.linalg.norm(pos - p)) + 0.2 * float(np.linalg.norm(_rot_log(r.T @ rot)))
    return q, err

  def _ik(self, pos, yaw, seed):
    """IK for a top-down tool pose; tries the yaw and its 180-degree twin, returns (q, yaw) or (None, yaw)."""
    best = None
    az = math.atan2(pos[1], pos[0])
    canon = np.array([az, 0.3, 0.0, -2.2, 0.0, 2.5, 0.785])
    for yw in (yaw, _wrap(yaw + math.pi)):
      rot = topdown(yw)
      seeds = []
      for base in (np.asarray(seed, float), canon, HOME_Q):
        seeds.append(base.copy())
        s3 = base.copy()
        _, r0 = self._fk(base)
        s3[6] = float(np.clip(s3[6] + _wrap(yw - math.atan2(r0[1, 1], r0[0, 1])), self.jlo[6] + 0.05, self.jhi[6] - 0.05))
        seeds.append(s3)
      for s in seeds:
        q, err = self._ik_local(s, pos, rot, iters=60)
        if err < 5e-4:
          margin = float(np.min(np.minimum(q - self.jlo, self.jhi - q)))
          cost = float(np.sum(np.abs(q - seed))) - 2.0 * min(margin, 0.25)
          if best is None or cost < best[0]:
            best = (cost, q, yw)
    if best is None and self.planner is not None:
      for yw in (yaw, _wrap(yaw + math.pi)):
        try:
          res = self.planner.solve_ik(np.asarray(pos, float), topdown(yw), q_seed=np.asarray(seed, float), num_restarts=6)
        except Exception:  # noqa: BLE001
          continue
        q, err = self._ik_local(np.asarray(res["q"], float), pos, topdown(yw), iters=40)
        if err < 5e-4:
          return q, yw
    if best is None:
      return None, yaw
    return best[1], best[2]

  def _tcp_yaw(self, q):
    _, r = self._fk(q)
    return math.atan2(r[1, 1], r[0, 1])

  # ================================================================ offsets (world - belief)
  def _off(self, p_world):
    if not self.offs:
      return np.zeros(3)
    d = [np.linalg.norm(p_world[:2] - (b[:2] + o[:2])) for b, o in self.offs]
    i = int(np.argmin(d))
    return self.offs[i][1]

  def _belief(self, p_world):
    return np.asarray(p_world, float) - self._off(p_world)

  def _calibrate_here(self):
    """Hand-eye check at the current (settled) pose; stores the offset for this work area."""
    yield from self._hold(0.15)
    fr = yield from self._fresh(self.t + 0.01)
    off = self._icp(fr, self.qcmd.copy(), self.grip)
    p, _ = self._fk(self.qcmd)
    self.log.append(("cal", np.round(p, 3).tolist(), None if off is None else np.round(off, 4).tolist()))
    if off is not None:
      self.offs = [(b, o) for b, o in self.offs if np.linalg.norm(b[:2] - p[:2]) > 0.12] + [(p, off)]
    return off

  def _icp(self, fr, q, grip):
    self.rd.qpos[:7] = q
    self.rd.qpos[7:9] = grip
    mujoco.mj_kinematics(self.rm, self.rd)
    p, _ = self._fk(q, grip)
    fx, fy, cx, cy = self.K
    h, w = fr.depth.shape
    rel = CAM_R.T @ (p - CAM_POS)
    u0, v0 = cx + fx * rel[0] / -rel[2], cy - fy * rel[1] / -rel[2]
    us = np.arange(max(0, int(u0) - 40), min(w, int(u0) + 40))
    vs = np.arange(max(0, int(v0) - 40), min(h, int(v0) + 40))
    if len(us) < 10 or len(vs) < 10:
      return None
    uu, vv = np.meshgrid(us, vs)
    uu, vv = uu.ravel(), vv.ravel()
    dirs = np.stack([(uu + 0.5 - cx) / fx, -(vv + 0.5 - cy) / fy, -np.ones(len(uu))], -1) @ CAM_R.T
    dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
    n = len(dirs)
    gid = np.zeros(n, np.int32)
    dist = np.zeros(n)
    mujoco.mj_multiRay(self.rm, self.rd, CAM_POS, dirs.ravel(), np.array([0, 0, 1, 0, 0, 0], np.uint8), 1, -1,
                       gid, dist, None, n, 3.0)
    hit = gid >= 0
    hit[hit] = self.cal_bodies[self.rm.geom_bodyid[gid[hit]]]
    if hit.sum() < 40:
      return None
    pred = CAM_POS + dirs[hit] * dist[hit, None]
    sil = np.zeros((h, w), bool)
    sil[vv[hit], uu[hit]] = True
    # dilate the predicted silhouette by 6 px (mount and joint errors move the arm by up to ~4 cm)
    dil = sil.copy()
    for _ in range(6):
      d2 = dil.copy()
      d2[1:] |= dil[:-1]; d2[:-1] |= dil[1:]; d2[:, 1:] |= dil[:, :-1]; d2[:, :-1] |= dil[:, 1:]
      dil = d2
    pts = fr.P
    # (and nothing well below the hand: a full cup under it would drag the fit)
    ok = dil & fr.valid & (fr.sat < 0.3) & (pts[..., 2] > max(0.03, float(pred[:, 2].min()) - 0.012))
    meas = pts[ok]
    if len(meas) < 40:
      return None
    rng = np.random.default_rng(0)
    if len(pred) > 500:
      pred = pred[rng.choice(len(pred), 500, replace=False)]
    if len(meas) > 400:
      meas = meas[rng.choice(len(meas), 400, replace=False)]
    best = None
    starts = [np.zeros(3), np.array([0, 0, 0.025]), np.array([0, 0, -0.025])]
    if self.offs:
      near = min(self.offs, key=lambda bo: float(np.linalg.norm(bo[0][:2] - p[:2])))[1]
      starts = [near.copy(), np.zeros(3)]
    for off in starts:
      off = -off.copy()       # ICP works on meas + x = pred, x = -(world - belief)
      good = True
      for gate in (0.04, 0.03, 0.02, 0.015, 0.01, 0.008, 0.008, 0.008):
        m2 = meas + off
        j, dd = _nn(m2, pred)
        k = dd < gate
        if k.sum() < 25:
          good = False
          break
        off = off + np.median(pred[j[k]] - m2[k], axis=0)
      if not good:
        continue
      m2 = meas + off
      _, dd = _nn(m2, pred)
      score = int((dd < 0.005).sum())
      if best is None or score > best[0]:
        best = (score, off)
    if best is None or best[0] < 25:
      return None
    # refinement against a model cloud ray-cast at half-pixel spacing (the coarse match is biased by sampling
    # both clouds on the same pixel grid)
    off = best[1]
    sil1 = sil.copy()
    sil1[1:] |= sil[:-1]; sil1[:-1] |= sil[1:]; sil1[:, 1:] |= sil[:, :-1]; sil1[:, :-1] |= sil[:, 1:]
    vv1, uu1 = np.nonzero(sil1)
    sub = np.array([[-0.25, -0.25], [0.25, -0.25], [-0.25, 0.25], [0.25, 0.25]])
    uf = (uu1[:, None] + 0.5 + sub[None, :, 0]).ravel()
    vf = (vv1[:, None] + 0.5 + sub[None, :, 1]).ravel()
    dirs = np.stack([(uf - cx) / fx, -(vf - cy) / fy, -np.ones(len(uf))], -1) @ CAM_R.T
    dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
    n = len(dirs)
    gid = np.zeros(n, np.int32)
    dist = np.zeros(n)
    mujoco.mj_multiRay(self.rm, self.rd, CAM_POS, dirs.ravel(), np.array([0, 0, 1, 0, 0, 0], np.uint8), 1, -1,
                       gid, dist, None, n, 3.0)
    hit = gid >= 0
    hit[hit] = self.cal_bodies[self.rm.geom_bodyid[gid[hit]]]
    pf = CAM_POS + dirs[hit] * dist[hit, None]
    if len(pf) < 100:
      return -off
    _, dn = _nn(pf, meas + off)
    pf = pf[dn < 0.015]
    if len(pf) < 50:
      return -off
    for gate in (0.012, 0.008, 0.006, 0.005, 0.005, 0.005):
      m2 = meas + off
      j, dd = _nn(m2, pf)
      k = dd < gate
      if k.sum() < 25:
        break
      off = off + 1.7 * np.mean(pf[j[k]] - m2[k], axis=0)
    # rigid refinement (rotation too): a tilted mount turns the wrist links, and a translation-only fit of
    # links that sit up to 0.3 m above the tool point would be biased.  world ~ R model + t.
    R, t = np.eye(3), -off
    for gate in (0.006, 0.005, 0.004, 0.004, 0.004, 0.004):
      pw = pf @ R.T + t
      j, dd = _nn(meas, pw)
      k = dd < gate
      if k.sum() < 40:
        break
      a, b = pf[j[k]], meas[k]
      ca, cb = a.mean(0), b.mean(0)
      U, _, Vt = np.linalg.svd((a - ca).T @ (b - cb))
      D = np.diag([1.0, 1.0, np.sign(np.linalg.det(Vt.T @ U.T))])
      Rn = Vt.T @ D @ U.T
      if np.degrees(np.arccos(np.clip((np.trace(Rn) - 1) / 2, -1, 1))) > 4.0:
        break
      R, t = Rn, cb - Rn @ ca
    return R @ p + t - p

  # ================================================================ motion primitives
  def _hold(self, seconds):
    for _ in range(max(1, int(round(seconds / self.dt)))):
      yield self._cmd()

  def _move_q(self, q_goal, vmax=1.2, settle=0.15, tmin=0.4):
    """Minimum-jerk joint move.  If the tool point's path crosses the customer zone, the move is slowed so
    that the tool point stays under the zone's speed limit."""
    q0 = self.qcmd.copy()
    dq = np.asarray(q_goal) - q0
    T = max(tmin, 1.875 * float(np.max(np.abs(dq))) / vmax)
    pts = []
    for s in np.linspace(0.0, 1.0, 21):
      pb, _ = self._fk(q0 + s * dq)
      pts.append(pb + self._off(pb))
    if any(self._in_zone(pw, 0.03) for pw in pts):
      L = float(sum(np.linalg.norm(pts[i + 1] - pts[i]) for i in range(len(pts) - 1)))
      T = max(T, 1.875 * L / 0.16)
    n = int(math.ceil(T / self.dt))
    for i in range(1, n + 1):
      s = i / n
      s = s * s * s * (10 - 15 * s + 6 * s * s)
      self.qcmd = q0 + s * dq
      yield self._cmd()
    yield from self._hold(settle)

  def _staging_clear(self, q0, q1):
    """True when a joint move keeps the hand (and a held cup) above the cups still on the staging arc."""
    if self.grip < OPEN - 0.002:
      hang, reach = self.cup_z_off + 0.004, self.grip + 0.02
    else:
      hang, reach = 0.015, 0.06
    cups = [c for c in getattr(self, "staging", []) if not c["used"]]
    if not cups:
      return True
    for s in np.linspace(0.0, 1.0, 21):
      pb, _ = self._fk(q0 + s * (q1 - q0))
      pw = pb + self._off(pb)
      for c in cups:
        R, H = CUPS[c["kind"]]
        if np.linalg.norm(pw[:2] - c["xy"]) < R + reach + 0.03 and pw[2] - hang < H + 0.025:
          return False
    return True

  def _move_q_safe(self, q_goal, yaw, **kw):
    """Joint move that first climbs above the staging cups (and crosses over them in a straight line) when the
    direct joint path would sweep the hand or the held cup through one."""
    if self._staging_clear(self.qcmd, q_goal):
      yield from self._move_q(q_goal, **kw)
      return
    hang = self.cup_z_off + 0.004 if self.grip < OPEN - 0.002 else 0.015
    z_safe = 0.10 + 0.04 + hang
    p = self._tcp_world()
    pg, _ = self._fk(q_goal)
    pg = pg + self._off(pg)
    self.log.append(("over_staging", np.round(p, 3).tolist(), np.round(pg, 3).tolist()))
    if p[2] < z_safe:
      yield from self._line_safe(np.array([p[0], p[1], z_safe]), vmax=0.5, amax=2.5, settle=0.0)
    zt = max(z_safe, pg[2])
    qh, _ = self._ik(self._belief(np.array([pg[0], pg[1], zt])), yaw, self.qcmd)
    if qh is not None and self._staging_clear(self.qcmd, qh):
      yield from self._move_q(qh, **kw)          # a joint swing between two high poses stays high
    else:
      yield from self._line_safe(np.array([pg[0], pg[1], zt]), yaw, vmax=0.6, amax=1.5, settle=0.0)
    q, _ = self._ik(self._belief(pg), yaw, self.qcmd)
    if q is None:
      q = q_goal
    yield from self._move_q(q, **kw)

  def _in_zone(self, p_world, margin=0.015):
    if "tray" not in self.fix:
      return False
    tray = self._fixture("tray")
    yaw = math.atan2(2 * (tray[3] * tray[6] + tray[4] * tray[5]), 1 - 2 * (tray[5] ** 2 + tray[6] ** 2))
    c, s = math.cos(yaw), math.sin(yaw)
    loc = np.array([[c, s], [-s, c]]) @ (np.asarray(p_world[:2]) - tray[:2])
    return (abs(loc[0]) < TRAY_HALF[0] + 0.03 + margin and abs(loc[1]) < TRAY_HALF[1] + 0.03 + margin
            and p_world[2] < 0.45 + margin)

  def _line(self, p_world, yaw=None, vmax=0.25, amax=1.5, settle=0.1, wmax=1.2):
    """Straight top-down Cartesian stroke (minimum-jerk timing) to a world target; raises Retry if IK fails.
    Inside the customer zone the stroke is slowed to 0.21 m/s."""
    qs = self._plan_line(self.qcmd, p_world, yaw, vmax, amax, wmax)
    for q in qs:
      self.qcmd = q
      yield self._cmd()
    yield from self._hold(settle)

  def _plan_line(self, q0, p_world, yaw=None, vmax=0.25, amax=1.5, wmax=1.2, log=True, tol=0.0045):
    p0b, r0 = self._fk(q0)
    y0 = math.atan2(r0[1, 1], r0[0, 1])
    y1 = y0 if yaw is None else y0 + _wrap(yaw - y0)
    if yaw is not None and abs(_wrap(yaw - y0)) > math.pi / 2:
      y1 = y0 + _wrap(yaw + math.pi - y0)
    p1b = self._belief(p_world)
    p0w = p0b + self._off(p0b)
    if any(self._in_zone(p0w + t * (np.asarray(p_world) - p0w)) for t in np.linspace(0, 1, 9)):
      vmax, amax = min(vmax, 0.21), min(amax, 1.2)
    D = float(np.linalg.norm(p1b - p0b))
    T = max(0.3, 1.875 * D / vmax, math.sqrt(5.774 * D / amax), 1.875 * abs(y1 - y0) / wmax)
    for _attempt in range(3):
      n = int(math.ceil(T / self.dt))
      q = np.array(q0, float)
      qs = []
      jump = 0.0
      for i in range(1, n + 1):
        s = i / n
        s = s * s * s * (10 - 15 * s + 6 * s * s)
        q, err = self._ik_local(q, p0b + s * (p1b - p0b), topdown(y0 + s * (y1 - y0)), iters=6)
        if err > 0.002:              # not converged yet: iterate longer before giving up on the stroke
          q, err = self._ik_local(q, p0b + s * (p1b - p0b), topdown(y0 + s * (y1 - y0)), iters=30)
        if err > tol:
          if log:
            self.log.append(("line_fail", np.round(p_world, 3).tolist(), round(err, 4)))
          raise Retry()
        jump = max(jump, float(np.max(np.abs(q - (qs[-1] if qs else q0)))))
        qs.append(q)
      if jump <= 2.5 * self.dt:
        return qs
      if jump > 0.5:             # a branch flip, not just a fast stretch
        if log:
          self.log.append(("line_flip", np.round(p_world, 3).tolist(), round(jump, 3)))
        raise Retry()
      T *= 1.2 * jump / (2.5 * self.dt)
    if log:
      self.log.append(("line_slow", np.round(p_world, 3).tolist()))
    raise Retry()

  def _line_safe(self, p_world, yaw=None, **kw):
    """A stroke that must not fail while a cup is held: straight, else via a raised midpoint, else a slow
    joint move."""
    try:
      yield from self._line(p_world, yaw, **kw)
      return
    except Retry:
      pass
    p0 = self._tcp_world()
    mid = 0.5 * (p0 + np.asarray(p_world)) + np.array([0, 0, 0.04])
    try:
      yield from self._line(mid, yaw, **kw)
      yield from self._line(p_world, yaw, **kw)
      return
    except Retry:
      pass
    # last resort: short joint moves between IK solutions along the stroke, so the hand stays top-down
    # (one long joint move would tip a held cup)
    y = self._tcp_yaw(self.qcmd) if yaw is None else yaw
    p0 = self._tcp_world()
    q = self.qcmd.copy()
    for t in np.linspace(0.0, 1.0, 9)[1:]:
      qn, y = self._ik(self._belief(p0 + t * (np.asarray(p_world) - p0)), y, q)
      if qn is None or float(np.max(np.abs(qn - q))) > 0.5:
        self.log.append(("safe_fail", np.round(p_world, 3).tolist()))
        return
      yield from self._move_q(qn, vmax=0.4, settle=0.0, tmin=0.15)
      q = qn
    yield from self._hold(0.1)

  def _go_high(self, p_world, yaw, vmax=1.0):
    """Joint-space move to a top-down pose (empty hand or free space)."""
    q, yw = self._ik(self._belief(p_world), yaw, self.qcmd)
    if q is None:
      self.log.append(("ik_fail", np.round(p_world, 3).tolist()))
      raise Retry()
    yield from self._move_q(q, vmax=vmax, settle=0.1)
    return yw

  def _grip_to(self, target, seconds=0.4):
    g0 = self.grip
    n = max(1, int(round(seconds / self.dt)))
    for i in range(1, n + 1):
      self.grip = g0 + (target - g0) * i / n
      yield self._cmd()

  def _finger(self, ticks=15):
    hist = []
    for _ in range(ticks):
      yield self._cmd()
      hist.append(float(self.obs["qpos"][7]))
    return float(np.mean(hist[-10:])) - self.finger_bias

  def _held_target(self, xy):
    """Tool point xy that puts the held cup's axis over xy (the cup sits off the pad centre by hand_off)."""
    y = self._tcp_yaw(self.qcmd)
    return np.asarray(xy, float) - self.hand_off * np.array([-math.sin(y), math.cos(y)])

  def _tcp_world(self):
    p, _ = self._fk(self.qcmd)
    return p + self._off(p)

  # ================================================================ perception
  def _camera_check(self, fr):
    """Camera xy correction: aligns the tray's footprint in the depth image with the fixture tracker's tray pose."""
    tray = self._fixture("tray")
    P = fr.P
    ctr = tray[:2].copy()
    m = fr.valid & (np.linalg.norm(P[..., :2] - ctr, axis=-1) < 0.34) & (P[..., 2] < 0.03) & (P[..., 2] > -0.01)
    pts = P[m]
    if len(pts) < 500:
      return
    lab = np.clip(pts[:, 2] / TRAY_H, 0.0, 1.0)
    yaw = math.atan2(2 * (tray[3] * tray[6] + tray[4] * tray[5]), 1 - 2 * (tray[5] ** 2 + tray[6] ** 2))
    c, s = math.cos(yaw), math.sin(yaw)
    rot = np.array([[c, -s], [s, c]])
    loc = (pts[:, :2] - ctr) @ rot
    soft = 0.0025

    def cost(sh):            # sh: (k, 2) world shifts; returns the squared mismatch for each
      ls = sh @ rot
      dx = TRAY_HALF[0] - np.abs(loc[None, :, 0] - ls[:, None, 0])
      dy = TRAY_HALF[1] - np.abs(loc[None, :, 1] - ls[:, None, 1])
      pred = 1.0 / (1.0 + np.exp(-np.minimum(dx, dy) / soft))
      return ((pred - lab[None]) ** 2).sum(1)

    best = np.zeros(2)
    for span, step in ((0.016, 0.002), (0.002, 0.0004), (0.0004, 0.0001)):
      g = np.arange(-span, span + 1e-9, step)
      cand = best + np.stack(np.meshgrid(g, g), -1).reshape(-1, 2)
      cs = np.concatenate([cost(cand[k:k + 64]) for k in range(0, len(cand), 64)])
      best = cand[int(np.argmin(cs))]
    shift = best
    self.log.append(("camcheck", np.round(shift, 4).tolist(), int(len(pts))))
    if np.linalg.norm(shift) < 0.03:
      self.cam_tray = ctr + shift + self.cam_off      # tray centre as the uncorrected camera sees it
      self._shift_frame(shift)

  def _shift_frame(self, delta):
    """Moves the camera correction by delta: frames, staging cups and arm offsets follow."""
    self.cam_off = self.cam_off + delta
    for f in self.frames:
      if "P" in f.__dict__:
        f.P[..., :2] -= delta
      else:
        f.cam_off = f.cam_off + delta
    for c in getattr(self, "staging", []):
      c["xy"] = c["xy"] - delta
    self.offs = [(b, np.concatenate([o[:2] - delta, o[2:]])) for b, o in self.offs]

  def _update_cam(self):
    """Re-derives the camera correction as more fixture-tracker readings of the tray arrive."""
    if getattr(self, "cam_tray", None) is None:
      return
    delta = self.cam_tray - self._fixture("tray")[:2] - self.cam_off
    if 1e-4 < np.linalg.norm(delta) < 0.03:
      self._shift_frame(delta)

  def _cups_in(self, fr, region):
    """Cups seen in a region: list of dicts (xy, kind, top)."""
    P = fr.P
    base = {"staging": 0.0, "tray": TRAY_H}[region]
    m = fr.valid & (fr.sat > 0.2) & (fr.val > 0.18) & (P[..., 2] > base + 0.035) & (P[..., 2] < base + 0.13)
    xy = P[..., :2]
    if region == "staging":
      r = np.linalg.norm(xy, axis=-1)
      a = np.degrees(np.arctan2(xy[..., 1], xy[..., 0]))
      m &= (r > 0.32) & (r < 0.72) & (a > 8) & (a < 128)
    else:
      tray = self._fixture("tray")
      m &= np.linalg.norm(xy - tray[:2], axis=-1) < 0.30
    out = []
    for rows, cols in _components(m):
      if len(rows) < 8:
        continue
      pts = P[rows, cols]
      top = float(np.percentile(pts[:, 2], 85))
      hgt = top - base
      kind = min(CUPS, key=lambda k: abs(CUPS[k][1] - hgt))
      if abs(CUPS[kind][1] - hgt) > 0.010:
        continue
      sel = pts[:, 2] > top - (0.006 if region == "staging" else 0.003)
      band = pts[sel]
      xy_c = band[:, :2].mean(0)
      h_img, w_img = m.shape
      br, bc = rows[sel], cols[sel]
      if br.min() == 0 or bc.min() == 0 or br.max() == h_img - 1 or bc.max() == w_img - 1:
        xy_c = self._rim_fit(br, bc, band[:, :2], CUPS[kind][0], top, (h_img, w_img), xy_c)
      out.append({"xy": xy_c, "kind": kind, "top": top, "n": len(rows)})
    return out

  def _rim_fit(self, rows, cols, xy, r, top, shape, c0):
    """Centre of a cup top cut off by the image border: known-radius circle fit to its visible rim pixels."""
    h, w = shape
    occ = np.zeros(shape, bool)
    occ[rows, cols] = True
    pad = np.pad(occ, 1)
    inner = pad[:-2, 1:-1] & pad[2:, 1:-1] & pad[1:-1, :-2] & pad[1:-1, 2:]
    rim = ~inner[rows, cols] & (rows > 0) & (cols > 0) & (rows < h - 1) & (cols < w - 1)
    pts = xy[rim]
    if len(pts) < 6:
      return c0
    px = (CAM_POS[2] - top) / self.K[0]
    rr = r - 0.5 * px
    c = c0.copy()
    for _ in range(20):
      dv = pts - c
      dist = np.linalg.norm(dv, axis=1) + 1e-9
      J = -dv / dist[:, None]
      res = dist - rr
      step = np.linalg.lstsq(J, -res, rcond=None)[0]
      c = c + step
      if np.linalg.norm(step) < 1e-5:
        break
    return c if np.linalg.norm(c - c0) < 0.03 else c0

  # ================================================================ the job
  def _run(self):
    fr = yield from self._fresh(0.0)
    yield from self._hold(0.3)
    self._camera_check(self.frames[-1])
    fr = yield from self._fresh(self.t + 0.01)
    self.staging = self._cups_in(fr, "staging")
    self.log.append(("staging", [(c["kind"], np.round(c["xy"], 3).tolist()) for c in self.staging]))
    for c in self.staging:
      c["used"] = False
    self.served = []           # (xy, radius, height) of cups set on the tray
    for line in self.ticket:
      r, h = CUPS[line["cup"]]
      for attempt in range(4):
        if self.t > CYCLE_END_S - 24.0:     # no time left for another cup: finish with an empty hand
          break
        self._update_cam()
        try:
          cup = self._choose_cup(line["cup"])
          self.log.append(("t_pick", round(self.t, 2)))
          yield from self._pick(cup, r, h)
        except Retry:
          yield from self._recover()
          continue
        cup["used"] = True
        self.log.append(("t_fill", round(self.t, 2)))
        try:
          ok = yield from self._fill(line, r, h)
        except Retry:
          ok = False
        if not ok:
          yield from self._put_back(cup, r, h)
          cup["used"] = False
          yield from self._recover()      # the cup went down where the hand held it: look again
          continue
        self.log.append(("t_deliver", round(self.t, 2)))
        yield from self._deliver(line, r, h)
        self.log.append(("t_done", round(self.t, 2)))
        break
      if not line.get("placed"):
        # the dispenser pours lines strictly in order, so nothing after an unserved line can be served
        self.log.append(("give_up", line["line"]))
        break
    yield from self._final_check()
    yield from self._park()

  def _park(self):
    p = self._tcp_world()
    if p[2] < 0.25:
      try:
        yield from self._line(np.array([p[0], p[1], 0.30]), vmax=0.3, settle=0.0)
      except Retry:
        pass
    if self.grip < OPEN:
      yield from self._grip_to(OPEN, 0.3)
    yield from self._move_q(HOME_Q, vmax=1.5, settle=0.2)
    # gripper check before reporting done: a servo that died after the last grip move only shows once it is
    # commanded again (act() compares the echo with every command)
    yield from self._grip_to(OPEN - 0.004, 0.1)
    yield from self._grip_to(OPEN, 0.1)

  def _recover(self):
    """After a failed pick (hand open): rise, go to the view pose and look at the staging area again."""
    p = self._tcp_world()
    if p[2] < 0.22:
      try:
        yield from self._line(np.array([p[0], p[1], 0.25]), vmax=0.2, amax=1.0, settle=0.0)
      except Retry:
        pass
    if self.grip < OPEN:
      yield from self._grip_to(OPEN, 0.3)
    yield from self._move_q(VIEW_Q, vmax=1.5, settle=0.2)
    fr = yield from self._fresh(self.t + 0.01)
    seen = self._cups_in(fr, "staging")
    for c in self.staging:
      if c["used"]:
        continue
      near = [s for s in seen if s["kind"] == c["kind"] and np.linalg.norm(s["xy"] - c["xy"]) < 0.12]
      if near:
        s = min(near, key=lambda s: np.linalg.norm(s["xy"] - c["xy"]))
        c["xy"] = s["xy"]
        c["lost"] = False
      else:
        c["lost"] = True

  def _choose_cup(self, kind):
    cand = [c for c in self.staging if not c["used"] and not c.get("lost") and c["kind"] == kind]
    if not cand:
      raise Retry()
    return min(cand, key=lambda c: abs(math.atan2(c["xy"][1], c["xy"][0])))   # nearest the dispenser first

  # ---------------------------------------------------------------- pick
  def _pick(self, cup, r, h):
    xy = cup["xy"]
    others = [(c["xy"], CUPS[c["kind"]][0], CUPS[c["kind"]][1]) for c in self.staging if c is not cup and not c["used"]]
    radial = math.atan2(xy[1], xy[0])
    yaws = sorted((math.radians(a) for a in range(0, 180, 10)),
                  key=lambda y: abs(_wrap(2 * (y - radial - math.pi / 2))))
    yaws = [y for y in yaws if grasp_yaw_ok(xy, h, others, y)] or yaws[:1]
    z_grasp = h - GRASP_BELOW_RIM
    hover = np.array([xy[0], xy[1], h + 0.09])
    p = self._tcp_world()
    if p[2] < 0.18:
      yield from self._line(np.array([p[0], p[1], 0.22]), vmax=0.4, settle=0.0)
    yaw = None
    for y in yaws[:6]:
      q, yw = self._ik(self._belief(hover), y, self.qcmd)
      if q is not None:
        yaw = yw
        break
    if yaw is None:
      raise Retry()
    yield from self._move_q_safe(q, yaw, vmax=2.4, settle=0.05)
    if not self._has_off(hover, 0.10):
      if xy[0] < -0.07:
        # the far left of the arc is at the image edge, where the hand is only partly in view: check the
        # hand-eye offset a little further in, then come back over the cup
        yield from self._line(np.array([-0.07, xy[1], hover[2]]), yaw, vmax=0.4, settle=0.0)
      yield from self._calibrate_here()
      yield from self._line(hover, yaw, vmax=0.2, settle=0.0)
    if self.grip < min(OPEN, r + 0.006) - 1e-6:
      # a set-down leaves the jaws at that cup's radius + 8 mm, too tight for a wider cup: a few mm of hand-eye
      # error then puts a pad on the rim on the way down (a takeaway rim takes it as a squeeze)
      yield from self._grip_to(OPEN, 0.15)
    yield from self._line(np.array([xy[0], xy[1], z_grasp + 0.025]), yaw, vmax=0.4, amax=2.0, settle=0.0)
    yield from self._line(np.array([xy[0], xy[1], z_grasp]), yaw, vmax=0.15, amax=1.5, settle=0.05)
    yield from self._grip_to(r + 0.004, 0.15)
    yield from self._grip_to(r - squeeze_for(r), 0.3)
    qf = yield from self._finger(15)
    self.log.append(("grasp", round(qf, 4), round(r, 4)))
    if not (r - 0.0018 < qf < r + 0.003):      # wrong cup type, or a grasp off the cup's axis
      yield from self._grip_to(OPEN, 0.25)
      yield from self._line(hover, yaw, vmax=0.3, settle=0.0)
      raise Retry()
    yield from self._grip_to(max(0.0, qf - squeeze_for(r)), 0.1)
    self.grip_qf = qf                  # finger reading at contact
    yield from self._line(np.array([xy[0], xy[1], z_grasp + 0.03]), yaw, vmax=0.15, amax=1.5, settle=0.0)
    qf2 = yield from self._finger(8)
    if qf2 < r - 0.0045:
      self.log.append(("lost_after_lift", round(qf2, 4)))
      yield from self._grip_to(OPEN, 0.25)
      raise Retry()
    self.cup_z_off = z_grasp           # tool point height above the cup base
    y = self._tcp_yaw(self.qcmd)
    self.hand_off = float((np.asarray(xy) - self._tcp_world()[:2]) @ np.array([-math.sin(y), math.cos(y)]))
    self.log.append(("hand_off", round(self.hand_off, 4)))
    self.pick_xy = np.array(xy, float)

  def _has_off(self, p_world, radius=0.16):
    return any(np.linalg.norm(p_world[:2] - (b[:2] + o[:2])) < radius for b, o in self.offs)

  def _put_back(self, cup, r, h):
    """Sets an empty cup down where it was picked from."""
    zc = self.cup_z_off
    p = self._tcp_world()
    yield from self._line_safe(np.array([p[0], p[1], 0.16 + zc]), vmax=0.3)
    xy = self.pick_xy
    yield from self._line_safe(np.array([xy[0], xy[1], 0.16 + zc]), vmax=0.4)
    yield from self._line_safe(np.array([xy[0], xy[1], zc + 0.003]), vmax=0.15)
    yield from self._grip_to(OPEN, 0.3)
    yield from self._line_safe(np.array([xy[0], xy[1], 0.2]), vmax=0.3)

  # ---------------------------------------------------------------- fill
  def _meas_z_gap(self):
    """Measured minus commanded tool height (from the joint encoders); grows when the hand is held up."""
    pm, _ = self._fk(np.asarray(self.obs["qpos"][:7], float))
    pc, _ = self._fk(self.qcmd)
    return float(pm[2] - pc[2])

  def _lower_until_seated(self, tgt, z_start):
    """Lowers the held cup 0.7 mm per tick until the dispenser reports it seated.  When the joint encoders
    show the hand being held up (the cup is on the plate) it stops pushing and waits for the dispenser."""
    gaps = []
    z = z_start
    for k in range(45):
      gaps.append(self._meas_z_gap())
      ref = float(np.median(gaps[:8])) if len(gaps) >= 8 else None
      touching = ref is not None and float(np.mean(gaps[-6:])) - ref > 0.0025
      if not touching and z > z_start - 0.016:     # never more than ~6 mm past the expected contact
        z -= 0.0007
        self.qcmd, _ = self._ik_local(self.qcmd, self._belief(np.array([tgt[0], tgt[1], z])),
                                      topdown(self._tcp_yaw(self.qcmd)), 3)
      yield self._cmd()
      if self.obs["io"]["dispenser"]["cup_detected"]:
        return True
      if touching:
        for _ in range(int(0.5 / self.dt)):
          yield self._cmd()
          if self.obs["io"]["dispenser"]["cup_detected"]:
            return True
        return False
    return False

  def _fill(self, line, r, h):
    disp = self._fixture("dispenser")
    noz = disp[:2]
    u = noz / np.linalg.norm(noz)
    yaw = math.atan2(u[1], u[0]) + math.pi / 2
    plate = disp[2] + PLATE_H
    zc = self.cup_z_off
    pre = np.array([*(noz - 0.14 * u), plate + 0.018 + zc])
    p = self._tcp_world()
    lift = max(p[2], 0.17 + zc)
    yield from self._line_safe(np.array([p[0], p[1], lift]), vmax=0.5, amax=2.5, settle=0.0)
    q, yaw = self._ik(self._belief(pre + np.array([0, 0, 0.03])), yaw, self.qcmd)
    if q is None:
      return False
    yield from self._move_q_safe(q, yaw, vmax=2.4, settle=0.0)
    yield from self._line(pre, yaw, vmax=0.4, amax=2.5, settle=0.05)
    if not self._has_off(pre, 0.10):
      yield from self._calibrate_here()
      yield from self._line(pre, yaw, vmax=0.1, settle=0.0)
    over = np.array([noz[0], noz[1], plate + 0.010 + zc])
    if not self._has_off(over, 0.03):
      yield from self._line(over, yaw, vmax=0.5, amax=2.5, settle=0.03)
      yield from self._calibrate_here()
    seated = False
    base = self._held_target(noz)
    # a held cup mostly creeps across the jaws (along the pads), so search that way first
    cy_, sy_ = math.cos(self._tcp_yaw(self.qcmd)), math.sin(self._tcp_yaw(self.qcmd))
    across, along = np.array([-sy_, cy_]), np.array([cy_, sy_])
    tried = []
    for da, dc in ((0, 0), (0.005, 0), (-0.005, 0), (0.009, 0), (-0.009, 0), (0.013, 0), (-0.013, 0),
                   (0, 0.006), (0, -0.006)):
      dx, dy = da * across + dc * along
      tgt = base + np.array([dx, dy])
      yield from self._line(np.array([tgt[0], tgt[1], plate + 0.010 + zc]), yaw, vmax=0.5, amax=2.5, settle=0.03)
      seated = yield from self._lower_until_seated(tgt, plate + 0.010 + zc)
      if seated:
        # the seat takes the cup axis within 8 mm of the fill point: the shifts tried across the jaws bound how
        # far the cup sits off the pad centre (seated: |o - da| <= 8 mm; not seated: further). Allow for the
        # middle of that interval at the tray too (a cup pushed into the jaws sits 10-20 mm off).
        if dc == 0.0:
          grid = np.linspace(-0.03, 0.03, 601)
          ok = np.abs(grid - da) <= 0.008
          for d_fail in tried:
            ok &= np.abs(grid - d_fail) > 0.008
          est = float(np.mean(grid[ok])) if ok.any() else da
        else:
          est = 0.0
        if abs(est) >= 0.006:
          self.hand_off -= est
          self.log.append(("hand_off", round(self.hand_off, 4), round(da, 4), round(est, 4)))
        break
      if dc == 0.0:
        tried.append(da)
      self.log.append(("no_seat", dx, dy))
      yield from self._line(np.array([tgt[0], tgt[1], plate + 0.010 + zc]), yaw, vmax=0.1, settle=0.0)
    if not seated:
      yield from self._line(pre, yaw, vmax=0.2, settle=0.0)
      return False
    yield from self._hold(0.1)
    # the cup base is on the plate now: tool height above it (the cup may have slid up in the fingers)
    # (this reads about 6 mm low on a cup that has not moved, so only a clear slide is taken)
    zc_meas = float(self._tcp_world()[2] + self._meas_z_gap() - plate) + 0.006
    self.log.append(("zc", round(zc, 4), round(zc_meas, 4)))
    if 0.006 < zc - zc_meas < 0.03:
      self.cup_z_off = zc_meas
    t0 = self.t
    lost, k = 0.0, 0
    nudges = (0.003, -0.003, 0.006, -0.006, 0.009, -0.009)
    while not self.obs["io"]["dispenser"]["fill_complete"]:
      io = self.obs["io"]["dispenser"]
      if io["filling"]:
        t0 = self.t                   # the pour is going: no time-out while it runs
      lost = 0.0 if io["cup_detected"] else lost + self.dt
      if lost > 0.4 and k < len(nudges):
        # the seat was lost (the cup sat at the edge of the fill point and crept off it as it filled): ease
        # it back a few millimetres across the jaws while the pour waits
        z_now = self._tcp_world()[2]
        nxy = tgt + nudges[k] * across
        k += 1
        self.log.append(("nudge", round(nudges[k - 1], 3)))
        yield from self._line(np.array([nxy[0], nxy[1], z_now]), yaw, vmax=0.02, amax=0.3, settle=0.15)
        lost = 0.0
      if self.t - t0 > 8.0:
        self.log.append(("no_pour",))
        yield from self._line(pre, yaw, vmax=0.2, settle=0.0)
        return False
      yield self._cmd()
    yield from self._hold(0.1)
    if abs(self.hand_off) >= 0.008:
      # the cup sits well off the pad centre (pushed into the jaws on the pick) and can turn or creep there on
      # the carry: while it stands on the plate, open, centre the hand on it and grip it again
      p = self._tcp_world()
      cy_, sy_ = math.cos(self._tcp_yaw(self.qcmd)), math.sin(self._tcp_yaw(self.qcmd))
      ctr_xy = p[:2] + self.hand_off * np.array([-sy_, cy_])
      yield from self._grip_to(r + 0.008, 0.25)
      yield from self._hold(0.2)
      yield from self._line(np.array([ctr_xy[0], ctr_xy[1], p[2]]), yaw, vmax=0.02, amax=0.3, settle=0.1)
      yield from self._grip_to(r + 0.002, 0.2)
      yield from self._grip_to(r - squeeze_for(r), 0.3)
      qf = yield from self._finger(12)
      yield from self._grip_to(max(0.0, qf - squeeze_for(r)), 0.1)
      self.grip_qf = qf
      self.log.append(("regrip", round(self.hand_off, 4), round(qf, 4)))
      self.hand_off = 0.0
    p = self._tcp_world()
    yield from self._line_safe(p + np.array([0, 0, 0.016]), vmax=0.05, amax=0.5, settle=0.0)
    yield from self._line_safe(np.array([pre[0], pre[1], p[2] + 0.016]), vmax=0.3, amax=1.2, settle=0.0)
    return True

  # ---------------------------------------------------------------- deliver
  def _tray(self):
    tray = self._fixture("tray")
    yaw_t = math.atan2(2 * (tray[3] * tray[6] + tray[4] * tray[5]), 1 - 2 * (tray[5] ** 2 + tray[6] ** 2))
    c, s = math.cos(yaw_t), math.sin(yaw_t)
    return tray[:2].copy(), np.array([[c, -s], [s, c]])

  def _route(self, a, b, ctr, rot, pad=0.10):
    """2D waypoints from a to b that keep out of the zone rectangle grown by `pad`."""
    hx, hy = TRAY_HALF[0] + 0.03 + pad, TRAY_HALF[1] + 0.03 + pad

    def inside_seg(p, q):
      for t in np.linspace(0, 1, 25):
        l = rot.T @ (p + t * (q - p) - ctr)
        if abs(l[0]) < hx - 0.02 and abs(l[1]) < hy - 0.02:
          return True
      return False
    if not inside_seg(a, b):
      return [b]
    corners = [ctr + rot @ np.array([sx * hx, sy * hy]) for sx in (-1, 1) for sy in (-1, 1)]
    best = None
    for c1 in corners:
      if not inside_seg(a, c1) and not inside_seg(c1, b):
        L = np.linalg.norm(c1 - a) + np.linalg.norm(b - c1)
        if best is None or L < best[0]:
          best = (L, [c1, b])
      for c2 in corners:
        if c2 is c1:
          continue
        if not inside_seg(a, c1) and not inside_seg(c1, c2) and not inside_seg(c2, b):
          L = np.linalg.norm(c1 - a) + np.linalg.norm(c2 - c1) + np.linalg.norm(b - c2)
          if best is None or L < best[0]:
            best = (L, [c1, c2, b])
    return [b] if best is None else best[1]

  def _path_clear(self, a, b, r, h, yaw, served):
    """True when a carried cup (radius r, height h) and the hand can travel low from a to b past served cups."""
    for t in np.linspace(0.0, 1.0, 15):
      p = a + t * (b - a)
      if not grasp_yaw_ok(p, h, served, yaw, margin=0.008):
        return False
      if any(np.linalg.norm(np.asarray(sv[0]) - p) < r + sv[1] + 0.012 for sv in served):
        return False
    return True

  def _entry(self, sxy, ctr, rot, r, h, zc, served, exclude=None, strict=True):
    """Ways into the zone: (cost, entry xy, z inside, yaw, outward normal), best first.  The entry sits on the
    tray edge nearest the slot along one tray axis, just outside the zone."""
    loc = rot.T @ (sxy - ctr)
    y_now = self._tcp_yaw(self.qcmd)
    p_now = self._tcp_world()[:2]
    top = max([sv[2] for sv in served] + [0.0])
    yaws = sorted((math.radians(a) for a in range(0, 180, 15)), key=lambda y: abs(_wrap(2 * (y - y_now))))
    yaws = [y for y in yaws if grasp_yaw_ok(sxy, h, served, y)] or yaws[:1]
    out = []
    for ax, sgn in ((0, -1), (0, 1), (1, 1), (1, -1)):
      e = loc.copy()
      e[ax] = sgn * (TRAY_HALF[ax] + ZONE_MARGIN)
      w = ctr + rot @ e
      rr = float(np.linalg.norm(w))
      if rr > 0.77 or rr < (0.33 if strict else 0.30):
        continue
      inside = float(np.linalg.norm(w - sxy))
      best = None
      for y in yaws:
        low = self._path_clear(w, sxy, r, h, y, served)
        z_in = TRAY_H + (0.026 if low else top + 0.025) + zc
        q, yw = self._ik(self._belief(np.array([w[0], w[1], z_in])), y, self.qcmd)
        if q is None:
          continue
        qs, _ = self._ik(self._belief(np.array([sxy[0], sxy[1], TRAY_H + zc])), yw, q)    # the slot itself
        if qs is None or float(np.min(np.minimum(qs - self.jlo, self.jhi - qs))) < 0.08:
          continue
        route = self._route(p_now, w, ctr, rot, pad=0.03)
        slot_pts = [np.array([sxy[0], sxy[1], z_in]), np.array([sxy[0], sxy[1], TRAY_H + zc - 0.0015])]
        if strict and not self._carry_ok(route, z_in, yw, slot_pts):    # the carry at this yaw runs into an awkward wrist
          continue
        behind = any(float(v[0]) < 0.05 for v in route)      # corners behind the base: awkward wrist, slow
        cost = (inside + (0.0 if low else 2 * (z_in - TRAY_H - zc)) + 0.15 * float(np.linalg.norm(w - p_now))
                + (0.3 if rr > 0.64 else 0.0)    # far reach: a held cup creeps in the fingers there
                + 0.1 * (len(route) - 1) + (0.5 if behind else 0.0))
        best = (cost, w, z_in, yw, rot @ (np.eye(2)[ax] * sgn))
        break
      if best is not None:
        out.append(best)
    out.sort(key=lambda o: o[0])
    if not out and strict:
      return self._entry(sxy, ctr, rot, r, h, zc, served, exclude, strict=False)
    if not out:
      raise Retry()
    return out

  def _carry_ok(self, route, z, yaw, extra=(), vmax=0.6, amax=1.3):
    """Dry run of the carry strokes (down to height z, then the route, then the extra points: into the zone
    and down to the slot): False when one would fail."""
    p0 = self._tcp_world()
    pts = [np.array([p0[0], p0[1], z])] + [np.array([v[0], v[1], z]) for v in route] + list(extra)
    q = self.qcmd.copy()
    try:
      for k, b in enumerate(pts):
        q = self._plan_line(q, b, yaw, 0.25 if k == 0 else vmax, amax, log=False, tol=0.0025)[-1]
    except Retry:
      self.log.append(("carry_bad", np.round(b, 3).tolist(), round(math.degrees(yaw))))
      return False
    return True

  def _carry(self, goal_xy, z, yaw, ctr, rot, vmax=0.6, amax=1.3):
    """Carries the held cup at height z to goal_xy without entering the zone (routes round its corners)."""
    p = self._tcp_world()
    if abs(p[2] - z) > 0.003:
      yield from self._line_safe(np.array([p[0], p[1], z]), yaw, vmax=0.25, amax=amax, settle=0.0)
    for w in self._route(p[:2], goal_xy, ctr, rot, pad=0.03):
      yield from self._line_safe(np.array([w[0], w[1], z]), yaw, vmax=vmax, amax=amax, settle=0.0)

  def _to_hub(self):
    """Empty hand from the tray side back to the hub in front of the dispenser, round the zone.  If a stroke
    fails (the straight way passes too close to the base), it climbs above the zone and swings over it."""
    ctr, rot = self._tray()
    p = self._tcp_world()
    z = max(p[2], 0.20)
    yaw = math.atan2(HUB[1], HUB[0]) + math.pi / 2
    if z - p[2] > 0.003:
      yield from self._line_safe(np.array([p[0], p[1], z]), vmax=0.5, amax=2.5, settle=0.0)
    if not self._in_zone(self._tcp_world(), 0.0):
      # empty hand: a joint move straight home when its whole path stays out of the zone
      qh, _ = self._ik(self._belief(np.array([HUB[0], HUB[1], 0.25])), yaw, self.qcmd)
      if qh is not None and self._joint_path_clear(self.qcmd, qh):
        yield from self._move_q(qh, vmax=2.0, settle=0.0)
        return
    for w in self._route(p[:2], HUB, ctr, rot, pad=0.03):
      tgt = np.array([w[0], w[1], z])
      try:
        yield from self._line(tgt, math.atan2(w[1], w[0]) + math.pi / 2, vmax=0.8, amax=3.0, settle=0.0)
        continue
      except Retry:
        pass
      p = self._tcp_world()
      yield from self._line_safe(np.array([p[0], p[1], 0.53]), vmax=0.8, amax=3.0, settle=0.0)
      q, _ = self._ik(self._belief(np.array([HUB[0], HUB[1], 0.53])), yaw, self.qcmd)
      if q is not None:
        yield from self._move_q(q, vmax=1.5, settle=0.0)
        yield from self._line_safe(np.array([HUB[0], HUB[1], 0.25]), yaw, vmax=0.8, amax=3.0, settle=0.0)
      return

  def _joint_path_clear(self, q0, q1, margin=0.03):
    """True when the tool point stays out of the zone (grown by margin) and away from the dispenser column
    along a joint-space move."""
    disp = self._fixture("dispenser")
    for s in np.linspace(0.0, 1.0, 16):
      pb, _ = self._fk(q0 + s * (q1 - q0))
      pw = pb + self._off(pb)
      if self._in_zone(pw, margin):
        self.log.append(("jp_zone", round(float(s), 2), np.round(pw, 3).tolist()))
        return False
      if np.linalg.norm(pw[:2] - (disp[:2] + np.array([0.165, 0.0]))) < 0.17 and pw[2] < 0.50:
        self.log.append(("jp_disp", round(float(s), 2), np.round(pw, 3).tolist()))
        return False
    return True

  def _deliver(self, line, r, h):
    ctr, rot = self._tray()
    sxy = ctr + rot @ np.array(SLOT_POS[line["slot"]])
    zc = self.cup_z_off
    options = self._entry(sxy, ctr, rot, r, h, zc, self.served)
    sxy_slot = sxy
    z_place = TRAY_H + zc
    for k, (_, entry, z_in, yaw, normal) in enumerate(options):
      self.log.append(("entry", line["slot"], np.round(entry, 3).tolist(), round(z_in - zc - TRAY_H, 3), round(math.degrees(yaw))))
      yield from self._carry(entry + 0.005 * normal, z_in, yaw, ctr, rot)
      # inside the customer zone: slow and straight.  If the stroke to the slot cannot be made, back out and
      # come in from the next side rather than improvise among the served cups.
      sxy = self._held_target(sxy_slot)          # tool point that centres the cup (hand yaw as carried)
      try:
        yield from self._line(np.array([sxy[0], sxy[1], z_in]), yaw, vmax=0.21, amax=1.2, settle=0.0)
        break
      except Retry:
        if k == len(options) - 1:
          yield from self._line_safe(np.array([sxy[0], sxy[1], z_in]), yaw, vmax=0.21, amax=1.2, settle=0.0)
          break
        yield from self._line_safe(np.array([entry[0] + 0.01 * normal[0], entry[1] + 0.01 * normal[1], z_in]), yaw,
                                   vmax=0.21, amax=1.2, settle=0.0)
    yield from self._calibrate_here()
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_in]), yaw, vmax=0.1, amax=1.0, settle=0.0)
    # the slow part starts well above the slot: the height estimate can be ~8 mm out, and a paper cup that meets
    # the tray at speed is squeezed past its limit by the pads
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_place + 0.018]), yaw, vmax=0.21, amax=1.2, settle=0.0)
    if r > 0.033:
      # paper cup: ease the squeeze before the tray takes the base, which loads one pad by 3-4 N (about 4.5 N
      # per pad left, against a 0.3 kg full cup with pad friction 1)
      yield from self._grip_to(max(0.0, self.grip_qf - 0.0018), 0.15)
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_place - 0.0015]), yaw, vmax=0.03, amax=0.5, settle=0.06)
    yield from self._grip_to(r + 0.008, 0.15)
    z_out = max(z_in, TRAY_H + h + 0.016)
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_out]), yaw, vmax=0.21, amax=1.2, settle=0.0)
    yield from self._exit_zone(np.array([entry[0] + 0.01 * normal[0], entry[1] + 0.01 * normal[1], z_out]), yaw)
    self.served.append((sxy_slot, r, h))
    line["xy"] = sxy_slot
    line["placed"] = True
    yield from self._to_hub()

  def _exit_zone(self, outer, yaw):
    """Empty hand back out to the zone edge.  If the stroke cannot be made, it climbs straight up instead
    (slowly, inside the zone) and leaves the way home to _to_hub."""
    try:
      yield from self._line(outer, yaw, vmax=0.21, amax=1.2, settle=0.0)
      return
    except Retry:
      pass
    p = self._tcp_world()
    try:
      yield from self._line(np.array([p[0], p[1], 0.25]), None, vmax=0.2, amax=1.0, settle=0.0)
    except Retry:
      yield from self._line_safe(np.array([p[0], p[1], p[2] + 0.06]), None, vmax=0.2, amax=1.0, settle=0.0)

  # ---------------------------------------------------------------- final check
  def _final_check(self):
    """Looks at the tray once the ticket is served and sets back any cup that sits off its slot."""
    if not any(ln.get("placed") for ln in self.ticket):
      return
    self._update_cam()
    yield from self._move_q(VIEW_Q, vmax=1.8, settle=0.1)
    for _ in range(2):
      fr = yield from self._fresh(self.t + 0.01)
      seen = self._cups_in(fr, "tray")
      bad = []
      for line in self.ticket:
        if not line.get("placed"):
          continue
        near = [c for c in seen if c["kind"] == line["cup"] and np.linalg.norm(c["xy"] - line["xy"]) < 0.06]
        if not near:
          continue
        cxy = min(near, key=lambda c: np.linalg.norm(c["xy"] - line["xy"]))["xy"]
        err = float(np.linalg.norm(cxy - line["xy"]))
        self.log.append(("check", line["slot"], round(err, 4), np.round(cxy, 4).tolist(), np.round(line["xy"], 4).tolist()))
        # set back anything over 9 mm (camera margin on the 12 mm slot test), but when a re-seat (about 10 s)
        # would run past the ticket budget, only a cup that is clearly off: a late ticket fails every line
        budget = 30.0 + 22.0 * len(self.ticket)
        if err > 0.009 and (err > 0.0112 or self.t + 12.0 < budget):
          bad.append((line, cxy))
      if not bad:
        return
      for line, cxy in bad:
        try:
          yield from self._reseat(line, cxy)
        except Retry:
          if self.grip < OPEN - 0.002:
            yield from self._grip_to(OPEN, 0.2)
          yield from self._to_hub()
      yield from self._move_q(VIEW_Q, vmax=1.8, settle=0.1)

  def _reseat(self, line, cxy):
    """Picks a filled cup off the tray (gently) and sets it back on its slot."""
    r, h = CUPS[line["cup"]]
    sxy = line["xy"]
    served = [sv for sv in self.served if np.linalg.norm(np.asarray(sv[0]) - sxy) > 0.01]
    ctr, rot = self._tray()
    zc = h - GRASP_BELOW_RIM
    _, entry, z_in, yaw, normal = self._entry(cxy, ctr, rot, r, h, zc, served)[0]
    z_out = max(z_in, TRAY_H + h + 0.016)
    z_grasp = TRAY_H + zc
    outer = entry + 0.01 * normal
    # empty hand to just outside the zone: hub, then round the zone
    qh, _ = self._ik(self._belief(np.array([HUB[0], HUB[1], 0.25])), math.atan2(HUB[1], HUB[0]) + math.pi / 2,
                     self.qcmd)
    if qh is None:
      raise Retry()
    yield from self._move_q(qh, vmax=1.8, settle=0.0)
    for w in self._route(HUB, outer, ctr, rot, pad=0.03):
      yield from self._line(np.array([w[0], w[1], 0.25]), None, vmax=0.8, amax=3.0, settle=0.0)
    yield from self._line(np.array([outer[0], outer[1], z_out]), yaw, vmax=0.5, amax=2.5, settle=0.0)
    # inside the zone
    yield from self._line(np.array([cxy[0], cxy[1], z_out]), yaw, vmax=0.21, amax=1.2, settle=0.0)
    if not self._has_off(np.asarray(cxy, float), 0.06):
      # the offset changes with the arm's pose: check it close to the grasp height, not high above it
      yield from self._line(np.array([cxy[0], cxy[1], TRAY_H + h + 0.02]), yaw, vmax=0.1, amax=1.0, settle=0.0)
      yield from self._calibrate_here()
      yield from self._line(np.array([cxy[0], cxy[1], TRAY_H + h + 0.02]), yaw, vmax=0.1, amax=1.0, settle=0.0)
    if self.grip < min(OPEN, r + 0.006) - 1e-6:     # as in _pick: room for the rim before going down
      yield from self._grip_to(OPEN, 0.15)
    yield from self._line(np.array([cxy[0], cxy[1], z_grasp]), yaw, vmax=0.1, amax=0.8, settle=0.05)
    yield from self._grip_to(r + 0.002, 0.25)
    yield from self._grip_to(r - squeeze_for(r), 0.35)
    qf = yield from self._finger(12)
    self.served = served
    if not (r - 0.0045 < qf < r + 0.004):
      yield from self._grip_to(r + 0.008, 0.25)
      yield from self._line(np.array([cxy[0], cxy[1], z_out]), yaw, vmax=0.1, amax=0.8, settle=0.0)
      yield from self._line(np.array([outer[0], outer[1], z_out]), yaw, vmax=0.21, amax=1.2, settle=0.0)
      self.served.append((sxy, r, h))
      raise Retry()
    yield from self._line_safe(np.array([cxy[0], cxy[1], z_grasp + 0.005]), yaw, vmax=0.03, amax=0.3, settle=0.0)
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_grasp + 0.005]), yaw, vmax=0.04, amax=0.3, settle=0.0)
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_grasp - 0.0015]), yaw, vmax=0.02, amax=0.3, settle=0.08)
    yield from self._grip_to(r + 0.008, 0.2)
    yield from self._line_safe(np.array([sxy[0], sxy[1], z_out]), yaw, vmax=0.21, amax=1.2, settle=0.0)
    yield from self._exit_zone(np.array([outer[0], outer[1], z_out]), yaw)
    self.served.append((sxy, r, h))
    yield from self._to_hub()