File size: 187,875 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
from copy import deepcopy as ext_deepcopy
from datetime import datetime as ext_datetime
from datetime import timedelta as ext_timedelta
from datetime import timezone as ext_timezone
from pathlib import Path as ext_Path
from rescopebench.raw_module_isolation import isolated_package_namespace as ext_isolated_package_namespace
from rescopebench.public_projection import assert_hard_public_projection as ext_assert_hard_public_projection
from typing import Any as ext_Any
import hashlib as mod_hashlib
import importlib as mod_importlib
import json as mod_json
import jsonschema as mod_jsonschema
import math as mod_math
import re as _re
import re as mod_re
import shutil as mod_shutil
import sys as mod_sys
import tempfile as mod_tempfile
from .spec import CASE_DIR, DATA_BUSINESS_CALL_LIMITS, DATA_ZONE_ADJACENCY, DATA_ORDERED_MUTATIONS, DATA_CONTRACT, DATA_ORDER_INDEX_BLUEPRINT, DATA_EPISODE_BUDGETS, DATA_TOOLS_2, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_EPISODE_BUDGETS_2, DATA_CHANGED_HANDLING_ATOMS, DATA_ID_FIELDS, DATA_STATE_TABLES, DATA_ORDER_INDEX_BLUEPRINT_2, DATA_TOOLS_3, DATA__TRAVERSE_PARAMETERS, DATA_TRANSFER_PROFILES, DATA__TOOL_BY_NAME, DATA__ID_FIELDS, DATA_ORDER_INDEX_BLUEPRINT_3, DATA_TOOLS_4, DATA_TOOLS_5, DATA__SNAPSHOT_FIELDS, DATA_TOOLS_6, DATA_INTAKE_CODES, DATA_HANDLING_CODES, DATA__SNAPSHOT_FIELDS_2, DATA__TRANSFER_EVIDENCE_FIELDS, DATA_REVALIDATION_STATES, DATA__PRIVATE_KEYS, DATA_TOOLS_7, DATA__SNAPSHOT_TABLES
_BOUNDARY_TIME = ContextVar('robot_boundary_timestamp', default=None)

def fn_scoped_staging_result(result, target_group):

    def visit(value):
        if isinstance(value, list):
            return [visit(item) for item in value]
        if not isinstance(value, dict):
            return value
        row = {key: visit(child) for (key, child) in value.items()}
        if 'access_state' in row and 'storage_handle' in row and ('stock_group' in row) and (row['stock_group'] != target_group):
            row.pop('stock_group')
            row.pop('calibration_records', None)
            row['objects'] = []
            row['matches_pending_stock_group'] = False
            row['scope'] = 'current_priority_order'
        return row
    scoped = visit(result)
    if scoped.get('data', {}).get('outcome') == 'retained_source_unavailable' and scoped.get('message') == 'OK':
        scoped['message'] = 'RETAINED_SOURCE_UNAVAILABLE: requested parcel is absent from the supplied source'
    return scoped

def fn_episode_spec(task_id):
    episode = next((row for row in mod_json.loads((CASE_DIR / 'data/world/private/config.json').read_text())['episodes'] if row['episode_id'] == task_id))
    if int(task_id[1:]) >= 9:
        for order in episode['orders']:
            order['source'] = fn_destinations().get(order['stock_group'], order['source'])
    return episode

def fn_destinations():
    return mod_json.loads((CASE_DIR / 'data/assets/design.json').read_text())['destinations']

def fn_prepare_episode(case, state_dir, episode_id):
    (case, state_dir) = (ext_Path(case).resolve(), ext_Path(state_dir).resolve())
    config = fn_read(case / 'private/config.json')
    requested = fn__episode(config, episode_id)
    episode_budget = fn__episode_budget(config, episode_id)
    sm = fn_open_state(case / 'private/world', state_dir)
    facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id')
    current = facility.get('experience_active_episode') if facility else None
    boundary_config = ext_deepcopy(config)
    boundary_config['budget'] = episode_budget
    if current == episode_id:
        receipt = fn__advance_boundary(sm, boundary_config, current, episode_id)
    else:
        if current is None:
            previous_episode_id = None
            if episode_id != 'T01':
                raise ValueError('a fresh state can only prepare T01')
        else:
            current_episode = fn__episode(config, current)
            if current_episode['next_episode_id'] != episode_id:
                raise ValueError('persistent state cannot skip or rewind episodes')
            previous_episode_id = current
        receipt = fn__advance_boundary(sm, boundary_config, previous_episode_id, episode_id)
    return (fn_restore_adapter(case, state_dir, episode_id), receipt)

def fn_public_task(task_id):
    task = fn_public_task_2(task_id)
    by_index = {row['order_index']: row['work_order'] for row in fn_episode_spec_3(task_id)['orders']}
    ordered = [by_index[index] for index in DATA_ORDER_INDEX_BLUEPRINT[task_id]]
    marker = '\n\nUse the work-order and local observation tools'
    (heading, remainder) = task['query'].split(marker, 1)
    task['work_orders'] = ordered
    task['query'] = heading.split('\n- ', 1)[0] + '\n- ' + '\n- '.join(ordered) + marker + remainder
    task['query'] = mod_re.sub('The starting battery is \\d+ units', f'The starting battery is {DATA_EPISODE_BUDGETS[task_id]} units', task['query'], count=1)
    task['query'] = task['query'].replace('and at most one previously unseen stock binding can be authorized in this episode. ', 'and each newly verified binding remains provisional until its own order closes. ')
    task['budget'] = {'battery_units': DATA_EPISODE_BUDGETS[task_id], 'business_call_limit': DATA_BUSINESS_CALL_LIMITS[task_id]}
    return task

def fn__zone_for_room_id(room_id):
    if not isinstance(room_id, str):
        return None
    for (token, zone) in (('-ground-', 'Zone-Ground'), ('-level-one-', 'Zone-Level-One'), ('-level-two-', 'Zone-Level-Two'), ('-mezzanine-', 'Zone-Mezzanine')):
        if token in room_id:
            return zone
    return None

def fn__profiles():
    prepare = next((row for row in DATA_TOOLS_2 if row['function']['name'] == 'prepare_transfer'))
    return tuple(prepare['function']['parameters']['properties']['profile']['enum'])

def fn_checkpoint_state(adapter, state_dir):
    return fn_checkpoint_state_2(adapter, state_dir)

def fn_load_config():
    return mod_json.loads((CASE_DIR / 'data/world/private/config.json').read_text(encoding='utf-8'))

def fn_episode_spec_2(task_id):
    if task_id not in DATA_TASK_IDS:
        raise ValueError(f'unknown Robot stream task: {task_id}')
    return ext_deepcopy(next((row for row in fn_load_config()['episodes'] if row['episode_id'] == task_id)))

def fn_restore_adapter(case, state_dir, task_id, **kwargs):
    adapter = fn_adapter_for(case, state_dir, task_id, **kwargs)
    ledger = kwargs.get('observation_ledger')
    path = ext_Path(state_dir) / 'observation-ledger.json'
    if ledger is None and path.is_file():
        ledger = mod_json.loads(path.read_text())
    if ledger is not None:
        fn_retain_observed_identities(adapter, ledger, task_id)
    return adapter

def fn_scoped_storage_diagnostics(value, object_name):
    """A failed compound action must not return the underlying unfiltered store."""
    if isinstance(value, dict):
        return {key: [fn_scoped_storage_diagnostics(row, object_name) for row in child if isinstance(row, dict) and row.get('display_name') == object_name] if key == 'objects' and isinstance(child, list) else fn_scoped_storage_diagnostics(child, object_name) for (key, child) in value.items()}
    if isinstance(value, list):
        return [fn_scoped_storage_diagnostics(child, object_name) for child in value]
    return value

def fn_read(path):
    return fn_read_2(path)

def fn__episode(config, episode_id):
    row = next((item for item in config['episodes'] if item['episode_id'] == episode_id), None)
    if row is None:
        raise ValueError(f'unknown episode: {episode_id}')
    return row

def fn__episode_budget(config, episode_id):
    episode = fn__episode(config, episode_id)
    value = episode.get('budget', config.get('budget'))
    if type(value) is not int or value <= 0:
        raise ValueError(f'invalid budget for {episode_id}: {value!r}')
    return value

def fn_open_state(world_dir, state_dir):
    """Open persistent stream state, seeding it from the world only once."""
    world_dir = ext_Path(world_dir).resolve()
    state_dir = ext_Path(state_dir).resolve()
    environment = world_dir / 'environment'
    source_database = environment / 'data' / 'database'
    if not source_database.is_dir():
        raise FileNotFoundError(source_database)
    state_dir.mkdir(parents=True, exist_ok=True)
    state_database = state_dir / 'database'
    if not state_database.exists():
        mod_shutil.copytree(source_database, state_database)
    elif not state_database.is_dir():
        raise NotADirectoryError(state_database)
    environment_path = str(environment)
    if environment_path in mod_sys.path:
        mod_sys.path.remove(environment_path)
    mod_sys.path.insert(0, environment_path)
    from mcp_servers.state.state_manager import StateManager
    return StateManager(db_path=str(state_dir))

def fn__advance_boundary(sm, config, previous_episode_id, next_episode_id):
    token = _BOUNDARY_TIME.set(fn__logical_boundary_time(fn_semantic_state(sm)))
    try:
        return fn_advance_boundary(sm, config, previous_episode_id, next_episode_id)
    finally:
        _BOUNDARY_TIME.reset(token)

def fn_public_task_2(task_id):
    task = fn_public_task_3(task_id)
    budget = DATA_EPISODE_BUDGETS_2[task_id]
    (query, count) = mod_re.subn('The starting battery is \\d+ units', f'The starting battery is {budget} units', task['query'], count=1)
    if count != 1:
        raise ValueError(f'Robot {task_id} public budget sentence changed upstream')
    task['query'] = query.rstrip() + f' Use locate_order_zone for the first pending listed order before cold search. Search is target-scoped: unrelated cabinets do not reveal their stock group or parcel identities, and at most one previously unseen stock binding can be authorized in this episode. The external business-tool limit is {32} calls, including rejected calls. Prefer execute_transfer_attempt once explicit route handles and an exact profile candidate are available. Benchmark credit is awarded only for fully closed work orders; partial milestones are diagnostics.'
    task['budget'] = {'battery_units': budget, 'business_call_limit': 32, 'new_stock_binding_limit': 1}
    task['scoring'] = {'complete_work_order_points': 25.0, 'partial_milestones': 'diagnostic_only'}
    return task

def fn_episode_spec_3(task_id):
    return ext_deepcopy(fn_episode_spec_4(task_id))

def fn_checkpoint_state_2(adapter, state_dir):
    ledger = adapter.export_observation_ledger()
    path = fn__ledger_path(ext_Path(state_dir))
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(mod_json.dumps(ledger, indent=2, sort_keys=True, ensure_ascii=True) + '\n', encoding='utf-8')
    return {'ledger': ledger, 'sha256': fn_digest(ledger), 'path': str(path.resolve())}

def fn_adapter_for(case, state_dir, episode_id, *, observation_ledger=None, rule_epoch_override=None, public_policy_version_override=None):
    (case, state_dir) = (ext_Path(case).resolve(), ext_Path(state_dir).resolve())
    config = fn_read_3(case / 'private/config.json')
    episode = fn__episode_3(config, episode_id)
    sm = fn_open_state(case / 'private/world', state_dir)
    facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id')
    if facility is None or facility.get('experience_active_episode') != episode_id:
        raise ValueError('episode has not been prepared in this persistent state')
    rule_epoch = rule_epoch_override or episode['rule_epoch']
    private_version = public_policy_version_override or episode['public_policy_version']
    rule_table = config['pre_rule_table'] if rule_epoch == 'pre' else config['post_rule_table']
    adapter = RobotExperienceStreamAdapter(sm, robot_id=config['robot_id'], handle_seed=config['handle_seed'], task_ids=[row['task_id'] for row in episode['orders']], rubric=fn__rubric(config, episode), rule_table=rule_table, active_object_ids={row['object_id'] for row in episode['orders']}, public_policy_version=private_version, expected_rule_epoch=rule_epoch, facility_id=config['facility_id'])
    adapter._construction_environment = str((case / 'private/world/environment').resolve())
    ledger = observation_ledger
    ledger_path = fn__ledger_path(state_dir)
    if ledger is None and ledger_path.is_file():
        ledger = fn_read_3(ledger_path)
    if ledger is not None:
        adapter.import_observation_ledger(ledger)
    return adapter

def fn_retain_observed_identities(adapter, ledger, task_id):
    """Past visibility survives relocation; current action permissions do not change."""
    requested = ledger.get('object_handles', [])
    if not isinstance(requested, list) or not all((isinstance(h, str) for h in requested)):
        raise ValueError('object_handles must be a list of strings')
    position = int(task_id[1:])
    prefix = {f'T{i:02d}' for i in range(1, position + 1)}
    objects = {row['object_id'] for row in adapter._all('object_item')}
    past = {row.get('object_id') for row in adapter._all('service_task') if row.get('experience_episode_id') in prefix}
    allowed = {adapter._handle('object', key) for key in objects & past}
    if not set(requested) <= allowed:
        raise ValueError('Observed identity must belong to an existing prefix object')
    adapter.issued_object_handles.update(requested)

def fn_public_retained_source_evidence(evidence):
    """Project retained source evidence onto fields safe for the learner."""
    return {key: str(evidence[key]) for key in ('station', 'storage_handle', 'zone') if isinstance(evidence.get(key), str)}

def fn_read_2(path):
    return fn_read_4(path)

def fn__logical_boundary_time(state):
    timestamps = []
    for rows in state.values():
        for row in rows:
            for field in ('created_at', 'updated_at', 'completed_at', 'released_at', 'accepted_at'):
                value = row.get(field)
                if not isinstance(value, str) or not value:
                    continue
                parsed = ext_datetime.fromisoformat(value.replace('Z', '+00:00'))
                timestamps.append(parsed.replace(tzinfo=ext_timezone.utc) if parsed.tzinfo is None else parsed)
    if not timestamps:
        raise ValueError('Robot boundary requires a timestamped source state')
    return (max(timestamps).astimezone(ext_timezone.utc) + ext_timedelta(seconds=1)).strftime('%Y-%m-%dT%H:%M:%SZ')

def fn_semantic_state(sm):
    return {table: sorted((ext_deepcopy(row) for row in sm.list_entities(table)), key=lambda row: str(row.get(DATA_ID_FIELDS[table], ''))) for table in DATA_STATE_TABLES}

def fn_advance_boundary(sm, config, previous_episode_id, next_episode_id):
    """Advance persistent state without announcing the private rule epoch."""
    facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id')
    if facility is None:
        raise ValueError('stream facility is missing')
    if facility.get('experience_active_episode') == next_episode_id:
        return fn__repeat_boundary(sm, config, previous_episode_id, next_episode_id)
    before_policy = fn__policy_state(sm, config)
    raw = fn_advance_boundary_2(sm, config, previous_episode_id, next_episode_id)
    after_policy = fn__policy_state(sm, config)
    drift = None
    if raw.get('drift') is not None:
        drift = fn__drift_receipt(config, before_policy, after_policy, duplicate=False)
    raw['drift'] = drift
    raw['activation'] = fn_activation_receipt(fn__episode_4(config, next_episode_id))
    raw['schema'] = 'robot-experience-stream-boundary/v4'
    raw['public_notice'] = fn__public_notice(config, previous_episode_id, raw['activation']['event_id'])
    fn_public_boundary_projection(raw)
    return raw

def fn_public_task_3(task_id):
    task = fn_public_task_4(task_id)
    if task_id != 'T09':
        by_index = {row['order_index']: row['work_order'] for row in fn_episode_spec_6(task_id)['orders']}
        indices = DATA_ORDER_INDEX_BLUEPRINT_2.get(task_id, tuple(sorted(by_index)))
        ordered = [by_index[index] for index in indices]
        marker = '\n\nUse the work-order and local observation tools'
        (heading, remainder) = task['query'].split(marker, 1)
        task['work_orders'] = ordered
        task['query'] = heading.split('\n- ', 1)[0] + '\n- ' + '\n- '.join(ordered) + marker + remainder
    if task_id == 'T01':
        before = task['query']
        task['query'] = before.replace(f'The starting battery is {93} units', f'The starting battery is {72} units')
        if task['query'] == before:
            raise ValueError('Robot T01 public budget sentence changed upstream')
    return task

def fn_episode_spec_4(task_id):
    spec = fn_episode_spec_5(task_id)
    spec['budget'] = DATA_EPISODE_BUDGETS_2[task_id]
    return spec

def fn__ledger_path(state_dir):
    return ext_Path(state_dir) / 'observation-ledger.json'

def fn_digest(value):
    return fn_digest_3(value)

def fn_read_3(path):
    return fn_read_2(path)

def fn__episode_3(config, episode_id):
    row = next((item for item in config['episodes'] if item['episode_id'] == episode_id), None)
    if row is None:
        raise ValueError(f'unknown episode: {episode_id}')
    return row

def fn__rubric(config, episode):
    return {'version': 'robot-experience-rubric/v1', 'policy_version': 'PV-18', 'home_room_id': config['home_room_id'], 'orders': [{'work_order': row['work_order'], 'task_id': row['task_id'], 'object_id': row['object_id'], 'destination_room_id': row['target']} for row in episode['orders']]}

def fn_episode_spec_5(task_id):
    return fn_episode_spec_6(task_id)

def fn_load_config_2():
    config = fn_load_config_3()
    config['episode_budgets']['T01'] = 72
    return config

def fn_digest_2(value):
    return mod_hashlib.sha256(fn__canonical(value)).hexdigest()

def fn_read_4(path):
    return fn_read_5(path)

def fn__repeat_boundary(sm, config, previous_episode_id, next_episode_id):
    if previous_episode_id != next_episode_id:
        raise ValueError('an idempotent replay must name the active episode')
    episode = fn__episode_4(config, next_episode_id)
    activation = fn_activation_receipt(episode)
    before_state = fn_semantic_state(sm)
    before_policy = fn__policy_state(sm, config)
    drift = None
    if next_episode_id == config['drift']['effective_episode_id']:
        prior_policy = {**before_policy, 'experience_rule_epoch': config['drift']['from_rule_epoch'], 'experience_policy_version': config['drift']['from_policy_version'], 'experience_policy_event_seq': before_policy['experience_policy_event_seq'] - 1}
        if prior_policy['experience_policy_event_seq'] < 0:
            raise ValueError('drift event sequence is inconsistent')
        drift = fn__drift_receipt(config, prior_policy, before_policy, duplicate=True)
    receipt = {'schema': 'robot-experience-stream-boundary/v4', 'previous_episode_id': previous_episode_id, 'next_episode_id': next_episode_id, 'already_prepared': True, 'before_sha256': fn__digest(before_state), 'after_sha256': fn__digest(before_state), 'closed': {'closed_orders': [], 'cancelled_assignments': []}, 'supervisor_recovery': {'performed': False}, 'drift': drift, 'activation': activation, 'public_notice': fn__public_notice(config, None if next_episode_id == config['episodes'][0]['episode_id'] else 'prior', activation['event_id']), 'changes': [], 'preservation_contract': {'world_reset': False, 'opened_storage_preserved': True, 'completed_records_preserved': True, 'unrelated_object_locations_preserved': True, 'payload_parking_is_not_delivery': True}}
    fn_public_boundary_projection(receipt)
    return receipt

def fn__policy_state(sm, config):
    facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id')
    if facility is None:
        raise ValueError('stream facility is missing')
    return {'experience_rule_epoch': facility.get('experience_rule_epoch'), 'experience_policy_version': facility.get('experience_policy_version'), 'experience_policy_event_seq': int(facility.get('experience_policy_event_seq', 0))}

def fn_advance_boundary_2(sm, config, previous_episode_id, next_episode_id):
    """Close one episode and activate the next without resetting world state."""
    previous_episode = fn__episode_5(config, previous_episode_id)
    next_episode = fn__episode_5(config, next_episode_id)
    if next_episode is None:
        raise ValueError('unknown next episode')
    if previous_episode_id is not None and previous_episode is None:
        raise ValueError('unknown previous episode')
    if previous_episode is not None:
        expected = previous_episode['next_episode_id']
        if expected != next_episode_id:
            raise ValueError('episode boundary is not sequential')
    before = fn_semantic_state_2(sm)
    closed = fn__close_previous(sm, previous_episode)
    recovery = fn__recover_robot(sm, budget=config['budget'])
    drift = fn__apply_drift(sm, config, next_episode_id)
    activation = fn__activate_next(sm, config, next_episode)
    after = fn_semantic_state_2(sm)
    changes = fn_state_diff(before, after)
    notice = f"Episode {next_episode_id} is active. The supervisor placed the robot at the service hub with {config['budget']} battery units and activated the new work orders."
    if previous_episode_id is not None:
        notice += ' Any payload left from the prior episode was parked at its actual terminal room without delivery credit; other world state and completed records were preserved.'
    if drift is not None:
        notice += ' ' + drift['public_notice']
    return {'schema': 'robot-experience-stream-boundary/v2', 'previous_episode_id': previous_episode_id, 'next_episode_id': next_episode_id, 'before_sha256': fn__digest_2(before), 'after_sha256': fn__digest_2(after), 'closed': closed, 'supervisor_recovery': recovery, 'drift': drift, 'activation': activation, 'public_notice': notice, 'changes': changes, 'preservation_contract': {'world_reset': False, 'opened_storage_preserved': True, 'completed_records_preserved': True, 'unrelated_object_locations_preserved': True, 'payload_parking_is_not_delivery': True}}

def fn__drift_receipt(config, before, after, *, duplicate):
    drift = config['drift']
    if after != {'experience_rule_epoch': drift['to_rule_epoch'], 'experience_policy_version': drift['to_policy_version'], 'experience_policy_event_seq': before['experience_policy_event_seq'] + 1}:
        raise ValueError('drift receipt does not match the expected policy transition')
    return {'schema': 'robot-experience-drift-application/v1', 'event_id': fn__drift_event_id(config), 'event_type': 'external_policy_update', 'receipt_kind': 'duplicate_application' if duplicate else 'first_application', 'status': 'already_applied' if duplicate else 'applied', 'applied_now': not duplicate, 'duplicate_noop': duplicate, 'exactly_once': True, 'application_before_sha256': fn__digest(before), 'application_after_sha256': fn__digest(after), 'call_before_sha256': fn__digest(after if duplicate else before), 'call_after_sha256': fn__digest(after), 'state_unchanged': duplicate, 'effective_episode_id': drift['effective_episode_id'], 'publicly_announced': False, 'policy_version_before': drift['from_policy_version'], 'policy_version_after': drift['to_policy_version'], 'changed_cell_count': len(drift['changed_cells'])}

def fn_activation_receipt(episode):
    """Project an active private episode into the exact public receipt."""
    orders = episode.get('orders')
    if not isinstance(episode.get('episode_id'), str) or not episode['episode_id']:
        raise ValueError('episode must define a non-empty episode_id')
    if not isinstance(orders, list) or not orders:
        raise ValueError('episode must define active work orders')
    work_orders = [row.get('work_order') for row in orders if isinstance(row, dict)]
    if len(work_orders) != len(orders) or any((not isinstance(value, str) or not value for value in work_orders)) or len(set(work_orders)) != len(work_orders):
        raise ValueError('episode work orders must be unique non-empty strings')
    return {'schema': 'robot-experience-activation-public/v4', 'event_type': 'work_order_activation', 'event_id': fn_opaque_event_id(work_orders), 'work_orders': sorted(work_orders), 'created_object_ids': [], 'world_reset': False}

def fn__episode_4(config, episode_id):
    episode = next((row for row in config.get('episodes', []) if row.get('episode_id') == episode_id), None)
    if episode is None:
        raise ValueError('unknown next episode')
    return episode

def fn__public_notice(config, previous_episode_id, event_id):
    notice = f"Work-order event {event_id} is active. The supervisor placed the robot at the service hub with {config['budget']} battery units and activated the new work orders."
    if previous_episode_id is not None:
        notice += ' Any payload left from the prior episode was parked at its actual terminal room without delivery credit; other business state and completed records were preserved.'
    return notice

def fn_public_boundary_projection(receipt):
    """Return only the boundary fields admitted to a learner/provider request."""
    activation = receipt.get('activation')
    notice = receipt.get('public_notice')
    if not isinstance(activation, dict) or not isinstance(notice, str):
        raise ValueError('boundary receipt is missing its public fields')
    projection = {'schema': 'robot-experience-stream-boundary-public/v2', 'event_id': activation.get('event_id'), 'activation': ext_deepcopy(activation), 'public_notice': notice}
    encoded = mod_json.dumps(projection, sort_keys=True, ensure_ascii=True).casefold()
    forbidden = ('pv-', 'policy_version', 'rule_epoch', 'drift', 'policy update', 'transfer policy', 'changed cell', 'rule change', 'environment change', 'prior compatibility', 'selective revision')
    if any((token in encoded for token in forbidden)):
        raise ValueError('learner-visible boundary exposes a private transition marker')
    fn_assert_opaque_learner_surface(projection, surface='public boundary')
    return projection

def fn_public_task_4(task_id):
    task = fn_public_task_5(task_id)
    if task_id != 'T09':
        by_index = {row['order_index']: row['work_order'] for row in fn_episode_spec_6(task_id)['orders']}
        indices = DATA_ORDER_INDEX_BLUEPRINT_3.get(task_id, tuple(sorted(by_index)))
        ordered = [by_index[index] for index in indices]
        marker = '\n\nUse the work-order and local observation tools'
        (heading, remainder) = task['query'].split(marker, 1)
        task['work_orders'] = ordered
        task['query'] = heading.split('\n- ', 1)[0] + '\n- ' + '\n- '.join(ordered) + marker + remainder
    sentence = ' Process the work orders in the listed priority order: do not start a later order until every earlier listed order has been fully closed.'
    if sentence.strip() not in task['query']:
        task['query'] = task['query'].rstrip() + sentence
    task['completion'] = {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': True}
    return task

def fn_episode_spec_6(task_id):
    return fn_episode_spec_2(task_id)

def fn_digest_3(value):
    return fn_digest_4(value)

def fn__error(code, message, data=None):
    return {'status': 'error', 'data': data or {}, 'message': f'{code}: {message}'}

def fn__code(result):
    message = str(result.get('message') or '')
    return message.split(':', 1)[0] if ':' in message else 'OK' if result.get('status') == 'success' else 'ERROR'

def fn__success(data, message='OK'):
    return {'status': 'success', 'data': data, 'message': message}

def fn__timestamp():
    return ext_datetime.now(ext_timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')

def fn_load_config_3():
    config = fn_load_config()
    config['episode_budgets']['T01'] = 93
    return config

def fn__canonical(value):
    return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('ascii')

def fn__validate_snapshot_extensions(snapshot):
    if not isinstance(snapshot, dict) or set(snapshot) != DATA__SNAPSHOT_FIELDS:
        raise ValueError('Robot v8 snapshot fields are incomplete or unexpected')
    if type(snapshot.get('business_call_count')) is not int:
        raise ValueError('Robot v8 business_call_count must be an integer')
    if snapshot['business_call_count'] < 0:
        raise ValueError('Robot v8 business_call_count must be non-negative')
    authorized = snapshot.get('authorized_new_stock_group')
    if authorized is not None and (not isinstance(authorized, str) or not authorized):
        raise ValueError('Robot v8 authorized stock group must be null or a string')
    provisional = snapshot.get('provisional_stock_groups')
    verified = snapshot.get('verified_stock_groups')
    if not isinstance(provisional, dict):
        raise ValueError('Robot v8 provisional_stock_groups must be an object')
    if not isinstance(verified, dict):
        raise ValueError('Robot v8 verified_stock_groups must be an object')
    if len(provisional) > 1:
        raise ValueError('Robot v8 provisional stock bindings exceed the task limit')
    if set(provisional) & set(verified):
        raise ValueError('Robot v8 stock evidence cannot be both provisional and verified')
    required = {'task_id', 'station', 'storage_handle', 'zone'}
    for (stock_group, evidence) in {**verified, **provisional}.items():
        if not isinstance(stock_group, str) or not stock_group:
            raise ValueError('Robot v8 verified stock-group keys must be strings')
        if not isinstance(evidence, dict) or set(evidence) != required:
            raise ValueError('Robot v8 verified stock evidence is malformed')
        if any((not isinstance(evidence[field], str) or not evidence[field] for field in required)):
            raise ValueError('Robot v8 verified stock evidence values must be strings')
        if evidence['task_id'] not in DATA_TASK_IDS:
            raise ValueError('Robot v8 verified stock evidence has an invalid task')
    if any((evidence['task_id'] != snapshot.get('task_id') for evidence in provisional.values())):
        raise ValueError('Robot v8 provisional stock evidence crossed a task boundary')
    visible_handles = snapshot.get('visible_object_handles')
    if not isinstance(visible_handles, list) or any((not isinstance(handle, str) or not handle for handle in visible_handles)) or len(visible_handles) != len(set(visible_handles)):
        raise ValueError('Robot v8 visible object handles must be unique strings')

def fn_read_5(path):
    return mod_json.loads(ext_Path(path).read_text(encoding='utf-8'))

def fn__digest(value):
    return mod_hashlib.sha256(mod_json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(',', ':'), allow_nan=False).encode('ascii')).hexdigest()

def fn__episode_5(config, episode_id):
    if episode_id is None:
        return None
    return next((row for row in config['episodes'] if row['episode_id'] == episode_id), None)

def fn_semantic_state_2(sm):
    return {table: sorted((ext_deepcopy(row) for row in sm.list_entities(table)), key=lambda row: str(row.get(DATA_ID_FIELDS[table], ''))) for table in DATA_STATE_TABLES}

def fn__close_previous(sm, episode):
    if episode is None:
        return {'closed_orders': [], 'cancelled_assignments': []}
    (closed, cancelled) = ([], [])
    task_ids = {row['task_id'] for row in episode['orders']}
    for spec in episode['orders']:
        task = sm.get_entity('service_task', spec['task_id'], id_field='task_id')
        obj = sm.get_entity('object_item', spec['object_id'], id_field='object_id')
        if task is None or obj is None:
            raise ValueError('previous episode records are missing')
        task_changes = {'experience_activation_state': 'closed', 'updated_at': fn__boundary_timestamp()}
        if task.get('status') != 'completed':
            task_changes.update(status='paused', assigned_robot_id=None, failure_reason='episode_closed_by_supervisor')
        fn__update(sm, 'service_task', spec['task_id'], task_changes)
        fn__update(sm, 'object_item', spec['object_id'], {'experience_activation_state': 'closed', 'updated_at': fn__boundary_timestamp()})
        closed.append(spec['work_order'])
    for assignment in sm.list_entities('task_assignment'):
        if assignment.get('task_id') in task_ids and assignment.get('status') == 'active':
            fn__update(sm, 'task_assignment', assignment['assignment_id'], {'status': 'cancelled', 'completed_at': fn__boundary_timestamp()})
            cancelled.append(assignment['assignment_id'])
    return {'closed_orders': sorted(closed), 'cancelled_assignments': sorted(cancelled)}

def fn__recover_robot(sm, *, budget):
    robot = sm.get_entity('robot_unit', 'robot-porter-atlas-north-one', id_field='robot_id')
    if robot is None:
        raise ValueError('controlled robot is missing')
    parked = None
    payload_id = robot.get('payload_object_id')
    if payload_id is not None:
        payload = sm.get_entity('object_item', payload_id, id_field='object_id')
        if payload is None or payload.get('held_by_robot_id') != 'robot-porter-atlas-north-one':
            raise ValueError('robot payload custody is inconsistent at the boundary')
        parked = {'object_id': payload_id, 'room_id': robot.get('current_room_id'), 'delivery_receipt_created': False}
        fn__update(sm, 'object_item', payload_id, {'current_room_id': robot.get('current_room_id'), 'held_by_robot_id': None, 'handling_state': 'stored', 'updated_at': fn__boundary_timestamp()})
    before = {key: ext_deepcopy(robot.get(key)) for key in ('current_room_id', 'battery_percent', 'payload_object_id', 'operational_status', 'active_task_id')}
    fn__update(sm, 'robot_unit', 'robot-porter-atlas-north-one', {'current_room_id': 'room-atlas-north-level-one-central-return-sort', 'battery_percent': budget, 'payload_object_id': None, 'operational_status': 'available', 'active_task_id': None, 'updated_at': fn__boundary_timestamp()})
    after_row = sm.get_entity('robot_unit', 'robot-porter-atlas-north-one', id_field='robot_id')
    return {'before': before, 'after': {key: ext_deepcopy(after_row.get(key)) for key in before}, 'parked_payload': parked}

def fn__apply_drift(sm, config, next_episode_id):
    drift = config['drift']
    if next_episode_id != drift['effective_episode_id']:
        return None
    facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id')
    if facility is None:
        raise ValueError('stream facility is missing')
    if facility.get('experience_rule_epoch') != drift['from_rule_epoch']:
        raise ValueError('drift must be applied exactly once from the pre-drift epoch')
    before = {'experience_rule_epoch': facility.get('experience_rule_epoch'), 'experience_policy_version': facility.get('experience_policy_version')}
    fn__update(sm, 'facility', config['facility_id'], {'experience_rule_epoch': 'post', 'experience_policy_version': 'PV-19', 'experience_policy_event_seq': int(facility.get('experience_policy_event_seq', 0)) + 1})
    return {'event_type': 'external_policy_update', 'effective_episode_id': next_episode_id, 'publicly_announced': True, 'policy_version_before': before['experience_policy_version'], 'policy_version_after': 'PV-19', 'changed_cell_count': len(drift['changed_cells']), 'public_notice': f"Transfer policy {'PV-19'} is effective for {next_episode_id}. Current work-order records show the active policy version; prior compatibility experience may need selective revision."}

def fn__activate_next(sm, config, episode):
    facility = sm.get_entity('facility', config['facility_id'], id_field='facility_id')
    if facility is None:
        raise ValueError('stream facility is missing')
    if facility.get('experience_rule_epoch') != episode['rule_epoch']:
        raise ValueError('next episode expects a different rule epoch')
    activated = []
    for spec in episode['orders']:
        task = sm.get_entity('service_task', spec['task_id'], id_field='task_id')
        obj = sm.get_entity('object_item', spec['object_id'], id_field='object_id')
        if task is None or obj is None:
            raise ValueError('next episode records are missing')
        if task.get('experience_activation_state') != 'inactive':
            raise ValueError('next service task is not inactive')
        if obj.get('experience_activation_state') != 'inactive':
            raise ValueError('next parcel is not inactive')
        fn__update(sm, 'service_task', spec['task_id'], {'experience_activation_state': 'active', 'updated_at': fn__boundary_timestamp()})
        fn__update(sm, 'object_item', spec['object_id'], {'experience_activation_state': 'active', 'updated_at': fn__boundary_timestamp()})
        activated.append(spec['work_order'])
    fn__update(sm, 'facility', config['facility_id'], {'experience_active_episode': episode['episode_id']})
    return {'schema': 'robot-experience-activation-public/v2', 'event_type': 'work_order_activation', 'episode_id': episode['episode_id'], 'work_orders': sorted(activated), 'policy_version': episode['public_policy_version'], 'created_object_ids': [], 'world_reset': False}

def fn_state_diff(before, after):
    changes = []
    for table in DATA_STATE_TABLES:
        (left, right) = (fn__row_index(before, table), fn__row_index(after, table))
        for identifier in sorted(set(left) | set(right)):
            if left.get(identifier) != right.get(identifier):
                changes.append({'table': table, 'id': identifier, 'before': ext_deepcopy(left.get(identifier)), 'after': ext_deepcopy(right.get(identifier))})
    return changes

def fn__digest_2(value):
    payload = mod_json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode('utf-8')
    return mod_hashlib.sha256(payload).hexdigest()

def fn__drift_event_id(config):
    drift = config['drift']
    payload = {'schema': 'robot-experience-drift-application/v1', 'facility_id': config['facility_id'], 'from_rule_epoch': drift['from_rule_epoch'], 'to_rule_epoch': drift['to_rule_epoch'], 'from_policy_version': drift['from_policy_version'], 'to_policy_version': drift['to_policy_version'], 'changed_cells': drift['changed_cells']}
    return 'evt-' + fn__digest(payload)[:20]

def fn_opaque_event_id(work_orders):
    """Derive a stable, non-sequential public ID from the public order set."""
    if not isinstance(work_orders, list) or not work_orders or any((not isinstance(value, str) or not value for value in work_orders)) or (len(set(work_orders)) != len(work_orders)):
        raise ValueError('opaque event IDs require unique non-empty work orders')
    payload = mod_json.dumps(['robot-final-public-event/v1', *sorted(work_orders)], ensure_ascii=True, separators=(',', ':')).encode('ascii')
    return 'evt-' + mod_hashlib.sha256(payload).hexdigest()[:20]

def fn_assert_opaque_learner_surface(value, *, surface):
    hits = fn_leakage_hits(value)
    present = {name: rows for (name, rows) in hits.items() if rows}
    if present:
        raise ValueError(f'{surface} exposes private lifecycle metadata: {present}')
    try:
        ext_assert_hard_public_projection(value)
    except ValueError as error:
        raise ValueError(f'{surface} exposes private lifecycle metadata: {error}') from error

def fn_public_task_5(task_id):
    task = fn_public_task_6(task_id)
    if task_id == 'T01':
        before = task['query']
        task['query'] = before.replace('The starting battery is 98 units', f'The starting battery is {93} units')
        if task['query'] == before:
            raise ValueError('Robot T01 public budget sentence changed upstream')
    return task

def fn_digest_4(value):
    return mod_hashlib.sha256(mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()).hexdigest()

def fn__validate_snapshot_extensions_2(snapshot):
    if not isinstance(snapshot, dict) or set(snapshot) != DATA__SNAPSHOT_FIELDS_2:
        raise ValueError('Robot v7 snapshot fields are incomplete or unexpected')
    evidence = snapshot.get('transfer_evidence')
    revalidation = snapshot.get('rule_revalidation')
    if not isinstance(evidence, dict) or not isinstance(revalidation, dict):
        raise ValueError('Robot v7 snapshot extensions must be objects')
    profiles = set(fn__profiles())
    for (cell, row) in evidence.items():
        (handling, intake) = fn__validate_cell(cell)
        if not isinstance(row, dict) or set(row) != DATA__TRANSFER_EVIDENCE_FIELDS:
            raise ValueError(f'Robot v7 transfer evidence is malformed for {cell}')
        if any((not isinstance(row[field], str) or not row[field] for field in row)):
            raise ValueError(f'Robot v7 transfer evidence values must be strings for {cell}')
        if row['task_id'] not in DATA_TASK_IDS or row['cell'] != cell:
            raise ValueError(f'Robot v7 transfer evidence identity mismatch for {cell}')
        if row['handling_code'] != handling or row['intake_code'] != intake:
            raise ValueError(f'Robot v7 transfer evidence crosses exact cells for {cell}')
        if row['profile'] not in profiles:
            raise ValueError(f'Robot v7 transfer evidence profile is invalid for {cell}')
    for (cell, state) in revalidation.items():
        fn__validate_cell(cell)
        if cell not in evidence or state not in DATA_REVALIDATION_STATES:
            raise ValueError(f'Robot v7 revalidation state is invalid for {cell}')

def fn__boundary_timestamp():
    return _BOUNDARY_TIME.get()

def fn__update(sm, table, identifier, changes):
    sm.update_entity(table, identifier, changes, id_field=DATA_ID_FIELDS[table])

def fn__row_index(state, table):
    field = DATA_ID_FIELDS[table]
    return {str(row[field]): row for row in state[table]}

def fn_leakage_hits(value):
    """Report private lifecycle labels in a learner/provider-visible value."""
    encoded = mod_json.dumps(value, ensure_ascii=True, sort_keys=True, allow_nan=False)
    private_keys: set[str] = set()

    def visit(item):
        if isinstance(item, dict):
            private_keys.update((str(key) for key in item if key in DATA__PRIVATE_KEYS))
            for nested in item.values():
                visit(nested)
        elif isinstance(item, list):
            for nested in item:
                visit(nested)
    visit(value)
    return {'private_episode_ids': sorted(set(_re.compile('(?<![A-Za-z0-9])T(?:0[1-9]|1[0-6])(?![A-Za-z0-9]|:[0-5][0-9])', 34).findall(encoded))), 'arm_labels': sorted(set(_re.compile('(?<![A-Za-z0-9])(?:native|reset|reflect)\\d{2}(?![A-Za-z0-9])', 34).findall(encoded))), 'run_paths': sorted(set(_re.compile('(?:benchmark_outputs[/\\\\]robot|robot-final-v\\d+[/\\\\]20\\d{6}-\\d{6})', 34).findall(encoded))), 'private_keys': sorted(private_keys)}

def fn_public_task_6(task_id):
    if task_id not in DATA_TASK_IDS:
        raise ValueError(f'unknown Robot stream task: {task_id}')
    return mod_json.loads((CASE_DIR / 'data/world' / f'public/tasks/{task_id}.json').read_text(encoding='utf-8'))

def fn__validate_rule_table(value):
    table = ext_deepcopy(value if value is not None else fn_default_rule_table())
    expected = {f'{handling}:{intake}' for handling in DATA_HANDLING_CODES for intake in DATA_INTAKE_CODES}
    if set(table) != expected or any((profile not in DATA_TRANSFER_PROFILES for profile in table.values())):
        raise ValueError('rule_table must define every handling:intake cell')
    return table

def fn__validate_cell(cell):
    if not isinstance(cell, str) or cell.count(':') != 1:
        raise ValueError('transfer evidence key must be an exact handling:intake cell')
    (handling, intake) = cell.split(':', 1)
    if not handling or not intake:
        raise ValueError('transfer evidence cell components must be non-empty')
    return (handling, intake)

def fn_default_rule_table():
    """Return the private finite relation used by the first candidate."""
    handling_rank = (2, 0, 3, 1)
    intake_rank = (1, 3, 0, 2)
    return {f'{handling}:{intake}': DATA_TRANSFER_PROFILES[(handling_rank[handling_index] + intake_rank[intake_index]) % len(DATA_TRANSFER_PROFILES)] for (handling_index, handling) in enumerate(DATA_HANDLING_CODES) for (intake_index, intake) in enumerate(DATA_INTAKE_CODES)}

def fn__strip_volatile(value):
    if isinstance(value, dict):
        return {key: fn__strip_volatile(item) for (key, item) in sorted(value.items()) if not key.endswith('_at')}
    if isinstance(value, list):
        return [fn__strip_volatile(item) for item in value]
    return ext_deepcopy(value)

class World:

    def __init__(self):
        self.runtime = RobotSourceScopeRuntime()
        self.t01_boundary = self.runtime.activate_task('T01')
        self.t01_pending = True

    def snapshot(self):
        return {'schema': 'rescopebench-robot-rule-formal-world/v6', 'runtime': self.runtime.snapshot(), 't01_boundary': ext_deepcopy(self.t01_boundary), 't01_pending': self.t01_pending}

    def restore(self, snapshot):
        if not isinstance(snapshot, dict) or set(snapshot) != {'schema', 'runtime', 't01_boundary', 't01_pending'}:
            raise ValueError('invalid Robot rule-v9 formal snapshot fields')
        if snapshot.get('schema') != 'rescopebench-robot-rule-formal-world/v6':
            raise ValueError('unsupported Robot rule-v9 formal snapshot')
        if not isinstance(snapshot.get('t01_pending'), bool):
            raise ValueError('Robot rule-v9 pending flag must be boolean')
        self.runtime.restore(ext_deepcopy(snapshot['runtime']))
        self.t01_boundary = ext_deepcopy(snapshot['t01_boundary'])
        self.t01_pending = snapshot['t01_pending']
        if self.snapshot() != snapshot:
            raise ValueError('Robot rule-v9 formal snapshot did not round trip')

    def activate(self, task_id):
        if task_id == 'T01' and self.t01_pending:
            self.t01_pending = False
            return ext_deepcopy(self.t01_boundary)
        self.t01_pending = False
        return self.runtime.activate_task(task_id)

    def close(self):
        self.runtime.close()

class RobotSourceScopeRuntime:

    def _stage_retained_source(self, arguments):
        result = self._robot_local_rule_runtime_stage_retained_source(arguments)
        order = self._task_order(arguments.get('work_order', ''))
        return fn_scoped_staging_result(result, (order or {}).get('stock_group'))

    def _validate_restored_evidence_against_world(self):
        try:
            return self._robot_source_runtime_validate_restored_evidence_against_world()
        except ValueError as error:
            if str(error) != 'Robot v8 replacement state lacks a stale rejection':
                raise
        original = self.rule_revalidation
        self.rule_revalidation = {cell: 'awaiting_exact_stale' if state == 'awaiting_replacement' else state for (cell, state) in original.items()}
        try:
            return self._robot_source_runtime_validate_restored_evidence_against_world()
        finally:
            self.rule_revalidation = original

    def __init__(self, *args, **kwargs):
        self._restoring_source = False
        self._robot_route_runtime_init(*args, **kwargs)

    def _task_order(self, work_order):
        if self.current_task_id is None:
            return None
        return next((row for row in fn_episode_spec(self.current_task_id)['orders'] if row['work_order'] == work_order), None)

    def activate_task(self, task_id):
        receipt = self._robot_route_runtime_activate_task(task_id)
        if int(task_id[1:]) >= 9:
            with self.isolated_raw():
                self._relocate_stock()
        return receipt

    def _relocate_stock(self):
        (adapter, moves) = (self.adapter, fn_destinations())
        facility = next((row for row in adapter._all('facility') if row['facility_id'] == mod_json.loads((CASE_DIR / 'data/assets/config.json').read_text())['facility_id']))
        if facility.get('stock_relocation_version') == 'robot-stock-relocation-evolution-v9':
            return
        rooms = {row['room_id']: ext_deepcopy(row) for row in adapter._all('room')}
        stores = {unit['stock_group']: (room['room_id'], ext_deepcopy(unit)) for room in rooms.values() for unit in room.get('storage_units', [])}
        targets = {}
        for (group, destination) in moves.items():
            (old_room, old_unit) = stores[group]
            target_group = next((key for key in moves if stores[key][0] == destination))
            target_unit = stores[target_group][1]
            targets[group] = (old_room, old_unit['unit_id'], destination, target_unit['unit_id'])
            unit = next((row for row in rooms[destination]['storage_units'] if row['unit_id'] == target_unit['unit_id']))
            unit['stock_group'] = group
            unit['calibration_records'] = ext_deepcopy(old_unit['calibration_records'])
        for destination in set(moves.values()):
            adapter.sm.update_entity('room', destination, {'storage_units': rooms[destination]['storage_units']}, id_field='room_id')
        for obj in adapter._all('object_item'):
            move = targets.get(obj.get('stock_group'))
            if move and obj.get('current_room_id') == move[0] and (obj.get('storage_unit_id') == move[1]) and (obj.get('handling_state') == 'stored') and (not obj.get('held_by_robot_id')):
                adapter.sm.update_entity('object_item', obj['object_id'], {'current_room_id': move[2], 'storage_unit_id': move[3]}, id_field='object_id')
        moved_tasks = {}
        for task in adapter._all('service_task'):
            target = moves.get(task.get('stock_group'))
            position = task.get('experience_episode_id', '')
            if target and position in {f'T{i:02}' for i in range(9, 17)}:
                adapter.sm.update_entity('service_task', task['task_id'], {'source_room_id': target}, id_field='task_id')
                moved_tasks[task['task_id']] = target
        for step in adapter._all('task_step'):
            if step['task_id'] in moved_tasks and step['step_type'] in {'navigate', 'pick'}:
                adapter.sm.update_entity('task_step', step['step_id'], {'room_id': moved_tasks[step['task_id']]}, id_field='step_id')
        adapter.sm.update_entity('facility', facility['facility_id'], {'stock_relocation_version': 'robot-stock-relocation-evolution-v9'}, id_field='facility_id')

    def _open_storage(self, arguments):
        result = self._robot_rule_successor_open_storage(arguments)
        data = result.get('data', {})
        if result.get('status') == 'success' and data.get('matches_pending_stock_group'):
            order = self._task_order(self._first_pending_work_order() or '')
            group = (order or {}).get('stock_group')
            prior = self.verified_stock_groups.get(group)
            robot = self.adapter._robot()
            room = self.adapter._room(robot['current_room_id'])
            if prior and (prior['station'] != room['name'] or prior['storage_handle'] != arguments['storage_handle']):
                del self.verified_stock_groups[group]
                self.authorized_new_stock_group = group
                self.provisional_stock_groups[group] = {'task_id': self.current_task_id, 'station': room['name'], 'storage_handle': arguments['storage_handle'], 'zone': self._room_zone(room['room_id'])}
                data['binding_retention_status'] = 'provisional_until_work_order_closed'
        return result

    def snapshot(self):
        value = self._robot_route_runtime_snapshot()
        if not self._restoring_source:
            value['source_relocation_contract'] = {'case_version': 'robot-stock-relocation-evolution-v9', 'design_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/design.json').read_bytes()).hexdigest()}
        return value

    def restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        expected = {'case_version': 'robot-stock-relocation-evolution-v9', 'design_sha256': mod_hashlib.sha256((CASE_DIR / 'data/assets/design.json').read_bytes()).hexdigest()}
        if value.pop('source_relocation_contract', None) != expected:
            raise ValueError('Robot source relocation identity differs')
        self._restoring_source = True
        try:
            self._robot_route_runtime_restore(value)
        finally:
            self._restoring_source = False
        if self.snapshot() != snapshot:
            raise ValueError('Robot source relocation snapshot did not round trip')

    def _locate_order_zone(self, arguments):
        before = self.authorized_new_stock_group
        try:
            response = self._robot_rule_successor_locate_order_zone(arguments)
        except Exception:
            self.authorized_new_stock_group = before
            raise
        if response.get('status') != 'success':
            self.authorized_new_stock_group = before
        return response

    def dispatch(self, tool, arguments):
        if tool == 'observe_self' and arguments == {}:
            result = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, tool, arguments)
            self._annotate_zone_response(tool, result)
            return self._attach_call_budget(result)
        if tool == 'read_work_order' and isinstance(arguments, dict) and (set(arguments) == {'work_order'}) and isinstance(arguments['work_order'], str) and (arguments['work_order'] in self._own_closeouts):
            return self._attach_call_budget({'status': 'success', 'data': {'work_order': arguments['work_order'], 'confirmation_only': True, 'completion_receipt': ext_deepcopy(self._own_closeouts[arguments['work_order']])}, 'message': 'Previously committed closeout from this episode.'})
        result = self._robot_rule_successor_dispatch_2(tool, arguments)
        if result.get('status') == 'success' and tool in {'finalize', 'execute_transfer_attempt'}:
            receipt = result
            if tool == 'execute_transfer_attempt':
                receipt = next((r['result'] for r in result.get('data', {}).get('steps', []) if r['tool'] == 'finalize'), None)
            if receipt is not None and receipt.get('status') == 'success':
                self._own_closeouts[arguments['work_order']] = ext_deepcopy(receipt)
        return result

    def _prepare_episode(self, task_id):
        return fn_prepare_episode(CASE_DIR / 'data/world', self.state_dir, task_id)

    def _revalidation_error(self, tool, context):
        return None

    def _listed_orders(self):
        if self.current_task_id is None:
            return []
        return list(fn_public_task(self.current_task_id)['work_orders'])

    def business_call_limit(self):
        return DATA_BUSINESS_CALL_LIMITS.get(self.current_task_id, 36)

    @staticmethod
    def _valid_retained_arguments(arguments):
        required = {'work_order', 'source_station', 'storage_handle', 'source_exit_handles'}
        if set(arguments) != required:
            return False
        if not all((isinstance(arguments[key], str) for key in ('work_order', 'source_station', 'storage_handle'))):
            return False
        return all((isinstance(arguments[key], list) and len(arguments[key]) <= 16 and all((isinstance(handle, str) for handle in arguments[key])) for key in ('source_exit_handles',)))

    def _attach_call_budget(self, result):
        value = ext_deepcopy(result)
        value['business_call_budget'] = {'used': self.business_call_count, 'limit': self.business_call_limit(), 'remaining': max(0, self.business_call_limit() - self.business_call_count)}
        return value

    def _first_pending_work_order(self):
        if self.adapter is None:
            return None
        completed = {row['work_order']: bool(row['workflow_completed']) for row in self.adapter.grade()['orders']}
        return next((work_order for work_order in self._listed_orders() if not completed.get(work_order, False)), None)

    def _room_zone(self, room_id):
        return fn__zone_for_room_id(room_id)

    def _station_zone(self, station_name):
        if self.adapter is None or not isinstance(station_name, str):
            return None
        room = next((row for row in self.adapter._all('room') if row.get('name') == station_name), None)
        return self._room_zone((room or {}).get('room_id'))

    def _zone_counts(self):
        if self.adapter is None:
            return {}
        counts = {zone: 0 for zone in DATA_ZONE_ADJACENCY}
        for room in self.adapter._all('room'):
            zone = self._room_zone(room.get('room_id'))
            if zone in counts and room.get('is_robot_accessible') is True:
                counts[zone] += 1
        return counts

    def _annotate_zone_response(self, tool, result):
        if result.get('status') != 'success' or self.adapter is None:
            return
        data = result.get('data') or {}
        if tool == 'observe_self':
            room = data.get('current_room') or {}
            room['zone'] = self._station_zone(room.get('name'))
            return
        if tool == 'scan_current_room':
            robot = self.adapter._robot() or {}
            room_id = robot.get('current_room_id')
            room = data.get('room') or {}
            room['zone'] = self._room_zone(room_id)
            for exit_row in data.get('exits', []):
                edge_id = self.adapter._edge_by_handle.get(exit_row.get('exit_handle'))
                edge = self.adapter._get('map_edge', 'edge_id', edge_id)
                destination_id = self.adapter._edge_destination(edge or {}, room_id)
                exit_row['destination_zone'] = self._room_zone(destination_id)
            pending = self._task_order(self._first_pending_work_order() or '')
            object_name = (pending or {}).get('object_name')
            data['objects'] = [row for row in data.get('objects', []) if row.get('display_name') == object_name]
            return
        if tool == 'traverse_known_exit':
            for key in ('previous_room', 'current_room'):
                room = data.get(key)
                if isinstance(room, dict):
                    room['zone'] = self._station_zone(room.get('name'))
            for segment in data.get('segments', []):
                segment_data = segment.get('data') or {}
                for key in ('previous_room', 'current_room'):
                    room = segment_data.get(key)
                    if isinstance(room, dict):
                        room['zone'] = self._station_zone(room.get('name'))

    @staticmethod
    def _visible_object_handles(value):
        handles: set[str] = set()
        if isinstance(value, dict):
            handle = value.get('object_handle')
            if isinstance(handle, str):
                handles.add(handle)
            for child in value.values():
                handles.update(RobotSourceScopeRuntime._visible_object_handles(child))
        elif isinstance(value, list):
            for child in value:
                handles.update(RobotSourceScopeRuntime._visible_object_handles(child))
        return handles

    def _revoke_hidden_object_handles(self, before, result):
        if self.adapter is None:
            return
        newly_issued = set(self.adapter.issued_object_handles) - before
        visible = self._visible_object_handles(result.get('data') or {})
        self.adapter.issued_object_handles.difference_update(newly_issued - visible)

    def _promote_completed_binding(self, work_order):
        if self.adapter is None:
            return
        order = self._task_order(work_order)
        if order is None:
            return
        completed = next((bool(row.get('workflow_completed')) for row in self.adapter.grade().get('orders', []) if row.get('work_order') == work_order), False)
        stock_group = order.get('stock_group')
        if completed and isinstance(stock_group, str):
            evidence = self.provisional_stock_groups.pop(stock_group, None)
            if evidence is not None:
                self.verified_stock_groups.setdefault(stock_group, evidence)

    @staticmethod
    def _valid_execute_arguments(arguments):
        required = {'work_order', 'object_handle', 'profile', 'delivery_exit_handles', 'closeout_exit_handles'}
        if set(arguments) != required:
            return False
        if not all((isinstance(arguments[key], str) for key in ('work_order', 'object_handle', 'profile'))):
            return False
        if arguments['profile'] not in fn__profiles():
            return False
        for key in ('delivery_exit_handles', 'closeout_exit_handles'):
            value = arguments[key]
            if not isinstance(value, list) or len(value) > 16 or any((not isinstance(row, str) for row in value)):
                return False
        return True

    def _execute_transfer_attempt(self, arguments):
        if not self._valid_execute_arguments(arguments):
            return {'status': 'error', 'data': {}, 'message': 'INVALID_ARGUMENTS: arguments do not match the tool schema'}
        work_order = arguments['work_order']
        reference = {'work_order': work_order}
        steps: list[dict[str, ext_Any]] = []
        robot = self.adapter._robot() if self.adapter is not None else None
        order = self.adapter._order(work_order) if self.adapter is not None else None
        if robot is None or order is None:
            return {'status': 'error', 'data': {'steps': steps}, 'message': 'WORK_ORDER_UNAVAILABLE: the requested work order is unavailable'}
        if robot.get('active_task_id') is None:
            assigned = self._robot_rule_successor_dispatch('assign_work_order', reference)
            steps.append({'tool': 'assign_work_order', 'result': assigned})
            if assigned.get('status') != 'success':
                return {'status': 'error', 'data': {'steps': steps}, 'message': assigned.get('message')}
        elif robot.get('active_task_id') != order['task_id']:
            return {'status': 'error', 'data': {'steps': steps}, 'message': 'ROBOT_BUSY: another work order is active'}
        prepared = self._robot_rule_successor_dispatch('prepare_transfer', {**reference, 'profile': arguments['profile']})
        steps.append({'tool': 'prepare_transfer', 'result': prepared})
        if prepared.get('status') != 'success':
            return {'status': 'error', 'data': {'steps': steps}, 'message': prepared.get('message')}
        robot = self.adapter._robot()
        if not robot.get('payload_object_id'):
            picked = self._robot_rule_successor_dispatch('pickup', {**reference, 'object_handle': arguments['object_handle']})
            steps.append({'tool': 'pickup', 'result': picked})
            if picked.get('status') != 'success':
                return {'status': 'error', 'data': {'steps': steps}, 'message': picked.get('message')}
        delivery_handles = arguments['delivery_exit_handles']
        if delivery_handles:
            moved = self._robot_rule_successor_dispatch('traverse_known_exit', {'exit_handles': delivery_handles})
            steps.append({'tool': 'traverse_known_exit', 'result': moved})
            if moved.get('status') != 'success':
                return {'status': 'error', 'data': {'steps': steps}, 'message': moved.get('message')}
        released = self._robot_rule_successor_dispatch('release', reference)
        steps.append({'tool': 'release', 'result': released})
        if released.get('status') != 'success':
            recovery = None
            if delivery_handles:
                recovery = self._robot_rule_successor_dispatch('traverse_known_exit', {'exit_handles': list(reversed(delivery_handles))})
                steps.append({'tool': 'return_to_source', 'result': recovery})
            message = str(released.get('message'))
            if 'EXACT_STALE_TUPLE_REQUIRED' in message:
                outcome = 'exact_stale_tuple_required'
            elif 'INTAKE_REJECTED' in message:
                outcome = 'intake_rejected'
            else:
                outcome = 'release_rejected'
            return {'status': 'error', 'data': {'outcome': outcome, 'returned_to_source': bool(recovery is None or recovery.get('status') == 'success'), 'steps': steps}, 'message': released.get('message')}
        closeout_handles = arguments['closeout_exit_handles']
        if closeout_handles:
            returned = self._robot_rule_successor_dispatch('traverse_known_exit', {'exit_handles': closeout_handles})
            steps.append({'tool': 'traverse_known_exit', 'result': returned})
            if returned.get('status') != 'success':
                return {'status': 'error', 'data': {'outcome': 'delivered_not_closed', 'steps': steps}, 'message': returned.get('message')}
        finalized = self._robot_rule_successor_dispatch('finalize', reference)
        steps.append({'tool': 'finalize', 'result': finalized})
        if finalized.get('status') != 'success':
            return {'status': 'error', 'data': {'outcome': 'delivered_not_closed', 'steps': steps}, 'message': finalized.get('message')}
        self._promote_completed_binding(work_order)
        return {'status': 'success', 'data': {'outcome': 'workflow_completed', 'work_order': work_order, 'steps': steps}, 'message': 'OK'}

    def grade(self):
        raw = self._robot_rule_successor_grade()
        completed = sum((bool(row['workflow_completed']) for row in raw['orders']))
        result = ext_deepcopy(raw)
        result['diagnostic_partial_score'] = raw['score']
        result['score'] = 25.0 * completed
        result['score_contract'] = '25 points per fully closed work order'
        result['partial_milestones'] = 'diagnostic_only'
        return result

    def _priority_error(self, tool, arguments):
        if tool not in DATA_ORDERED_MUTATIONS or self.adapter is None:
            return None
        if not self.adapter._schema_valid(tool, arguments):
            return None
        work_order = arguments.get('work_order')
        listed = self._listed_orders()
        if work_order not in listed:
            return None
        completed = {row['work_order']: bool(row['workflow_completed']) for row in self.adapter.grade()['orders']}
        requested_index = listed.index(work_order)
        pending = next((prior for prior in listed[:requested_index] if not completed.get(prior, False)), None)
        if pending is None:
            return None
        return self.adapter._attempt(tool, lambda : {'status': 'error', 'data': {}, 'message': f'PRIORITY_WORK_ORDER_PENDING: an earlier listed work order must be fully closed first ({pending})'})

    def _release_context(self, arguments):
        if self.adapter is None or not isinstance(arguments.get('work_order'), str):
            return None
        order = self.adapter._order(arguments['work_order'])
        if order is None:
            return None
        (task, obj) = self.adapter._work_context(order)
        if task is None or obj is None:
            return None
        handling = obj.get('handling_code')
        intake = task.get('intake_code')
        profile = task.get('transfer_profile_submitted')
        if not all((isinstance(value, str) for value in (handling, intake, profile))):
            return None
        storage_handle = None
        if isinstance(obj.get('storage_unit_id'), str):
            storage_handle = self.adapter._handle('storage', obj['storage_unit_id'])
        return {'task_id': self.current_task_id, 'work_order': arguments['work_order'], 'cell': f'{handling}:{intake}', 'handling_code': handling, 'intake_code': intake, 'profile': profile, 'stock_group': task.get('stock_group'), 'source_station': self.adapter._room_name(task.get('source_room_id')), 'destination_station': self.adapter._room_name(task.get('target_room_id')), 'storage_handle': storage_handle, 'object_name': obj.get('display_name')}

    def _record_release(self, context, result):
        if context is None:
            return
        cell = context['cell']
        state = self.rule_revalidation.get(cell)
        if state == 'awaiting_exact_stale' and result.get('status') == 'error' and ('INTAKE_REJECTED' in str(result.get('message'))) and (context['profile'] == (self.transfer_evidence.get(cell) or {}).get('profile')):
            self.rule_revalidation[cell] = 'awaiting_replacement'
            return
        if result.get('status') != 'success':
            return
        self.transfer_evidence[cell] = ext_deepcopy(context)
        if state in {'awaiting_exact_stale', 'awaiting_replacement'}:
            self.rule_revalidation[cell] = 'validated'

    @contextmanager
    def isolated_raw(self):
        with ext_isolated_package_namespace(CASE_DIR / 'data/world/private/world/environment'):
            yield

    def checkpoint(self):
        if self.adapter is None:
            raise RuntimeError('activate a task before checkpointing')
        with self.isolated_raw():
            return ext_deepcopy(fn_checkpoint_state(self.adapter, self.state_dir))

    def raw_database(self):
        return ext_deepcopy(self.snapshot()['database'])

    def close(self):
        if self._temporary is not None:
            self._temporary.cleanup()
            self._temporary = None

    def _robot_local_rule_runtime_stage_retained_source(self, arguments):
        result = self._robot_rule_successor_stage_retained_source(arguments)
        order = self._task_order(arguments.get('work_order', ''))
        return fn_scoped_storage_diagnostics(result, (order or {}).get('object_name'))

    def _robot_source_runtime_validate_restored_evidence_against_world(self):
        if self.current_task_id is None or int(self.current_task_id[1:]) < 9:
            return self._robot_rule_successor_validate_restored_evidence_against_world()
        fields = ('verified_stock_groups', 'transfer_evidence', 'rule_revalidation', 'provisional_stock_groups')
        original = {name: getattr(self, name) for name in fields}
        adapter = self.adapter
        moved = fn_destinations()
        old_source = {key for (key, row) in original['verified_stock_groups'].items() if key in moved and row['task_id'] < 'T09'}
        old_transfer = {key for (key, row) in original['transfer_evidence'].items() if row.get('stock_group') in moved and row['task_id'] < 'T09'}
        try:
            for historical in (False, True):
                self.verified_stock_groups = {key: row for (key, row) in original['verified_stock_groups'].items() if (key in old_source) == historical}
                self.transfer_evidence = {key: row for (key, row) in original['transfer_evidence'].items() if (key in old_transfer) == historical}
                self.rule_revalidation = {key: row for (key, row) in original['rule_revalidation'].items() if key in self.transfer_evidence}
                self.provisional_stock_groups = {} if historical else original['provisional_stock_groups']
                self.adapter = HistoricalStorageView(adapter) if historical else adapter
                self._robot_rule_successor_validate_restored_evidence_against_world()
        finally:
            self.adapter = adapter
            for (name, value) in original.items():
                setattr(self, name, value)

    def _robot_route_runtime_init(self, *args, **kwargs):
        self._restoring_route = False
        self._robot_intake_runtime_init(*args, **kwargs)

    def _robot_route_runtime_activate_task(self, task_id):
        receipt = self._robot_intake_runtime_activate_task(task_id)
        if int(task_id[1:]) >= DATA_CONTRACT['before_task']:
            with self.isolated_raw():
                edge = next((row for row in self.adapter._all('map_edge') if row['edge_id'] == 'edge-atlas-north-ground-south-specimen-intake-to-level-one-central-return-sort'))
                if edge['status'] != 'blocked':
                    self.adapter.sm.update_entity('map_edge', 'edge-atlas-north-ground-south-specimen-intake-to-level-one-central-return-sort', {'status': 'blocked'}, id_field='edge_id')
        return receipt

    def _robot_rule_successor_open_storage(self, arguments):
        if self.adapter is None:
            raise RuntimeError('activate a task before calling tools')
        handle = arguments.get('storage_handle')
        if not isinstance(handle, str):
            return self._robot_rule_successor_dispatch('open_storage', arguments)
        pending = self._task_order(self._first_pending_work_order() or '')
        target_group = (pending or {}).get('stock_group')
        resolved = self.adapter._storage(handle)
        actual_group = resolved[1].get('stock_group') if resolved else None
        authorized = actual_group in self.verified_stock_groups or (actual_group is not None and actual_group == self.authorized_new_stock_group)
        if actual_group == target_group and (not authorized):
            return self.adapter._attempt('open_storage', lambda : {'status': 'error', 'data': {}, 'message': 'SEARCH_SCOPE_NOT_AUTHORIZED: call locate_order_zone for the first pending listed order'})
        issued_before = set(self.adapter.issued_object_handles)
        result = self._robot_rule_successor_dispatch('open_storage', arguments)
        if result.get('status') != 'success':
            self._revoke_hidden_object_handles(issued_before, result)
            return result
        data = result.get('data') or {}
        if actual_group != target_group:
            data.pop('stock_group', None)
            data.pop('calibration_records', None)
            data['objects'] = []
            data['matches_pending_stock_group'] = False
            data['scope'] = 'current_priority_order'
            self._revoke_hidden_object_handles(issued_before, result)
            return result
        object_name = (pending or {}).get('object_name')
        data['objects'] = [row for row in data.get('objects', []) if row.get('display_name') == object_name]
        data['matches_pending_stock_group'] = True
        data['scope'] = 'current_priority_order'
        data['binding_retention_status'] = 'retained_verified' if actual_group in self.verified_stock_groups else 'provisional_until_work_order_closed'
        robot = self.adapter._robot() or {}
        room = self.adapter._room(robot.get('current_room_id')) or {}
        if isinstance(actual_group, str):
            evidence = {'task_id': str(self.current_task_id), 'station': str(room.get('name')), 'storage_handle': handle, 'zone': str(self._room_zone(room.get('room_id')))}
            if actual_group in self.verified_stock_groups:
                self.verified_stock_groups.setdefault(actual_group, evidence)
            else:
                self.provisional_stock_groups.setdefault(actual_group, evidence)
        self._revoke_hidden_object_handles(issued_before, result)
        return result

    def _robot_route_runtime_snapshot(self):
        value = self._robot_intake_runtime_snapshot()
        if not self._restoring_route:
            value['route_migration_contract'] = ext_deepcopy(DATA_CONTRACT)
        return value

    def _robot_route_runtime_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        if value.pop('route_migration_contract', None) != DATA_CONTRACT:
            raise ValueError('Robot route migration identity differs')
        self._restoring_route = True
        try:
            self._robot_intake_runtime_restore(value)
        finally:
            self._restoring_route = False
        if self.snapshot() != snapshot:
            raise ValueError('Robot route migration snapshot did not round trip')

    def _robot_rule_successor_locate_order_zone(self, arguments):
        spec = self._task_order(arguments.get('work_order', ''))
        if spec is not None and spec['stock_group'] not in self.verified_stock_groups:
            self.authorized_new_stock_group = None
        result = self._robot_rule_successor_locate_order_zone_2(arguments)
        if result.get('status') == 'success':
            data = result.get('data') or {}
            data.pop('new_stock_binding_limit', None)
        return result

    def _robot_rule_successor_dispatch(self, tool, arguments):
        if self.adapter is None:
            raise RuntimeError('activate a task before calling tools')
        values = ext_deepcopy(arguments)
        with self.isolated_raw():
            priority = self._priority_error(tool, values)
            if priority is not None:
                return ext_deepcopy(priority)
            context = self._release_context(values) if tool == 'release' else None
            revalidation = self._revalidation_error(tool, context)
            if revalidation is not None:
                return ext_deepcopy(revalidation)
            result = ext_deepcopy(self.adapter.call(tool, values))
            if tool == 'release':
                self._record_release(context, result)
            return result

    def _robot_rule_successor_dispatch_2(self, tool, arguments):
        if self.adapter is None:
            raise RuntimeError('activate a task before calling tools')
        self.business_call_count += 1
        if self.business_call_count > self.business_call_limit():
            return self._attach_call_budget({'status': 'error', 'data': {}, 'message': 'BUSINESS_CALL_LIMIT_EXHAUSTED: no further business calls are available in this episode'})
        values = ext_deepcopy(arguments)
        if tool == 'stage_retained_source':
            result = self._stage_retained_source(values)
        elif tool == 'locate_order_zone':
            result = self._locate_order_zone(values)
        elif tool == 'execute_transfer_attempt':
            result = self._execute_transfer_attempt(values)
        elif tool == 'open_storage':
            result = self._open_storage(values)
        else:
            issued_before = set(self.adapter.issued_object_handles) if tool == 'scan_current_room' else set()
            result = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, tool, values)
            self._annotate_zone_response(tool, result)
            if tool == 'scan_current_room':
                self._revoke_hidden_object_handles(issued_before, result)
            if tool == 'finalize' and result.get('status') == 'success':
                work_order = values.get('work_order')
                if isinstance(work_order, str):
                    self._promote_completed_binding(work_order)
        self.visible_object_handles.update(self._visible_object_handles(result))
        return self._attach_call_budget(result)

    def _robot_rule_successor_grade(self):
        if self.adapter is None:
            raise RuntimeError('activate a task before grading')
        with self.isolated_raw():
            return ext_deepcopy(self.adapter.grade())

    def _robot_rule_successor_stage_retained_source(self, arguments):
        if not self._valid_retained_arguments(arguments):
            return {'status': 'error', 'data': {}, 'message': 'INVALID_ARGUMENTS: arguments do not match the tool schema'}
        spec = self._task_order(arguments['work_order'])
        evidence = self.verified_stock_groups.get((spec or {}).get('stock_group'))
        if spec is None or evidence is None or evidence.get('station') != arguments['source_station'] or (evidence.get('storage_handle') != arguments['storage_handle']):
            return {'status': 'error', 'data': {'outcome': 'retained_binding_mismatch'}, 'message': 'RETAINED_BINDING_MISMATCH: exact verified source evidence is required'}
        source_handles = arguments['source_exit_handles']
        if source_handles:
            moved = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, 'traverse_known_exit', {'exit_handles': source_handles})
            if moved.get('status') != 'success':
                return {'status': 'error', 'data': {'outcome': 'source_route_stale', 'steps': [moved]}, 'message': moved.get('message')}
        robot = self.adapter._robot()
        room = self.adapter._room(robot.get('current_room_id')) if robot else None
        if (room or {}).get('name') != arguments['source_station']:
            return {'status': 'error', 'data': {'outcome': 'source_route_mismatch'}, 'message': 'SOURCE_ROUTE_MISMATCH: route did not reach retained station'}
        issued_before = set(self.adapter.issued_object_handles)
        opened = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, 'open_storage', {'storage_handle': arguments['storage_handle']})
        objects = (opened.get('data') or {}).get('objects') or []
        matches = [row for row in objects if row.get('display_name') == spec['object_name']]
        if opened.get('status') != 'success' or len(matches) != 1:
            self._revoke_hidden_object_handles(issued_before, {'data': {'objects': matches}})
            return {'status': 'error', 'data': {'outcome': 'retained_source_unavailable', 'steps': [opened]}, 'message': opened.get('message') or 'retained source object unavailable'}
        object_row = matches[0]
        self._revoke_hidden_object_handles(issued_before, {'data': {'objects': matches}})
        inspected = RobotSourceScopeRuntime._robot_rule_successor_dispatch(self, 'inspect_local_object', {'object_handle': object_row['object_handle']})
        if inspected.get('status') != 'success':
            return {'status': 'error', 'data': {'outcome': 'retained_object_unavailable', 'steps': [opened, inspected]}, 'message': inspected.get('message')}
        return {'status': 'success', 'data': {'outcome': 'retained_source_staged', 'retained_source': fn_public_retained_source_evidence(evidence), 'object': ext_deepcopy(object_row), 'inspection': ext_deepcopy(inspected.get('data') or {}), 'battery_percent': self.adapter._battery()}, 'message': 'OK'}

    def _robot_rule_successor_validate_restored_evidence_against_world(runtime):
        try:
            RobotSourceScopeRuntime._robot_rule_successor_validate_restored_evidence_against_world_2(runtime)
        except ValueError as error:
            if str(error) != 'Robot v8 snapshot contains object handles absent from public evidence':
                raise
            current = DATA_TASK_IDS.index(runtime.current_task_id)
            objects = {row.get('object_id') for row in runtime.adapter._all('object_item')}
            ids = {row.get('object_id') for row in runtime.adapter._all('service_task') if row.get('experience_episode_id') in DATA_TASK_IDS[:current + 1]}
            allowed = {runtime.adapter._handle('object', ident) for ident in ids & objects if isinstance(ident, str)}
            visible = set(runtime.visible_object_handles)
            if visible != set(runtime.adapter.issued_object_handles) or not visible <= allowed:
                raise

    def _robot_intake_runtime_init(self, *args, **kwargs):
        self._own_closeouts = {}
        self._restoring_evolution = False
        self._robot_rule_successor_init(*args, **kwargs)

    def _robot_intake_runtime_activate_task(self, task_id):
        old = self.current_task_id
        result = self._robot_rule_successor_activate_task(task_id)
        if old != self.current_task_id:
            self._own_closeouts = {}
        return result

    def _robot_intake_runtime_snapshot(self):
        value = self._robot_rule_successor_snapshot()
        if not self._restoring_evolution:
            value['evolution_contract'] = {'case_version': 'robot-scope-reuse-evolution-v12', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'config_sha256': mod_hashlib.sha256((CASE_DIR / 'data/world/private/config.json').read_bytes()).hexdigest()}
            value['own_closeout_receipts'] = ext_deepcopy(self._own_closeouts)
        return value

    def _robot_intake_runtime_restore(self, snapshot):
        value = ext_deepcopy(snapshot)
        expected = {'case_version': 'robot-scope-reuse-evolution-v12', 'schedule': DATA_SCHEDULE_2, 'config_sha256': mod_hashlib.sha256((CASE_DIR / 'data/world/private/config.json').read_bytes()).hexdigest()}
        if value.pop('evolution_contract', None) != expected:
            raise ValueError('Robot intake-balanced contract differs')
        receipts = value.pop('own_closeout_receipts')
        self._restoring_evolution = True
        try:
            self._robot_rule_successor_restore(value)
        finally:
            self._restoring_evolution = False
        self._own_closeouts = receipts
        if self.snapshot() != snapshot:
            raise ValueError('Robot intake-balanced snapshot did not round trip')

    def _robot_rule_successor_locate_order_zone_2(self, arguments):
        if set(arguments) != {'work_order'} or not isinstance(arguments.get('work_order'), str):
            return {'status': 'error', 'data': {}, 'message': 'INVALID_ARGUMENTS: arguments do not match the tool schema'}
        work_order = arguments['work_order']
        pending = self._first_pending_work_order()
        if work_order != pending:
            return {'status': 'error', 'data': {'first_pending_work_order': pending}, 'message': 'PRIORITY_WORK_ORDER_PENDING: zone lookup is limited to the first pending listed work order'}
        spec = self._task_order(work_order)
        if spec is None:
            return {'status': 'error', 'data': {}, 'message': 'WORK_ORDER_NOT_FOUND: the work-order reference is unknown'}
        stock_group = spec['stock_group']
        retained = stock_group in self.verified_stock_groups
        if not retained:
            if self.authorized_new_stock_group is None:
                self.authorized_new_stock_group = stock_group
            elif self.authorized_new_stock_group != stock_group:
                return {'status': 'error', 'data': {'new_stock_bindings_authorized': 1, 'new_stock_binding_limit': 1}, 'message': 'NEW_STOCK_BINDING_LIMIT: this episode already authorized one previously unseen stock binding'}
        return {'status': 'success', 'data': {'work_order': work_order, 'source_zone': self._room_zone(spec['source']), 'destination_zone': self._room_zone(spec['target']), 'zone_adjacency': ext_deepcopy(DATA_ZONE_ADJACENCY), 'candidate_station_counts': self._zone_counts(), 'binding_status': 'retained_verified' if retained else 'new_authorized', 'exact_source_disclosed': False}, 'message': 'OK'}

    def _robot_rule_successor_validate_restored_evidence_against_world_2(self):
        if self.adapter is None or self.current_task_id is None:
            raise ValueError('Robot v8 restore did not create an active world')
        current_index = DATA_TASK_IDS.index(self.current_task_id)

        def task_is_in_prefix(task_id):
            return isinstance(task_id, str) and task_id in DATA_TASK_IDS and (DATA_TASK_IDS.index(task_id) <= current_index)
        rooms = {row.get('room_id'): row for row in self.adapter._all('room')}
        objects = {row.get('object_id'): row for row in self.adapter._all('object_item')}
        service_tasks = self.adapter._all('service_task')

        def storage_matches(stock_group, evidence):
            resolved = self.adapter._storage(evidence['storage_handle'])
            if resolved is None:
                return False
            (room, storage) = resolved
            return bool(storage.get('stock_group') == stock_group and room.get('name') == evidence['station'] and (self._room_zone(room.get('room_id')) == evidence['zone']))
        for (stock_group, evidence) in self.verified_stock_groups.items():
            if not task_is_in_prefix(evidence['task_id']):
                raise ValueError('Robot v8 verified stock evidence is from the future')
            if not storage_matches(stock_group, evidence):
                raise ValueError('Robot v8 verified stock evidence does not match storage')
            completed = any((row.get('experience_episode_id') == evidence['task_id'] and row.get('stock_group') == stock_group and (row.get('status') == 'completed') and ((row.get('source_inspection_receipt') or {}).get('status') == 'verified') and ((rooms.get(row.get('source_room_id')) or {}).get('name') == evidence['station']) for row in service_tasks))
            if not completed:
                raise ValueError('Robot v8 verified stock evidence lacks a completed work order')
        pending_order = self._task_order(self._first_pending_work_order() or '')
        for (stock_group, evidence) in self.provisional_stock_groups.items():
            if evidence['task_id'] != self.current_task_id:
                raise ValueError('Robot v8 provisional stock evidence crossed tasks')
            if stock_group != self.authorized_new_stock_group:
                raise ValueError('Robot v8 provisional stock evidence lacks matching authorization')
            if (pending_order or {}).get('stock_group') != stock_group:
                raise ValueError('Robot v8 provisional stock evidence is not the current target')
            if not storage_matches(stock_group, evidence):
                raise ValueError('Robot v8 provisional stock evidence does not match storage')
        current_groups = {row['stock_group'] for row in fn_episode_spec_5(self.current_task_id)['orders']}
        if self.authorized_new_stock_group is not None and self.authorized_new_stock_group not in current_groups:
            raise ValueError('Robot v8 stock authorization is outside the current task')
        config = fn_load_config_2()
        rule_epoch = str(self.adapter.snapshot().get('rule_epoch'))
        rule_table = config['pre_rule_table'] if rule_epoch == config['drift']['from_rule_epoch'] else config['post_rule_table']
        for (cell, evidence) in self.transfer_evidence.items():
            if not task_is_in_prefix(evidence.get('task_id')):
                raise ValueError('Robot v8 transfer evidence is from the future')
            order_spec = next((row for row in fn_episode_spec_5(evidence['task_id'])['orders'] if row.get('work_order') == evidence.get('work_order')), None)
            task = next((row for row in service_tasks if row.get('task_id') == (order_spec or {}).get('task_id')), None)
            obj = objects.get((task or {}).get('object_id'))
            source = rooms.get((task or {}).get('source_room_id'))
            destination = rooms.get((task or {}).get('target_room_id'))
            intake_receipt = (task or {}).get('intake_receipt') or {}
            inspection = (task or {}).get('source_inspection_receipt') or {}
            storage_ok = storage_matches(evidence.get('stock_group', ''), {'station': str(evidence.get('source_station')), 'storage_handle': str(evidence.get('storage_handle')), 'zone': str(self._room_zone((source or {}).get('room_id'))), 'task_id': str(evidence.get('task_id'))})
            if not (task is not None and obj is not None and (order_spec is not None) and (task.get('experience_episode_id') == evidence.get('task_id')) and (task.get('stock_group') == evidence.get('stock_group')) and (task.get('intake_code') == evidence.get('intake_code')) and (source is not None) and (source.get('name') == evidence.get('source_station')) and (destination is not None) and (destination.get('name') == evidence.get('destination_station')) and (obj.get('display_name') == evidence.get('object_name')) and (inspection.get('status') == 'verified') and (inspection.get('handling_code') == evidence.get('handling_code')) and (intake_receipt.get('status') == 'accepted') and (intake_receipt.get('profile') == evidence.get('profile')) and storage_ok):
                raise ValueError(f'Robot v8 transfer evidence does not match business state for {cell}')
        action_reasons = {str(row.get('reason')) for row in self.adapter.snapshot().get('action_ledger', [])}
        for (cell, state) in self.rule_revalidation.items():
            evidence = self.transfer_evidence[cell]
            evidence_task = evidence['task_id']
            (handling, intake) = cell.split(':', 1)
            if current_index < DATA_TASK_IDS.index('T09'):
                raise ValueError('Robot v8 revalidation state appeared before drift')
            if state in {'awaiting_exact_stale', 'awaiting_replacement'}:
                if not (evidence_task < 'T09' and handling in DATA_CHANGED_HANDLING_ATOMS and (config['pre_rule_table'][cell] == evidence['profile'])):
                    raise ValueError('Robot v8 stale revalidation evidence is invalid')
                if state == 'awaiting_replacement' and 'INTAKE_REJECTED' not in action_reasons:
                    raise ValueError('Robot v8 replacement state lacks a stale rejection')
            elif state == 'validated':
                if not (evidence_task >= 'T09' and rule_table[cell] == evidence['profile']):
                    raise ValueError('Robot v8 validated revalidation state is invalid')
        allowed_object_ids = set()
        for row in service_tasks:
            episode_id = row.get('experience_episode_id')
            if not task_is_in_prefix(episode_id):
                continue
            if row.get('status') == 'completed' or (row.get('source_inspection_receipt') or {}).get('status') == 'verified':
                allowed_object_ids.add(row.get('object_id'))
        robot = self.adapter._robot() or {}
        if isinstance(robot.get('payload_object_id'), str):
            allowed_object_ids.add(robot['payload_object_id'])
        if pending_order is not None:
            allowed_object_ids.add(pending_order['object_id'])
        allowed_handles = {self.adapter._handle('object', object_id) for object_id in allowed_object_ids if isinstance(object_id, str)}
        issued_handles = set(self.adapter.issued_object_handles)
        if issued_handles != self.visible_object_handles:
            raise ValueError('Robot v8 object capability ledger differs from public visibility')
        hidden_handles = self.visible_object_handles - allowed_handles
        if hidden_handles:
            raise ValueError('Robot v8 snapshot contains object handles absent from public evidence')

    def _robot_rule_successor_init(self, state_dir=None, *, snapshot=None):
        self._restoring_v8_snapshot = False
        self._robot_rule_successor_init_2(state_dir=state_dir, snapshot=snapshot)

    def _robot_rule_successor_activate_task(self, task_id):
        receipt = self._robot_rule_successor_activate_task_2(task_id)
        if receipt.get('already_prepared') is True:
            return receipt
        with self.isolated_raw():
            self.adapter._set_battery(170)
            after = fn_semantic_state(self.adapter.sm)
        receipt = ext_deepcopy(receipt)
        recovery = receipt.get('supervisor_recovery') or {}
        if isinstance(recovery.get('after'), dict):
            recovery['after']['battery_percent'] = 170
        for change in receipt.get('changes', []):
            if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict):
                change['after'] = next((row for row in after['robot_unit'] if row['robot_id'] == change['id']))
        receipt['after_sha256'] = fn_digest_2(after)
        if isinstance(receipt.get('public_notice'), str):
            receipt['public_notice'] = mod_re.sub('with \\d+ battery units', f'with {170} battery units', receipt['public_notice'])
        receipt['successor_budget_override'] = {'task_id': task_id, 'battery_units': 170, 'business_call_limit': self.business_call_limit(), 'basis': 'one physical allowance independent of stream position and rule epoch'}
        return receipt

    def _robot_rule_successor_snapshot(self):
        value = self._robot_rule_successor_snapshot_2()
        if self._restoring_v8_snapshot:
            return value
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v9'
        return value

    def _robot_rule_successor_restore(self, snapshot):
        if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v9':
            raise ValueError('unsupported Robot rule v9 snapshot')
        value = ext_deepcopy(snapshot)
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v8'
        self._restoring_v8_snapshot = True
        try:
            self._robot_rule_successor_restore_2(value)
        finally:
            self._restoring_v8_snapshot = False
        if self.snapshot() != snapshot:
            raise ValueError('Robot rule v9 snapshot did not round trip')

    def _robot_rule_successor_init_2(self, state_dir=None, *, snapshot=None):
        self.business_call_count = 0
        self.authorized_new_stock_group: str | None = None
        self.provisional_stock_groups: dict[str, dict[str, str]] = {}
        self.verified_stock_groups: dict[str, dict[str, str]] = {}
        self.visible_object_handles: set[str] = set()
        self._restoring_v7_snapshot = False
        self._robot_rule_successor_init_3(state_dir=state_dir, snapshot=snapshot)

    def _robot_rule_successor_activate_task_2(self, task_id):
        receipt = self._robot_rule_successor_activate_task_3(task_id)
        if receipt.get('already_prepared') is not True:
            budget = DATA_EPISODE_BUDGETS[task_id]
            with self.isolated_raw():
                self.adapter._set_battery(budget)
            receipt = ext_deepcopy(receipt)
            recovery = receipt.get('supervisor_recovery') or {}
            if isinstance(recovery.get('after'), dict):
                recovery['after']['battery_percent'] = budget
            for change in receipt.get('changes', []):
                if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict):
                    change['after']['battery_percent'] = budget
            notice = receipt.get('public_notice')
            if isinstance(notice, str):
                receipt['public_notice'] = mod_re.sub('with \\d+ battery units', f'with {budget} battery units', notice)
            receipt['successor_budget_override'] = {'task_id': task_id, 'battery_units': budget, 'business_call_limit': self.business_call_limit(), 'basis': 'uniform post-cold physical envelope with public call frontier'}
        return receipt

    def _robot_rule_successor_snapshot_2(self):
        value = self._robot_rule_successor_snapshot_3()
        if self._restoring_v7_snapshot:
            return value
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v8'
        value['business_call_count'] = self.business_call_count
        value['authorized_new_stock_group'] = self.authorized_new_stock_group
        value['provisional_stock_groups'] = ext_deepcopy(self.provisional_stock_groups)
        value['verified_stock_groups'] = ext_deepcopy(self.verified_stock_groups)
        value['visible_object_handles'] = sorted(self.visible_object_handles)
        return value

    def _robot_rule_successor_restore_2(self, snapshot):
        if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v8':
            raise ValueError('unsupported Robot rule v8 snapshot')
        fn__validate_snapshot_extensions(snapshot)
        value = ext_deepcopy(snapshot)
        self.business_call_count = value.pop('business_call_count')
        self.authorized_new_stock_group = value.pop('authorized_new_stock_group')
        self.provisional_stock_groups = value.pop('provisional_stock_groups')
        self.verified_stock_groups = value.pop('verified_stock_groups')
        self.visible_object_handles = set(value.pop('visible_object_handles'))
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v7'
        self._restoring_v7_snapshot = True
        try:
            self._robot_rule_successor_restore_3(value)
        finally:
            self._restoring_v7_snapshot = False
        self._validate_restored_evidence_against_world()
        if self.snapshot() != snapshot:
            raise ValueError('Robot rule v8 snapshot did not round trip')

    def _robot_rule_successor_init_3(self, state_dir=None, *, snapshot=None):
        self._restoring_v6_snapshot = False
        self._robot_rule_successor_init_4(state_dir=state_dir, snapshot=snapshot)

    def _robot_rule_successor_activate_task_3(self, task_id):
        receipt = self._robot_rule_successor_activate_task_4(task_id)
        if receipt.get('already_prepared') is not True:
            self.business_call_count = 0
            self.authorized_new_stock_group = None
            self.provisional_stock_groups = {}
            budget = DATA_EPISODE_BUDGETS_2[task_id]
            with self.isolated_raw():
                self.adapter._set_battery(budget)
            receipt = ext_deepcopy(receipt)
            recovery = receipt.get('supervisor_recovery') or {}
            if isinstance(recovery.get('after'), dict):
                recovery['after']['battery_percent'] = budget
            for change in receipt.get('changes', []):
                if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict):
                    change['after']['battery_percent'] = budget
            notice = receipt.get('public_notice')
            if isinstance(notice, str):
                receipt['public_notice'] = mod_re.sub('with \\d+ battery units', f'with {budget} battery units', notice)
            receipt['successor_budget_override'] = {'task_id': task_id, 'battery_units': budget, 'business_call_limit': 32, 'new_stock_binding_limit': 1, 'basis': 'full informed replay plus worst-order bounded zone search'}
        return receipt

    def _robot_rule_successor_snapshot_3(self):
        value = self._robot_rule_successor_snapshot_4()
        if self._restoring_v6_snapshot:
            return value
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v7'
        return value

    def _robot_rule_successor_restore_3(self, snapshot):
        if not isinstance(snapshot, dict) or snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v7':
            raise ValueError('unsupported Robot rule v7 snapshot')
        fn__validate_snapshot_extensions_2(snapshot)
        value = ext_deepcopy(snapshot)
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v6'
        self._restoring_v6_snapshot = True
        try:
            self._robot_rule_successor_restore_4(value)
        finally:
            self._restoring_v6_snapshot = False
        if self.snapshot() != snapshot:
            raise ValueError('Robot rule v7 snapshot did not round trip')

    def _robot_rule_successor_init_4(self, state_dir=None, *, snapshot=None):
        self.transfer_evidence: dict[str, dict[str, ext_Any]] = {}
        self.rule_revalidation: dict[str, str] = {}
        self._restoring_parent_snapshot = False
        self._robot_rule_successor_init_5(state_dir=state_dir, snapshot=snapshot)

    def _robot_rule_successor_activate_task_4(self, task_id):
        receipt = self._robot_rule_successor_activate_task_5(task_id)
        if task_id != 'T01' or receipt.get('already_prepared') is True:
            return receipt
        with self.isolated_raw():
            self.adapter._set_battery(72)
        receipt = ext_deepcopy(receipt)
        recovery = receipt.get('supervisor_recovery') or {}
        if isinstance(recovery.get('after'), dict):
            recovery['after']['battery_percent'] = 72
        for change in receipt.get('changes', []):
            if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict):
                change['after']['battery_percent'] = 72
        notice = receipt.get('public_notice')
        if isinstance(notice, str):
            receipt['public_notice'] = notice.replace(f'with {93} battery units', f'with {72} battery units')
        receipt['successor_budget_override'] = {'task_id': 'T01', 'battery_units': 72, 'basis': 'provider-free cold cap plus honest weighted cost intervals'}
        return receipt

    def _robot_rule_successor_snapshot_4(self):
        value = self._robot_rule_successor_snapshot_5()
        if self._restoring_parent_snapshot:
            return value
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v6'
        value['transfer_evidence'] = ext_deepcopy(self.transfer_evidence)
        value['rule_revalidation'] = ext_deepcopy(self.rule_revalidation)
        return value

    def _robot_rule_successor_restore_4(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v6':
            raise ValueError('unsupported Robot rule v6 snapshot')
        value = ext_deepcopy(snapshot)
        self.transfer_evidence = ext_deepcopy(value.pop('transfer_evidence', {}))
        self.rule_revalidation = ext_deepcopy(value.pop('rule_revalidation', {}))
        value['schema'] = 'rescopebench-robot-rule-runtime-snapshot/v4'
        self._restoring_parent_snapshot = True
        try:
            self._robot_rule_successor_restore_5(value)
        finally:
            self._restoring_parent_snapshot = False

    def _robot_rule_successor_init_5(self, state_dir=None, *, snapshot=None):
        self._temporary = None
        if state_dir is None:
            self._temporary = mod_tempfile.TemporaryDirectory(prefix='robot-rule-v4-')
            state_dir = ext_Path(self._temporary.name) / 'state'
        self.state_dir = ext_Path(state_dir).resolve()
        self.current_task_id: str | None = None
        self.adapter = None
        if snapshot is not None:
            self.restore(snapshot)

    def _robot_rule_successor_activate_task_5(self, task_id):
        receipt = self._robot_rule_successor_activate_task_6(task_id)
        if task_id == 'T09':
            for (cell, evidence) in self.transfer_evidence.items():
                handling = cell.split(':', 1)[0]
                if handling in DATA_CHANGED_HANDLING_ATOMS and evidence.get('task_id', 'T99') < 'T09':
                    self.rule_revalidation.setdefault(cell, 'awaiting_exact_stale')
        return receipt

    def _robot_rule_successor_snapshot_5(self):
        if self.adapter is None or self.current_task_id is None:
            raise RuntimeError('activate a task before snapshotting')
        with self.isolated_raw():
            fn_checkpoint_state(self.adapter, self.state_dir)
            adapter_state = ext_deepcopy(self.adapter.snapshot())
        database = {path.name: mod_json.loads(path.read_text(encoding='utf-8')) for path in sorted((self.state_dir / 'database').glob('*.json'))}
        return {'schema': 'rescopebench-robot-rule-runtime-snapshot/v4', 'task_id': self.current_task_id, 'database': database, 'adapter': adapter_state}

    def _robot_rule_successor_restore_5(self, snapshot):
        if snapshot.get('schema') != 'rescopebench-robot-rule-runtime-snapshot/v4':
            raise ValueError('unsupported Robot rule successor snapshot')
        task_id = snapshot.get('task_id')
        if task_id not in DATA_TASK_IDS or not isinstance(snapshot.get('database'), dict):
            raise ValueError('invalid Robot rule successor snapshot')
        if self.state_dir.exists():
            mod_shutil.rmtree(self.state_dir)
        database_dir = self.state_dir / 'database'
        database_dir.mkdir(parents=True)
        for (name, value) in snapshot['database'].items():
            if ext_Path(name).name != name or not name.endswith('.json'):
                raise ValueError('snapshot database contains an invalid file name')
            (database_dir / name).write_text(mod_json.dumps(value, ensure_ascii=True, indent=2, sort_keys=True) + '\n', encoding='utf-8')
        adapter_state = ext_deepcopy(snapshot.get('adapter') or {})
        ledger = adapter_state.get('observation_ledger')
        if not isinstance(ledger, dict):
            raise ValueError('snapshot is missing its observation ledger')
        (self.state_dir / 'observation-ledger.json').write_text(mod_json.dumps(ledger, ensure_ascii=True, indent=2, sort_keys=True) + '\n', encoding='utf-8')
        with self.isolated_raw():
            self.adapter = fn_restore_adapter(CASE_DIR / 'data/world', self.state_dir, task_id)
            self.adapter._actions = ext_deepcopy(adapter_state.get('action_ledger', []))
            self.adapter._next_action_index = 1 + max((int(row.get('index', 0)) for row in self.adapter._actions), default=0)
            metering = adapter_state.get('episode_metering') or {}
            self.adapter._scanned_rooms_this_episode = set(metering.get('scanned_room_ids', []))
            self.adapter._accessed_storage_this_episode = set(metering.get('accessed_storage_handles', []))
        self.current_task_id = task_id
        if self.snapshot() != snapshot:
            raise ValueError('Robot rule successor snapshot did not round trip')

    def _robot_rule_successor_activate_task_6(self, task_id):
        receipt = self._robot_rule_successor_activate_task_7(task_id)
        if task_id != 'T01' or receipt.get('already_prepared') is True:
            return receipt
        with self.isolated_raw():
            self.adapter._set_battery(93)
        receipt = ext_deepcopy(receipt)
        recovery = receipt.get('supervisor_recovery') or {}
        if isinstance(recovery.get('after'), dict):
            recovery['after']['battery_percent'] = 93
        for change in receipt.get('changes', []):
            if change.get('table') == 'robot_unit' and isinstance(change.get('after'), dict):
                change['after']['battery_percent'] = 93
        notice = receipt.get('public_notice')
        if isinstance(notice, str):
            receipt['public_notice'] = notice.replace('with 98 battery units', f'with {93} battery units')
        receipt['successor_budget_override'] = {'task_id': 'T01', 'battery_units': 93, 'basis': 'deterministic action-cost frontier'}
        return receipt

    def _robot_rule_successor_activate_task_7(self, task_id):
        if task_id not in DATA_TASK_IDS:
            raise ValueError(f'unknown Robot stream task: {task_id}')
        with self.isolated_raw():
            if self.adapter is not None and self.current_task_id != task_id:
                fn_checkpoint_state(self.adapter, self.state_dir)
            (self.adapter, receipt) = self._prepare_episode(task_id)
        self.current_task_id = task_id
        return ext_deepcopy(receipt)

class HistoricalStorageView:

    def __init__(self, adapter):
        self.adapter = adapter
        source = CASE_DIR / 'data/assets/rooms.json'
        self.units = {unit['unit_id']: unit for room in mod_json.loads(source.read_text()) for unit in room.get('storage_units', [])}

    def __getattr__(self, name):
        return getattr(self.adapter, name)

    def _storage(self, handle):
        found = self.adapter._storage(handle)
        if found is None:
            return None
        (room, unit) = found
        historical = self.units.get(unit['unit_id'])
        return (room, {**unit, 'stock_group': historical['stock_group']}) if historical else found

class RobotExperienceStreamAdapter:

    def __init__(self, *args, **kwargs):
        self._robot_experience_stream_adapter_init(*args, **kwargs)
        self.tools = ext_deepcopy(DATA_TOOLS_3)

    def traverse_known_exit(self, exit_handle=None, exit_handles=None):
        if exit_handles is None:
            return self._robot_state_action_adapter_traverse_known_exit(exit_handle)
        segments = []
        total_cost = 0
        for (index, handle) in enumerate(exit_handles, 1):
            result = self._robot_state_action_adapter_traverse_known_exit(handle)
            data = ext_deepcopy(result.get('data') or {})
            total_cost += int(data.get('battery_cost') or 0)
            segments.append({'index': index, 'exit_handle': handle, 'status': result.get('status'), 'message': result.get('message'), 'data': data})
            if result.get('status') != 'success':
                return fn__error(fn__code(result), 'known-route execution stopped at the first failed edge', {'requested_segments': len(exit_handles), 'completed_segments': index - 1, 'stopped_at_index': index, 'segments': segments, 'battery_percent': self._battery(), 'battery_cost': total_cost})
        return fn__success({'requested_segments': len(exit_handles), 'completed_segments': len(exit_handles), 'stopped_at_index': None, 'segments': segments, 'battery_percent': self._battery(), 'battery_cost': total_cost})

    def call(self, name, arguments):
        if name != 'traverse_known_exit':
            return self._robot_experience_adapter_call(name, arguments)
        try:
            mod_jsonschema.validate(arguments, DATA__TRAVERSE_PARAMETERS)
        except mod_jsonschema.ValidationError:
            return self._finish(name, fn__error('INVALID_ARGUMENTS', 'arguments do not match the tool schema'))
        has_single = 'exit_handle' in arguments
        has_batch = 'exit_handles' in arguments
        if has_single == has_batch:
            return self._finish(name, fn__error('INVALID_ARGUMENTS', 'provide exactly one of exit_handle or exit_handles'))
        return self.traverse_known_exit(**ext_deepcopy(arguments))

    def snapshot(self):
        state = self._robot_experience_stream_adapter_snapshot()
        state['schema'] = 'robot-experience-stream-snapshot/v4'
        return state

    def _scan_observation(self):
        robot = self._robot()
        room = self._room((robot or {}).get('current_room_id'))
        if not robot or not room:
            return fn__error('CURRENT_ROOM_NOT_FOUND', 'the controlled robot has no valid current room')
        room_id = room['room_id']
        exits = []
        for edge in sorted(self._all('map_edge'), key=lambda row: row.get('edge_id', '')):
            destination = self._edge_destination(edge, room_id)
            if not destination:
                continue
            handle = self._handle('exit', edge['edge_id'])
            self.issued_exit_handles.add(handle)
            exits.append({'exit_handle': handle, 'route_type': edge.get('route_type'), 'distance_m': edge.get('distance_m'), 'status': 'open' if self._edge_usable(edge, destination) else 'blocked'})
        units = []
        for unit in sorted(room.get('storage_units', []), key=lambda row: row['unit_id']):
            handle = self._handle('storage', unit['unit_id'])
            self.issued_storage_handles.add(handle)
            units.append({'storage_handle': handle, 'display_name': unit.get('display_name') or f'Storage-{handle[-8:].upper()}', 'access_state': 'open' if unit.get('opened') else 'closed'})
        objects = []
        for obj in sorted(self._all('object_item'), key=lambda row: row.get('object_id', '')):
            if not self._object_visible_in_room(obj, room_id):
                continue
            handle = self._handle('object', obj['object_id'])
            self.issued_object_handles.add(handle)
            objects.append({'object_handle': handle, 'display_name': obj.get('display_name'), 'handling_state': obj.get('handling_state'), 'actionable': self._active_handle(handle)})
        peers = []
        for peer in sorted(self._all('robot_unit'), key=lambda row: row.get('robot_id', '')):
            if peer.get('robot_id') == self.robot_id or peer.get('current_room_id') != room_id:
                continue
            robot_handle = self._handle('robot', peer['robot_id'])
            self.issued_robot_handles.add(robot_handle)
            peers.append({'robot_handle': robot_handle, 'display_name': peer.get('display_name'), 'operational_status': peer.get('operational_status')})
        obstacles = [{'obstacle_type': row.get('obstacle_type'), 'severity': row.get('severity')} for row in sorted(self._all('obstacle'), key=lambda item: item.get('obstacle_id', '')) if row.get('room_id') == room_id and row.get('status') == 'active']
        condition = self._condition(room_id)
        return fn__success({'room': {'name': room.get('name')}, 'room_state': {'access_state': (condition or {}).get('access_state'), 'occupancy': (condition or {}).get('occupancy')}, 'peers': peers, 'storage_units': units, 'objects': objects, 'active_obstacles': obstacles, 'exits': exits})

    def scan_current_room(self):
        robot = self._robot()
        room_id = (robot or {}).get('current_room_id')
        if not isinstance(room_id, str):
            return self._finish('scan_current_room', self._scan_observation())
        if room_id in self._scanned_rooms_this_episode:
            result = self._scan_observation()
            result.setdefault('data', {}).update({'battery_percent': self._battery(), 'battery_cost': 0})
            return self._finish('scan_current_room', result)
        result = self._attempt('scan_current_room', self._scan_observation)
        if result.get('status') == 'success':
            self._scanned_rooms_this_episode.add(room_id)
        return result

    def open_storage(self, storage_handle):
        if not isinstance(storage_handle, str) or storage_handle not in self.issued_storage_handles:
            return self._finish('open_storage', fn__error('STORAGE_NOT_OBSERVED', 'scan the local room before accessing a storage unit'))
        resolved = self._storage(storage_handle)
        robot = self._robot()
        if resolved is None or not robot or resolved[0].get('room_id') != robot.get('current_room_id'):
            return self._finish('open_storage', fn__error('STORAGE_NOT_LOCAL', 'the storage unit is not in the current room'))

        def access():
            current = self._storage(storage_handle)
            if current is None:
                return fn__error('STORAGE_NOT_FOUND', 'the storage unit is unavailable')
            (current_room, current_unit) = current
            if current_unit.get('opened') is not True:
                current_unit['opened'] = True
                current_room['storage_units'] = [current_unit if row.get('unit_id') == current_unit['unit_id'] else row for row in current_room.get('storage_units', [])]
                self._save('room', current_room)
            return fn__success(self._storage_view(current_room, current_unit))
        if storage_handle in self._accessed_storage_this_episode:
            result = access()
            result.setdefault('data', {}).update({'battery_percent': self._battery(), 'battery_cost': 0})
            return self._finish('open_storage', result)
        result = self._attempt('open_storage', access)
        if result.get('status') == 'success':
            self._accessed_storage_this_episode.add(storage_handle)
        return result

    def read_work_order(self, work_order):
        result = self._robot_experience_stream_adapter_read_work_order(work_order)
        if result.get('status') == 'success':
            result.get('data', {}).pop('policy_version', None)
        return result

    def public_snapshot(self):
        """Return a minimal learner-safe projection of current runtime state.

    This is intentionally not a reload format. In particular, it exposes
    episode-local metering counts rather than private room IDs or a cache that
    a later adapter could silently restore.
    """
        robot = self._robot() or {}
        room = self._room(robot.get('current_room_id'))
        active_work_order = next((work_order for (work_order, order) in self._orders.items() if order['task_id'] == robot.get('active_task_id')), None)
        return {'schema': 'robot-experience-stream-public-snapshot/v1', 'robot': {'operational_status': robot.get('operational_status'), 'battery_percent': int(robot.get('battery_percent') or 0), 'current_room_name': (room or {}).get('name'), 'active_work_order': active_work_order, 'carrying_payload': robot.get('payload_object_id') is not None}, 'work_orders': sorted(self._orders), 'episode_metering': {'rooms_scanned': len(self._scanned_rooms_this_episode), 'storage_units_accessed': len(self._accessed_storage_this_episode), 'cache_scope': 'current_adapter_instance'}, 'actions': ext_deepcopy(self._actions)}

    def _active_handle(self, object_handle):
        return isinstance(object_handle, str) and self._object_by_handle.get(object_handle) in self.active_object_ids

    def _storage_view(self, room, unit):
        result = self._robot_experience_adapter_storage_view(room, unit)
        for row in result['objects']:
            row['actionable'] = self._active_handle(row['object_handle'])
        return result

    def inspect_local_object(self, object_handle):
        if not self._active_handle(object_handle):
            return self._finish('inspect_local_object', fn__error('OBJECT_NOT_IN_ACTIVE_EPISODE', 'the parcel is visible but its private attributes are not actionable now'))
        return self._robot_experience_adapter_inspect_local_object(object_handle)

    def pickup(self, work_order, object_handle):
        if not self._active_handle(object_handle):
            return self._finish('pickup', fn__error('OBJECT_NOT_IN_ACTIVE_EPISODE', 'the parcel is visible but cannot be moved in this episode'))
        return self._robot_experience_adapter_pickup(work_order, object_handle)

    def import_observation_ledger(self, ledger):
        """Restore learned handles without allowing memory to mutate physical state."""
        if not isinstance(ledger, dict):
            raise ValueError('observation ledger must be an object')
        opened = ledger.get('opened_storage_handles', [])
        if not isinstance(opened, list) or not all((isinstance(value, str) for value in opened)):
            raise ValueError('opened_storage_handles must be a list of strings')
        physically_open = {handle for handle in self._storage_by_handle if (resolved := self._storage(handle)) is not None and resolved[1].get('opened') is True}
        sanitized = ext_deepcopy(ledger)
        sanitized['opened_storage_handles'] = sorted(set(opened) & physically_open)
        counts = self._robot_experience_adapter_import_observation_ledger(sanitized)
        counts['stale_opened_storage_handles_rejected'] = len(set(opened) - physically_open)
        return counts

    def grade(self):
        result = self._robot_experience_adapter_grade()
        result['public_components'] = {f"{row['work_order']}:{name}": {'correct': int(row[name]), 'total': 1} for row in result['orders'] for name in ('source_verified', 'transfer_authorized', 'custody_obtained', 'physical_delivery', 'workflow_completed')}
        return result

    def _storage(self, storage_handle):
        binding = self._storage_by_handle.get(storage_handle)
        if binding is None:
            return None
        room = self._room(binding[0])
        if not room:
            return None
        unit = next((row for row in room.get('storage_units', []) if row.get('unit_id') == binding[1]), None)
        return (room, unit) if unit else None

    def _storage_for_object(self, obj):
        unit_id = obj.get('storage_unit_id')
        if not unit_id:
            return None
        for room in self._all('room'):
            unit = next((row for row in room.get('storage_units', []) if row.get('unit_id') == unit_id), None)
            if unit:
                return (room, unit)
        return None

    def _object_visible_in_room(self, obj, room_id):
        if obj.get('held_by_robot_id') or obj.get('current_room_id') != room_id:
            return False
        storage = self._storage_for_object(obj)
        if storage is None:
            return True
        (storage_room, unit) = storage
        return storage_room.get('room_id') != room_id or unit.get('opened') is True

    @staticmethod
    def _source_inspection_valid(order, task, obj):
        receipt = task.get('source_inspection_receipt') or {}
        return bool(receipt.get('status') == 'verified' and receipt.get('object_id') == order.get('object_id') == obj.get('object_id') and (receipt.get('source_room_id') == task.get('source_room_id')) and (receipt.get('handling_code') == obj.get('handling_code')) and (receipt.get('stock_group') == task.get('stock_group') == obj.get('stock_group')))

    def _source_storage_open(self, task, obj):
        unit_id = obj.get('storage_unit_id')
        if not unit_id:
            return True
        room = self._room(task.get('source_room_id'))
        unit = next((row for row in (room or {}).get('storage_units', []) if row.get('unit_id') == unit_id), None)
        return bool(unit and unit.get('opened') is True)

    def assign_work_order(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('assign_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'unknown work order'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not obj or (not actor):
                return fn__error('WORK_ORDER_UNAVAILABLE', 'incomplete work-order records')
            if task.get('status') != 'queued' or task.get('assigned_robot_id') or self._active_assignments(task_id=task['task_id']):
                return fn__error('WORK_ORDER_NOT_QUEUED', 'work order is not queued')
            if actor.get('operational_status') != 'available' or actor.get('active_task_id') or actor.get('payload_object_id') or self._active_assignments(robot_id=self.robot_id):
                return fn__error('ROBOT_NOT_AVAILABLE', 'the robot is occupied')
            if actor.get('facility_id') != task.get('facility_id'):
                return fn__error('FACILITY_MISMATCH', 'robot and work order are in different facilities')
            if obj.get('requires_gripper') and 'grasp' not in actor.get('capabilities', []):
                return fn__error('CAPABILITY_MISMATCH', 'required actuator is unavailable')
            now = fn__timestamp()
            task.update(status='assigned', assigned_robot_id=self.robot_id, updated_at=now)
            actor.update(operational_status='busy', active_task_id=task['task_id'], updated_at=now)
            domain = mod_importlib.import_module('mcp_servers.robot_domain')
            domain._make_assignment(self.sm, task, actor, note='Metered delivery assignment.')
            self._save('service_task', task)
            self._save('robot_unit', actor)
            return fn__success({'work_order': work_order, 'status': 'assigned'})
        return self._attempt('assign_work_order', mutate)

    def prepare_transfer(self, work_order, profile):
        order = self._order(work_order)
        if not order:
            return self._finish('prepare_transfer', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        if profile not in DATA_TRANSFER_PROFILES:
            return self._finish('prepare_transfer', fn__error('INVALID_ARGUMENTS', 'the transfer profile is not declared'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not obj or (not actor):
                return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete')
            if task.get('status') not in {'assigned', 'in_progress'}:
                return fn__error('WORK_ORDER_NOT_CONFIGURABLE', 'the work order is not active')
            if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1 or actor.get('active_task_id') != task['task_id']:
                return fn__error('ASSIGNMENT_REQUIRED', 'the work order is not actively assigned')
            if not self._source_inspection_valid(order, task, obj):
                return fn__error('LOCAL_INSPECTION_REQUIRED', 'inspect the target parcel before configuration')
            at_source = actor.get('current_room_id') == task.get('source_room_id')
            unheld_local = obj.get('current_room_id') == actor.get('current_room_id') and (not obj.get('held_by_robot_id'))
            held_by_actor = actor.get('payload_object_id') == obj['object_id'] and obj.get('held_by_robot_id') == self.robot_id
            if not at_source or not (unheld_local or held_by_actor):
                return fn__error('SOURCE_CONFIGURATION_REQUIRED', 'configure this parcel at its opened source storage location')
            if not self._source_storage_open(task, obj):
                return fn__error('SOURCE_STORAGE_CLOSED', "open the parcel's local source storage before configuration")
            now = fn__timestamp()
            task.update(transfer_profile_submitted=profile, transfer_policy_version=task['policy_version'], transfer_object_id=obj['object_id'], transfer_authorized=False, intake_receipt=None, updated_at=now)
            self._save('service_task', task)
            return fn__success({'work_order': work_order, 'transfer_state': 'configured_unverified'})
        return self._attempt('prepare_transfer', mutate)

    def _configured_profile_valid(self, task, obj):
        key = f"{obj.get('handling_code')}:{task.get('intake_code')}"
        return task.get('policy_version') == 'PV-18' and task.get('transfer_policy_version') == task.get('policy_version') and (task.get('transfer_object_id') == obj.get('object_id')) and (task.get('transfer_profile_submitted') == self.rule_table.get(key))

    def release(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('release', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        (task, obj) = self._work_context(order)
        actor = self._robot()
        if not task or not obj or (not actor) or (actor.get('current_room_id') != order['destination_room_id']) or (actor.get('payload_object_id') != obj.get('object_id')) or (obj.get('held_by_robot_id') != self.robot_id):
            return self._robot_state_action_adapter_release(work_order)
        if task.get('transfer_profile_submitted') not in DATA_TRANSFER_PROFILES or task.get('transfer_policy_version') != task.get('policy_version') or task.get('transfer_object_id') != obj.get('object_id'):
            return self._attempt('release', lambda : fn__error('TRANSFER_NOT_CONFIGURED', 'destination intake requires a current parcel-bound configuration'))
        if not self._configured_profile_valid(task, obj):
            return self._attempt('release', lambda : fn__error('INTAKE_REJECTED', 'destination intake did not accept the configured transfer'))
        result = self._robot_state_action_adapter_release(work_order)
        if result.get('status') == 'success':
            task = self._get('service_task', 'task_id', order['task_id'])
            if task:
                task.update(transfer_authorized=True, intake_receipt={'status': 'accepted', 'object_id': obj['object_id'], 'policy_version': task['policy_version'], 'profile': task['transfer_profile_submitted'], 'destination_room_id': order['destination_room_id'], 'accepted_at': fn__timestamp()}, updated_at=fn__timestamp())
                self._save('service_task', task)
            result.setdefault('data', {})['intake_state'] = 'accepted'
        return result

    def finalize(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('finalize', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        (task, obj) = self._work_context(order)
        actor = self._robot()
        receipt = (task or {}).get('intake_receipt') or {}
        if not task or not obj or task.get('transfer_authorized') is not True or (receipt.get('status') != 'accepted') or (receipt.get('object_id') != obj.get('object_id')) or (receipt.get('policy_version') != task.get('policy_version')) or (receipt.get('destination_room_id') != order['destination_room_id']):
            return self._attempt('finalize', lambda : fn__error('INTAKE_RECEIPT_REQUIRED', "closure requires this parcel's current accepted intake receipt"))
        if not actor or actor.get('current_room_id') != self.home_room_id:
            return self._attempt('finalize', lambda : fn__error('SERVICE_HUB_REQUIRED', 'return to the service hub before closing the work order'))
        return self._robot_state_action_adapter_finalize(work_order)

    def export_observation_ledger(self):
        ledger = self._robot_state_action_adapter_export_observation_ledger()
        ledger['storage_handles'] = sorted(self.issued_storage_handles)
        ledger['opened_storage_handles'] = sorted((handle for handle in self._storage_by_handle if (resolved := self._storage(handle)) is not None and resolved[1].get('opened') is True))
        ledger['inspected_target_object_ids'] = sorted(self._inspected_target_ids)
        return ledger

    def _schema_valid(self, name, arguments):
        if name not in DATA__TOOL_BY_NAME or not isinstance(arguments, dict):
            return False
        schema = DATA__TOOL_BY_NAME[name]
        properties = schema.get('properties', {})
        if set(arguments) - set(properties) or any((key not in arguments for key in schema.get('required', []))):
            return False
        for (key, value) in arguments.items():
            spec = properties[key]
            if spec.get('type') == 'string' and (not isinstance(value, str)):
                return False
            if spec.get('type') == 'array' and (not isinstance(value, list) or not all((isinstance(item, str) for item in value))):
                return False
            if 'enum' in spec and value not in spec['enum']:
                return False
        return True

    def _handle(self, kind, internal_id):
        token = mod_hashlib.sha256(f'{self.handle_seed}:{kind}:{internal_id}'.encode('utf-8')).hexdigest()[:16]
        return f'{kind}-{token}'

    def _all(self, entity):
        return self.sm.list_entities(entity)

    def _get(self, entity, id_field, entity_id):
        if not entity_id:
            return None
        return self.sm.get_entity(entity, entity_id, id_field=id_field)

    def _save(self, entity, row):
        return self.sm.replace_entity(entity, row)

    def _refresh_plan_handles(self):
        self._plan_by_handle = {self._handle('plan', row['plan_id']): row['plan_id'] for row in self._all('navigation_plan')}

    def _finish(self, tool, result, battery_cost=0):
        self._actions.append({'index': self._next_action_index, 'tool': tool, 'status': result.get('status'), 'battery_cost': battery_cost, 'reason': fn__code(result)})
        self._next_action_index += 1
        if len(self._actions) > 256:
            self._actions = self._actions[-256:]
        return result

    def _robot(self):
        return self._get('robot_unit', 'robot_id', self.robot_id)

    def _room(self, room_id):
        return self._get('room', 'room_id', room_id)

    def _room_name(self, room_id):
        room = self._room(room_id)
        return room.get('name') if room else None

    def _robot_name(self, robot_id):
        robot = self._get('robot_unit', 'robot_id', robot_id)
        return robot.get('display_name') if robot else None

    def _order(self, work_order):
        return self._orders.get(work_order) if isinstance(work_order, str) else None

    def _task_steps(self, task_id):
        return sorted((row for row in self._all('task_step') if row.get('task_id') == task_id), key=lambda row: (row.get('step_order', 0), row.get('step_id', '')))

    def _active_assignments(self, task_id=None, robot_id=None):
        rows = []
        for row in self._all('task_assignment'):
            if row.get('status') != 'active':
                continue
            if task_id is not None and row.get('task_id') != task_id:
                continue
            if robot_id is not None and row.get('robot_id') != robot_id:
                continue
            rows.append(row)
        return rows

    def _condition(self, room_id):
        return next((row for row in self._all('room_condition') if row.get('room_id') == room_id), None)

    def _room_open(self, room_id):
        room = self._room(room_id)
        condition = self._condition(room_id) if room_id else None
        return bool(room and room.get('is_robot_accessible') and (not condition or condition.get('access_state') != 'closed'))

    def _edge_destination(self, edge, room_id):
        if edge.get('from_room_id') == room_id:
            return edge.get('to_room_id')
        if edge.get('is_bidirectional') and edge.get('to_room_id') == room_id:
            return edge.get('from_room_id')
        return None

    def _active_edge_blockers(self, edge_id):
        return [row for row in self._all('obstacle') if row.get('status') == 'active' and edge_id in (row.get('affects_edge_ids') or [])]

    def _edge_usable(self, edge, destination_id):
        return bool(edge.get('status') == 'open' and (not self._active_edge_blockers(edge['edge_id'])) and self._room_open(destination_id))

    def _capture_state(self):
        if hasattr(self.sm, 'get_full_state'):
            return ext_deepcopy(self.sm.get_full_state())
        return {entity: ext_deepcopy(self._all(entity)) for entity in DATA__ID_FIELDS}

    def _restore_state(self, state):
        if hasattr(self.sm, 'database') and isinstance(self.sm.database, dict):
            self.sm.database = ext_deepcopy(state)
            return
        for (entity, rows) in state.items():
            id_field = DATA__ID_FIELDS.get(entity)
            if not id_field:
                continue
            if hasattr(self.sm, 'delete_entity'):
                desired = {row.get(id_field) for row in rows}
                for current in self._all(entity):
                    entity_id = current.get(id_field)
                    if entity_id not in desired:
                        self.sm.delete_entity(entity, entity_id, id_field=id_field)
            for row in rows:
                self._save(entity, ext_deepcopy(row))

    def _battery(self):
        robot = self._robot()
        return int((robot or {}).get('battery_percent') or 0)

    def _set_battery(self, value):
        self.sm.update_entity('robot_unit', self.robot_id, {'battery_percent': value}, id_field='robot_id')

    def _attempt(self, tool, mutation):
        starting_battery = self._battery()
        if starting_battery < 1:
            return self._finish(tool, fn__error('INSUFFICIENT_BATTERY', 'the controlled robot cannot pay the one-unit attempt cost', {'battery_percent': starting_battery, 'battery_cost': 0}), 0)
        before = self._capture_state()
        try:
            result = mutation()
        except Exception:
            self._restore_state(before)
            raise
        if result.get('status') != 'success':
            self._restore_state(before)
        self._set_battery(starting_battery - 1)
        result.setdefault('data', {})
        result['data'].update({'battery_percent': starting_battery - 1, 'battery_cost': 1})
        self._refresh_plan_handles()
        return self._finish(tool, result, 1)

    def _work_context(self, order):
        task = self._get('service_task', 'task_id', order['task_id'])
        obj = self._get('object_item', 'object_id', order['object_id'])
        return (task, obj)

    def _required_destination(self, task, obj):
        pick_done = any((row.get('step_type') == 'pick' and row.get('status') == 'completed' for row in self._task_steps(task['task_id'])))
        if obj and (obj.get('held_by_robot_id') or pick_done or obj.get('handling_state') in {'in_transit', 'delivered'}):
            return task.get('target_room_id')
        return task.get('source_room_id')

    def observe_self(self):
        robot = self._robot()
        if not robot:
            return self._finish('observe_self', fn__error('ROBOT_NOT_FOUND', 'the controlled robot is missing'))
        payload = self._get('object_item', 'object_id', robot.get('payload_object_id'))
        payload_view = None
        if payload:
            handle = self._handle('object', payload['object_id'])
            self.issued_object_handles.add(handle)
            payload_view = {'object_handle': handle, 'display_name': payload.get('display_name'), 'handling_state': payload.get('handling_state')}
        active_order = next((ref for (ref, row) in self._orders.items() if row['task_id'] == robot.get('active_task_id')), None)
        return self._finish('observe_self', fn__success({'robot': {'display_name': robot.get('display_name'), 'operational_status': robot.get('operational_status'), 'capabilities': ext_deepcopy(robot.get('capabilities') or []), 'battery_percent': int(robot.get('battery_percent') or 0)}, 'current_room': {'name': self._room_name(robot.get('current_room_id'))}, 'payload': payload_view, 'active_work_order': active_order}))

    def _route_consistent(self, plan):
        route = plan.get('route_room_ids') or []
        if not route or route[0] != plan.get('origin_room_id') or route[-1] != plan.get('destination_room_id'):
            return False
        edges = self._all('map_edge')
        for (left, right) in zip(route, route[1:]):
            if not any((edge.get('from_room_id') == left and edge.get('to_room_id') == right or (edge.get('is_bidirectional') and edge.get('from_room_id') == right and (edge.get('to_room_id') == left)) for edge in edges)):
                return False
        return True

    def _route_currently_usable(self, plan):
        route = plan.get('route_room_ids') or []
        if not self._route_consistent(plan) or not self._room_open(route[0]):
            return False
        edges = self._all('map_edge')
        for (left, right) in zip(route, route[1:]):
            edge = next((row for row in edges if row.get('from_room_id') == left and row.get('to_room_id') == right or (row.get('is_bidirectional') and row.get('from_room_id') == right and (row.get('to_room_id') == left))), None)
            if edge is None or not self._edge_usable(edge, right):
                return False
        return True

    def inspect_plan(self, plan_handle):
        self._refresh_plan_handles()
        if not isinstance(plan_handle, str) or plan_handle not in self.issued_plan_handles or plan_handle not in self._plan_by_handle:
            return self._finish('inspect_plan', fn__error('PLAN_NOT_OBSERVED', 'read the work order before inspecting its plan'))
        plan = self._get('navigation_plan', 'plan_id', self._plan_by_handle[plan_handle])
        if not plan:
            return self._finish('inspect_plan', fn__error('PLAN_UNAVAILABLE', 'the observed plan no longer exists'))
        owner = self._get('robot_unit', 'robot_id', plan.get('robot_id'))
        active_obstacles = {row.get('obstacle_id') for row in self._all('obstacle') if row.get('status') == 'active'}
        blockers = set(plan.get('blocked_by_obstacle_ids') or []) & active_obstacles
        order = next((row for row in self._orders.values() if row['task_id'] == plan.get('task_id')), None)
        task = self._get('service_task', 'task_id', plan.get('task_id'))
        obj = self._get('object_item', 'object_id', (order or {}).get('object_id'))
        required = self._required_destination(task, obj) if task else None
        return self._finish('inspect_plan', fn__success({'plan_handle': plan_handle, 'status': plan.get('status'), 'owner': {'display_name': (owner or {}).get('display_name'), 'operational_status': (owner or {}).get('operational_status')}, 'blocker_count': len(blockers), 'owned_by_controlled_robot': plan.get('robot_id') == self.robot_id, 'origin_is_owner_current_room': bool(owner and plan.get('origin_room_id') == owner.get('current_room_id')), 'destination_matches_unfinished_work': plan.get('destination_room_id') == required, 'route_is_contiguous': self._route_consistent(plan)}))

    def handoff_work_order(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('handoff_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not obj or (not actor):
                return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete')
            source_id = task.get('assigned_robot_id')
            source = self._get('robot_unit', 'robot_id', source_id)
            active = self._active_assignments(task_id=task['task_id'], robot_id=source_id)
            if not source or source_id == self.robot_id or len(active) != 1:
                return fn__error('HANDOFF_SOURCE_INVALID', 'the work order has no coherent peer assignment')
            if actor.get('operational_status') != 'available' or actor.get('active_task_id') or actor.get('payload_object_id'):
                return fn__error('CONTROLLED_ROBOT_NOT_AVAILABLE', "finish the controlled robot's current work before handoff")
            held = obj.get('held_by_robot_id') is not None or source.get('payload_object_id') is not None
            if held and (not (obj.get('held_by_robot_id') == source_id and source.get('payload_object_id') == obj.get('object_id'))):
                return fn__error('CUSTODY_INCOHERENT', 'peer and parcel custody records disagree')
            if held and actor.get('current_room_id') != source.get('current_room_id'):
                return fn__error('HANDOFF_ROOM_MISMATCH', 'held cargo requires both robots in the same room')
            source_status = source.get('operational_status')
            old_steps = self._task_steps(task['task_id'])
            old_plans = [row for row in self._all('navigation_plan') if row.get('task_id') == task['task_id']]
            domain = mod_importlib.import_module('mcp_servers.robot_domain')
            native = domain.execute_task_handoff(self.sm, task_id=task['task_id'], from_robot_id=source_id, to_robot_id=self.robot_id, handoff_room_id=source.get('current_room_id'), handoff_reason='Interrupted work-order recovery.')
            if native.get('status') != 'success':
                return fn__error(fn__code(native), 'handoff was rejected')
            self.sm.update_entity('robot_unit', source_id, {'operational_status': source_status}, id_field='robot_id')
            for row in old_steps:
                self._save('task_step', row)
            for row in old_plans:
                self._save('navigation_plan', row)
            current = self._get('service_task', 'task_id', task['task_id'])
            return fn__success({'work_order': work_order, 'status': (current or {}).get('status'), 'physical_custody_transferred': held, 'former_robot_status': source_status})
        return self._attempt('handoff_work_order', mutate)

    def _validate_supplied_route(self, handles, start, destination):
        rooms = [start]
        distance = 0.0
        current = start
        for handle in handles:
            edge = self._get('map_edge', 'edge_id', self._edge_by_handle[handle])
            nxt = self._edge_destination(edge or {}, current)
            if not edge or not nxt:
                return (None, 0.0, 'ROUTE_NOT_CONTIGUOUS')
            if not self._edge_usable(edge, nxt):
                return (None, 0.0, 'ROUTE_NOT_TRAVERSABLE')
            rooms.append(nxt)
            current = nxt
            distance += float(edge.get('distance_m') or 1)
        if current != destination:
            return (None, 0.0, 'ROUTE_WRONG_DESTINATION')
        return (rooms, distance, None)

    def _new_plan_id(self, task_id):
        existing = {row.get('plan_id') for row in self._all('navigation_plan')}
        ordinal = 1
        while True:
            token = mod_hashlib.sha256(f'{self.handle_seed}:recovery-plan:{task_id}:{ordinal}'.encode('utf-8')).hexdigest()[:16]
            candidate = f'plan-recovery-{token}'
            if candidate not in existing:
                return candidate
            ordinal += 1

    def resolve_work_order(self, work_order, action, route_exit_handles=None):
        order = self._order(work_order)
        if not order:
            return self._finish('resolve_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        if action not in {'retry', 'reroute'} or (route_exit_handles is not None and (not isinstance(route_exit_handles, list) or not all((isinstance(value, str) for value in route_exit_handles)))):
            return self._finish('resolve_work_order', fn__error('INVALID_ARGUMENTS', 'action or route handles do not match the tool schema'))
        handles = list(route_exit_handles or [])
        if any((handle not in self.issued_exit_handles or handle not in self._edge_by_handle for handle in handles)):
            return self._finish('resolve_work_order', fn__error('EXIT_NOT_KNOWN', 'every route exit must have been observed locally'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not actor or task.get('status') != 'blocked':
                return fn__error('WORK_ORDER_NOT_BLOCKED', 'only a blocked work order can be resolved')
            if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1:
                return fn__error('ASSIGNMENT_REQUIRED', 'the blocked work order is not coherently assigned to the controlled robot')
            if int(actor.get('battery_percent') or 0) < 10:
                return fn__error('LOW_BATTERY_PRECONDITION_FAILED', 'robot battery is below the recovery threshold')
            destination = self._required_destination(task, obj)
            now = fn__timestamp()
            plan = None
            if action == 'retry':
                if handles:
                    return fn__error('ROUTE_NOT_ALLOWED_FOR_RETRY', 'retry reuses an existing plan')
                active_obstacles = {row.get('obstacle_id') for row in self._all('obstacle') if row.get('status') == 'active'}
                candidates = [row for row in self._all('navigation_plan') if row.get('task_id') == task['task_id'] and row.get('robot_id') == self.robot_id and (row.get('status') == 'draft') and (row.get('origin_room_id') == actor.get('current_room_id')) and (row.get('destination_room_id') == destination) and (not set(row.get('blocked_by_obstacle_ids') or []) & active_obstacles) and self._route_currently_usable(row)]
                if len(candidates) != 1:
                    return fn__error('REUSABLE_PLAN_NOT_FOUND', 'retry requires one current, unblocked, controlled draft plan')
                plan = candidates[0]
                plan.update(status='active', updated_at=now)
                self._save('navigation_plan', plan)
            else:
                (route, distance, failure) = self._validate_supplied_route(handles, actor.get('current_room_id'), destination)
                if failure:
                    return fn__error(failure, 'the supplied observed route cannot resume this work order')
                plan = {'plan_id': self._new_plan_id(task['task_id']), 'facility_id': task.get('facility_id'), 'robot_id': self.robot_id, 'task_id': task['task_id'], 'origin_room_id': actor.get('current_room_id'), 'destination_room_id': destination, 'route_room_ids': route, 'route_edge_ids': [self._edge_by_handle[value] for value in handles], 'status': 'active', 'blocked_by_obstacle_ids': [], 'estimated_distance_m': round(distance, 2), 'estimated_duration_seconds': max(30, len(handles) * 30), 'created_at': now, 'updated_at': now}
                self._save('navigation_plan', plan)
            for step in self._task_steps(task['task_id']):
                if step.get('status') == 'blocked':
                    step.update(status='in_progress', blocked_reason=None, updated_at=now)
                    self._save('task_step', step)
            task.update(status='in_progress', failure_reason=None, updated_at=now)
            actor.update(operational_status='busy', active_task_id=task['task_id'], updated_at=now)
            self._save('service_task', task)
            self._save('robot_unit', actor)
            handle = self._handle('plan', plan['plan_id'])
            self.issued_plan_handles.add(handle)
            return fn__success({'work_order': work_order, 'status': 'in_progress', 'action': action, 'plan_handle': handle})
        return self._attempt('resolve_work_order', mutate)

    def _robot_experience_stream_adapter_init(self, *args, **kwargs):
        self._scanned_rooms_this_episode: set[str] = set()
        self._accessed_storage_this_episode: set[str] = set()
        self._robot_experience_stream_adapter_init_2(*args, **kwargs)
        self.tools = ext_deepcopy(DATA_TOOLS_5)

    def _robot_state_action_adapter_traverse_known_exit(self, exit_handle):
        if not isinstance(exit_handle, str) or exit_handle not in self.issued_exit_handles or exit_handle not in self._edge_by_handle:
            return self._finish('traverse_known_exit', fn__error('EXIT_NOT_KNOWN', 'scan the current room before using an exit'))
        robot = self._robot()
        edge = self._get('map_edge', 'edge_id', self._edge_by_handle[exit_handle])
        destination = self._edge_destination(edge or {}, (robot or {}).get('current_room_id'))
        if not robot or not edge or (not destination):
            return self._finish('traverse_known_exit', fn__error('EXIT_CHANGED', 'the observed exit is not adjacent now'))
        if not self._edge_usable(edge, destination):
            return self._finish('traverse_known_exit', fn__error('EXIT_BLOCKED', 'the observed exit is not traversable now'))
        cost = max(1, mod_math.ceil(float(edge.get('distance_m') or 1) / 10))
        if int(robot.get('battery_percent') or 0) < cost:
            return self._finish('traverse_known_exit', fn__error('INSUFFICIENT_BATTERY', 'movement cannot be paid', {'battery_percent': int(robot.get('battery_percent') or 0), 'battery_cost': 0}))
        previous_name = self._room_name(robot.get('current_room_id'))
        domain = mod_importlib.import_module('mcp_servers.robot_domain')
        result = domain.move_robot_to_room(self.sm, robot_id=self.robot_id, destination_room_id=destination, battery_cost_percent=cost)
        if result.get('status') != 'success':
            return self._finish('traverse_known_exit', fn__error(fn__code(result), 'movement was rejected', {'battery_percent': self._battery(), 'battery_cost': 0}))
        now = fn__timestamp()
        actor = self._robot()
        active_task_id = (actor or {}).get('active_task_id')
        task = self._get('service_task', 'task_id', active_task_id)
        if task:
            for step in self._task_steps(active_task_id):
                if step.get('step_type') == 'navigate' and step.get('room_id') == destination and (step.get('status') in {'pending', 'in_progress'}):
                    step.update(status='completed', completed_at=now, blocked_reason=None, updated_at=now)
                    self._save('task_step', step)
                    if task.get('status') == 'assigned':
                        task.update(status='in_progress', updated_at=now)
                        self._save('service_task', task)
                    break
        for plan in self._all('navigation_plan'):
            if plan.get('robot_id') == self.robot_id and plan.get('status') == 'active' and (plan.get('destination_room_id') == destination):
                plan.update(status='completed', updated_at=now)
                self._save('navigation_plan', plan)
        return self._finish('traverse_known_exit', fn__success({'previous_room': {'name': previous_name}, 'current_room': {'name': self._room_name(destination)}, 'battery_percent': self._battery(), 'battery_cost': cost}), cost)

    def _robot_experience_adapter_call(self, name, arguments):
        if name not in DATA__TOOL_BY_NAME:
            return self._finish(str(name), fn__error('UNKNOWN_TOOL', 'tool is not in the public experience profile'))
        if not self._schema_valid(name, arguments):
            return self._finish(name, fn__error('INVALID_ARGUMENTS', 'arguments do not match the tool schema'))
        return getattr(self, name)(**ext_deepcopy(arguments))

    def _robot_experience_stream_adapter_snapshot(self):
        """Return the complete private checkpoint used for replay and grading."""
        state = self._robot_experience_stream_adapter_snapshot_2()
        state['schema'] = 'robot-experience-stream-snapshot/v3'
        state['episode_metering'] = {'scanned_room_ids': sorted(self._scanned_rooms_this_episode), 'accessed_storage_handles': sorted(self._accessed_storage_this_episode)}
        return state

    def _robot_experience_stream_adapter_read_work_order(self, work_order):
        result = self._robot_experience_adapter_read_work_order(work_order)
        if result.get('status') == 'success':
            result['data']['policy_version'] = self.public_policy_version
        return result

    def _robot_experience_adapter_storage_view(self, room, unit):
        objects = []
        for obj in sorted(self._all('object_item'), key=lambda row: row.get('object_id', '')):
            if obj.get('current_room_id') == room['room_id'] and (not obj.get('held_by_robot_id')) and (obj.get('storage_unit_id') == unit['unit_id']):
                handle = self._handle('object', obj['object_id'])
                self.issued_object_handles.add(handle)
                objects.append({'object_handle': handle, 'display_name': obj.get('display_name'), 'handling_state': obj.get('handling_state')})
        return {'storage_handle': self._handle('storage', unit['unit_id']), 'display_name': unit.get('display_name') or f"Storage-{self._handle('storage', unit['unit_id'])[-8:].upper()}", 'access_state': 'open', 'stock_group': unit.get('stock_group'), 'objects': objects, 'calibration_records': ext_deepcopy(unit.get('calibration_records', []))}

    def _robot_experience_adapter_inspect_local_object(self, object_handle):
        if not isinstance(object_handle, str) or object_handle not in self.issued_object_handles or object_handle not in self._object_by_handle:
            return self._finish('inspect_local_object', fn__error('OBJECT_NOT_OBSERVED', 'observe the parcel locally before inspecting it'))
        robot = self._robot()
        obj = self._get('object_item', 'object_id', self._object_by_handle[object_handle])
        if not robot or not obj or (not self._object_visible_in_room(obj, robot.get('current_room_id'))):
            return self._finish('inspect_local_object', fn__error('OBJECT_NOT_LOCAL', 'the observed parcel is no longer visible here'))
        matching_order = next((order for order in self._orders.values() if order['object_id'] == obj['object_id']), None)
        if matching_order is not None:
            (task, _) = self._work_context(matching_order)
            if task and robot.get('current_room_id') == task.get('source_room_id') and (obj.get('current_room_id') == task.get('source_room_id')) and (not obj.get('held_by_robot_id')):
                task.update(source_inspection_receipt={'status': 'verified', 'object_id': obj['object_id'], 'source_room_id': task.get('source_room_id'), 'handling_code': obj.get('handling_code'), 'stock_group': task.get('stock_group')}, updated_at=fn__timestamp())
                self._save('service_task', task)
                self._inspected_target_ids.add(obj['object_id'])
        return self._finish('inspect_local_object', fn__success({'object': {'object_handle': object_handle, 'display_name': obj.get('display_name'), 'handling_state': obj.get('handling_state'), 'handling_code': obj.get('handling_code')}}))

    def _robot_experience_adapter_pickup(self, work_order, object_handle):
        order = self._order(work_order)
        if not order:
            return self._finish('pickup', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        (task, obj) = self._work_context(order)
        if not task or not obj or (not self._source_inspection_valid(order, task, obj)) or (task.get('transfer_profile_submitted') not in DATA_TRANSFER_PROFILES) or (task.get('transfer_policy_version') != task.get('policy_version')) or (task.get('transfer_object_id') != obj['object_id']):
            return self._attempt('pickup', lambda : fn__error('TRANSFER_NOT_CONFIGURED', 'pickup requires a current parcel-bound transfer configuration'))
        return self._robot_state_action_adapter_pickup(work_order, object_handle)

    def _robot_experience_adapter_import_observation_ledger(self, ledger):
        if not isinstance(ledger, dict):
            raise ValueError('observation ledger must be an object')
        storage_handles = ledger.get('storage_handles', [])
        opened_handles = ledger.get('opened_storage_handles', [])
        if not isinstance(storage_handles, list) or not all((isinstance(value, str) for value in storage_handles)):
            raise ValueError('storage_handles must be a list of strings')
        if not isinstance(opened_handles, list) or not all((isinstance(value, str) for value in opened_handles)):
            raise ValueError('opened_storage_handles must be a list of strings')
        accepted_storage = set(storage_handles) & set(self._storage_by_handle)
        accepted_opened = set(opened_handles) & accepted_storage
        before_storage = len(self.issued_storage_handles)
        self.issued_storage_handles.update(accepted_storage)
        for handle in accepted_opened:
            resolved = self._storage(handle)
            if resolved and resolved[1].get('opened') is not True:
                (room, unit) = resolved
                unit['opened'] = True
                room['storage_units'] = [unit if row.get('unit_id') == unit['unit_id'] else row for row in room.get('storage_units', [])]
                self._save('room', room)
        allowed_object_handles = set()
        for (handle, object_id) in self._object_by_handle.items():
            obj = self._get('object_item', 'object_id', object_id)
            storage = self._storage_for_object(obj or {}) if obj else None
            if not storage or storage[1].get('opened') is True or obj.get('held_by_robot_id'):
                allowed_object_handles.add(handle)
        sanitized = ext_deepcopy(ledger)
        sanitized['object_handles'] = [handle for handle in ledger.get('object_handles', []) if handle in allowed_object_handles]
        counts = self._robot_state_action_adapter_import_observation_ledger(sanitized)
        inspected = ledger.get('inspected_target_object_ids', [])
        if not isinstance(inspected, list) or not all((isinstance(value, str) for value in inspected)):
            raise ValueError('inspected_target_object_ids must be a list of strings')
        durable_targets = set()
        for order in self._orders.values():
            (task, obj) = self._work_context(order)
            if task and obj and self._source_inspection_valid(order, task, obj):
                durable_targets.add(order['object_id'])
        before_inspected = len(self._inspected_target_ids)
        self._inspected_target_ids.update(set(inspected) & durable_targets)
        counts['storage_handles_imported'] = len(self.issued_storage_handles) - before_storage
        counts['opened_storage_handles_imported'] = len(accepted_opened)
        counts['inspected_target_object_ids_imported'] = len(self._inspected_target_ids) - before_inspected
        return counts

    def _robot_experience_adapter_grade(self):
        rows = []
        total = 0.0
        for (work_order, order) in self._orders.items():
            (task, obj) = self._work_context(order)
            steps = self._task_steps(order['task_id'])
            assignments = [row for row in self._all('task_assignment') if row.get('task_id') == order['task_id']]
            plans = [row for row in self._all('navigation_plan') if row.get('task_id') == order['task_id']]
            source_verified = bool(task and obj and self._source_inspection_valid(order, task, obj))
            receipt = (task or {}).get('intake_receipt') or {}
            authorized = bool(task and obj and (task.get('transfer_authorized') is True) and (receipt.get('status') == 'accepted') and (receipt.get('object_id') == obj.get('object_id')) and (receipt.get('policy_version') == task.get('policy_version')) and (receipt.get('destination_room_id') == order['destination_room_id']))
            custody_obtained = any((row.get('step_type') == 'pick' and row.get('status') == 'completed' for row in steps))
            physical = bool(authorized and obj and (obj.get('current_room_id') == order['destination_room_id']) and (not obj.get('held_by_robot_id')) and (obj.get('handling_state') in {'stored', 'delivered'}))
            workflow = bool(physical and task and (task.get('status') == 'completed') and (obj.get('handling_state') == 'delivered') and steps and all((row.get('status') == 'completed' for row in steps)) and (not any((row.get('status') == 'active' for row in assignments))) and any((row.get('status') == 'completed' for row in assignments)) and (not any((row.get('status') == 'active' for row in plans))) and (not any((row.get('payload_object_id') == order['object_id'] for row in self._all('robot_unit')))) and (not any((row.get('active_task_id') == order['task_id'] for row in self._all('robot_unit')))))
            anchors = {'source_verified': 2.5 if source_verified else 0.0, 'transfer_authorized': 5.0 if authorized else 0.0, 'custody_obtained': 5.0 if custody_obtained else 0.0, 'physical_delivery': 5.0 if physical else 0.0, 'workflow_completed': 7.5 if workflow else 0.0}
            score = sum(anchors.values())
            total += score
            rows.append({'work_order': work_order, **{key: value > 0 for (key, value) in anchors.items()}, 'score': score, 'max_score': 25.0})
        components = {f'item_{index}_{name}': {'correct': int(row[name]), 'total': 1} for (index, row) in enumerate(rows, 1) for name in ('source_verified', 'transfer_authorized', 'custody_obtained', 'physical_delivery', 'workflow_completed')}
        return {'score': total, 'max_score': 100.0, 'orders': rows, 'public_components': components}

    def _robot_state_action_adapter_release(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('release', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not obj or (not actor):
                return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete')
            if task.get('status') not in {'assigned', 'in_progress'}:
                return fn__error('WORK_ORDER_NOT_RELEASABLE', 'blocked or terminal work cannot record release')
            if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1:
                return fn__error('ASSIGNMENT_REQUIRED', "release requires the controlled robot's active assignment")
            if actor.get('payload_object_id') != obj.get('object_id') or obj.get('held_by_robot_id') != self.robot_id:
                return fn__error('CUSTODY_MISMATCH', 'the controlled robot does not hold this work-order parcel')
            if actor.get('current_room_id') != order['destination_room_id']:
                return fn__error('WRONG_DESTINATION', 'the parcel can only be released at the work-order destination')
            steps = self._task_steps(task['task_id'])
            place_index = next((index for (index, row) in enumerate(steps) if row.get('step_type') == 'place'), None)
            if place_index is None or steps[place_index].get('status') not in {'pending', 'in_progress'} or any((row.get('status') != 'completed' for row in steps[:place_index])):
                return fn__error('WORKFLOW_NOT_READY_FOR_RELEASE', 'earlier work-order obligations are not complete')
            domain = mod_importlib.import_module('mcp_servers.robot_domain')
            native = domain.release_object_at_room(self.sm, object_id=obj['object_id'], robot_id=self.robot_id, room_id=order['destination_room_id'], delivery_state='stored', task_id=task['task_id'])
            if native.get('status') != 'success':
                return fn__error(fn__code(native), 'release was rejected')
            return fn__success({'work_order': work_order, 'destination': {'name': self._room_name(order['destination_room_id'])}, 'physical_state': 'stored'})
        return self._attempt('release', mutate)

    def _robot_state_action_adapter_finalize(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('finalize', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not obj or (not actor):
                return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete')
            if task.get('status') not in {'assigned', 'in_progress'}:
                return fn__error('WORK_ORDER_NOT_COMPLETABLE', 'the work order is blocked or terminal')
            steps = self._task_steps(task['task_id'])
            if not steps or any((row.get('status') != 'completed' for row in steps)):
                return fn__error('REQUIRED_STEPS_OPEN', 'finalize cannot create or skip execution evidence')
            if obj.get('current_room_id') != order['destination_room_id'] or obj.get('held_by_robot_id') or obj.get('handling_state') != 'stored':
                return fn__error('PHYSICAL_DELIVERY_INCOMPLETE', 'the parcel must already be stored unheld at the destination')
            if any((row.get('payload_object_id') == obj.get('object_id') for row in self._all('robot_unit'))):
                return fn__error('PAYLOAD_REFERENCE_CONFLICT', 'a robot still references the delivered parcel')
            active = self._active_assignments(task_id=task['task_id'])
            if task.get('assigned_robot_id') != self.robot_id or len(active) != 1 or active[0].get('robot_id') != self.robot_id or (actor.get('active_task_id') != task['task_id']) or (actor.get('operational_status') != 'busy'):
                return fn__error('ASSIGNMENT_INCOHERENT', 'strict completion requires one coherent controlled assignment')
            now = fn__timestamp()
            assignment = active[0]
            assignment.update(status='completed', released_at=now, updated_at=now)
            self._save('task_assignment', assignment)
            for plan in self._all('navigation_plan'):
                if plan.get('task_id') == task['task_id'] and plan.get('robot_id') == self.robot_id and (plan.get('status') in {'active', 'draft'}):
                    plan.update(status='completed', updated_at=now)
                    self._save('navigation_plan', plan)
            actor.update(operational_status='available', active_task_id=None, payload_object_id=None, updated_at=now)
            obj.update(handling_state='delivered', held_by_robot_id=None, current_room_id=order['destination_room_id'], updated_at=now)
            task.update(status='completed', completed_at=now, failure_reason=None, updated_at=now)
            self._save('robot_unit', actor)
            self._save('object_item', obj)
            self._save('service_task', task)
            return fn__success({'work_order': work_order, 'status': 'completed', 'object_state': 'delivered', 'controlled_robot_status': 'available'})
        return self._attempt('finalize', mutate)

    def _robot_state_action_adapter_export_observation_ledger(self):
        return {'exit_handles': sorted(self.issued_exit_handles), 'object_handles': sorted(self.issued_object_handles), 'plan_handles': sorted(self.issued_plan_handles), 'robot_handles': sorted(self.issued_robot_handles), 'work_orders': sorted(self.issued_work_orders)}

    def _robot_experience_stream_adapter_init_2(self, sm, *, active_object_ids, public_policy_version, expected_rule_epoch, facility_id, **kwargs):
        if not isinstance(active_object_ids, set) or len(active_object_ids) != 4:
            raise ValueError('active_object_ids must contain exactly four objects')
        if public_policy_version not in {'PV-18', 'PV-19'}:
            raise ValueError('unknown public policy version')
        if expected_rule_epoch not in {'pre', 'post'}:
            raise ValueError('unknown rule epoch')
        self.active_object_ids = frozenset(active_object_ids)
        self.public_policy_version = public_policy_version
        self.expected_rule_epoch = expected_rule_epoch
        self.facility_id = facility_id
        self._robot_experience_adapter_init(sm, **kwargs)
        self.tools = ext_deepcopy(DATA_TOOLS_4)
        inventory = {row['object_id'] for row in self._all('object_item')}
        if (missing := (self.active_object_ids - inventory)):
            raise ValueError(f'active episode references missing objects: {sorted(missing)}')
        facility = self._get('facility', 'facility_id', facility_id)
        if facility is None:
            raise ValueError('stream facility is missing')
        if facility.get('experience_rule_epoch') != expected_rule_epoch:
            raise ValueError('physical state rule epoch does not match the requested episode')
        if facility.get('experience_policy_version') != public_policy_version:
            raise ValueError('physical state policy version does not match the requested episode')
        for order in self._orders.values():
            (task, obj) = self._work_context(order)
            if task is None or obj is None:
                raise ValueError('active episode has an incomplete order')
            if obj['object_id'] not in self.active_object_ids:
                raise ValueError('rubric contains a non-active object')
            if task.get('experience_activation_state') != 'active':
                raise ValueError('active service task is not activated')
            if obj.get('experience_activation_state') != 'active':
                raise ValueError('active parcel is not activated')
            if task.get('experience_policy_version') != public_policy_version:
                raise ValueError('service task policy version differs from the episode')

    def _robot_experience_stream_adapter_snapshot_2(self):
        state = self._robot_experience_adapter_snapshot()
        state['schema'] = 'robot-experience-stream-snapshot/v2'
        state['active_object_ids'] = sorted(self.active_object_ids)
        state['public_policy_version'] = self.public_policy_version
        state['rule_epoch'] = self.expected_rule_epoch
        return state

    def _robot_experience_adapter_read_work_order(self, work_order):
        order = self._order(work_order)
        if not order:
            return self._finish('read_work_order', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        (task, obj) = self._work_context(order)
        if not task or not obj:
            return self._finish('read_work_order', fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete'))
        if (task.get('intake_receipt') or {}).get('status') == 'accepted':
            transfer_state = 'intake_accepted'
        elif task.get('transfer_profile_submitted'):
            transfer_state = 'configured_unverified'
        else:
            transfer_state = 'unconfigured'
        assigned = self._get('robot_unit', 'robot_id', task.get('assigned_robot_id'))
        return self._finish('read_work_order', fn__success({'work_order': work_order, 'status': task.get('status'), 'destination': {'name': self._room_name(order['destination_room_id'])}, 'object': {'display_name': obj.get('display_name')}, 'stock_group': task.get('stock_group'), 'intake_code': task.get('intake_code'), 'policy_version': task.get('policy_version'), 'transfer_state': transfer_state, 'assigned_robot_display_name': (assigned or {}).get('display_name')}))

    def _robot_state_action_adapter_pickup(self, work_order, object_handle):
        order = self._order(work_order)
        if not order:
            return self._finish('pickup', fn__error('WORK_ORDER_NOT_FOUND', 'the work-order reference is unknown'))
        if not isinstance(object_handle, str) or object_handle not in self.issued_object_handles or object_handle not in self._object_by_handle:
            return self._finish('pickup', fn__error('OBJECT_NOT_OBSERVED', 'observe the parcel locally before pickup'))

        def mutate():
            (task, obj) = self._work_context(order)
            actor = self._robot()
            if not task or not obj or (not actor):
                return fn__error('WORK_ORDER_UNAVAILABLE', 'the work-order records are incomplete')
            if task.get('status') not in {'assigned', 'in_progress'}:
                return fn__error('WORK_ORDER_NOT_PICKABLE', 'blocked or terminal work cannot record pickup')
            if task.get('assigned_robot_id') != self.robot_id or len(self._active_assignments(task_id=task['task_id'], robot_id=self.robot_id)) != 1:
                return fn__error('ASSIGNMENT_REQUIRED', "pickup requires the controlled robot's active assignment")
            if self._object_by_handle[object_handle] != order['object_id']:
                return fn__error('WORK_ORDER_OBJECT_MISMATCH', 'the observed parcel does not belong to this work order')
            if actor.get('payload_object_id') or obj.get('held_by_robot_id') or obj.get('current_room_id') != actor.get('current_room_id') or (actor.get('current_room_id') != task.get('source_room_id')):
                return fn__error('PICKUP_LOCATION_OR_CUSTODY_INVALID', 'the work-order parcel is not locally pickable')
            steps = self._task_steps(task['task_id'])
            pick_index = next((index for (index, row) in enumerate(steps) if row.get('step_type') == 'pick'), None)
            if pick_index is None or steps[pick_index].get('status') not in {'pending', 'in_progress'}:
                return fn__error('PICK_STEP_NOT_OPEN', 'the pickup obligation is not open')
            now = fn__timestamp()
            for step in steps[:pick_index]:
                if step.get('step_type') == 'navigate' and step.get('room_id') == actor.get('current_room_id') and (step.get('status') in {'pending', 'in_progress'}):
                    step.update(status='completed', completed_at=now, blocked_reason=None, updated_at=now)
                    self._save('task_step', step)
                elif step.get('status') != 'completed':
                    return fn__error('PRIOR_STEP_OPEN', 'pickup requires earlier obligations to be complete')
            domain = mod_importlib.import_module('mcp_servers.robot_domain')
            native = domain.attach_object_to_robot(self.sm, object_id=obj['object_id'], robot_id=self.robot_id, task_id=task['task_id'])
            if native.get('status') != 'success':
                return fn__error(fn__code(native), 'pickup was rejected')
            task = self._get('service_task', 'task_id', task['task_id'])
            if task and task.get('status') == 'assigned':
                task.update(status='in_progress', updated_at=now)
                self._save('service_task', task)
            return fn__success({'work_order': work_order, 'object_handle': object_handle, 'handling_state': 'in_transit'})
        return self._attempt('pickup', mutate)

    def _robot_state_action_adapter_import_observation_ledger(self, ledger):
        if not isinstance(ledger, dict):
            raise ValueError('observation ledger must be an object')
        self._refresh_plan_handles()
        specs = {'exit_handles': (self.issued_exit_handles, set(self._edge_by_handle)), 'object_handles': (self.issued_object_handles, set(self._object_by_handle)), 'plan_handles': (self.issued_plan_handles, set(self._plan_by_handle)), 'robot_handles': (self.issued_robot_handles, set(self._robot_by_handle)), 'work_orders': (self.issued_work_orders, set(self._orders))}
        counts = {}
        for (key, (target, known)) in specs.items():
            values = ledger.get(key, [])
            if not isinstance(values, list) or not all((isinstance(value, str) for value in values)):
                raise ValueError(f'{key} must be a list of strings')
            accepted = set(values) & known
            before = len(target)
            target.update(accepted)
            counts[f'{key}_imported'] = len(target) - before
        return counts

    def _robot_experience_adapter_init(self, sm, *, robot_id, handle_seed, task_ids, rubric, rule_table=None):
        if not isinstance(rubric, dict) or rubric.get('version') != 'robot-experience-rubric/v1':
            raise ValueError('unsupported robot experience rubric')
        if rubric.get('policy_version') != 'PV-18':
            raise ValueError('rubric policy version does not match the adapter')
        home_room_id = rubric.get('home_room_id')
        if not isinstance(home_room_id, str) or not home_room_id:
            raise ValueError('rubric must define a home_room_id')
        legacy_rubric = {'version': 'robot-state-action-rubric/v1', 'orders': ext_deepcopy(rubric.get('orders'))}
        self._robot_state_action_adapter_init(sm, robot_id=robot_id, handle_seed=handle_seed, task_ids=task_ids, rubric=legacy_rubric)
        self.tools = ext_deepcopy(DATA_TOOLS_6)
        self.home_room_id = home_room_id
        self.rule_table = fn__validate_rule_table(rule_table)
        self._rubric_v3 = ext_deepcopy(rubric)
        self._inspected_target_ids: set[str] = set()
        self._storage_by_handle: dict[str, tuple[str, str]] = {}
        seen_unit_ids: set[str] = set()
        for room in self._all('room'):
            units = room.get('storage_units', [])
            if not isinstance(units, list):
                raise ValueError('room storage_units must be a list')
            for unit in units:
                unit_id = unit.get('unit_id') if isinstance(unit, dict) else None
                if not isinstance(unit_id, str) or not unit_id or unit_id in seen_unit_ids:
                    raise ValueError('storage unit IDs must be unique non-empty strings')
                if not isinstance(unit.get('stock_group'), str) or not unit['stock_group']:
                    raise ValueError('storage units must define a stock_group')
                if not isinstance(unit.get('opened'), bool):
                    raise ValueError('storage units must define boolean opened state')
                if not isinstance(unit.get('calibration_records'), list):
                    raise ValueError('storage calibration_records must be a list')
                seen_unit_ids.add(unit_id)
                self._storage_by_handle[self._handle('storage', unit_id)] = (room['room_id'], unit_id)
        self.issued_storage_handles: set[str] = set()
        for (work_order, order) in self._orders.items():
            (task, obj) = self._work_context(order)
            if not task or not obj:
                raise ValueError(f'incomplete records for {work_order}')
            if task.get('policy_version') != 'PV-18':
                raise ValueError('task policy version does not match the adapter')
            if task.get('intake_code') not in DATA_INTAKE_CODES:
                raise ValueError('task has an unknown intake code')
            if obj.get('handling_code') not in DATA_HANDLING_CODES:
                raise ValueError('object has an unknown handling code')
            if task.get('stock_group') != obj.get('stock_group'):
                raise ValueError('work order and parcel stock groups differ')
            if self._source_inspection_valid(order, task, obj):
                self._inspected_target_ids.add(obj['object_id'])

    def _robot_experience_adapter_snapshot(self):
        state = self._robot_state_action_adapter_snapshot()
        state['schema'] = 'robot-experience-snapshot/v1'
        state['inspected_target_object_ids'] = sorted(self._inspected_target_ids)
        return state

    def _robot_state_action_adapter_init(self, sm, *, robot_id, handle_seed, task_ids, rubric):
        if not isinstance(robot_id, str) or not robot_id:
            raise ValueError('robot_id must be a non-empty string')
        if not isinstance(handle_seed, str) or not handle_seed:
            raise ValueError('handle_seed must be a non-empty string')
        if not isinstance(task_ids, list) or len(task_ids) != 4 or len(set(task_ids)) != 4 or (not all((isinstance(x, str) and x for x in task_ids))):
            raise ValueError('task_ids must contain four unique strings')
        if not isinstance(rubric, dict) or rubric.get('version') != 'robot-state-action-rubric/v1':
            raise ValueError('unsupported robot state-action rubric')
        orders = rubric.get('orders')
        if not isinstance(orders, list) or len(orders) != 4:
            raise ValueError('rubric must contain exactly four orders')
        self.sm = sm
        self.robot_id = robot_id
        self.handle_seed = handle_seed
        self.tools = ext_deepcopy(DATA_TOOLS_7)
        self._task_ids = tuple(task_ids)
        self._orders: dict[str, dict[str, str]] = {}
        for row in orders:
            if not isinstance(row, dict) or any((not isinstance(row.get(key), str) or not row[key] for key in ('work_order', 'task_id', 'object_id', 'destination_room_id'))):
                raise ValueError('rubric order fields must be non-empty strings')
            if row['work_order'] in self._orders:
                raise ValueError('work_order values must be unique')
            self._orders[row['work_order']] = {key: row[key] for key in ('work_order', 'task_id', 'object_id', 'destination_room_id')}
        if set(self._task_ids) != {row['task_id'] for row in self._orders.values()}:
            raise ValueError('task_ids and rubric orders differ')
        if self._get('robot_unit', 'robot_id', robot_id) is None:
            raise ValueError('controlled robot does not exist')
        self._edge_by_handle = {self._handle('exit', row['edge_id']): row['edge_id'] for row in self._all('map_edge')}
        self._object_by_handle = {self._handle('object', row['object_id']): row['object_id'] for row in self._all('object_item')}
        self._robot_by_handle = {self._handle('robot', row['robot_id']): row['robot_id'] for row in self._all('robot_unit')}
        self._plan_by_handle: dict[str, str] = {}
        self.issued_exit_handles: set[str] = set()
        self.issued_object_handles: set[str] = set()
        self.issued_plan_handles: set[str] = set()
        self.issued_robot_handles: set[str] = set()
        self.issued_work_orders: set[str] = set(self._orders)
        self._actions: list[dict[str, ext_Any]] = []
        self._next_action_index = 1
        self._refresh_plan_handles()

    def _robot_state_action_adapter_snapshot(self):
        state: dict[str, ext_Any] = {'schema': 'robot-state-action-snapshot/v1'}
        relevant_tasks = set(self._task_ids)
        for (output_key, (entity, id_field)) in DATA__SNAPSHOT_TABLES.items():
            rows = self._all(entity)
            if entity == 'service_task':
                rows = [row for row in rows if row.get('task_id') in relevant_tasks]
            elif entity in {'task_step', 'task_assignment', 'navigation_plan'}:
                rows = [row for row in rows if row.get('task_id') in relevant_tasks]
            state[output_key] = [fn__strip_volatile(row) for row in sorted(rows, key=lambda row: str(row.get(id_field) or ''))]
        state['observation_ledger'] = self.export_observation_ledger()
        state['action_ledger'] = ext_deepcopy(self._actions)
        return state