File size: 165,435 Bytes
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
ff86ab2
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
2bcbba2
 
 
 
ff86ab2
 
 
2bcbba2
ff86ab2
2bcbba2
 
 
 
 
ff86ab2
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
 
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
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
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
# SPDX-License-Identifier: Apache-2.0
"""Episode control and dataset writing for VR hand teleop collection.

Three pieces, deliberately separate from the scene:

  *Success      the task's success criterion, evaluated live -- six of them,
                one per shape of task: a height (LiftSuccess), a fraction of a
                joint's travel (JointOpenSuccess), an absolute joint angle
                (JointAngleSuccess), an axis brought upright
                (AxisUprightSuccess), a cube rolled onto a neighbouring face
                (FaceNeighborSuccess), one part driven into another
                (InsertSuccess -- reads two bodies) and one part taken OFF
                another (SeparateSuccess, the same two bodies). All of them
                share one interface -- arm / update / holds / progress /
                terms -- and each declares in VALUE what it wants fed to it, so
                the collection loop never branches on the task.
  EpisodeWriter LeRobot-v2-style layout: parquet per episode plus a meta/ dir
  TeleopHUD     the in-headset indicator, which is the entire operator
                interface

The operator never touches the keyboard. The whole session is driven by the LEFT
hand; the gesture itself lives in embodiment/openxr/gesture.py, since it reads
the tracker rather than the scene.

LEFT hand, not right, and this is not a preference. A right-hand pinch is the
Quest's own system gesture and using it ends the XR session -- which ends the
capture. So the side is forced by the platform.

⚠️ With ``--hand both`` the left hand ALSO manipulates, and the gesture is then
the same fingers as the grasp. What still separates them is the PALM: a verdict
is only read inside a cone about vertical (``--palm-up-deg``), held for
``--pinch-hold-s``. That is a narrower margin than the original design had --
it once demanded BOTH hands pinched, which manipulation does not produce by
accident -- so a two-handed session should expect to tune those two numbers.
"""

from __future__ import annotations

import json
import os
import sys
import time

import numpy as np

from tools.contact_io import SIDECAR_DIR
from tools.recording_paths import check_recording_hands, check_recording_table, embodiment_of
from embodiment.openxr.tracking import HAND_JOINTS as _HAND_JOINTS

# -------------------------------------------------------- success criteria ---


def initially_successful(criterion, value) -> bool:
    """Check a prospective start against its reset baseline without advancing it.

    Stateful criteria must observe the value once: a joint sequence can have
    every absolute goal already met while holds() is false until its latches
    advance. Preserve the baseline armed by reset, rather than re-arming on
    the potentially stale start state.
    """
    import copy  # noqa: PLC0415

    check = copy.deepcopy(criterion)
    check.update(value)
    return bool(check.holds(value))


class LiftSuccess:
    """Object lifted >= `height_m` above its resting z, for `hold_steps` steps.

    The sustained count matters: a cube knocked upward crosses any height
    threshold for an instant, and counting that as success fills a dataset with
    demos of the operator batting the object across the table.
    """

    #: what update()/holds() want fed to them; see collect_env.success_value.
    VALUE = "z"

    def __init__(self, height_m: float = 0.10, hold_steps: int = 25):
        self.height_m = height_m
        self.hold_steps = hold_steps
        self.rest_z: float | None = None
        self.count = 0
        self.peak = 0.0

    def arm(self, obj_z: float):
        self.rest_z, self.count, self.peak = float(obj_z), 0, 0.0

    def update(self, obj_z: float) -> bool:
        if self.rest_z is None:
            self.arm(obj_z)
            return False
        lift = float(obj_z) - self.rest_z
        self.peak = max(self.peak, lift)
        self.count = self.count + 1 if lift >= self.height_m else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        """0..1 toward the goal, for the in-headset ring."""
        if self.rest_z is None or self.height_m <= 0.0:
            return 0.0
        return max(0.0, min(1.0, self.peak / self.height_m))

    def hold_progress(self) -> float:
        """0..1 through the sustained hold. Drops straight back to 0 the moment
        the criterion stops being satisfied, which is the point of it."""
        if self.hold_steps <= 0:
            return 0.0
        return max(0.0, min(1.0, self.count / self.hold_steps))

    def holds(self, obj_z: float) -> bool:
        """Does the criterion hold RIGHT NOW? Non-mutating."""
        if self.rest_z is None:
            return False
        return (float(obj_z) - self.rest_z) >= self.height_m

    def terms(self) -> dict:
        return {"criterion": f"object z >= rest_z + {self.height_m:.3f} m "
                             f"for {self.hold_steps} consecutive steps",
                "peak_lift_m": round(self.peak, 5),
                "threshold_m": self.height_m,
                "rest_z": None if self.rest_z is None else round(self.rest_z, 5)}


class MultiLiftSuccess:
    """EVERY named object lifted >= `height_m` above where it started, for
    `hold_steps` consecutive steps -- one LiftSuccess per object, satisfied
    together. The two-cube sanity check: a cube in each hand, both off the
    table at once, which one hand cannot do.
    """

    VALUE = "zs"

    def __init__(self, names, height_m: float = 0.10, hold_steps: int = 25):
        self.names = list(names)
        self.height_m = float(height_m)
        self.hold_steps = int(hold_steps)
        self.parts = [LiftSuccess(height_m, hold_steps) for _ in self.names]
        self.count = 0

    def arm(self, zs):
        """Re-arm every part where its object is NOW: a reset, or the start
        of a demo. The value is the same list update() takes."""
        for p, z in zip(self.parts, zs):
            p.arm(z)
        self.count = 0

    def update(self, zs) -> bool:
        for p, z in zip(self.parts, zs):
            if p.rest_z is None:
                p.arm(z)
            p.peak = max(p.peak, float(z) - p.rest_z)
        ok = all(p.holds(z) for p, z in zip(self.parts, zs))
        self.count = self.count + 1 if ok else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        """The LEAST-lifted object's progress: both have to come up."""
        return min((p.progress() for p in self.parts), default=0.0)

    def hold_progress(self) -> float:
        if self.hold_steps <= 0:
            return 0.0
        return max(0.0, min(1.0, self.count / self.hold_steps))

    def holds(self, zs) -> bool:
        return all(p.holds(z) for p, z in zip(self.parts, zs))

    def terms(self) -> dict:
        return {"criterion": f"every one of {self.names} at z >= its rest_z + "
                             f"{self.height_m:.3f} m for {self.hold_steps} "
                             f"consecutive steps",
                "threshold_m": self.height_m,
                "peak_lift_m": {n: round(p.peak, 5) for n, p in zip(self.names, self.parts)},
                "rest_z": {n: (None if p.rest_z is None else round(p.rest_z, 5))
                           for n, p in zip(self.names, self.parts)}}


class MultiLiftHandsSuccess(MultiLiftSuccess):
    """MultiLiftSuccess, and on every step of the hold no more than
    `max_hands` hands touch any of the named objects. With max_hands 1: two
    cubes carried in ONE hand while the other hand is in the scene -- it may
    help set the grasp up, but it has to be off both cubes for the whole hold,
    and touching one again restarts the hold.

    Fed (zs, hands): the heights as MultiLiftSuccess takes them, and how many
    hands are in contact with any named object this step (collect_env reads
    the hydroelastic contact surface; bddl_eval the contact sidecars).
    """

    VALUE = "zs_hands"

    def __init__(self, names, height_m: float = 0.10, hold_steps: int = 25,
                 max_hands: int = 1):
        super().__init__(names, height_m, hold_steps)
        self.max_hands = int(max_hands)
        self.peak_hands_held = 0     # most hands seen on the objects while lifted

    def arm(self, value):
        super().arm(value[0])
        self.peak_hands_held = 0

    def update(self, value) -> bool:
        zs, hands = value
        super().update(zs)
        lifted = all(p.holds(z) for p, z in zip(self.parts, zs))
        if lifted:
            self.peak_hands_held = max(self.peak_hands_held, int(hands))
        if lifted and int(hands) > self.max_hands:
            self.count = 0
        return self.count >= self.hold_steps

    def holds(self, value) -> bool:
        zs, hands = value
        return super().holds(zs) and int(hands) <= self.max_hands

    def terms(self) -> dict:
        out = super().terms()
        out["criterion"] += (f", with at most {self.max_hands} hand(s) touching "
                             f"them on every one of those steps")
        out["max_hands"] = self.max_hands
        out["peak_hands_while_lifted"] = self.peak_hands_held
        return out


class HandoverSuccess:
    """The object, lifted, passes from one hand to the other.

    Graded on GEOMETRY, not on contact: the object's centre is "with" a hand
    when it is within `near_m` of that hand's THUMB TIP and further than
    `far_m` from the other's. Phase 1: lifted >= `height_m` above its rest
    and with hand A. Phase 2: lifted and with hand B, held `hold_steps`
    steps. A cube lifted with the right and set down is not a handover; a
    cube carried by both hands at once is with neither (both thumbs near)
    and the hold restarts.

    `direction` is "right_to_left", "left_to_right" or "any".

    THE THUMB TIP, NOT THE WRIST (2026-09-12). It was the wrist, at 12/20
    cm, and that could not tell a hand holding the cube from a hand next to
    it: a cube in the fingers sits ~8 cm from the wrist origin, so did a
    cube held by the OTHER hand 8 cm away, and the giver had to withdraw a
    whole hand-width before the hold would count. Every grasp of a 5 cm
    cube has the thumb on it -- a pinch, a fingertip hold, a wrap -- within
    ~4 cm of its centre, and a thumb that has let go is off it at once, so
    `near_m` is now 6 cm and `far_m` 12. The caller feeds the tip; a rig
    with no recorded tip falls back to the wrist, and the old numbers.

    A DROP STARTS OVER. Once a giver is latched the object has to stay
    lifted until the taker's hold completes; if it comes back below
    `height_m` the giver is forgotten and the next hand to lift it is the
    giver again. Without this, a cube lifted with the right, dropped, and
    picked up off the table by the left would pass -- and that is two lifts,
    not a handover. `drops` in terms() counts how often it happened.
    """

    VALUE = "handover"

    def __init__(self, height_m: float = 0.08, near_m: float = 0.06,
                 far_m: float = 0.12, hold_steps: int = 25,
                 direction: str = "any"):
        self.height_m, self.near_m, self.far_m = float(height_m), float(near_m), float(far_m)
        self.hold_steps = int(hold_steps)
        self.direction = str(direction)
        self.rest_z: float | None = None
        self.giver: str | None = None
        self.count = 0
        self.peak = 0.0
        self.drops = 0

    def arm(self, value):
        """The same (obj_z, obj_p, tips) update() takes; only the height
        is remembered. A re-arm also forgets the giver: a reset starts over."""
        obj_z = value[0] if isinstance(value, (tuple, list)) else value
        self.rest_z, self.giver, self.count, self.peak = float(obj_z), None, 0, 0.0
        self.drops = 0

    def _with(self, obj_p, tips) -> str | None:
        """Which hand the object is with: {side: thumb tip (or None)} in."""
        d = {s: float(np.linalg.norm(np.asarray(obj_p) - np.asarray(w)))
             for s, w in tips.items() if w is not None}
        near = [s for s, v in d.items() if v <= self.near_m]
        if len(near) != 1:
            return None
        s = near[0]
        others = [v for k, v in d.items() if k != s]
        if others and min(others) < self.far_m:
            return None
        return s

    def _allowed_giver(self, s: str) -> bool:
        return (self.direction == "any"
                or (self.direction == "right_to_left" and s == "right")
                or (self.direction == "left_to_right" and s == "left"))

    def update(self, value) -> bool:
        obj_z, obj_p, tips = value
        if self.rest_z is None:
            self.arm(value)
        lift = float(obj_z) - self.rest_z
        self.peak = max(self.peak, lift)
        w = self._with(obj_p, tips) if lift >= self.height_m else None
        if self.giver is not None and lift < self.height_m:
            # Down again before the taker held it: not a handover. Over.
            self.giver, self.count = None, 0
            self.drops += 1
        if self.giver is None:
            if w is not None and self._allowed_giver(w):
                self.giver = w
            self.count = 0
            return False
        ok = w is not None and w != self.giver
        self.count = self.count + 1 if ok else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        if self.rest_z is None or self.height_m <= 0.0:
            return 0.0
        lifted = max(0.0, min(1.0, self.peak / self.height_m))
        return 0.5 * lifted + (0.5 if self.giver is not None else 0.0)

    def hold_progress(self) -> float:
        if self.hold_steps <= 0:
            return 0.0
        return max(0.0, min(1.0, self.count / self.hold_steps))

    def holds(self, value) -> bool:
        obj_z, obj_p, tips = value
        if self.rest_z is None or self.giver is None:
            return False
        if float(obj_z) - self.rest_z < self.height_m:
            return False
        w = self._with(obj_p, tips)
        return w is not None and w != self.giver

    def terms(self) -> dict:
        return {"criterion": f"object lifted >= {self.height_m:.3f} m, taken by "
                             f"one hand (within {self.near_m:.2f} m of its thumb "
                             f"tip, > {self.far_m:.2f} m from the other's) then held "
                             f"by the other for {self.hold_steps} consecutive steps"
                             + ("" if self.direction == "any" else f" ({self.direction})"),
                "giver": self.giver, "peak_lift_m": round(self.peak, 5),
                "drops": self.drops,
                "rest_z": None if self.rest_z is None else round(self.rest_z, 5)}


class JointOpenSuccess:
    """An articulated joint driven a fraction of its travel, held N steps.

    The articulated counterpart to :class:`LiftSuccess`. Same interface -- one
    scalar in, bool out -- so the collection loop does not branch: a lift task
    feeds it the object's z, a drawer task feeds it the joint coordinate.

    Why a FRACTION of the range rather than an absolute distance: these
    assets are scaled at spawn (the storage unit at 0.35), and the joint limits
    scale with them. A fixed "0.10 m open" is a different fraction of travel on
    every asset and silently becomes unreachable on a small one.

    Progress is measured from the coordinate at arm() time, not from the lower
    limit, so a drawer that starts already ajar still needs real travel.

    It is also what a SHORT-THROW LEVER wants, and for a different reason. "The
    laptop is open past 90 degrees" is a statement about a laptop; "the espresso
    lever is at 60 degrees" is not a statement about anything -- the lever has
    ~80 degrees of travel and what matters is that it was pulled THROUGH it.
    An absolute angle on such a joint is also brittle: it is chosen as a
    proportion of a stop that is itself a judgement, so re-importing the asset
    with a better stop silently changes what fraction of the throw the task
    asks for. Naming the fraction says the intended thing and moves with it.

    `direction` is "any" (the default, absolute), "increase" or "decrease",
    matching :class:`JointAngleSuccess` -- without it a lever shoved the
    closing way counts as having been operated.

    `min_tool_speed` (m/s) makes it a criterion about HOW the joint moved, and
    exists for the hammer: a nail is "driven" when a swung tool drives it, not
    when the operator presses it in with a hand, and the joint coordinate alone
    cannot tell those apart. With it set, only the travel accumulated while the
    task's tool (the graded object -- the hammer) is moving at least that fast
    counts toward the fraction, AND the joint must still be that far from rest
    at the end, so a nail driven and then pulled back out does not pass. The
    threshold is not a measurement of a blow: a hammer mid-swing measured
    1.6-2.6 m/s on 67 recorded demos and 0.3 m/s is simply well clear of a hand
    resting a tool against something, which is what has to be excluded. Leave
    it None and the criterion is the plain position test it always was.
    """

    #: what update()/holds() want fed to them; see collect_env.success_value.
    #: `min_tool_speed` upgrades it per instance to "joint_tool" -- the pair
    #: (coordinate, tool speed) -- because the rule then needs both.
    VALUE = "joint"

    def __init__(self, lo: float, hi: float, fraction: float = 0.30,
                 hold_steps: int = 25, label: str = "joint",
                 direction: str = "any", unit: str = "rad",
                 min_tool_speed: float | None = None,
                 require_tool_contact: bool = False, tool_contact_window_steps: int = 0):
        self.lo, self.hi = float(lo), float(hi)
        self.span = abs(self.hi - self.lo)
        self.fraction = float(fraction)
        self.need = self.span * self.fraction
        self.hold_steps = int(hold_steps)
        self.label = label
        self.direction = str(direction)
        # "rad" for a hinge, "m" for a slide. Only the REPORTING differs: the
        # criterion itself is a fraction of whatever the coordinate's travel
        # is, which is the reason it exists. A nail driven into a board or a
        # drawer pulled open is graded exactly like a lid, and its terms are
        # printed in millimetres rather than as a meaningless "degrees".
        if unit not in ("rad", "m"):
            raise ValueError(f"unit must be 'rad' or 'm', got {unit!r}")
        self.unit = unit
        #: None, or the speed the tool must be moving for travel to count.
        self.min_tool_speed = (None if min_tool_speed is None
                               else float(min_tool_speed))
        if self.min_tool_speed is not None:
            if self.min_tool_speed < 0:
                raise ValueError("min_tool_speed must be >= 0")
            self.VALUE = "joint_tool"
        self.rest: float | None = None
        self.count = 0
        self.peak = 0.0
        #: Travel accumulated while the tool was moving fast enough. Only
        #: meaningful with min_tool_speed; it is what the fraction is tested
        #: against there, instead of the distance from rest.
        self.driven = 0.0
        self._last_q: float | None = None
        # `require_tool_contact`: a step's travel counts only when the TOOL is touching the
        # driven body and the hand is not. The speed gate alone cannot tell a blow from a hand
        # pressing the nail while the hammer happens to be moving -- nobody did that in the 54
        # human demos (the hand never touched the nail), but an optimiser retargeting them to a
        # robot hand would find it. The contact is fed as a third element, (tool_on, hand_on),
        # by tools/bddl_eval.py from a recording's contact sidecars; the live recorder feeds none
        # (no per-step contact readback during collection), and a step with no contact reading
        # counts as before -- `tool_contact_checked` in terms() says which it was.
        # The blow's own follow-through: a struck nail keeps sinking for a few steps after the
        # hammer has bounced off it (measured: all of that travel within 60 ms of the last
        # contact over the 54 human demos). `tool_contact_window_steps` credits travel made that
        # soon after the tool last touched -- still never with the hand on the driven body.
        self.require_tool_contact = bool(require_tool_contact)
        if self.require_tool_contact and self.min_tool_speed is None:
            raise ValueError("require_tool_contact qualifies min_tool_speed; set that too")
        self.tool_window = int(tool_contact_window_steps)
        if self.tool_window < 0:
            raise ValueError("tool_contact_window_steps must be >= 0")
        self._contact_seen = False
        self._since_tool: int | None = None

    @staticmethod
    def _split(v):
        """(coordinate, tool speed) from what success_value fed us."""
        if isinstance(v, (tuple, list)):
            return float(v[0]), float(v[1])
        return float(v), None

    @staticmethod
    def _contact(v):
        """(tool_on, hand_on) when the caller read contacts, else None."""
        if isinstance(v, (tuple, list)) and len(v) > 2 and v[2] is not None:
            return bool(v[2][0]), bool(v[2][1])
        return None

    def _human(self, v: float) -> tuple[float, str]:
        """A coordinate in the unit a person reads it in."""
        return ((float(np.degrees(v)), "deg") if self.unit == "rad"
                else (float(v) * 1e3, "mm"))

    def _moved(self, q: float) -> float:
        """Signed travel from rest, resolved to the direction that counts."""
        d = float(q) - float(self.rest)
        if self.direction == "increase":
            return d
        if self.direction == "decrease":
            return -d
        return abs(d)

    def arm(self, q):
        q, _ = self._split(q)
        self.rest, self.count, self.peak = float(q), 0, 0.0
        self.driven, self._last_q = 0.0, float(q)
        self._contact_seen = False
        self._since_tool = None

    def _accumulate(self, q: float, speed: float | None, contact=None) -> None:
        """Add this step's travel to `driven` if the tool was moving.

        A missing speed (a caller that fed a bare coordinate) counts as not
        moving: the criterion must not silently fall back to the position test
        it exists to replace.
        """
        if self._last_q is None:
            self._last_q = q
            return
        step = self._moved(q) - self._moved(self._last_q)
        self._last_q = q
        if self.require_tool_contact and contact is not None:
            # steps since the tool last touched the driven body, tracked on EVERY step
            self._since_tool = 0 if contact[0] else (
                None if self._since_tool is None else self._since_tool + 1)
        if step > 0.0 and speed is not None and speed >= self.min_tool_speed:
            if self.require_tool_contact and contact is not None:
                self._contact_seen = True
                recent = self._since_tool is not None and self._since_tool <= self.tool_window
                if not recent or contact[1]:
                    return
            self.driven += step

    def _reached(self, q: float) -> bool:
        """The goal, whichever rule is in force. Both halves are required
        under min_tool_speed: enough travel was DRIVEN, and the joint is still
        that far from rest now."""
        if self.min_tool_speed is None:
            return self._moved(q) >= self.need
        return self.driven >= self.need and self._moved(q) >= self.need

    def update(self, v) -> bool:
        q, speed = self._split(v)
        if self.rest is None:
            self.arm(q)
            return False
        if self.min_tool_speed is not None:
            self._accumulate(q, speed, self._contact(v))
        moved = self._moved(q)
        self.peak = max(self.peak, moved)
        self.count = self.count + 1 if self._reached(q) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        """0..1 toward the goal, for the in-headset ring."""
        if self.rest is None or self.need <= 0.0:
            return 0.0
        near = self.peak if self.min_tool_speed is None else min(self.peak, self.driven)
        return max(0.0, min(1.0, near / self.need))

    def hold_progress(self) -> float:
        """0..1 through the sustained hold. Drops straight back to 0 the moment
        the criterion stops being satisfied, which is the point of it."""
        if self.hold_steps <= 0:
            return 0.0
        return max(0.0, min(1.0, self.count / self.hold_steps))

    def holds(self, q) -> bool:
        """Does the criterion hold RIGHT NOW? Non-mutating -- `driven` is
        whatever update() has accumulated, and is not added to here."""
        if self.rest is None:
            return False
        return self._reached(self._split(q)[0])

    def terms(self) -> dict:
        span, u = self._human(self.span)
        need, _ = self._human(self.need)
        driven_by = ("" if self.min_tool_speed is None else
                     f", driven while the tool moved >= "
                     f"{self.min_tool_speed:.2f} m/s"
                     + (f" AND had touched it within {self.tool_window} steps, with no hand "
                        f"on it" if self.require_tool_contact
                        else " (a hand pressing it in does not count)"))
        out = {"criterion": f"{self.label} moved >= {self.fraction:.0%} of its "
                            f"{span:.1f} {u} travel ({need:.1f} {u}, "
                            f"{self.direction}){driven_by} for "
                            f"{self.hold_steps} consecutive steps",
               "peak_travel": round(self.peak, 5),
               "threshold": round(self.need, 5),
               "fraction": self.fraction,
               "direction": self.direction,
               "unit": self.unit,
               "joint_range": [round(self.lo, 5), round(self.hi, 5)],
               "rest": None if self.rest is None else round(self.rest, 5)}
        if self.min_tool_speed is not None:
            out["min_tool_speed_mps"] = self.min_tool_speed
            if self.require_tool_contact:
                out["require_tool_contact"] = True
                out["tool_contact_window_steps"] = self.tool_window
                out["tool_contact_checked"] = self._contact_seen
            out["driven_travel"] = round(self.driven, 5)
            out[f"driven_travel_{'deg' if self.unit == 'rad' else 'mm'}"] = \
                round(self._human(self.driven)[0], 3)
        # The human-readable copies keep their old names for a hinge, so a
        # reader of the ARCTIC datasets sees the keys it always did.
        k = "deg" if self.unit == "rad" else "mm"
        out[f"peak_travel_{k}"] = round(self._human(self.peak)[0], 3)
        out[f"threshold_{k}"] = round(need, 3)
        out[f"joint_range_{k}"] = [round(self._human(self.lo)[0], 3),
                                   round(self._human(self.hi)[0], 3)]
        return out


def _qrot(q_xyzw, v):
    """Rotate v by quaternion q. Newton's body_q stores rotation as XYZW."""
    x, y, z, w = (float(c) for c in q_xyzw)
    vx, vy, vz = (float(c) for c in v)
    # t = 2 * (q_vec x v);  v' = v + w*t + q_vec x t
    tx = 2.0 * (y * vz - z * vy)
    ty = 2.0 * (z * vx - x * vz)
    tz = 2.0 * (x * vy - y * vx)
    return (vx + w * tx + (y * tz - z * ty),
            vy + w * ty + (z * tx - x * tz),
            vz + w * tz + (x * ty - y * tx))


class AxisUprightSuccess:
    """A body's chosen LOCAL axis brought within `tolerance_deg` of world up.

    An orientation test with no positional target: "stand it upright". Held
    for `hold_steps` like every other criterion, so a wobble through vertical
    does not count.
    """

    #: what update()/holds() want fed to them; see collect_env.success_value.
    VALUE = "pose"

    def __init__(self, axis_local=(0.0, 0.0, 1.0), tolerance_deg: float = 20.0,
                 hold_steps: int = 25, label: str = "upright"):
        a = np.asarray(axis_local, dtype=float)
        self.axis = a / max(float(np.linalg.norm(a)), 1e-12)
        self.max_tilt = float(np.radians(tolerance_deg))
        self.hold_steps = int(hold_steps)
        self.label = label
        self.count = 0
        self.best_tilt = float("inf")

    @staticmethod
    def _rot(q, v):
        q = np.asarray(q, dtype=float)
        u, w = q[:3], q[3]
        return v + 2.0 * np.cross(u, np.cross(u, v) + w * v)

    def _tilt(self, v) -> float:
        """`v` is a 7-vector pose (xyz + xyzw)."""
        up = self._rot(np.asarray(v[3:7], dtype=float), self.axis)
        return float(np.arccos(np.clip(up[2], -1.0, 1.0)))

    def arm(self, v):
        self.count = 0
        self.best_tilt = float("inf")

    def holds(self, v) -> bool:
        tilt = self._tilt(v)
        self.best_tilt = min(self.best_tilt, tilt)
        return tilt <= self.max_tilt

    def update(self, v) -> bool:
        self.count = self.count + 1 if self.holds(v) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        if not np.isfinite(self.best_tilt):
            return 0.0
        return float(np.clip(1.0 - self.best_tilt / max(self.max_tilt, 1e-9), 0.0, 1.0))

    def hold_progress(self) -> float:
        return float(np.clip(self.count / max(self.hold_steps, 1), 0.0, 1.0))

    def terms(self) -> dict:
        return {"best_tilt_deg": float(np.degrees(self.best_tilt))
                if np.isfinite(self.best_tilt) else None}


class InsertSuccess:
    """The target's head driven into a SECOND body's bore, held N steps.

    The first criterion that reads two bodies, which is what an assembly task
    is: "the peg is in the hole" is a statement about the pair, and no function
    of the peg's pose alone can express it -- move the hole and the same peg
    pose is right or wrong. So VALUE is "poses" and the pair arrives as
    ``(target_pose, into_pose)``, each a 7-vector (xyz + quaternion).

    Both are measured IN THE HOLE'S FRAME, not the world's, so a hole knocked
    askew or deliberately placed at an angle still grades correctly:

        head  = target_pos + R_target . head_local        (world)
        d     = R_into^-1 . (head - into_pos)             (hole frame)
        axial = d . axis          lateral = |d - axial.axis|

    and the criterion is ``lateral <= clearance_m and axial >= depth_m``.
    ``depth_m`` is measured from the hole's OWN ORIGIN along the axis, so on a
    symmetric part it is "past halfway"; a peg merely resting in the mouth has
    a negative axial and cannot satisfy it, which is the point.

    Two optional gates for a THROUGH-hole shorter than the peg (a 50 mm
    collar on a 200 mm peg, square_peg_socket_bimanual): ``max_depth_m``
    bounds the head from above -- past it the peg has gone through and out,
    and without the bound a peg held coaxially BEHIND the collar grades as
    inserted -- and ``tail_local`` is a second point on the target that must
    also be within ``clearance_m`` of the axis, so the peg is coaxial along
    its length and therefore threads the bore rather than poking its tip
    near the axis at an angle. With both, "the collar is fully on the peg,
    anywhere along it" is exactly head in [depth, max_depth] and both ends
    on the axis.

    The lateral gate is what makes this an insertion rather than a reach. The
    peg's head can be the right distance away while sitting beside the hole,
    and without the gate that grades as success.

    ``lateral_box_m`` replaces the round clearance with a BOX in the hole's
    frame, about ``into_local``: {"x": [lo, hi], "y": [lo, hi]} (any of
    x/y/z). For a receptacle that is a slot, not a bore -- a shelf, where the
    book may stand anywhere between the walls (Richard 2026-10-01: a book on
    the shelf's right side, on the floor 92 mm off centre, never went green
    under the 75 mm circle). "lateral" is then how far the head is OUTSIDE the
    box (0 inside), so the readout and the gate keep their meaning.

    ⚠️ The quaternion is read XYZW, the same way :class:`AxisUprightSuccess`
    reads it. Isaac Lab DOCUMENTS root_state_w as WXYZ, but passes the tuple
    verbatim into an XYZW slot for anything Newton drives -- see
    task_spec.rotation_xyzw, which is the same trap on the spawn side.
    """

    #: what update()/holds() want fed to them; see collect_env.success_value.
    VALUE = "poses"

    def __init__(self, head_local=(0.1, 0.0, 0.0), axis_local=(1.0, 0.0, 0.0),
                 clearance_m: float = 0.023, depth_m: float = 0.015,
                 hold_steps: int = 25, into: str = "hole",
                 into_local=(0.0, 0.0, 0.0), max_depth_m: float | None = None,
                 tail_local=None, tail_max_depth_m: float | None = None,
                 lateral_box_m: dict | None = None):
        a = np.asarray(axis_local, dtype=float)
        self.box = None
        if lateral_box_m:
            idx = {"x": 0, "y": 1, "z": 2}
            self.box = [(idx[k], float(lo), float(hi)) for k, (lo, hi) in lateral_box_m.items()]
            if any(lo > hi for _, lo, hi in self.box):
                raise ValueError(f"lateral_box_m needs [lo, hi] per axis, got {lateral_box_m!r}")
            clearance_m = 0.0
        self.axis = a / max(float(np.linalg.norm(a)), 1e-12)
        self.max_depth = None if max_depth_m is None else float(max_depth_m)
        if self.max_depth is not None and self.max_depth <= float(depth_m):
            raise ValueError(f"max_depth_m {max_depth_m} must exceed depth_m {depth_m}")
        self.tail = None if tail_local is None else np.asarray(tail_local, dtype=float)
        if self.tail is not None and self.tail.shape != (3,):
            raise ValueError(f"tail_local must be one xyz point, got {tail_local!r}")
        self.tail_max_depth = None if tail_max_depth_m is None else float(tail_max_depth_m)
        if self.tail_max_depth is not None and self.tail is None:
            raise ValueError("tail_max_depth_m requires tail_local")
        # ONE head, or SEVERAL: a symmetric part (Factory's round peg) goes in
        # either end first, and grading one tip would fail half the demos an
        # operator would call a success. With several, the head that is
        # deepest on the axis is the one graded; see state().
        self.heads = np.atleast_2d(np.asarray(head_local, dtype=float))
        if self.heads.shape[1] != 3:
            raise ValueError(f"head_local must be one xyz point or a list of "
                             f"them, got {head_local!r}")
        self.head = self.heads[0]
        # A point the axis passes through, in the hole's OWN frame. The
        # default is its origin, which is right for a socket whose bore is
        # centred. A gear base carries three shafts and none of them is at
        # the origin, so without this a gear seated on the middle shaft grades
        # as "20 mm off axis" forever. Depth is measured from this point too.
        # ONE hole, or SEVERAL: a tabletop with four threaded corner holes
        # takes a leg in any of them (FurnitureBench's one_leg), the way a
        # symmetric peg goes in either end. With several, the hole nearest
        # the head is the one graded, and ``origin`` is that hole each time
        # state() is read -- the tail check and the logged terms follow it.
        self.origins = np.atleast_2d(np.asarray(into_local, dtype=float))
        if self.origins.shape[1] != 3:
            raise ValueError(f"into_local must be one xyz point or a list of them, "
                             f"got {into_local!r}")
        self.origin = self.origins[0]
        self.clearance = float(clearance_m)
        self.depth = float(depth_m)
        self.hold_steps = int(hold_steps)
        self.into = str(into)
        self.count = 0
        self.start_depth: float | None = None
        self.best_depth = -float("inf")
        self.min_lateral = float("inf")

    @staticmethod
    def _rot(q, v):
        q = np.asarray(q, dtype=float)
        u, w = q[:3], q[3]
        v = np.asarray(v, dtype=float)
        return v + 2.0 * np.cross(u, np.cross(u, v) + w * v)

    @classmethod
    def _unrot(cls, q, v):
        q = np.asarray(q, dtype=float)
        return cls._rot(np.array([-q[0], -q[1], -q[2], q[3]]), v)

    def state(self, v):
        """(axial, lateral, head_world) for a `(target_pose, into_pose)` pair.

        Public because the startup banner prints it: a criterion that reads two
        bodies through a quaternion convention is exactly the kind that grades
        silently wrong, and one printed head position settles it.
        """
        obj, into = v
        obj = np.asarray(obj, dtype=float)
        into = np.asarray(into, dtype=float)
        best = None
        for origin in self.origins:
            for head in self.heads:
                head_w = obj[:3] + self._rot(obj[3:7], head)
                d = self._unrot(into[3:7], head_w - into[:3]) - origin
                axial = float(d @ self.axis)
                lateral = float(np.linalg.norm(d - axial * self.axis))
                if self.box is not None:
                    lateral = float(np.linalg.norm([max(0.0, lo - d[i], d[i] - hi)
                                                    for i, lo, hi in self.box]))
                # The head (and hole) to grade: on the axis and deepest wins;
                # if none is on the axis, the one nearest to it, so the banner
                # and the ring describe what the operator is actually offering.
                key = (lateral <= self.clearance, axial if lateral <= self.clearance
                       else -lateral)
                if best is None or key > best[0]:
                    best = (key, axial, lateral, head_w, origin)
        self.origin = best[4]
        return best[1], best[2], best[3]

    def arm(self, v):
        self.count = 0
        self.best_depth = -float("inf")
        self.min_lateral = float("inf")
        self.start_depth = None if v is None else self.state(v)[0]

    def tail_state(self, v) -> tuple[float, float]:
        """Tail position along and away from the bore axis, in the hole's frame."""
        obj, into = v
        obj = np.asarray(obj, dtype=float)
        into = np.asarray(into, dtype=float)
        tail_w = obj[:3] + self._rot(obj[3:7], self.tail)
        d = self._unrot(into[3:7], tail_w - into[:3]) - self.origin
        axial = float(d @ self.axis)
        return axial, float(np.linalg.norm(d - axial * self.axis))

    def tail_lateral(self, v) -> float:
        return self.tail_state(v)[1]

    def holds(self, v) -> bool:
        axial, lateral, _ = self.state(v)
        if self.start_depth is None:
            self.start_depth = axial
        self.min_lateral = min(self.min_lateral, lateral)
        # Depth is only credited while the head is ON the bore axis. A peg
        # swung past the hole reaches any axial distance you like.
        if lateral <= self.clearance:
            self.best_depth = max(self.best_depth, axial)
        ok = lateral <= self.clearance and axial >= self.depth
        if self.max_depth is not None:
            ok = ok and axial <= self.max_depth
        if ok and self.tail is not None:
            tail_axial, tail_lateral = self.tail_state(v)
            ok = tail_lateral <= self.clearance
            if self.tail_max_depth is not None:
                ok = ok and tail_axial <= self.tail_max_depth
        return ok

    def update(self, v) -> bool:
        self.count = self.count + 1 if self.holds(v) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        """0..1 along the journey from where the peg was armed to the depth
        asked for.

        NOT `best_depth / depth`. `depth_m` is measured from the hole's own
        origin and is routinely NEGATIVE -- a bore deeper than the engagement
        being asked for puts its mouth behind its centre -- so a ratio of the
        two is meaningless and, with the guard that used to sit here, read a
        flat zero for the whole demo. Anchoring on the armed pose is what
        LiftSuccess does with `rest_z` and it works for either sign.

        Credit needs the head ON THE AXIS, so an aligned peg being pushed in
        fills the ring through its approach, and one swung past the hole from
        the side earns nothing.
        """
        if not np.isfinite(self.best_depth) or self.start_depth is None:
            return 0.0
        span = self.depth - self.start_depth
        if span <= 0.0:                # armed already at or past the threshold
            return 1.0 if self.best_depth >= self.depth else 0.0
        return float(np.clip((self.best_depth - self.start_depth) / span,
                             0.0, 1.0))

    def hold_progress(self) -> float:
        return float(np.clip(self.count / max(self.hold_steps, 1), 0.0, 1.0))

    def terms(self) -> dict:
        where = (f"head inside the box {[(('xyz'[i]), round(lo * 1e3), round(hi * 1e3)) for i, lo, hi in self.box]} mm of {self.into}'s frame"
                 if self.box is not None else
                 f"head within {self.clearance * 1e3:.0f} mm of the {self.into} axis")
        return {"criterion": f"{where} AND >= {self.depth * 1e3:.0f} mm "
                             f"past its origin"
                             + (f" AND <= {self.max_depth * 1e3:.0f} mm"
                                if self.max_depth is not None else "")
                             + (f" AND the tail within {self.clearance * 1e3:.0f} mm "
                                f"of the axis" if self.tail is not None else "")
                             + (f" AND tail <= {self.tail_max_depth * 1e3:.0f} mm"
                                if self.tail_max_depth is not None else "")
                             + f", for {self.hold_steps} consecutive steps",
                **({"max_depth_mm": round(self.max_depth * 1e3, 3)}
                   if self.max_depth is not None else {}),
                **({"tail_local_m": [round(float(c), 5) for c in self.tail]}
                   if self.tail is not None else {}),
                **({"tail_max_depth_mm": round(self.tail_max_depth * 1e3, 3)}
                   if self.tail_max_depth is not None else {}),
                "into": self.into,
                "armed_at_mm": (None if self.start_depth is None
                                else round(self.start_depth * 1e3, 3)),
                "deepest_mm": (None if not np.isfinite(self.best_depth)
                               else round(self.best_depth * 1e3, 3)),
                "closest_to_axis_mm": (None if not np.isfinite(self.min_lateral)
                                       else round(self.min_lateral * 1e3, 3)),
                "clearance_mm": round(self.clearance * 1e3, 3),
                "depth_mm": round(self.depth * 1e3, 3),
                "head_local_m": [round(float(c), 5) for c in self.head],
                **({"heads_local_m": [[round(float(c), 5) for c in h]
                                      for h in self.heads]}
                   if len(self.heads) > 1 else {}),
                "axis_local": [round(float(c), 5) for c in self.axis],
                "into_local_m": [round(float(c), 5) for c in self.origin],
                **({"holes_local_m": [[round(float(c), 5) for c in o]
                                      for o in self.origins]}
                   if len(self.origins) > 1 else {})}


class ThroughSuccess(InsertSuccess):
    """A peg IN a through-bore by at least `min_engagement_m`, entering by EITHER end from
    EITHER mouth, the part inside within `clearance_m` of the axis -- held N steps.

    `InsertSuccess` grades one point on the peg against a one-sided depth, which is right for
    a blind hole and wrong for a tunnel: square_peg_socket graded only the orange head going in
    through the teal mouth, so the same square peg offered tail first failed, and anything on
    the axis BEHIND the socket passed without entering it. Here the peg is its centreline, the
    segment from `tail_local` to `head_local`, and what is graded is how much of that segment
    lies inside the bore's extent `bore_m` = [lo, hi] along the axis (in the fixture's frame,
    from `into_local`) -- the same number whichever end leads and whichever mouth it used, and
    it only grows as the peg goes deeper, so a peg pushed right through still passes.

    The lateral gate is checked on the centreline where it is INSIDE the bore, at both ends of
    the overlap: the distance from the bore axis to points along a straight segment is convex,
    so the ends of the overlap bound all of it. A peg beside the socket, or lying across its
    mouth, has its inside part off the axis or no inside part at all.

    `min_engagement_m` equal to the bore's length (hi - lo) is "all the way through": the
    collar of square_peg_socket_bimanual is fully on the peg, either way round.

    `end_clearance_m` (optional) also gates BOTH ends of the peg to within that of the axis --
    the collar's rule before it was made symmetric, kept so its recorded demos grade on the
    same frames (a peg genuinely through a 3 mm-clearance collar can have its far end 24 mm off
    the axis, and 7 of its 50 demos cross 25 mm on the way).
    """

    VALUE = "poses"
    _EPS = 1e-9

    def __init__(self, bore_m, min_engagement_m: float, head_local, tail_local,
                 axis_local=(1.0, 0.0, 0.0), clearance_m: float = 0.023, hold_steps: int = 25,
                 into: str = "socket", into_local=(0.0, 0.0, 0.0),
                 end_clearance_m: float | None = None):
        lo, hi = (float(x) for x in bore_m)
        if not hi > lo:
            raise ValueError(f"bore_m {bore_m} must be [lo, hi] with hi > lo")
        if not 0.0 < float(min_engagement_m) <= hi - lo + self._EPS:
            raise ValueError(f"min_engagement_m {min_engagement_m} must be in (0, {hi - lo}]")
        if tail_local is None or np.atleast_2d(np.asarray(head_local, float)).shape[0] != 1:
            raise ValueError("ThroughSuccess needs ONE head_local and a tail_local: the peg's "
                             "two ends")
        super().__init__(head_local=head_local, axis_local=axis_local, clearance_m=clearance_m,
                         depth_m=float(min_engagement_m), hold_steps=hold_steps, into=into,
                         into_local=into_local, tail_local=tail_local)
        self.bore = (lo, hi)
        self.min_engagement = float(min_engagement_m)
        self.end_clearance = None if end_clearance_m is None else float(end_clearance_m)
        self.best_engagement = 0.0
        self.entry: dict | None = None

    def _local(self, v, point):
        obj, into = (np.asarray(x, dtype=float) for x in v)
        w = obj[:3] + self._rot(obj[3:7], point)
        return self._unrot(into[3:7], w - into[:3]) - self.origin

    def engagement(self, v) -> tuple[float, float, dict]:
        """(length of the centreline inside the bore, its worst distance from the axis there,
        which end leads and through which mouth)."""
        dh, dt = self._local(v, self.head), self._local(v, self.tail)
        ah, at = float(dh @ self.axis), float(dt @ self.axis)
        lo, hi = self.bore
        a0, a1 = max(lo, min(ah, at)), min(hi, max(ah, at))
        if a1 <= a0 or abs(ah - at) < 1e-12:
            return 0.0, float("inf"), {}
        worst = 0.0
        for a in (a0, a1):
            p = dt + (a - at) / (ah - at) * (dh - dt)
            worst = max(worst, float(np.linalg.norm(p - float(p @ self.axis) * self.axis)))
        # Which mouth it came in by: the side the rest of the peg still sticks out of. The
        # leading end is the one deeper from that mouth. Through, or wholly inside, neither
        # is knowable from one frame -- say which end is on the `hi` side instead.
        out_lo, out_hi = min(ah, at) < lo, max(ah, at) > hi
        if out_lo and not out_hi:
            entry = {"mouth": "lo", "leading_end": "head" if ah > at else "tail"}
        elif out_hi and not out_lo:
            entry = {"mouth": "hi", "leading_end": "head" if ah < at else "tail"}
        else:
            entry = {"mouth": "through" if out_lo else "inside",
                     "hi_side_end": "head" if ah > at else "tail"}
        return a1 - a0, worst, entry

    def state(self, v):
        """(engagement, its lateral, head_world) -- the banner and ring read `state()`, and for
        a through-bore the number that grows toward the goal is the engagement."""
        eng, lat, _ = self.engagement(v)
        obj = np.asarray(v[0], dtype=float)
        return eng, (lat if np.isfinite(lat) else 1.0), obj[:3] + self._rot(obj[3:7], self.head)

    def ends_lateral(self, v) -> float:
        """The farther of the peg's two ends from the bore axis."""
        return max(float(np.linalg.norm(d - float(d @ self.axis) * self.axis))
                   for d in (self._local(v, self.head), self._local(v, self.tail)))

    def holds(self, v) -> bool:
        eng, lat, entry = self.engagement(v)
        if self.start_depth is None:
            self.start_depth = eng
        if np.isfinite(lat):
            self.min_lateral = min(self.min_lateral, lat)
        if lat <= self.clearance:
            self.best_depth = max(self.best_depth, eng)
            self.best_engagement = max(self.best_engagement, eng)
            # How it went in is only readable as it ENTERS -- pushed through, the peg sticks out
            # of the far mouth and looks as if it came from there. The first frame on the axis
            # with some of it inside and the rest still out of one mouth decides.
            if self.entry is None and eng > 0.0 and entry.get("leading_end"):
                self.entry = entry
        ok = lat <= self.clearance and eng >= self.min_engagement - self._EPS
        if ok and self.end_clearance is not None:
            ok = self.ends_lateral(v) <= self.end_clearance
        return ok

    def progress(self) -> float:
        return float(np.clip(self.best_engagement / self.min_engagement, 0.0, 1.0))

    def terms(self) -> dict:
        lo, hi = self.bore
        return {"criterion": f"the peg's centreline inside the {self.into}'s bore "
                             f"[{lo * 1e3:.0f}, {hi * 1e3:.0f}] mm for >= "
                             f"{self.min_engagement * 1e3:.0f} mm, entering by either end from "
                             f"either mouth, within {self.clearance * 1e3:.0f} mm of the axis "
                             f"there"
                             + (f", both ends within {self.end_clearance * 1e3:.0f} mm of it"
                                if self.end_clearance is not None else "")
                             + f", for {self.hold_steps} consecutive steps",
                "into": self.into,
                "bore_mm": [round(lo * 1e3, 3), round(hi * 1e3, 3)],
                "min_engagement_mm": round(self.min_engagement * 1e3, 3),
                "engaged_mm": round(self.best_engagement * 1e3, 3),
                "entered": self.entry,
                **({"end_clearance_mm": round(self.end_clearance * 1e3, 3)}
                   if self.end_clearance is not None else {}),
                "closest_to_axis_mm": (None if not np.isfinite(self.min_lateral)
                                       else round(self.min_lateral * 1e3, 3)),
                "clearance_mm": round(self.clearance * 1e3, 3),
                "head_local_m": [round(float(c), 5) for c in self.head],
                "tail_local_m": [round(float(c), 5) for c in self.tail],
                "axis_local": [round(float(c), 5) for c in self.axis],
                "into_local_m": [round(float(c), 5) for c in self.origin]}

    def arm(self, v):
        super().arm(None)
        self.best_engagement, self.entry = 0.0, None
        self.start_depth = None if v is None else self.engagement(v)[0]


class ThreadSuccess(InsertSuccess):
    """Require net screwing motion while aligned and engaged, then hold.

    Rotation is measured about the insertion axis in the bolt's frame.
    Positive rotation follows the right-hand rule around that axis (clockwise
    viewed from above for a downward axis). holds() never credits motion;
    only update() advances history, so HUD/probe reads cannot add turns.

    Two things a hand does to a real screw are NOT cheats (headset,
    2026-09-29, furniture_one_leg: seated after two clean turns, never green):

    * a moment off the axis or tilted -- a regrip shove, a grip spike. Up to
      ``max_gap_steps`` consecutive such steps PAUSE the count (nothing is
      credited across the gap, and a pitch skipped during it is caught by the
      pitch check on the next aligned step); a longer loss still resets.
    * a mismatch between turning and advancing. The credit is CLAMPED to
      what the advance supports rather than thrown away (headset,
      2026-09-29, bolt_nut_in_air: reset at 0.43, 1.90 and 0.33 turns, each
      time a ~2.2 mm settle in the thread's play or on its start while the
      nut was turning properly). Rotation that outruns the advance --
      spinning in place, backing up, tightening against a seat -- is
      capped at advance / pitch (+ tolerance), so it earns nothing; advance
      that outruns rotation -- a shove, a settle, a ridge skipped -- moves
      the reference instead, so the drop earns nothing either. Every credited
      turn is a turn the nut ALSO travelled a pitch for, which is all the
      old reset guaranteed, without losing the turns already earned.
    """

    def __init__(self, *, pitch_m, min_turns, engagement_depth_m,
                 max_tilt_deg, pitch_tolerance_m, max_gap_steps=25, **kwargs):
        super().__init__(**kwargs)
        self.pitch = float(pitch_m)
        self.min_turns = float(min_turns)
        self.engagement_depth = float(engagement_depth_m)
        self.max_tilt = float(max_tilt_deg)
        self.pitch_tolerance = float(pitch_tolerance_m)
        #: 25 = 0.1 s at 250 Hz
        self.max_gap = int(max_gap_steps)
        #: why the last attempt that had credit was thrown away (for the log)
        self.last_reset = None
        self.resets = 0
        #: steps whose credit was clamped to the advance (or the drop dropped)
        self.clamps = 0
        self._clear_thread()

    def _clear_thread(self, why=None):
        if why is not None and getattr(self, "turns", 0.0) > 0.05:
            self.last_reset = f"{why} at {self.turns:.2f} turns"
            self.resets += 1
        self.turns = 0.0
        self._thread_start = None
        self._previous_radial = None
        self._gap = 0
        self.count = 0

    def arm(self, v):
        super().arm(v)
        self.last_reset, self.resets, self.clamps = None, 0, 0
        self._clear_thread()

    def _thread_pose(self, v):
        obj, into = (np.asarray(p, dtype=float) for p in v)
        axial, lateral, _ = self.state(v)
        up = self._unrot(into[3:7], self._rot(obj[3:7], [0, 0, 1]))
        tilt = np.degrees(np.arccos(np.clip(up @ -self.axis, -1, 1)))
        radial = self._unrot(into[3:7], self._rot(obj[3:7], [1, 0, 0]))
        radial -= self.axis * (radial @ self.axis)
        radial /= max(float(np.linalg.norm(radial)), 1e-12)
        valid = (np.isfinite(axial + lateral + tilt) and
                 axial >= self.engagement_depth and lateral <= self.clearance
                 and tilt <= self.max_tilt)
        return axial, radial, valid

    def holds(self, v):
        axial, _, valid = self._thread_pose(v)
        return bool(valid and self._thread_start is not None and
                    self.turns >= self.min_turns - 1e-9 and axial >= self.depth - 1e-9 and
                    abs(axial - self._thread_start - self.pitch * self.turns)
                    <= self.pitch_tolerance + 1e-9)     # a clamp lands exactly on it

    def update(self, v):
        axial, radial, valid = self._thread_pose(v)
        if not np.isfinite(axial) or axial < self.engagement_depth:
            self._clear_thread("left the thread")
            return False
        if not valid:
            # Engaged, but off the axis or tilted: pause, then reset if it lasts.
            self._previous_radial = None
            self.count = 0
            self._gap += 1
            if self._gap > self.max_gap:
                self._clear_thread(f"off the axis or tilted for over {self.max_gap} steps")
            return False
        self._gap = 0
        if self._thread_start is None:
            self._thread_start = axial
        elif self._previous_radial is not None:
            delta = np.arctan2(self.axis @ np.cross(self._previous_radial, radial),
                               self._previous_radial @ radial)
            self.turns += float(delta / (2 * np.pi))
        slip = axial - self._thread_start - self.pitch * self.turns
        if slip < -self.pitch_tolerance:
            # Turned more than it advanced (spin in place, backed up, a seat):
            # only the advance's worth of turning counts.
            self.turns = (axial - self._thread_start + self.pitch_tolerance) / self.pitch
            self.clamps += 1
        elif slip > self.pitch_tolerance:
            # Advanced more than it turned (shove, settle, skipped ridge): the
            # drop is not credited, the turns already earned stand.
            self._thread_start = axial - self.pitch * self.turns - self.pitch_tolerance
            self.clamps += 1
        self._previous_radial = radial.copy()
        return super().update(v)

    def progress(self):
        return float(np.clip(self.turns / self.min_turns, 0, 1))

    def terms(self):
        return {**super().terms(),
                "criterion": "aligned, pitch-consistent net screwing motion, then depth held",
                "net_turns": self.turns, "required_turns": self.min_turns,
                "pitch_mm": self.pitch * 1000, "max_tilt_deg": self.max_tilt,
                "pitch_tolerance_mm": self.pitch_tolerance * 1000}


class SeparateSuccess(InsertSuccess):
    """The target's head carried AWAY from a point on a second body, held N
    steps: a cap OFF its neck, a nut OFF its bolt.

    The inverse of :class:`InsertSuccess`, sharing its frame arithmetic --
    the head measured in the other body's frame, so a bottle held at an
    angle grades the same -- and differing in what it asks: the DISTANCE
    from the seat, in any direction, not a depth along an axis::

        d = R_into^-1 . (head - into_pos) - into_local
        |d| >= min_m

    Why not ``insert`` with a large clearance: an insertion's gate is
    "on the axis", and a cap that has been unscrewed is no longer on any
    axis -- it is in the other hand, then on the table, wherever the
    operator put it. A criterion that resets the moment the removed cap
    leaves a cylinder round the neck never fires for a real uncapping
    (measured in the headset, 2026-09-11). Distance from the seat is met
    by any of those and by nothing a cap does while it is still on its
    thread: on a 5 mm-pitch, one-turn thread with 0.5 mm of play the
    ceiling cannot get 4.5 mm from its seat without a turn.

    ``min_m`` should be where NOTHING of the target can still be on the
    other body -- for a cap, its skirt's length above the rim, not the
    thread's pitch. 🔴 It was a pitch less the play (4.5 mm on the bottle),
    "where the thread lets go", and that fired for caps that had NOT been
    unscrewed: a cap cross-threaded by the grip reaches 5 mm of rise, or 3 mm
    of rise plus 4 mm sideways, while its skirt is still round the neck
    (headset, 2026-09-12, two of eight demos). Nothing a cap does with the
    neck inside it puts its ceiling a skirt's length from the rim, in any
    direction, so 20 mm on an 18 mm skirt is "separated" and a pitch is
    "loose". A probe pose that hangs the cap on its last ridge is then a
    pose the criterion must NOT accept -- the task file's probe block says
    so with ``"criterion": "must_not_hold"``. The progress ring fills with
    the distance.
    """

    VALUE = "poses"

    def __init__(self, head_local=(0.0, 0.0, 0.0), min_m: float = 0.005,
                 hold_steps: int = 25, into: str = "bottle",
                 into_local=(0.0, 0.0, 0.0)):
        # The axis is unused by the test but drawn by the HUD's banner and
        # read by InsertSuccess.state to pick a head; one head, any axis.
        super().__init__(head_local=head_local, axis_local=(0.0, 0.0, 1.0),
                         clearance_m=float("inf"), depth_m=0.0,
                         hold_steps=hold_steps, into=into, into_local=into_local)
        self.min_m = float(min_m)
        self.best_dist = 0.0

    def distance(self, v) -> float:
        axial, lateral, _ = self.state(v)
        return float(np.hypot(axial, lateral))

    def arm(self, v):
        self.count = 0
        self.best_dist = 0.0
        self.start_depth = None if v is None else self.distance(v)

    def holds(self, v) -> bool:
        d = self.distance(v)
        self.best_dist = max(self.best_dist, d)
        return d >= self.min_m

    def progress(self) -> float:
        return float(np.clip(self.best_dist / max(self.min_m, 1e-9), 0.0, 1.0))

    def terms(self) -> dict:
        return {"criterion": f"head at least {self.min_m * 1e3:.1f} mm from its "
                             f"seat on the {self.into}, any direction, for "
                             f"{self.hold_steps} consecutive steps",
                "into": self.into,
                "farthest_mm": round(self.best_dist * 1e3, 3),
                "min_mm": round(self.min_m * 1e3, 3),
                "head_local_m": [round(float(c), 5) for c in self.head],
                "into_local_m": [round(float(c), 5) for c in self.origin]}


class JointSequenceSuccess:
    """Several joints, in ORDER: a long-horizon task whose steps each read one
    joint coordinate -- pull nail A out, then drive nail B in.

    ``steps`` is a list of dicts, each with ``name`` (the object whose joint
    is read; the value fed to update() is ``{name: q}``), ``direction``
    ("increase" / "decrease"), and either ``to`` -- an absolute coordinate
    the joint must reach in that direction (q <= to for decrease, q >= to for
    increase) -- or ``need`` -- a travel from where the joint was when the
    criterion was armed. ``unit`` per step ("m" / "rad") is for reporting.

    A step LATCHES once met: the nail that was pulled out may be nudged back
    a little while the second one is driven without undoing the first. The
    LAST step is the one held: `hold_steps` consecutive steps with it
    satisfied. Progress is the number of steps done plus the fraction of the
    current one. Re-arming forgets every latch, so a scene reset starts over.
    """

    VALUE = "joints"

    def __init__(self, steps: list, hold_steps: int = 25):
        if not steps:
            raise ValueError("a joint sequence needs at least one step")
        self.steps = []
        for s in steps:
            d = str(s.get("direction", "increase"))
            if d not in ("increase", "decrease"):
                raise ValueError(f"step direction must be increase or decrease, got {d!r}")
            if ("to" in s) == ("need" in s):
                raise ValueError("each step needs exactly one of 'to' (absolute) or "
                                 "'need' (travel from rest)")
            self.steps.append({"name": str(s["name"]), "direction": d,
                               "to": (None if "to" not in s else float(s["to"])),
                               "need": (None if "need" not in s else float(s["need"])),
                               "unit": str(s.get("unit", "m"))})
        self.hold_steps = int(hold_steps)
        self.names = [s["name"] for s in self.steps]
        self.rest: dict | None = None
        self.done = 0            # steps latched so far
        self.count = 0           # consecutive steps the LAST one has held
        self.best = 0.0          # best fraction of the current step seen

    def arm(self, value):
        self.rest = {k: float(v) for k, v in dict(value).items()}
        self.done, self.count, self.best = 0, 0, 0.0

    def _frac(self, i: int, value) -> float:
        """0..1: how far step i is toward being met, from its own start."""
        s = self.steps[i]
        q = float(value[s["name"]])
        r = float(self.rest[s["name"]])
        sign = 1.0 if s["direction"] == "increase" else -1.0
        if s["to"] is not None:
            goal = sign * (s["to"] - r)
            if goal <= 0.0:          # already past it at rest: met at once
                return 1.0
            return max(0.0, min(1.0, sign * (q - r) / goal))
        return max(0.0, min(1.0, sign * (q - r) / max(s["need"], 1e-12)))

    def _met(self, i: int, value) -> bool:
        return self._frac(i, value) >= 1.0

    def update(self, value) -> bool:
        if self.rest is None:
            self.arm(value)
            return False
        # Latch every step that is met, in order, on this same tick.
        while self.done < len(self.steps) - 1 and self._met(self.done, value):
            self.done += 1
            self.best = 0.0
        last = len(self.steps) - 1
        if self.done == last:
            self.best = max(self.best, self._frac(last, value))
            self.count = self.count + 1 if self._met(last, value) else 0
            return self.count >= self.hold_steps
        self.best = max(self.best, self._frac(self.done, value))
        self.count = 0
        return False

    def progress(self) -> float:
        if self.rest is None:
            return 0.0
        return max(0.0, min(1.0, (self.done + self.best) / len(self.steps)))

    def hold_progress(self) -> float:
        if self.hold_steps <= 0:
            return 0.0
        return max(0.0, min(1.0, self.count / self.hold_steps))

    def holds(self, value) -> bool:
        """Every latched step is behind us and the last one is met now."""
        if self.rest is None:
            return False
        return self.done == len(self.steps) - 1 and self._met(self.done, value)

    def state(self, value) -> str:
        """One line for the status column: which step, and how far."""
        if self.rest is None:
            return "unarmed"
        i = min(self.done, len(self.steps) - 1)
        s = self.steps[i]
        q = float(value[s["name"]])
        scale, u = (1e3, "mm") if s["unit"] == "m" else (float(np.degrees(1.0)), "deg")
        return (f"step {i + 1}/{len(self.steps)} {s['name']} {q * scale:+.1f} {u} "
                f"({self._frac(i, value):.0%})")

    def terms(self) -> dict:
        def _h(s, v):
            return (round(v * 1e3, 3), "mm") if s["unit"] == "m" else (round(float(np.degrees(v)), 3), "deg")
        return {"criterion": " then ".join(
                    f"{s['name']} {s['direction']} "
                    + (f"to {_h(s, s['to'])[0]} {_h(s, s['to'])[1]}" if s["to"] is not None
                       else f"by {_h(s, s['need'])[0]} {_h(s, s['need'])[1]}")
                    for s in self.steps) + f", the last held {self.hold_steps} consecutive steps",
                "steps_done": self.done, "steps": len(self.steps),
                "rest": None if self.rest is None else {k: round(v, 5) for k, v in self.rest.items()}}


class PoseTargetSuccess:
    """An object brought to a place on the table (and, optionally, a facing).

    For the tasks where nothing is lifted or inserted: a T pushed onto its
    outline, a cube pulled back with a hook, a crate walked across the table.
    Reads ONE object's pose, the target's or the one ``of`` names -- a hook
    task holds the hook, and it is the CUBE that has to arrive.

    The goal is written in the TABLE frame (x toward the far edge, y left,
    z up from the table top, origin at the table's centre), because a goal is
    a place on the table and the table is what an operator sees:

    * ``goal_xy`` + ``tol_m``: centre within tol_m of that point (xy only);
    * ``region``: {"x": [lo, hi], "y": [lo, hi], "z": [lo, hi]} -- every
      named axis inside its range (z is the object centre's height above the
      table top);
    * ``goal_yaw_deg`` + ``tol_deg`` (+ ``symmetry`` n: a T has 1, a square 4):
      the object's local +x, projected on the table, within tol of the goal
      yaw, modulo 360/n;
    * ``displace_m``: the centre's xy has moved at least this far from where
      it started -- "walk the crate over there", graded without naming where;
    * ``goal_of``: the goal is ANOTHER OBJECT's pose -- its origin is the goal
      point and its local +x the goal yaw -- read every frame, so a goal
      marker can be randomized like everything else (push_t's outline,
      2026-09-30). Replaces ``goal_xy`` / ``goal_yaw_deg``; tol_m, tol_deg and
      symmetry still apply.

    Every condition given must hold together, for hold_steps.
    """

    VALUE = "named_poses"

    def __init__(self, name: str, table_xyz, hold_steps: int, goal_xy=None, tol_m=0.02,
                 region=None, goal_yaw_deg=None, tol_deg=15.0, symmetry=1, displace_m=None,
                 label="pose", goal_of=None):
        if goal_of is not None and (goal_xy is not None or goal_yaw_deg is not None):
            raise ValueError("pose_target: goal_of replaces goal_xy / goal_yaw_deg")
        self.name = name
        self.goal_of = goal_of
        self.pose_names = [name] + ([goal_of] if goal_of else [])
        self.table = np.asarray(table_xyz, dtype=float)
        self.hold_steps = int(hold_steps)
        self.goal_xy = None if goal_xy is None else np.asarray(goal_xy, dtype=float)
        self.tol = float(tol_m)
        self.region = {k: tuple(float(x) for x in v) for k, v in (region or {}).items()}
        self.goal_yaw = None if goal_yaw_deg is None else float(goal_yaw_deg)
        self.tol_deg = float(tol_deg)
        self.sym = max(1, int(symmetry))
        self.displace = None if displace_m is None else float(displace_m)
        self.label = label
        self.count = 0
        self.start = None
        self.best = {}

    def _local(self, v, name=None):
        p = np.asarray(v[name or self.name][:3], dtype=float) - self.table
        return p

    @staticmethod
    def _yaw(pose7):
        ax = _qrot(np.asarray(pose7[3:7], dtype=float), np.array([1.0, 0.0, 0.0]))
        return float(np.degrees(np.arctan2(ax[1], ax[0])))

    def _goal(self, v):
        """(goal xy in the table frame, goal yaw in degrees), either as
        written or off the goal object this frame."""
        if self.goal_of is None:
            return self.goal_xy, self.goal_yaw
        return self._local(v, self.goal_of)[:2], self._yaw(v[self.goal_of])

    def _yaw_err(self, v, goal_yaw=None):
        yaw = self._yaw(v[self.name])
        per = 360.0 / self.sym
        d = (yaw - (self.goal_yaw if goal_yaw is None else goal_yaw)) % per
        return float(min(d, per - d))

    def state(self, v) -> dict:
        p = self._local(v)
        st = {"x": float(p[0]), "y": float(p[1]), "z": float(p[2])}
        goal_xy, goal_yaw = self._goal(v)
        if goal_xy is not None:
            st["dist_m"] = float(np.linalg.norm(p[:2] - goal_xy))
        if goal_yaw is not None:
            st["yaw_err_deg"] = self._yaw_err(v, goal_yaw)
        if self.displace is not None and self.start is not None:
            st["moved_m"] = float(np.linalg.norm(p[:2] - self.start[:2]))
        return st

    def arm(self, v):
        self.count = 0
        self.start = self._local(v)
        self.best = {}

    def holds(self, v) -> bool:
        st = self.state(v)
        for k in ("dist_m", "yaw_err_deg"):
            if k in st:
                self.best[k] = min(self.best.get(k, float("inf")), st[k])
        if "moved_m" in st:
            self.best["moved_m"] = max(self.best.get("moved_m", 0.0), st["moved_m"])
        ok = True
        if "dist_m" in st:
            ok &= st["dist_m"] <= self.tol
        for ax, (lo, hi) in self.region.items():
            ok &= lo <= st[ax] <= hi
        if "yaw_err_deg" in st:
            ok &= st["yaw_err_deg"] <= self.tol_deg
        if self.displace is not None:
            ok &= st.get("moved_m", 0.0) >= self.displace
        return bool(ok)

    def update(self, v) -> bool:
        self.count = self.count + 1 if self.holds(v) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        if "dist_m" in self.best:
            return float(np.clip(1.0 - (self.best["dist_m"] - self.tol) / 0.2, 0.0, 1.0))
        if self.displace is not None:
            return float(np.clip(self.best.get("moved_m", 0.0) / self.displace, 0.0, 1.0))
        return 0.0

    def hold_progress(self) -> float:
        return float(np.clip(self.count / max(self.hold_steps, 1), 0.0, 1.0))

    def terms(self) -> dict:
        return {k: round(v, 5) for k, v in self.best.items()}


class CountSuccess:
    """N of a set of objects each in place, held together.

    Nine pegs in a nine-hole board, four pegs in a tray, balls poured into a
    bowl. Each named object is IN when one of the ``into`` body's seats holds
    it; a seat holds at most one object.

    * ``mode: "insert"`` -- a seat is a point on ``into`` (``holes``, in its
      frame) with an ``axis``; the object's ``head_local`` point is within
      ``clearance_m`` of that axis and at least ``depth_m`` along it, like
      :class:`InsertSuccess` per peg;
    * ``mode: "region"`` -- one seat, a cylinder in ``into``'s frame about
      ``axis`` through ``center_local``, ``radius_m`` wide and ``z_m``
      [lo, hi] along the axis: a bowl's inside. Any number may be in it.

    ``max_tilt_deg`` (insert mode, optional): the object's ``up_local`` axis
    must also be within that angle of ``-axis`` in the ``into`` frame --
    FurnitureBench's orientation bound (cos 0.94, ~20 deg) without its yaw
    term, which a thread's axial play makes meaningless at the seat.
    """

    VALUE = "named_poses"

    def __init__(self, names, into: str, need: int, hold_steps: int, mode="insert",
                 holes=None, axis=(0.0, 0.0, 1.0), head_local=(0.0, 0.0, 0.0), clearance_m=0.003,
                 depth_m=0.01, center_local=(0.0, 0.0, 0.0), radius_m=0.05, z_m=(-0.05, 0.05),
                 max_tilt_deg=None, up_local=(0.0, 0.0, 1.0), max_depth_m=None):
        self.names = list(names)
        self.into = into
        self.pose_names = self.names + [into]
        self.need = int(need)
        self.hold_steps = int(hold_steps)
        self.mode = mode
        self.holes = [np.asarray(h, dtype=float) for h in (holes or [(0.0, 0.0, 0.0)])]
        a = np.asarray(axis, dtype=float)
        self.axis = a / max(np.linalg.norm(a), 1e-12)
        self.head = np.asarray(head_local, dtype=float)
        self.clear = float(clearance_m)
        self.depth = float(depth_m)
        # The far end of a hole along its axis: without it a slot's line runs on
        # past its seat, and a plate standing on its stand across the table,
        # lined up with one, counted as racked (2026-10-28).
        self.max_depth = None if max_depth_m is None else float(max_depth_m)
        if self.max_depth is not None and self.max_depth <= self.depth:
            raise ValueError(f"max_depth_m {max_depth_m} must exceed depth_m {depth_m}")
        self.center = np.asarray(center_local, dtype=float)
        self.radius = float(radius_m)
        self.zr = tuple(float(x) for x in z_m)
        self.cos_tilt = (None if max_tilt_deg is None
                         else float(np.cos(np.radians(float(max_tilt_deg)))))
        self.up = np.asarray(up_local, dtype=float)
        self.count = 0
        self.best = 0

    def _upright(self, v, name) -> bool:
        if self.cos_tilt is None:
            return True
        up = (np.asarray(self._to_into(v, self._in_frame(v, name, self.up)), dtype=float)
              - np.asarray(self._to_into(v, self._in_frame(v, name, np.zeros(3))), dtype=float))
        up /= max(float(np.linalg.norm(up)), 1e-12)
        return float(up @ -self.axis) >= self.cos_tilt

    def _in_frame(self, v, name, local):
        P = np.asarray(v[name], dtype=float)
        return P[:3] + _qrot(P[3:7], local)

    def _to_into(self, v, w):
        R = np.asarray(v[self.into], dtype=float)
        qi = np.array([-R[3], -R[4], -R[5], R[6]])
        return _qrot(qi, w - R[:3])

    def n_in(self, v) -> int:
        if self.mode == "region":
            n = 0
            for nm in self.names:
                x = self._to_into(v, self._in_frame(v, nm, self.head)) - self.center
                ax = float(x @ self.axis)
                lat = float(np.linalg.norm(x - ax * self.axis))
                n += int(lat <= self.radius and self.zr[0] <= ax <= self.zr[1])
            return n
        used = set()
        n = 0
        for nm in self.names:
            if not self._upright(v, nm):
                continue
            x = self._to_into(v, self._in_frame(v, nm, self.head))
            for k, h in enumerate(self.holes):
                if k in used:
                    continue
                d = x - h
                ax = float(d @ self.axis)
                lat = float(np.linalg.norm(d - ax * self.axis))
                if (lat <= self.clear and ax >= self.depth
                        and (self.max_depth is None or ax <= self.max_depth)):
                    used.add(k)
                    n += 1
                    break
        return n

    def arm(self, v):
        self.count = 0
        self.best = 0

    def holds(self, v) -> bool:
        k = self.n_in(v)
        self.best = max(self.best, k)
        return k >= self.need

    def update(self, v) -> bool:
        self.count = self.count + 1 if self.holds(v) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        return float(np.clip(self.best / max(self.need, 1), 0.0, 1.0))

    def hold_progress(self) -> float:
        return float(np.clip(self.count / max(self.hold_steps, 1), 0.0, 1.0))

    def terms(self) -> dict:
        return {"best_in": int(self.best), "need": self.need}


class NamedPoseCriterion:
    """Adapter: a pose criterion (AxisUprightSuccess) graded on the object
    ``of`` names rather than on the target."""

    VALUE = "named_poses"

    def __init__(self, inner, name: str):
        self.inner = inner
        self.name = name
        self.pose_names = [name]
        self.hold_steps = getattr(inner, "hold_steps", 1)

    def arm(self, v):
        return self.inner.arm(v[self.name])

    def holds(self, v):
        return self.inner.holds(v[self.name])

    def update(self, v):
        return self.inner.update(v[self.name])

    def progress(self):
        return self.inner.progress()

    def hold_progress(self):
        return self.inner.hold_progress()

    def terms(self):
        return self.inner.terms()

    @property
    def count(self):
        return self.inner.count


class StaySupported:
    """No carrying: an inner criterion that only counts while ``name`` has
    stayed SUPPORTED -- its lowest corner within ``max_h`` of the table top --
    with no airborne spell longer than ``max_air_steps``. Once one is, the
    episode is spoiled for good (latched until the next arm): the demo can no
    longer succeed, however it ends.

    pivot_box_against_wall (Richard, 2026-10-01): the box is meant to be pushed
    to the ledge and pivoted up, never picked up. All 10 demos of 2026-09-30
    lifted it clear of table and ledge for 0.7-1.7 s and still passed, because
    the inner criterion only reads the END state.

    ``corners`` are the object's bounding-box corners in its own frame; the
    lowest of them, in the world, against ``table_z + max_h``.
    """

    VALUE = "named_poses"

    def __init__(self, inner, name: str, corners, table_z: float, max_h: float,
                 max_air_steps: int, part: str, into: str | None = None):
        self.inner = inner
        self.name = name
        self.corners = np.asarray(corners, dtype=float).reshape(-1, 3)
        self.table_z = float(table_z)
        self.max_h = float(max_h)
        self.max_air = int(max_air_steps)
        self.part, self.into = part, into
        names = list(getattr(inner, "pose_names", []) or [])
        for n in (part, into, name):
            if n and n not in names:
                names.append(n)
        self.pose_names = names
        self.hold_steps = getattr(inner, "hold_steps", 1)
        self._reset()

    def _reset(self):
        self.air = 0
        self.longest_air = 0
        self.carried = False

    def _inner_value(self, v):
        return AllSuccess._value(self.inner, self.part, self.into, v)

    def height(self, v) -> float:
        """The object's lowest corner above the table top [m]."""
        pose = np.asarray(v[self.name], dtype=float)
        z = min(_qrot(pose[3:7], c)[2] for c in self.corners) + pose[2]
        return float(z - self.table_z)

    def _watch(self, v):
        if self.height(v) > self.max_h:
            self.air += 1
            self.longest_air = max(self.longest_air, self.air)
            if self.air > self.max_air and not self.carried:
                self.carried = True
                print(f"  ⛔ no carrying: {self.name} was off the table and ledge for "
                      f"{self.air} steps -- this demo can no longer succeed; reset it "
                      f"(palm-down pinch)", flush=True)
        else:
            self.air = 0

    def arm(self, v):
        self._reset()
        return self.inner.arm(self._inner_value(v))

    def holds(self, v) -> bool:
        return (not self.carried) and bool(self.inner.holds(self._inner_value(v)))

    def update(self, v) -> bool:
        self._watch(v)
        done = self.inner.update(self._inner_value(v))
        return bool(done) and not self.carried

    def progress(self) -> float:
        return 0.0 if self.carried else self.inner.progress()

    def hold_progress(self) -> float:
        return 0.0 if self.carried else self.inner.hold_progress()

    def terms(self) -> dict:
        return dict(self.inner.terms(), carried=bool(self.carried),
                    longest_air_steps=int(self.longest_air))

    @property
    def count(self):
        return 0 if self.carried else getattr(self.inner, "count", 0)


class AllSuccess:
    """Several criteria at once, held together: an assembly that is only done
    when every part is in (a frame in its base AND the tool on its hook; a
    leg in the top AND the base on the leg).

    Each sub-criterion grades its own ``part`` (default: the target) and, for
    the two-body ones, its own ``into``; they are updated every step (a
    thread's turn counter needs every step) and the composite holds when all
    of them hold at once.
    """

    VALUE = "named_poses"

    def __init__(self, subs, hold_steps: int):
        # subs: [(criterion, part, into or None)]
        self.subs = subs
        self.hold_steps = int(hold_steps)
        names = []
        for c, part, into in subs:
            for n in [part, into] + list(getattr(c, "pose_names", [])):
                if n and n not in names:
                    names.append(n)
        self.pose_names = names
        self.count = 0
        self.best = 0

    @staticmethod
    def _value(c, part, into, v):
        want = getattr(c, "VALUE", "z")
        if want == "poses":
            return (np.asarray(v[part]), np.asarray(v[into]))
        if want == "named_poses":
            return v
        if want == "pose":
            return np.asarray(v[part])
        return float(np.asarray(v[part])[2])

    def arm(self, v):
        self.count = 0
        self.best = 0
        for c, part, into in self.subs:
            c.arm(self._value(c, part, into, v))

    def _n_ok(self, v, step: bool):
        n = 0
        for c, part, into in self.subs:
            x = self._value(c, part, into, v)
            if step:
                c.update(x)
            n += int(bool(c.holds(x)))
        return n

    def holds(self, v) -> bool:
        n = self._n_ok(v, step=False)
        self.best = max(self.best, n)
        return n == len(self.subs)

    def update(self, v) -> bool:
        n = self._n_ok(v, step=True)
        self.best = max(self.best, n)
        self.count = self.count + 1 if n == len(self.subs) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        return float(self.best) / max(len(self.subs), 1)

    def hold_progress(self) -> float:
        return float(np.clip(self.count / max(self.hold_steps, 1), 0.0, 1.0))

    def terms(self) -> dict:
        return {"best_parts_done": int(self.best), "parts": len(self.subs),
                "subs": [dict(c.terms(), part=part, into=into) for c, part, into in self.subs]}


class JointAngleSuccess:
    """An articulated joint driven >= `min_deg` AWAY FROM WHERE IT STARTED.

    :class:`JointOpenSuccess` asks for a fraction of the travel, which is what
    a drawer wants when the asset is scaled and the limits scale with it. This
    asks for an ABSOLUTE angle, which is what a lid wants: "opened past 90
    degrees" is a statement about the object, not about its joint limits, and
    it stays the same number whatever range the asset happens to author.

    Measured from the coordinate at arm() time, not from the lower limit, so
    an asset that spawns ajar still has to be opened by the full angle -- and
    a task cannot be satisfied by spawning the object already open.

    `direction` is "any" (the default, absolute), "increase" or "decrease",
    for an asset whose joint axis points the closing way.
    """

    #: what update()/holds() want fed to them; see collect_env.success_value.
    VALUE = "joint"

    def __init__(self, min_deg: float = 90.0, hold_steps: int = 25,
                 direction: str = "any", label: str = "joint"):
        self.min_deg = float(min_deg)
        self.need = float(np.radians(self.min_deg))
        self.hold_steps = int(hold_steps)
        self.direction = str(direction)
        self.label = label
        self.rest: float | None = None
        self.count = 0
        self.peak = 0.0

    def _moved(self, q) -> float:
        """Signed travel from rest, resolved to the direction that counts.

        `q` may be SEVERAL joints (a task file's ``success.joints``): then the
        LEAST-moved one decides, so "all three fingers closed" cannot be
        satisfied by one finger closed three times as far.
        """
        d = np.asarray(q, dtype=float) - np.asarray(self.rest, dtype=float)
        if self.direction == "increase":
            m = d
        elif self.direction == "decrease":
            m = -d
        else:
            m = np.abs(d)
        return float(np.min(m))

    def arm(self, q):
        self.rest = (np.array(q, dtype=float) if np.ndim(q) else float(q))
        self.count, self.peak = 0, 0.0

    def update(self, q) -> bool:
        if self.rest is None:
            self.arm(q)
            return False
        self.peak = max(self.peak, self._moved(q))
        self.count = self.count + 1 if self._moved(q) >= self.need else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        if self.rest is None or self.need <= 0.0:
            return 0.0
        return max(0.0, min(1.0, self.peak / self.need))

    def hold_progress(self) -> float:
        if self.hold_steps <= 0:
            return 0.0
        return max(0.0, min(1.0, self.count / self.hold_steps))

    def holds(self, q: float) -> bool:
        """Does the criterion hold RIGHT NOW? Non-mutating."""
        if self.rest is None:
            return False
        return self._moved(q) >= self.need

    def terms(self) -> dict:
        return {"criterion": f"{self.label} moved >= {self.min_deg:.0f} deg "
                             f"from its starting angle ({self.direction}) for "
                             f"{self.hold_steps} consecutive steps",
                "peak_travel_deg": round(float(np.degrees(self.peak)), 3),
                "threshold_deg": self.min_deg,
                "direction": self.direction,
                "rest_deg": (None if self.rest is None
                             else [round(float(np.degrees(r)), 3) for r in self.rest]
                             if np.ndim(self.rest)
                             else round(float(np.degrees(self.rest)), 3))}


class TurnSuccess:
    """The target TURNED >= `min_deg` about an axis of a SECOND body, held N steps.

    For a part that turns by contact rather than on a joint (the timer's dial
    on its case's post, Richard 2026-10-02: "Dont use a joint, use contact to
    restrict the motion"): there is no joint coordinate to read, so the turn
    is measured from the pair's poses, in the second body's frame -- the
    target's local x, projected on the plane normal to `axis_local`, and the
    signed angle it sweeps, accumulated step by step (unwrapped, so a turn
    past 180 deg counts on, and the case being carried or turned with it does
    not). `direction` "cw" counts clockwise SEEN FROM the axis's tip (looking
    down -axis: clockwise from above for an axis that points up), "ccw" the
    other way, "any" the larger of the two.

    The target must stay SEATED for any of it to count: its origin within
    `max_offset_m` of where it started, in the second body's frame. A dial
    pulled off its post (or knocked loose) pauses the count.
    """

    VALUE = "poses"

    def __init__(self, axis_local=(0.0, 0.0, 1.0), min_deg: float = 180.0,
                 hold_steps: int = 25, direction: str = "cw",
                 max_offset_m: float = 0.003, into: str = "", label: str = "the target"):
        a = np.asarray(axis_local, dtype=float)
        self.axis = a / max(float(np.linalg.norm(a)), 1e-12)
        self.min_deg = float(min_deg)
        self.need = float(np.radians(self.min_deg))
        self.hold_steps = int(hold_steps)
        if direction not in ("cw", "ccw", "any"):
            raise ValueError(f"turn direction must be cw, ccw or any, got {direction!r}")
        self.direction = direction
        self.max_offset = float(max_offset_m)
        self.into, self.label = into, label
        self.arm(None)

    _rot = staticmethod(InsertSuccess._rot)

    @classmethod
    def _unrot(cls, q, v):
        q = np.asarray(q, dtype=float)
        return cls._rot(np.array([-q[0], -q[1], -q[2], q[3]]), v)

    def _rel(self, v):
        """(offset of the target in the second body's frame, its radial reference)."""
        obj, into = (np.asarray(p, dtype=float) for p in v)
        off = self._unrot(into[3:7], obj[:3] - into[:3])
        x = self._unrot(into[3:7], self._rot(obj[3:7], [1.0, 0.0, 0.0]))
        x = x - self.axis * float(x @ self.axis)
        n = float(np.linalg.norm(x))
        return off, (x / n if n > 1e-9 else None)

    def arm(self, v):
        self.turned = 0.0           # signed, + = counter-clockwise about +axis
        self.peak = 0.0
        self.count = 0
        self._prev = None
        self._seat = None
        if v is not None:
            self._seat, self._prev = self._rel(v)

    def _moved(self) -> float:
        if self.direction == "cw":
            return -self.turned
        if self.direction == "ccw":
            return self.turned
        return abs(self.turned)

    def _seated(self, off) -> bool:
        return self._seat is not None and float(np.linalg.norm(off - self._seat)) <= self.max_offset

    def update(self, v) -> bool:
        if self._seat is None:
            self.arm(v)
            return False
        off, x = self._rel(v)
        if x is None or not np.all(np.isfinite(off)) or not self._seated(off):
            self._prev, self.count = None, 0
            return False
        if self._prev is not None:
            self.turned += float(np.arctan2(self.axis @ np.cross(self._prev, x), self._prev @ x))
        self._prev = x
        self.peak = max(self.peak, self._moved())
        self.count = self.count + 1 if self._moved() >= self.need else 0
        return self.count >= self.hold_steps

    def holds(self, v) -> bool:
        if self._seat is None:
            return False
        off, _ = self._rel(v)
        return bool(self._seated(off) and self._moved() >= self.need)

    def progress(self) -> float:
        return max(0.0, min(1.0, self.peak / self.need)) if self.need > 0 else 0.0

    def hold_progress(self) -> float:
        return max(0.0, min(1.0, self.count / self.hold_steps)) if self.hold_steps > 0 else 0.0

    def terms(self) -> dict:
        return {"criterion": f"{self.label} turned >= {self.min_deg:.0f} deg {self.direction} about "
                             f"{self.into}'s axis {self.axis.round(4).tolist()}, staying within "
                             f"{self.max_offset * 1e3:.1f} mm of its seat, for {self.hold_steps} "
                             f"consecutive steps",
                "turned_deg": round(float(np.degrees(self.turned)), 3),
                "peak_deg": round(float(np.degrees(self.peak)), 3),
                "threshold_deg": self.min_deg, "direction": self.direction}


class FaceNeighborSuccess:
    """A cube rolled onto a NAMED face, or onto any NEIGHBOURING one.

    Six faces, six colours (tasks/assets/color_cube, built by
    tools/make_color_cube.py). At arm() the face pointing most nearly up is
    the START face.

    ``up_color`` (or ``up_face``) names the goal: THAT colour must end up,
    and no other. Without it the criterion is the older, weaker one -- any
    DIFFERENT face whose axis is PERPENDICULAR to the start one, a quarter
    turn to one of the four neighbours, never the opposite face (a half turn,
    and the thing a "did it change colour?" test would wrongly accept).

    A named goal subsumes that: the cube spawns +z up and the draw is a yaw
    about +z, so the start face is always +z and any other named face is one
    of its neighbours by construction. What the name adds is that the
    operator no longer chooses the answer -- the yaw draw decides which way
    the cube has to roll, so the randomization now varies the TASK and not
    only the grasp. The named face must still differ from the start face: a
    goal that is already up at arm() is refused for the whole episode rather
    than passing at spawn, because a criterion true before the operator moves
    is not a demonstration of anything (`goal_already_up` in terms()).

    Two more conditions, because "which face is up" alone is satisfied by a
    cube held at an angle in mid-air:

    * the new up face must be within `tolerance_deg` of world up, so the cube
      is really ON that face rather than balanced on an edge;
    * with `require_resting` (the default) the cube's centre must be back
      within `resting_tol_m` of the height it started at. A cube is as tall as
      it is wide, so every one of its six resting orientations puts the centre
      at exactly the same z -- which makes "resting on the table on a new
      face" a one-line test, and makes the success state one the operator has
      to LET GO of to reach.

    Together with the settle window (--post-success-s) that is what puts the
    verdict on the FINAL state: the cube has been placed on a new face and
    left there, not waved through the orientation on the way somewhere else.
    """

    #: what update()/holds() want fed to them; see collect_env.success_value.
    VALUE = "pose"

    #: local axis of each face, in the order tools/make_color_cube.py writes.
    AXES = {"+x": (1.0, 0.0, 0.0), "-x": (-1.0, 0.0, 0.0),
            "+y": (0.0, 1.0, 0.0), "-y": (0.0, -1.0, 0.0),
            "+z": (0.0, 0.0, 1.0), "-z": (0.0, 0.0, -1.0)}

    def __init__(self, face_colors: dict | None = None,
                 tolerance_deg: float = 25.0, hold_steps: int = 25,
                 require_resting: bool = True, resting_tol_m: float = 0.01,
                 up_color: str | None = None, up_face: str | None = None):
        self.colors = dict(face_colors or {})
        self.max_tilt = float(np.radians(tolerance_deg))
        self.tolerance_deg = float(tolerance_deg)
        self.hold_steps = int(hold_steps)
        self.require_resting = bool(require_resting)
        self.resting_tol = float(resting_tol_m)
        self.up_color = None if up_color is None else str(up_color)
        self.up_face = self._resolve_face(up_face, self.up_color)
        self.start_face: str | None = None
        self.rest_z: float | None = None
        self.count = 0
        self.best_turn = 0.0          # 0..1, how far round the quarter turn
        self.last_face: str | None = None

    # ------------------------------------------------------------- geometry --
    @staticmethod
    def _rot(q_xyzw, v):
        q = np.asarray(q_xyzw, dtype=float)
        u, w = q[:3], q[3]
        v = np.asarray(v, dtype=float)
        return v + 2.0 * np.cross(u, np.cross(u, v) + w * v)

    def _up_face(self, pose):
        """(face key, tilt from world up in radians) for the highest face."""
        q = np.asarray(pose[3:7], dtype=float)
        best, best_dot = None, -2.0
        for key, ax in self.AXES.items():
            d = float(self._rot(q, ax)[2])
            if d > best_dot:
                best, best_dot = key, d
        return best, float(np.arccos(np.clip(best_dot, -1.0, 1.0)))

    def color(self, face: str | None) -> str | None:
        return None if face is None else self.colors.get(face, face)

    def _resolve_face(self, face: str | None, color: str | None) -> str | None:
        """The goal as a face key. A task file names a COLOUR (that is what an
        operator sees); a face key is accepted too, for a cube with no colour
        map. Raises rather than grading the wrong face silently."""
        if face is not None:
            if face not in self.AXES:
                raise ValueError(f"up_face {face!r} is not one of {sorted(self.AXES)}")
            if color is not None and self.colors.get(face, face) != color:
                raise ValueError(f"up_face {face!r} is {self.colors.get(face)!r}, "
                                 f"not the up_color {color!r} asked for")
            return face
        if color is None:
            return None
        if color in self.AXES:
            return color
        hit = [k for k, v in self.colors.items() if v == color]
        if len(hit) != 1:
            raise ValueError(f"up_color {color!r} names {len(hit)} of the "
                             f"target's faces ({self.colors}); it has to name "
                             f"exactly one")
        return hit[0]

    @staticmethod
    def _axis_of(face: str) -> str:
        return face[1]

    def relation(self, face: str | None) -> str:
        """same / opposite / neighbour, against the face that started up."""
        if self.start_face is None or face is None:
            return "unknown"
        if face == self.start_face:
            return "same"
        if self._axis_of(face) == self._axis_of(self.start_face):
            return "opposite"
        return "neighbour"

    @property
    def goal_already_up(self) -> bool:
        """The named goal was the face that started up -- nothing to do, so
        nothing can be demonstrated. Refused rather than passed; see arm()."""
        return self.up_face is not None and self.up_face == self.start_face

    # ------------------------------------------------------------ criterion --
    def arm(self, pose):
        self.start_face, _ = self._up_face(pose)
        self.rest_z = float(pose[2])
        self.count = 0
        self.best_turn = 0.0
        self.last_face = self.start_face

    def holds(self, pose) -> bool:
        if self.start_face is None:
            return False
        face, tilt = self._up_face(pose)
        self.last_face = face
        # How far the ORIGINAL up face has swung away from vertical, as a
        # fraction of the quarter turn the task asks for. |cos| rather than
        # the angle: a half turn puts the opposite face up and is back to no
        # progress at all, which is honest -- it is not a neighbour.
        if self.up_face is None:
            start_up = self._rot(np.asarray(pose[3:7], dtype=float),
                                 self.AXES[self.start_face])
            self.best_turn = float(1.0 - abs(np.clip(start_up[2], -1.0, 1.0)))
        else:
            # Progress toward a NAMED face is how nearly that face points up.
            # It starts horizontal (dot 0) and has to reach vertical (dot 1),
            # so the fraction is the dot itself -- and rolling the wrong way
            # takes it negative, i.e. no progress, which is the truth.
            goal_up = self._rot(np.asarray(pose[3:7], dtype=float),
                                self.AXES[self.up_face])
            self.best_turn = float(np.clip(goal_up[2], 0.0, 1.0))
        if self.goal_already_up:
            return False
        reached = (face == self.up_face if self.up_face is not None
                   else self.relation(face) == "neighbour")
        if not reached or tilt > self.max_tilt:
            return False
        if self.require_resting and self.rest_z is not None:
            if abs(float(pose[2]) - self.rest_z) > self.resting_tol:
                return False
        return True

    def update(self, pose) -> bool:
        self.count = self.count + 1 if self.holds(pose) else 0
        return self.count >= self.hold_steps

    def progress(self) -> float:
        """Live, not peak: rolling on past the neighbour to the opposite face
        really does undo the progress, and the ring should say so."""
        return float(np.clip(self.best_turn, 0.0, 1.0))

    def hold_progress(self) -> float:
        return float(np.clip(self.count / max(self.hold_steps, 1), 0.0, 1.0))

    def terms(self) -> dict:
        what = (f"the {self.color(self.up_face)} face ({self.up_face}) is up"
                if self.up_face else
                "a face PERPENDICULAR to the one that started up is up")
        return {"criterion": f"{what} within {self.tolerance_deg:.0f} deg"
                             + (f", the cube back within "
                                f"{self.resting_tol * 1000:.0f} mm of its "
                                f"resting height" if self.require_resting else "")
                             + f", for {self.hold_steps} consecutive steps",
                "goal_face": self.up_face,
                "goal_color": self.color(self.up_face),
                "goal_already_up": self.goal_already_up,
                "start_face": self.start_face,
                "start_color": self.color(self.start_face),
                "end_face": self.last_face,
                "end_color": self.color(self.last_face),
                "relation": self.relation(self.last_face),
                "tolerance_deg": self.tolerance_deg,
                "require_resting": self.require_resting,
                "rest_z": None if self.rest_z is None else round(self.rest_z, 5)}


# ----------------------------------------------------------------- writer ----


class EpisodeWriter:
    """LeRobot-v2-style dataset, plus a sidecar for the ragged contact sets.

        <root>/meta/info.json          schema + fps + feature shapes
        <root>/meta/episodes.jsonl     one line per episode
        <root>/meta/tasks.jsonl        task index -> language string
        <root>/data/episode_000000.parquet
        <root>/contacts/hand_obj/episode_000000.npz
        <root>/contacts/obj_obj/episode_000000.npz  (object_pairs only)
    Written in that order deliberately: the metadata that says what the
    dataset IS costs microseconds and goes FIRST, the arrays cost seconds and
    go second, and ``meta/episodes.jsonl`` goes LAST -- its line is what
    vouches for an episode being complete, so an interrupted save leaves a
    readable dataset with one episode missing rather than an unreadable one.

    Contacts do NOT go in the parquet: a contact set is RAGGED, and a columnar
    table would have to pad to the worst case or truncate. They go in a sidecar
    keyed by frame_index, with `contact_count` in the parquet so a reader can
    tell an empty frame from a missing one.
    Two things per frame: the hydroelastic PATCH (tri / depth / shape_pair --
    the geometry; force = area * kh * |depth| is derived on read, the pressure
    law's estimate) and the SOLVER'S contacts (mj_* -- the constraint force
    MuJoCo-Warp actually applied on each reduced hand-object contact, see
    tools/solver_contacts.py), with `mj_contact_count` in the parquet.
    With ``object_pairs`` (collect_env --record-pairs both) the object-object
    faces of the same surface go to contacts/obj_obj/, in exactly the layout
    tools/compile_contacts.py --pairs object-object writes: per-frame keys
    plus whole-episode ``contact_count`` / ``contact_available_count`` arrays
    inside the file, the parquet untouched. Neither sidecar is split per
    shape pair: with three objects in the scene all three interactions share
    obj_obj/, told apart by ``<frame>_shape_pair`` (tools/contact_io.py).
    """

    FPS_KEY = "fps"
    #: Record contacts/obj_obj/ too (set per instance by __init__).
    object_pairs = False
    #: A tools.sim_recorder.SimRecorder, when the episode is recorded on the
    #: device (attach_sim); None records from what add() is handed.
    sim = None
    #: Write saved episodes on a background thread (the collector: a save
    #: must not freeze the headset). Off by default, so a caller that reads
    #: the files straight after save() finds them.
    background = False

    def __init__(self, root: str, task: str, fps: float, config: dict,
                 hands: tuple[str, ...] = ("right",), robot_type: str | None = None,
                 object_pairs: bool = False):
        self.root = root
        self.object_pairs = bool(object_pairs)
        self.task = task
        self.fps = fps
        self.config = config
        #: info.json's robot_type. Defaults by hand count -- "mano_hand" for
        #: one hand, "mano_hand_bimanual" for two, the names main's bimanual
        #: collector wrote -- so a reader keyed on it tells the layouts apart
        #: without opening `hands`. A gripper dataset says "robotiq_2f140"
        #: (recording_paths.ROBOT_TYPES).
        self.robot_type = robot_type or (
            "mano_hand_bimanual" if len(tuple(hands)) > 1 else "mano_hand")
        #: Which hands drove these demos, in the order ``observation.wrist_pose``
        #: concatenates them. Written into info.json rather than left implicit:
        #: a bare 14-float column with no key is unreadable, and guessing the
        #: order from the file name is exactly the silent-corruption class this
        #: pipeline keeps out of its datasets.
        self.hands = tuple(hands)
        if not self.hands or len(set(self.hands)) != len(self.hands) or any(
                s not in ("left", "right") for s in self.hands):
            raise ValueError(f"invalid hands: {self.hands}")
        # Check before the collector overwrites scene.json or exports assets.
        # Existing one-hand episodes cannot share a state layout with two hands,
        # nor a gripper's with a hand's.
        check_recording_hands(root, self.hands, embodiment_of(self.robot_type))
        # ... nor episodes on another table: scene.json's table is the run's.
        check_recording_table(root, config.get("table_pos"), config.get("table_size"))
        os.makedirs(os.path.join(root, "meta"), exist_ok=True)
        os.makedirs(os.path.join(root, "data"), exist_ok=True)
        os.makedirs(os.path.join(root, SIDECAR_DIR["hand-object"]), exist_ok=True)
        if self.object_pairs:
            os.makedirs(os.path.join(root, SIDECAR_DIR["object-object"]), exist_ok=True)
        self.episode_index = self._next_index()
        episodes = os.path.join(root, "meta", "episodes.jsonl")
        self.global_index = 0
        if os.path.exists(episodes):
            with open(episodes) as fh:
                self.global_index = sum(int(json.loads(line).get("length", 0))
                                        for line in fh if line.strip())
        self._reset_buffers()

    def _next_index(self) -> int:
        """One past the HIGHEST episode index on record, not the row count.

        The two agree for a directory that was only ever appended to, which is
        every directory the recorder makes. They stop agreeing the moment an
        episode is withdrawn -- and then a row count points at a file that is
        still on disk, and the next demo silently overwrites a real one. (It
        came up for real: rj45_insert's first 11 episodes were withdrawn on
        2026-09-23 because they were drawn from a start-pose range the task no
        longer asks for, leaving 53 episodes numbered 11..63.)
        """
        p = os.path.join(self.root, "meta", "episodes.jsonl")
        if not os.path.exists(p):
            return 0
        top = -1
        with open(p) as f:
            for line in f:
                if line.strip():
                    top = max(top, int(json.loads(line).get("episode_index", -1)))
        return top + 1

    def _config_hash(self) -> str:
        """Stable short hash of this run's configuration."""
        import hashlib  # noqa: PLC0415
        blob = json.dumps(self.config, sort_keys=True, default=str)
        return hashlib.sha256(blob.encode()).hexdigest()[:12]

    def _write_config_snapshot(self):
        """Store the full config once per distinct configuration.

        meta/configs/<hash>.json, referenced by config_hash on each episode --
        so a mixed directory stays readable without duplicating the config on
        every line.
        """
        _write_config_snapshot(self.root, self.config)

    def _reset_buffers(self):
        self.rows: list[dict] = []
        self.contacts: dict[str, np.ndarray] = {}
        self.object_contacts: dict[str, np.ndarray] = {}
        self._oo_count: list[int] = []
        self._oo_available: list[int] = []
        self._warned_contact_cap = False
        #: Unix time of this episode's first row: with wall_timestamp it puts every frame on
        #: the wall clock, which is how a photo or video of the operator is matched to it.
        self._unix0 = None

    def add(self, t, joint_q, action, wrist, obj_pose, contact: dict | None,
            obj_joint=None, wall_time=None, contact_stats=None, tracked=None,
            object_contact: dict | None = None, object_contact_stats=None,
            head_pose=None, hand_tracking=None):
        """One physics step. ``tracked`` (optional) is one flag per hand, in
        ``hands`` order: whether that hand's command on this step came from a
        tracker frame less than 100 ms old. Stored as ``observation.tracked``
        so a reader can drop the frames where a hand was frozen on its last
        pose (Yuemin's column, from main's bimanual collector).

        ``head_pose`` (optional) is the headset's ``[x y z qx qy qz qw]`` in the
        stage frame (tracking.read_head_xrcore), NaN on a frame the runtime
        marked it invalid. Stored as ``observation.head_pose``; a session with
        no headset passes None on every step and the column is not written.

        ``hand_tracking`` (optional) is the RAW tracking frame that drove this
        step, ``(2, 26, 7)``: left then right, OpenXR's 26 joints
        (tracking.HAND_JOINTS), ``x y z qx qy qz qw`` in the stage frame, NaN
        where not reported. Stored flat as ``observation.hand_tracking``."""
        if np.asarray(wrist).shape != (7 * len(self.hands),):
            raise ValueError(f"wrist must contain one 7-float pose per hand: {self.hands}")
        if tracked is not None and len(tracked) != len(self.hands):
            raise ValueError(f"tracked must have one flag per hand: {self.hands}")
        if head_pose is not None and np.asarray(head_pose).shape != (7,):
            raise ValueError("head_pose must be one 7-float pose")
        if hand_tracking is not None and np.asarray(hand_tracking).size != 2 * 26 * 7:
            raise ValueError("hand_tracking must be (2, 26, 7): left/right x joints x pose")
        if (joint_q is None or action is None) and self.sim is None:
            raise ValueError("joint_q and action are required without a device recorder")
        i = len(self.rows)
        if i == 0:
            self._unix0 = time.time()
        self.rows.append({
            "timestamp": float(t),
            "frame_index": i,
            "episode_index": self.episode_index,
            "index": self.global_index + i,
            "task_index": 0,
            # None when a device recorder holds it; save() fills it in.
            "observation.state": (None if joint_q is None
                                  else np.asarray(joint_q, dtype=np.float32)),
            "observation.wrist_pose": np.asarray(wrist, dtype=np.float32),
            "observation.object_pose": np.asarray(obj_pose, dtype=np.float32),
            "action": None if action is None else np.asarray(action, dtype=np.float32),
            # An articulated object's ROOT pose says nothing about the
            # thing the task is actually about. A faucet's root never moves;
            # the whole demo lives in the handle joint. Without this a
            # downstream policy cannot see the state it is being trained to
            # change.
            "observation.object_joint_pos": np.asarray(
                [] if obj_joint is None else obj_joint, dtype=np.float32),
            "contact_count": 0 if contact is None else int(len(contact.get("depth", ()))),
        })
        if wall_time is not None:
            self.rows[-1]["wall_timestamp"] = float(wall_time)
        if tracked is not None:
            self.rows[-1]["observation.tracked"] = np.asarray(
                [1.0 if bool(x) else 0.0 for x in tracked], dtype=np.float32)
        if head_pose is not None:
            self.rows[-1]["observation.head_pose"] = np.asarray(head_pose, dtype=np.float32)
        if hand_tracking is not None:
            self.rows[-1]["observation.hand_tracking"] = np.asarray(
                hand_tracking, dtype=np.float32).reshape(-1)
        if contact_stats is not None:
            self.rows[-1].update(contact_stats)
            if contact_stats.get("contact_dropped_count", 0) and not self._warned_contact_cap:
                print("  WARNING: contact recording is truncated by --max-faces; "
                      "use --max-faces 0 for every valid face. Physics is unchanged.")
                self._warned_contact_cap = True
        if contact:
            for k, v in contact.items():
                self.contacts[f"{i:06d}_{k}"] = v
        if self.object_pairs:
            # One entry per frame whatever it holds, so the counts line up
            # with the parquet's rows as the compile's do.
            self._oo_count.append(0 if object_contact is None
                                  else int(len(object_contact.get("depth", ()))))
            self._oo_available.append(
                int((object_contact_stats or {}).get("contact_available_count", 0)))
            if object_contact:
                for k, v in object_contact.items():
                    self.object_contacts[f"{i:06d}_{k}"] = v

    def discard(self):
        n = len(self.rows)
        self._reset_buffers()
        if self.sim is not None:
            self.sim.reset()
        return n

    def attach_sim(self, recorder) -> None:
        """Record through a device-side :class:`tools.sim_recorder.SimRecorder`:
        ``add()`` then takes ``joint_q`` / ``action`` / the contacts as None
        and :meth:`save` fills them -- plus ``observation.velocity``,
        contacts/obj_obj/ and sim_state/ -- from one bulk readback."""
        self.sim = recorder
        if recorder is not None:
            self.object_pairs = "object-object" in getattr(recorder, "pairs", ())
            for d in (SIDECAR_DIR["object-object"], "sim_state"):
                os.makedirs(os.path.join(self.root, d), exist_ok=True)

    def save(self, success: bool, verdict: str, terms: dict,
             extra: dict | None = None) -> str | None:
        """Write the episode. ``extra`` is merged into its episodes.jsonl
        line -- per-episode facts that are not success terms, such as the
        randomized start poses the demo began from.

        With ``background`` nothing here waits on the device, the CPU work or
        the disk. A device-recorded episode's buffers are handed off
        (tools/sim_recorder.DoubleRecorder); a collector thread reads them back
        into pinned memory and copies them into shared memory -- GPU copies
        and memcpys, no Python work to speak of -- and a writer PROCESS
        (tools/episode_writer_proc.py) splits the frames, fills the rows and
        compresses, with its own GIL: in-process, compressing a gear_mesh
        episode (~13 s) slowed the next demo's loop 10-15 %, dips to half
        rate. Files are written in save order. :func:`flush_writers` waits for
        all of it -- call it before the process can end."""
        if not self.rows:
            return None
        t_save = time.perf_counter()
        rows = self.rows
        for r in rows:
            r["next.done"] = False
            r["next.success"] = bool(success)
        rows[-1]["next.done"] = True
        ep = self.episode_index
        if self._unix0 is not None:
            extra = {"unix_time_frame0": self._unix0, **(extra or {})}
        path = os.path.join(self.root, "data", f"episode_{ep:06d}.parquet")
        handle = self.sim.handoff() if self.sim is not None else None
        patch = (handle is not None and bool(getattr(self.sim, "pairs", ()))
                 and getattr(self.sim, "get_surface", None) is not None)
        host = None
        if handle is None:
            object_contacts = None
            if self.object_pairs:
                object_contacts = dict(self.object_contacts)
                object_contacts["contact_count"] = np.asarray(self._oo_count, dtype=np.int64)
                object_contacts["contact_available_count"] = np.asarray(
                    self._oo_available, dtype=np.int64)
            host = (self.contacts, object_contacts, None)
        # Rows become columns on the thread that uses them (~8 ms for 3000
        # rows -- two frames the loop would otherwise stall at every save).
        # terms / extra snapshotted now: the loop may reuse or edit its
        # per-episode dict for the next demo before a thread writes this one.
        spec = {"root": self.root, "task": self.task, "ep": ep, "success": bool(success),
                "verdict": verdict,
                "terms": json.loads(json.dumps(terms, default=_jsonable)),
                "extra": json.loads(json.dumps(extra or {}, default=_jsonable)),
                "config": dict(self.config), "config_hash": self._config_hash(),
                "hands": list(self.hands), "robot_type": self.robot_type, "fps": self.fps,
                "fps_key": self.FPS_KEY, "patch": patch}
        n = len(rows)
        self.global_index += n
        self.episode_index += 1
        self._reset_buffers()
        name = f"{os.path.basename(self.root)} episode {ep}"
        if handle is None:
            job = lambda: _finish_episode(spec, *_columns(rows), host=host)  # noqa: E731
            if self.background:
                _DISK.submit(job, name)
            else:
                job()
        elif not self.background:
            _finish_episode(spec, *_columns(rows), bulk=handle.collect_raw(n))
        else:
            _COLLECT.submit(lambda: _ship(spec, rows, handle, n, name), name)
        if self.background:
            print(f"  episode {ep}: handed off in "
                  f"{1e3 * (time.perf_counter() - t_save):.1f} ms (the loop's whole wait); "
                  f"collected and written in the background", flush=True)
        return path

    def flush(self) -> None:
        """Wait until every episode this process saved is on disk."""
        flush_writers()

    def _info(self, rows: list, ep: int, object_pairs: bool, sim_state) -> dict:
        return _info_dict(self.hands, self.robot_type, self.fps, self.FPS_KEY, self.config,
                          rows[0], ep, object_pairs, sim_state)


def _info_dict(hands, robot_type, fps, fps_key, config, first: dict, ep: int,
               object_pairs: bool, sim_state) -> dict:
    """meta/info.json for a dataset whose newest episode is ``ep``; ``first``
    is one row (its keys and cell shapes)."""
    info = {
        "codebase_version": "v2.0-compatible-layout",
        "robot_type": robot_type,
        # The hands this dataset was recorded with, in the order they
        # occupy observation.wrist_pose. meta/scene.json's "hands" says the
        # same thing and names the rig directory under meta/rig/ for each.
        "hands": list(hands),
        fps_key: fps,
        "total_episodes": ep + 1,
        "features": {
            "observation.state": {"dtype": "float32",
                                  "shape": [len(first["observation.state"])]},
            "observation.wrist_pose": {
                "dtype": "float32",
                "shape": [len(first["observation.wrist_pose"])],
                # The COMMANDED wrist pose, one 7-float (x y z, then xyzw)
                # block per hand, concatenated in `hands` order.
                "hands": list(hands),
                "layout": "per hand: [px, py, pz, qx, qy, qz, qw]"},
            "observation.object_pose": {"dtype": "float32", "shape": [7]},
            "observation.object_joint_pos": {
                "dtype": "float32",
                "shape": [len(first["observation.object_joint_pos"])]},
            "action": {"dtype": "float32",
                       "shape": [len(first["action"])]},
            **({"observation.velocity": {
                    "dtype": "float32",
                    "shape": [len(first["observation.velocity"])],
                    "layout": "Newton joint_qd after the step, the velocity "
                              "of observation.state's coordinates (free "
                              "joints: linear then angular, world frame)"}}
               if "observation.velocity" in first else {}),
            **({"observation.tracked": {
                    "dtype": "float32", "shape": [len(hands)],
                    "hands": list(hands),
                    "layout": "1.0 where that hand's command came from a "
                              "tracker frame under 100 ms old, else 0.0"}}
               if "observation.tracked" in first else {}),
            **({"observation.head_pose": {
                    "dtype": "float32", "shape": [7],
                    "layout": "the headset (OpenXR /user/head, between the "
                              "eyes) in the world frame: [px, py, pz, qx, qy, "
                              "qz, qw]; NaN where the runtime marked it invalid"}}
               if "observation.head_pose" in first else {}),
            **({"observation.hand_tracking": {
                    "dtype": "float32", "shape": [2 * 26 * 7],
                    "sides": ["left", "right"],
                    "joints": list(_HAND_JOINTS),
                    "layout": "the RAW OpenXR hand-tracking frame that drove the step "
                              "(before retarget, filter or physics), flat [side][joint][7]: "
                              "left then right, the 26 joints in `joints` order, each "
                              "[px, py, pz, qx, qy, qz, qw] in the world frame; NaN where "
                              "the runtime reported nothing"}}
               if "observation.hand_tracking" in first else {}),
        },
        "contacts": {
            "scope": config.get("contact_recording_scope", "all"),
            "location": "contacts/hand_obj/episode_*.npz",
            "keys": "<frame:06d>_{tri,depth,shape_pair} and "
                    "<frame:06d>_mj_{pair,pos,normal,dist,force}",
            "tri": "(n, 3, 3) float32 — the contact face's three vertices, "
                   "world frame. The patch geometry itself, not a summary "
                   "of it.",
            "depth": "(n,) float32, negative — penetration.",
            "shape_pair": "(n, 2) int32 — indices into meta/scene.json's "
                          "shape list.",
            "derived": "centroid = mean(tri, axis=1); "
                       "n_raw = cross(v1-v0, v2-v0); area = |n_raw|/2; "
                       "normal = n_raw/|n_raw|; "
                       "force = area * kh * abs(depth). "
                       "tools/contact_io.py does this and also reads the "
                       "older <frame>_{c,normal,area,force} layout.",
            "note": "ragged per frame. kh is a property of the RUN (see "
                    "collection_config), deliberately not baked into a "
                    "stored force, so a dataset can be re-scored under a "
                    "different stiffness. That derived force is the "
                    "pressure law's ESTIMATE (~3.5x high in a measured "
                    "pinch); the solver's force is mj_force.",
            "mj_pair": "(n, 2) int32 — (hand shape, object shape), indices "
                       "into meta/scene.json's shape list. One row per "
                       "contact the SOLVER integrated: Newton reduces the "
                       "patch to a few dozen representative contacts per "
                       "shape pair and MuJoCo-Warp solves a constraint "
                       "force on each.",
            "mj_pos": "(n, 3) float32 — contact point, world metres.",
            "mj_normal": "(n, 3) float32 — unit normal from the hand INTO "
                         "the object.",
            "mj_dist": "(n,) float32 — signed distance, negative = "
                       "penetration.",
            "mj_force": "(n, 3) float32 — the force ON THE OBJECT from the "
                        "hand, world frame, newtons: MuJoCo's contact "
                        "force (normal + friction) decoded from efc_force "
                        "after the step's last solve. Sum over a frame for "
                        "the net force the hand exerts on the object. "
                        "Recorded live only; a compiled sidecar carries "
                        "the live values over, a state-only recording has "
                        "none (mj_contact_count == -1 in the parquet).",
        },
        "collection_config": config,
    }
    for key, dtype in (("wall_timestamp", "float64"),
                       ("contact_available_count", "int64"),
                       ("contact_dropped_count", "int64"),
                       ("mj_contact_count", "int64")):
        if key in first:
            info["features"][key] = {"dtype": dtype, "shape": [1]}
    if object_pairs:
        info["object_contacts"] = {
            "scope": "object-object: every pair of hydroelastic task-object "
                     "shapes -- the target and the props, the two bodies of "
                     "one asset included -- and never a hand, the table or "
                     "the world. Recorded live from the same surface read as "
                     "contacts/hand_obj/; see each episode's "
                     "`object_contacts` in "
                     "meta/episodes.jsonl for which were live and which "
                     "compiled offline.",
            "location": "contacts/obj_obj/episode_*.npz",
            "keys": "<frame:06d>_{tri,depth,shape_pair} as in hand_obj/, plus "
                    "contact_count and contact_available_count: one entry per "
                    "recorded frame (what the parquet's columns of those names "
                    "are for the hand-object patch). A live recording through "
                    "sim_state also has <frame:06d>_mj_{pair,pos,normal,dist,"
                    "force} and mj_contact_count.",
            "mj_force": "(n, 3) float32 — the solver's force ON the second "
                        "shape of mj_pair FROM the first (MuJoCo's own "
                        "orientation; normal first -> second). Only on frames "
                        "with an object-object patch, as in hand_obj/.",
            "note": "A compiled sidecar has geometry only: nothing can "
                    "compile solver forces.",
            "live": True}
    if sim_state is not None:
        info["sim_state"] = {
            "location": "sim_state/episode_*.npz",
            "timing": "every array is AFTER the row's step, as "
                      "observation.state; solver_contacts are the step's "
                      "own contacts (the ones mj_* in contacts/ come from)",
            "fields": {k: {"shape": list(np.asarray(v).shape[1:])
                           if k.startswith(("newton.", "mujoco."))
                           and k != "mujoco.eq_active" else list(np.asarray(v).shape),
                           "dtype": str(np.asarray(v).dtype)}
                       for k, v in sorted(sim_state.items())},
            "newton": "newton.<field>: the State (joint_q, joint_qd, body_q "
                      "[px py pz qx qy qz qw], body_qd) and every Control "
                      "array, per frame.",
            "mujoco": "mujoco.<field>: MuJoCo-Warp's Data, world 0. time "
                      "qpos qvel act qacc_warmstart ctrl qfrc_applied "
                      "xfrc_applied mocap_pos mocap_quat are MuJoCo's "
                      "integration state (mjSTATE_INTEGRATION): set them and "
                      "the solver continues from that frame. qacc and the "
                      "qfrc_* / actuator_force / solver_niter / nacon / nefc "
                      "are the step's outputs. eq_active is once per "
                      "episode (its value at save).",
            "solver_contacts": "Every contact the solver integrated, all "
                               "pairs: rows [frame_offsets[i], "
                               "frame_offsets[i+1]) are frame i. pair = "
                               "(shape of geom1, shape of geom2), -1 for a "
                               "geom with no Newton shape; normal geom1 -> "
                               "geom2; force ON geom2, world N; class 1 "
                               "hand-object, 2 object-object, 3 other "
                               "(table, hand-hand); finite = False rows are "
                               "a solver NaN, kept for honesty.",
        }
    info["timestamp_clock"] = "simulation seconds at fixed fps"
    info["wall_timestamp_clock"] = "monotonic seconds since collection loop started"
    return info


class _DiskQueue:
    """One background thread that writes saved episodes in order."""

    def __init__(self):
        import queue  # noqa: PLC0415
        import threading  # noqa: PLC0415
        self._q = queue.Queue()
        self._thread = None
        self._lock = threading.Lock()
        self.errors: list[str] = []

    def _run(self):
        while True:
            job, name = self._q.get()
            try:
                job()
            except Exception:                   # noqa: BLE001
                import traceback  # noqa: PLC0415
                msg = f"  ❌ writing {name} FAILED:\n{traceback.format_exc()}"
                print(msg, flush=True)
                self.errors.append(msg)
            finally:
                self._q.task_done()

    def submit(self, job, name: str) -> None:
        import threading  # noqa: PLC0415
        with self._lock:
            if self._thread is None or not self._thread.is_alive():
                self._thread = threading.Thread(target=self._run, name="episode-writer",
                                                daemon=True)
                self._thread.start()
        self._q.put((job, name))

    def flush(self) -> None:
        self._q.join()


#: Two threads, two queues: a handed-off episode is COLLECTED (off the
#: device, into rows) at once, freeing its buffer set for the episode after
#: next; the disk thread then compresses at its own pace.
_COLLECT = _DiskQueue()
_DISK = _DiskQueue()


def flush_writers() -> None:
    """Block until every saved episode is on disk. The collector calls this
    before Kit's close(), which ends the process with os._exit."""
    _COLLECT.flush()
    _DISK.flush()
    if _PROC:
        _PROC.flush()
    _DISK.flush()                             # a fallback may have queued nothing, but be sure


def _atomic(path: str, write) -> None:
    """``write(fh)`` into ``path`` via a temporary name, renamed into place
    only once the whole file is written. An interrupted write (a Ctrl+C, a
    kill, a full disk) then leaves a ``.partial`` file behind, never a
    truncated archive under the final name that loads as if it were complete
    -- which is what np.savez_compressed leaves when interrupted, because its
    zip writer's context manager closes the archive on the way out."""
    tmp = f"{path}.partial"
    try:
        with open(tmp, "wb") as fh:
            write(fh)
        os.replace(tmp, path)
    except BaseException:
        try:
            os.remove(tmp)
        except OSError:
            pass
        raise


def _savez(path: str, arrays: dict) -> None:
    _atomic(path, lambda fh: np.savez_compressed(fh, **arrays))


def _write_config_snapshot(root: str, config: dict) -> None:
    """meta/configs/<hash>.json, once per distinct configuration."""
    import hashlib  # noqa: PLC0415
    blob = json.dumps(config, sort_keys=True, default=str)
    h = hashlib.sha256(blob.encode()).hexdigest()[:12]
    d = os.path.join(root, "meta", "configs")
    os.makedirs(d, exist_ok=True)
    f = os.path.join(d, f"{h}.json")
    if not os.path.exists(f):
        with open(f, "w") as fh:
            json.dump(config, fh, indent=1, default=str)


# ---------------------------------------------------------------- overlay ----

#: Seven-segment glyphs for the HUD's demo counter (Richard, 2026-10-21: "current
#: count / target count" in the environment). Segments a..g in the usual order:
#: a top, b upper right, c lower right, d bottom, e lower left, f upper left, g middle.
_SEG = {"0": "abcdef", "1": "bc", "2": "abged", "3": "abgcd", "4": "fgbc",
        "5": "afgcd", "6": "afgedc", "7": "abc", "8": "abcdefg", "9": "abcdfg",
        "-": "g"}


def seven_segment_quads(text: str, h: float, stroke: float) -> tuple[list, float]:
    """``text`` (digits, ``-``, ``/``, spaces) as filled quads in a 2D (u right,
    v up) frame, baseline at v = 0 and starting at u = 0. Returns (quads, width):
    each quad is four (u, v) corners in order. Unknown characters are blank."""
    w = 0.55 * h
    gap = 0.40 * h
    m = h / 2.0
    ends = {"a": ((0, h), (w, h)), "b": ((w, h), (w, m)), "c": ((w, m), (w, 0)),
            "d": ((0, 0), (w, 0)), "e": ((0, 0), (0, m)), "f": ((0, m), (0, h)),
            "g": ((0, m), (w, m))}
    quads, u0 = [], 0.0
    for ch in text:
        if ch == "1":                     # a narrow cell: one stroke, no hole beside it
            segs, cw = [((0, h), (0, m)), ((0, m), (0, 0))], 0.0
        else:
            segs = ([((0, 0), (w, h))] if ch == "/"
                    else [ends[s] for s in _SEG.get(ch, "")])
            cw = w
        for (pu, pv), (qu, qv) in segs:
            d = np.array([qu - pu, qv - pv], dtype=np.float64)
            d /= np.linalg.norm(d)
            n = np.array([-d[1], d[0]]) * stroke / 2.0
            e = d * stroke / 2.0          # square ends overlap at the corners
            p = np.array([u0 + pu, pv]) - e
            q = np.array([u0 + qu, qv]) + e
            quads.append([tuple(p - n), tuple(q - n), tuple(q + n), tuple(p + n)])
        u0 += cw + gap
    return quads, max(0.0, u0 - gap)


class TeleopHUD:
    """In-headset feedback: is my hand tracked, and what stage am I in?

      progress ring   12 dots filling over the hold, in the YZ plane
      stage dot       world-anchored, one colour per stage
      demo counter    "saved / target" under the ring, green once the target is met

    The five colours are the whole operator interface, so each one means
    exactly one thing and nothing shares a colour:

      grey    idle. Palm-up pinch ARMS a demo.
      purple  armed: the start pinch was seen and recording begins the
              moment it is RELEASED, so the gesture itself never enters the
              data. The ring is full while the pinch is still held.
      yellow  recording.
      green   the success criterion is holding; the ring counts out the
              seconds it has to hold for.
      blue    the demo is recorded and the scene has already been reset.
              Palm-up saves it, palm-down bins it.
      red     binned. Held for --verdict-hold-s, then grey.
      orange  the scene has not reset: a hand is where the next layout puts an
              object. Lift the hands clear; the layout is never redrawn for them.

    Palm-DOWN also resets the scene from any stage; while idle that is the
    only thing it does, and the dot deliberately does not change -- nothing
    was recorded, so there is no verdict to show.
    The stage dot DIMS to 30% when the gesture hand's thumb or index tip is
    missing -- without that, an untracked hand looks identical to an idle one.
    It is WORLD-anchored, not hand-anchored: riding the wrist moved the
    indicator exactly while the operator was pinching.
    Widths and displayColor must be VERTEX interpolation, or a per-point colour
    array on a constant-interpolation prim renders undefined.
    """

    N_RING = 12
    # Size is CONSTANT across stages (every multiplier 1.0), on request: a dot
    # that swells in peripheral vision is distracting. The colours therefore
    # have to be separable on their own -- they are far apart in hue and value.
    STAGES = {
        # name:        (colour,                size multiplier)
        "IDLE":        ((0.30, 0.30, 0.34), 1.0),   # grey   - not recording
        "ARMED":       ((0.80, 0.30, 1.00), 1.0),   # purple - start seen; release the pinch
        "RECORDING":   ((1.00, 0.85, 0.00), 1.0),   # yellow - live
        "HOLDING":     ((0.00, 0.90, 0.20), 1.0),   # green  - in success, counting
        "DECIDE":      ((0.15, 0.45, 1.00), 1.0),   # blue   - recorded; save or bin it
        "DISCARDED":   ((1.00, 0.05, 0.05), 1.0),   # red    - thrown away
        "NEXT":        ((0.00, 0.85, 0.85), 1.0),   # cyan   - palm down still held: leaving for the next task
        "CLEAR":       ((1.00, 0.45, 0.00), 1.0),   # orange - the reset waits: a hand is where an object goes
    }
    RING_ON = (1.00, 1.00, 1.00)
    RING_OFF = (0.14, 0.14, 0.16)

    COUNT_TODO = (0.92, 0.92, 0.92)          # the demo counter while short of the target
    COUNT_DONE = (0.00, 0.90, 0.20)          # ... and once it is met

    def __init__(self, get_stage, path: str = "/World/TeleopHUD",
                 dot: float = 0.026, ring_r: float = 0.060, count_h: float = 0.035):
        self.ok = False
        self._latch_stage = None
        self._latch_left = 0
        self.dot, self.ring_r = dot, ring_r
        self.anchor = None
        self._get_stage, self._path = get_stage, path
        self.count_h = count_h
        self._count = None                    # (have, target) from set_count
        self._count_drawn = None              # (text, anchor) the mesh shows
        self._count_mesh = None
        try:
            from pxr import UsdGeom, Vt  # noqa: PLC0415
            stage = get_stage()
            if stage is None:
                print("  ⚠️  HUD: no USD stage — no in-headset feedback")
                return
            self._Vt = Vt
            n = 1 + self.N_RING               # stage dot + ring
            self._n = n
            pts = UsdGeom.Points.Define(stage, path)
            self._pos = np.zeros((n, 3), dtype=np.float32)
            self._wid = np.zeros(n, dtype=np.float32)
            self._col = np.zeros((n, 3), dtype=np.float32)
            self._ext = np.zeros((2, 3), dtype=np.float32)
            self._pa = pts.CreatePointsAttr()
            self._wa = pts.CreateWidthsAttr()
            self._ca = pts.CreateDisplayColorAttr()
            self._ea = pts.CreateExtentAttr()

            # Seed with real, visible geometry. A points prim first published
            # with zero widths is dropped by Hydra permanently and never renders
            # again, however correct every later write is -- and it looks healthy
            # to every check you can make on it.
            self._pos[:] = (0.0, 0.0, 1.0)
            self._wid[:] = dot * 0.5
            self._col[:] = self.RING_OFF
            self._ext[0], self._ext[1] = (-0.3, -0.3, 0.7), (0.3, 0.3, 1.3)
            self._push()
            pts.SetWidthsInterpolation(UsdGeom.Tokens.vertex)
            pts.GetDisplayColorPrimvar().SetInterpolation(UsdGeom.Tokens.vertex)
            self.ok = True
            print(f"  HUD: {n} dots at {path} — stage dot + {self.N_RING}-dot "
                  f"ring (dot {dot*1000:.0f} mm, ring r {ring_r*1000:.0f} mm)")
        except Exception as exc:  # noqa: BLE001
            print(f"  ⚠️  HUD unavailable ({exc}) — running without in-headset "
                  f"feedback, which means you cannot see stage changes at all")

    def _push(self):
        Vt = self._Vt
        self._ea.Set(Vt.Vec3fArray.FromNumpy(self._ext))
        self._pa.Set(Vt.Vec3fArray.FromNumpy(self._pos))
        self._wa.Set(Vt.FloatArray.FromNumpy(self._wid))
        self._ca.Set(Vt.Vec3fArray.FromNumpy(self._col))

    def set_anchor(self, xyz):
        self.anchor = np.asarray(xyz, dtype=np.float32)

    def set_count(self, have: int, target: int | None):
        """The demo counter under the ring: ``have / target`` (``have`` alone when
        there is no target). A plain attribute write, like latch(): the mesh is
        rebuilt by update(), on whichever thread authors the HUD."""
        self._count = (int(have), None if target is None else int(target))

    def _draw_count(self, base):
        """Rebuild the counter mesh when its text or the anchor changed. Under the
        ring, centred on it, in the ring's YZ plane, read by an operator facing +x
        (their right is -y). Emissive so it reads in any lighting; no shadow."""
        have, target = self._count
        text = f"{have}/{target}" if target else f"{have}"
        key = (text, tuple(np.round(base, 4)))
        if key == self._count_drawn:
            return
        from pxr import Gf, Sdf, UsdGeom, UsdShade  # noqa: PLC0415
        h = self.count_h
        quads, width = seven_segment_quads(text, h, 0.16 * h)
        z0 = float(base[2]) - self.ring_r - self.dot - 1.5 * h
        y0 = float(base[1]) + width / 2.0
        x = float(base[0])
        pts = [Gf.Vec3f(x, y0 - u, z0 + v) for q in quads for u, v in q]
        col = self.COUNT_DONE if target and have >= target else self.COUNT_TODO
        if self._count_mesh is None:
            stage = self._get_stage()
            path = self._path + "Count"
            mesh = UsdGeom.Mesh.Define(stage, path)
            mesh.CreateDoubleSidedAttr(True)
            UsdGeom.PrimvarsAPI(mesh).CreatePrimvar(
                "doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
            mat = UsdShade.Material.Define(stage, path + "_mat")
            sh = UsdShade.Shader.Define(stage, path + "_mat/surface")
            sh.CreateIdAttr("UsdPreviewSurface")
            sh.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.8)
            mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface")
            UsdShade.MaterialBindingAPI.Apply(mesh.GetPrim()).Bind(mat)
            self._count_mesh, self._count_shader = mesh, sh
        mesh, sh = self._count_mesh, self._count_shader
        mesh.CreatePointsAttr().Set(pts)
        mesh.CreateFaceVertexIndicesAttr().Set(list(range(len(pts))))
        mesh.CreateFaceVertexCountsAttr().Set([4] * len(quads))
        lo = (x - 0.01, y0 - width - 0.01, z0 - 0.01)
        hi = (x + 0.01, y0 + 0.01, z0 + h + 0.01)
        mesh.CreateExtentAttr().Set([Gf.Vec3f(*lo), Gf.Vec3f(*hi)])
        mesh.CreateDisplayColorAttr().Set([Gf.Vec3f(*col)])
        sh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*col))
        sh.CreateInput("emissiveColor", Sdf.ValueTypeNames.Color3f).Set(
            Gf.Vec3f(*(0.8 * c for c in col)))
        self._count_drawn = key

    def latch(self, stage: str | None, frames: int = 0):
        """Show `stage` immediately; hold it until told otherwise.

        `frames > 0` releases the latch by itself after that many updates,
        which is what the verdict colours want: blue or red long enough to be
        unmissable, then back to grey with the reset scene.

        A latch changes colour on the frame the event happens and stays there
        until the next event replaces it, so the dot always shows the CURRENT
        state and nothing has to be caught in time. That is why the verdicts
        latch rather than blink: an indicator that reverts on its own can be
        missed entirely between two render frames, and the operator is left
        not knowing whether their pinch registered.

        Pass None to release the latch.
        """
        self._latch_stage = stage
        self._latch_left = int(frames)

    def update(self, stage: str, progress: float, frame: dict, side: str):
        if not self.ok:
            return
        try:
            if self._latch_stage is not None:
                stage = self._latch_stage
                if self._latch_left:
                    self._latch_left -= 1
                    if not self._latch_left:
                        self._latch_stage = None

            if self.anchor is None:
                self._wid[:] = 0.0
                self._push()
                return
            base = self.anchor

            # Tracking liveness, now that the fingertip dots are gone.
            pos = ((frame or {}).get(side) or {}).get("positions") or {}
            tracked = (pos.get("thumb_tip") is not None
                       and pos.get("index_tip") is not None)

            col, mult = self.STAGES.get(stage, self.STAGES["IDLE"])
            if not tracked:
                col = tuple(c * 0.30 for c in col)
            self._pos[0] = base
            self._col[0] = col
            self._wid[0] = self.dot * mult

            # Ring lies in the YZ plane: a 90 deg rotation about z from the
            # original XZ placement, so it faces an operator looking down +x
            # at the object rather than presenting edge-on.
            ang = np.linspace(0.0, 2.0 * np.pi, self.N_RING, endpoint=False)
            self._pos[1:1 + self.N_RING, 0] = base[0]
            self._pos[1:1 + self.N_RING, 1] = base[1] + self.ring_r * np.cos(ang)
            self._pos[1:1 + self.N_RING, 2] = base[2] + self.ring_r * np.sin(ang)
            lit = int(round(float(np.clip(progress, 0.0, 1.0)) * self.N_RING))
            self._col[1:1 + self.N_RING] = self.RING_OFF
            if lit:
                self._col[1:1 + lit] = self.RING_ON
            self._wid[1:1 + self.N_RING] = self.dot * 0.30

            # extent does not follow the points and Hydra culls against it.
            self._ext[0] = self._pos.min(axis=0) - 0.1
            self._ext[1] = self._pos.max(axis=0) + 0.1
            self._push()
            if self._count is not None:
                try:
                    self._draw_count(base)
                except Exception as exc:  # noqa: BLE001
                    self._count = None    # the dot and ring carry on without it
                    print(f"  ⚠️  HUD demo counter failed ({exc}) — hidden")
        except Exception:  # noqa: BLE001
            self.ok = False
            print("  ⚠️  HUD failed mid-run — disabled; collection continues")


def _columns(rows: list) -> tuple[dict, dict, list]:
    """Rows -> (columns, masks, order). An array-valued key becomes one
    (n, ...) array; a key some rows left None (filled from the device later)
    gets a mask of the rows that HAVE a value; a key no row has is left out."""
    order: list = []
    for r in rows:
        for k in r:
            if k not in order:
                order.append(k)
    n = len(rows)
    cols: dict = {}
    masks: dict = {}
    for k in order:
        vals = [r.get(k) for r in rows]
        have = [v is not None for v in vals]
        if not any(have):
            continue
        ex = next(v for v in vals if v is not None)
        if isinstance(ex, np.ndarray):
            arr = np.zeros((n,) + ex.shape, ex.dtype)
            for i, v in enumerate(vals):
                if v is not None:
                    arr[i] = v
            cols[k] = arr
        else:
            cols[k] = np.asarray([ex if v is None else v for v in vals])
        if not all(have):
            masks[k] = np.asarray(have)
    return cols, masks, order


def _finish_episode(spec: dict, cols: dict, masks: dict, order: list,
                    bulk: dict | None = None, host: tuple | None = None) -> None:
    """Everything after the episode left the loop: the device bulk into rows
    and sidecars (tools/sim_recorder.split), meta, and the files. Runs in the
    writer process, on a thread, or inline -- the same code either way."""
    root, ep, task = spec["root"], int(spec["ep"]), spec["task"]
    order = list(order)
    n = len(cols["timestamp"])
    contacts, object_contacts, sim_state = host if host is not None else ({}, None, None)

    def put(k, arr):
        cols[k] = arr
        masks.pop(k, None)
        if k not in order:
            order.append(k)

    if bulk is not None:
        from tools.sim_recorder import split  # noqa: PLC0415
        t0 = time.perf_counter()
        rec = split(**bulk)
        m = int(rec["rows"])
        if m < n:                             # the device short of rows: keep what exists
            for k in list(cols):
                cols[k] = cols[k][:m]
            for k in list(masks):
                masks[k] = masks[k][:m]
            n = m
            if n:
                cols["next.done"][-1] = True
        st, cnt = rec["state"], rec["counts"]
        q, qd = st.get("newton.joint_q"), st.get("newton.joint_qd")
        tq = st.get("newton.control.joint_target_q")
        if "observation.state" not in cols or "observation.state" in masks:
            put("observation.state", np.asarray(q, np.float32))
        if qd is not None:
            put("observation.velocity", np.asarray(qd, np.float32))
        if "action" not in cols:
            put("action", np.asarray(tq, np.float32) if tq is not None
                else np.zeros((n, 0), np.float32))
        elif "action" in masks and tq is not None:
            a = cols["action"].copy()
            miss = ~masks.pop("action")
            a[miss] = tq[miss]
            cols["action"] = a
        if spec.get("patch"):
            put("contact_count", cnt["contact_count"].astype(np.int64))
            put("contact_available_count", cnt["contact_available_count"].astype(np.int64))
            put("contact_dropped_count", cnt["contact_dropped_count"].astype(np.int64))
            put("mj_contact_count", cnt["mj_contact_count"].astype(np.int64))
        else:
            # --record-mode state: no patch recorded. -1, not 0, is how
            # tools/compile_contacts.py finds the frames to build; the
            # solver's contacts are in sim_state/ all the same.
            put("contact_count", np.zeros(n, np.int64))
            put("contact_available_count", np.full(n, -1, np.int64))
            put("contact_dropped_count", np.zeros(n, np.int64))
            put("mj_contact_count", np.full(n, -1, np.int64))
        contacts = {}
        for i, fr in enumerate(rec["contacts"]):
            if fr:
                for k, v in fr.items():
                    contacts[f"{i:06d}_{k}"] = v
        if rec.get("object_contacts") is not None:
            object_contacts = {}
            for i, fr in enumerate(rec["object_contacts"]):
                if fr:
                    for k, v in fr.items():
                        object_contacts[f"{i:06d}_{k}"] = v
            object_contacts["contact_count"] = cnt["object_contact_count"].astype(np.int64)
            object_contacts["contact_available_count"] = \
                cnt["object_contact_available_count"].astype(np.int64)
            object_contacts["mj_contact_count"] = cnt["object_mj_contact_count"].astype(np.int64)
        sim_state = dict(st)
        sim_state["frame_index"] = np.arange(n, dtype=np.int64)
        print(f"  episode {ep}: {n} frames split in {1e3 * (time.perf_counter() - t0):.0f} ms "
              f"({int(cnt['contact_count'].sum())} hand-object faces"
              + (f", {int(cnt['object_contact_count'].sum())} object-object"
                 if object_contacts is not None else "")
              + f", {len(st['solver_contacts.class'])} solver contacts)", flush=True)
    for k in [k for k in order if k not in cols]:
        order.remove(k)
    oo_stamp = {}
    if object_contacts is not None:
        avail = np.asarray(object_contacts["contact_available_count"])
        kept = np.asarray(object_contacts["contact_count"])
        oo_stamp = {"object_contacts": {
            "live": True,
            "contact_dropped_count": int(np.maximum(avail - kept, 0).sum())}}
    dropped = cols.get("contact_dropped_count", np.zeros(n, np.int64))
    line = {
        "episode_index": ep,
        "tasks": [task],
        "length": n,
        "success": bool(spec["success"]),
        "operator_verdict": spec["verdict"],
        "success_terms": spec["terms"],
        # Per-episode provenance. Episodes APPEND across sessions but info.json is
        # rewritten whole on every save, so without this a directory recorded over
        # several sessions attributes the newest settings to every episode.
        "config_hash": spec["config_hash"],
        "contact_dropped_count": int(np.asarray(dropped).sum()),
        "contact_truncated_frames": int((np.asarray(dropped) > 0).sum()),
        **oo_stamp,
        **({"sim_state": {"live": True}} if sim_state is not None else {}),
        **(spec.get("extra") or {}),
    }
    first = {k: cols[k][0] for k in order} if n else {k: cols[k] for k in order}
    info = _info_dict(spec["hands"], spec["robot_type"], spec["fps"], spec["fps_key"],
                      spec["config"], first, ep, object_contacts is not None, sim_state)

    # 🔴 THE CHEAP METADATA GOES FIRST, THE HEAVY ARRAYS SECOND, AND
    # episodes.jsonl LAST. It used to be the other way round, and a
    # gear_mesh save (2026-09-28: 37.3 M object-object faces, 255 MB of
    # np.savez_compressed) put every file that says what the dataset IS
    # behind a write long enough to be interrupted. Killed in that window the
    # directory held a parquet and two sidecars and NO info.json, tasks.jsonl,
    # config snapshot or episodes.jsonl -- 281 MB of good physics that no
    # reader could open and whose config could not be recovered, because the
    # snapshot only ever existed in the dead process's memory.
    #
    # So: write what costs microseconds before what costs seconds. A kill at
    # any point now leaves a dataset that still describes itself, and
    # episodes.jsonl -- the last line written -- is what vouches for an
    # episode being COMPLETE. That is the order the readers already assume:
    # tools/check_dataset.py counts parquets against episodes.jsonl lines, so
    # a partial episode is reported as one ("N in episodes.jsonl but M
    # parquet") instead of silently making the whole directory unreadable.
    _write_config_snapshot(root, spec["config"])
    tp = os.path.join(root, "meta", "tasks.jsonl")
    if not os.path.exists(tp):
        with open(tp, "w") as f:
            f.write(json.dumps({"task_index": 0, "task": task}) + "\n")
    ip = os.path.join(root, "meta", "info.json")
    # info.json is rewritten whole on every save, so a block this writer does
    # not own -- object_contacts, stamped by an offline compile -- is carried
    # over rather than lost with the next episode.
    prev_oo = None
    if os.path.exists(ip):
        try:
            with open(ip) as f:
                prev_oo = json.load(f).get("object_contacts")
        except (OSError, ValueError):
            prev_oo = None
    if "object_contacts" in info:
        merged = dict(prev_oo or {})
        merged.update(info["object_contacts"])
        info["object_contacts"] = merged
    elif prev_oo is not None:
        info["object_contacts"] = prev_oo
    with open(ip, "w") as f:
        json.dump(info, f, indent=2, default=str)

    import pandas as pd  # noqa: PLC0415
    frame = pd.DataFrame({k: (list(cols[k]) if cols[k].ndim > 1 else cols[k]) for k in order})
    _atomic(os.path.join(root, "data", f"episode_{ep:06d}.parquet"),
            lambda fh: frame.to_parquet(fh, index=False))
    if contacts:
        os.makedirs(os.path.join(root, SIDECAR_DIR["hand-object"]), exist_ok=True)
        _savez(os.path.join(root, SIDECAR_DIR["hand-object"], f"episode_{ep:06d}.npz"), contacts)
    if object_contacts is not None:
        # Written even when empty: the file's presence is what tells
        # tools/compile_contacts.py this episode has its object-object
        # sidecar, and "no faces" is an answer, not a gap.
        os.makedirs(os.path.join(root, SIDECAR_DIR["object-object"]), exist_ok=True)
        _savez(os.path.join(root, SIDECAR_DIR["object-object"], f"episode_{ep:06d}.npz"),
               object_contacts)
    if sim_state is not None:
        os.makedirs(os.path.join(root, "sim_state"), exist_ok=True)
        _savez(os.path.join(root, "sim_state", f"episode_{ep:06d}.npz"), sim_state)
    # Last, and only now: every file this line refers to is on disk.
    with open(os.path.join(root, "meta", "episodes.jsonl"), "a") as f:
        f.write(json.dumps(line, default=str) + "\n")


def _ship(spec, rows, handle, n, name) -> None:
    """Collector thread: the episode off the device, then to the writer
    process (or, without one, to the disk thread)."""
    t0 = time.perf_counter()
    bulk = handle.collect_raw(n)
    cols, masks, order = _columns(rows)
    spec = dict(spec, order=order)
    print(f"  episode {spec['ep']}: {n} frames off the device in "
          f"{1e3 * (time.perf_counter() - t0):.0f} ms", flush=True)
    proc = _writer_proc()
    if proc is not None:
        try:
            proc.submit(spec, cols, masks, bulk, name)
            return
        except Exception as exc:                 # noqa: BLE001
            print(f"  ⚠️  writer process refused {name} ({exc}); writing it in-process",
                  flush=True)
    # The pinned views are reused an episode later: this queue may be slower.
    bulk = {k: (np.array(v) if isinstance(v, np.ndarray) else v) for k, v in bulk.items()}
    _DISK.submit(lambda: _finish_episode(spec, cols, masks, order, bulk=bulk), name)


class _WriterProc:
    """tools/episode_writer_proc.py, fed through shared memory: one JSON line
    per episode on its stdin (names, dtypes, shapes, offsets and the spec),
    one reply per episode on its stdout. A reply of failure -- or the process
    dying -- makes the parent finish that episode itself from the same shared
    memory, so nothing handed to it is ever lost."""

    def __init__(self):
        import subprocess  # noqa: PLC0415
        import threading  # noqa: PLC0415
        self.p = subprocess.Popen(
            [sys.executable, "-m", "tools.episode_writer_proc"],
            cwd=os.path.dirname(os.path.abspath(__file__)),
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1)
        self.pending: dict = {}
        self.claimed: set = set()
        self.cv = threading.Condition()
        self.next_id = 0
        self.dead = False
        threading.Thread(target=self._read, name="episode-writer-replies", daemon=True).start()

    def submit(self, spec, cols, masks, bulk, name) -> None:
        from multiprocessing import shared_memory  # noqa: PLC0415
        arrays = [(f"cols/{k}", v) for k, v in cols.items()]
        arrays += [(f"masks/{k}", v) for k, v in masks.items()]
        arrays += [(f"bulk/{k}", v) for k, v in bulk.items() if isinstance(v, np.ndarray)]
        if any(a.dtype == object for _, a in arrays):
            raise ValueError("an object-dtype column cannot cross shared memory")
        sizes = [(-(-a.nbytes // 64)) * 64 for _, a in arrays]
        shm = shared_memory.SharedMemory(create=True, size=max(sum(sizes), 64))
        meta, off = [], 0
        for (key, a), sz in zip(arrays, sizes):
            a = np.ascontiguousarray(a)
            dst = np.ndarray(a.shape, a.dtype, buffer=shm.buf, offset=off)
            np.copyto(dst, a)                    # releases the GIL
            del dst
            meta.append({"key": key, "dtype": a.dtype.str, "shape": list(a.shape), "offset": off})
            off += sz
        scal = {k: v for k, v in bulk.items() if not isinstance(v, np.ndarray)}
        scal["fields"] = [{k: v for k, v in f.items() if k != "ptr"} for f in scal["fields"]]
        with self.cv:
            jid = self.next_id
            self.next_id += 1
            msg = {"id": jid, "shm": shm.name, "arrays": meta, "spec": spec, "bulk": scal}
            self.pending[jid] = (shm, msg, name)
        if self.dead:
            self._fallback(jid)
            return
        try:
            self.p.stdin.write(json.dumps(msg, default=_jsonable) + "\n")
            self.p.stdin.flush()
        except (OSError, ValueError):            # the process is gone
            self.dead = True
            self._fallback(jid)

    def _fallback(self, jid) -> None:
        with self.cv:                            # claim it: the reply thread may race us
            entry = self.pending.get(jid)
            if entry is None or jid in self.claimed:
                return
            self.claimed.add(jid)
        shm, msg, name = entry
        try:
            spec, cols, masks, bulk = _unpack(msg, shm.buf, copy=True)
            _finish_episode(spec, cols, masks, spec["order"], bulk=bulk)
            print(f"  {name}: written in-process (writer process unavailable)", flush=True)
        except Exception:                        # noqa: BLE001
            import traceback  # noqa: PLC0415
            print(f"  ❌ writing {name} FAILED:\n{traceback.format_exc()}", flush=True)
            _DISK.errors.append(name)
        self._release(jid)

    def _release(self, jid) -> None:
        with self.cv:
            shm, _, _ = self.pending.pop(jid)
            self.claimed.discard(jid)
            self.cv.notify_all()
        shm.close()
        shm.unlink()

    def _read(self) -> None:
        for line in self.p.stdout:
            try:
                rep = json.loads(line)
            except ValueError:
                continue
            jid = rep.get("id")
            if jid not in self.pending:
                continue
            if rep.get("ok"):
                with self.cv:
                    mine = jid not in self.claimed
                if mine:
                    self._release(jid)
            else:
                print(f"  ⚠️  writer process failed {self.pending[jid][2]}:\n"
                      f"{rep.get('error')}\n  retrying in-process", flush=True)
                self._fallback(jid)
        self.dead = True                         # EOF: the process is gone
        for jid in list(self.pending):
            self._fallback(jid)

    def flush(self) -> None:
        with self.cv:
            while self.pending:
                self.cv.wait(timeout=1.0)


def _jsonable(v):
    if isinstance(v, np.generic):
        return v.item()
    if isinstance(v, (tuple, set)):
        return list(v)
    return str(v)


def _unpack(msg: dict, buf, copy: bool) -> tuple:
    """A writer message back into (spec, cols, masks, bulk)."""
    cols, masks, bulk = {}, {}, dict(msg["bulk"])
    for a in msg["arrays"]:
        v = np.ndarray(tuple(a["shape"]), np.dtype(a["dtype"]), buffer=buf, offset=a["offset"])
        if copy:
            v = np.array(v)
        kind, key = a["key"].split("/", 1)
        {"cols": cols, "masks": masks, "bulk": bulk}[kind][key] = v
    bulk.setdefault("eq_active", None)
    return msg["spec"], cols, masks, bulk


_PROC = None


def _writer_proc():
    """The writer process, started on first use; None when disabled
    (VR_TELEOP_WRITER_PROC=0) or it could not start."""
    global _PROC
    if os.environ.get("VR_TELEOP_WRITER_PROC", "1") == "0":
        return None
    if _PROC is None:
        try:
            _PROC = _WriterProc()
        except Exception as exc:                 # noqa: BLE001
            print(f"  ⚠️  writer process unavailable ({exc}); writing in-process", flush=True)
            _PROC = False
    return _PROC or None