File size: 94,915 Bytes
b62faac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""V20 runtime: pre-prefill 1-3 hop routing, RadixCache-friendly <v20_recall> delivery, AutoSessionV20, and SleeperV20."""

from __future__ import annotations

import calendar
from collections import Counter
import datetime as dt
import hashlib
import io
import json
import math
from pathlib import Path
import re
import struct
import time
from uuid import uuid4

from PIL import Image
from safetensors import SafetensorError
from safetensors.torch import load, load_file, save
import torch

from .store_v20 import (
    EventStoreV20,
    _CHECKPOINT_INTERVAL,
    _clean_query_text,
    _light_stem,
    _salient_terms,
    query_references,
    record_links,
    source_reference as normalize_reference,
)


_PORTABLE_STATE_FORMAT = "inkling-v20-state-v3"
_MONTH_MAP = {
    "jan": 1, "january": 1,
    "feb": 2, "february": 2,
    "mar": 3, "march": 3,
    "apr": 4, "april": 4,
    "may": 5,
    "jun": 6, "june": 6,
    "jul": 7, "july": 7,
    "aug": 8, "august": 8,
    "sep": 9, "sept": 9, "september": 9,
    "oct": 10, "october": 10,
    "nov": 11, "november": 11,
    "dec": 12, "december": 12,
}
_WEEKDAY_MAP = {
    "monday": 0, "mon": 0,
    "tuesday": 1, "tue": 1, "tues": 1,
    "wednesday": 2, "wed": 2,
    "thursday": 3, "thu": 3, "thur": 3, "thurs": 3,
    "friday": 4, "fri": 4,
    "saturday": 5, "sat": 5,
    "sunday": 6, "sun": 6,
}
_NUM_WORD_MAP = {
    "a": 1, "an": 1, "one": 1, "two": 2, "couple": 2, "couple of": 2,
    "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7,
    "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12,
}
_DOW_SHORT = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_MONTH_NAMES = (
    "", "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December",
)

_ISO_DATE_RE = re.compile(r"\b(20\d{2}|19\d{2})[-/](0?[1-9]|1[0-2])[-/](0?[1-9]|[12]\d|3[01])\b")
_DMY_DATE_RE = re.compile(
    r"\b([12]?\d|3[01])(?:st|nd|rd|th)?\s+(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?),?\s+(20\d{2}|19\d{2})\b",
    re.I,
)
_MDY_DATE_RE = re.compile(
    r"\b(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+([12]?\d|3[01])(?:st|nd|rd|th)?,?\s+(20\d{2}|19\d{2})\b",
    re.I,
)
_EVENT_HEADER_DATE_RE = re.compile(
    r"(?i)(?:\[\s*session\s+\d+\s*\|\s*date\s*:\s*([^\]]+)\]|^###\s*session\s+\d+\s*\(\s*date\s*:\s*([^)]+)\)|\(\s*(?:place\s*:[^;)]*;\s*)?time\s*:\s*([^)]+)\)|^\[\s*(?:date\s*[:=]\s*)?((?:20|19)\d{2}[-/]\d{1,2}[-/]\d{1,2}[^\]]*)\])"
)
_QUERY_REF_DATE_RE = re.compile(
    r"(?im)^\s*(?:current\s+(?:date|time)|today(?:'s)?\s+date|reference\s+date|目前日期|今天日期)\s*[::]\s*(.+)$"
)
_SESSION_KEY_RE = re.compile(
    r"(?i)(?:\[\s*session\s+(\d+)\b|^###\s*session\s+(\d+)\b)"
)

_AGGREGATION_INTENT_RE = re.compile(
    r"(?i)\b(?:how\s+many|how\s+much|total|altogether|combined|all\s+the|list\s+all|how\s+often|every\s+time|both|in\s+common|what\s+else|all\s+\w+\s+(?:that|i|we|they|he|she)|number\s+of|count\s+of)\b|總共|一共|幾個|幾次|幾項|哪些|列出|所有|合計|共同"
)
_TEMPORAL_INTENT_RE = re.compile(
    r"(?i)\b(?:when|what\s+(?:date|year|month|day)|how\s+many\s+(?:days|weeks|months|years)|how\s+long\s+(?:ago|since|between)|between\s+.+\s+and\s+|before\s+.+\s+or\s+|which\s+.+\s+(?:first|earlier|later|more\s+recent)|earliest|most\s+recent|latest|chronological|timeline)\b|何時|什麼時候|幾天|幾週|幾個月|多久|先後|最早|最近"
)
_PREFERENCE_INTENT_RE = re.compile(
    r"(?i)\b(?:suggest|recommend|recommendations?|advice|tips|ideas?|complement|tailored|prefer(?:ence|s)?)\b|推薦|建議"
)


def _safe_date(y: int, m: int, d: int) -> dt.date | None:
    try:
        return dt.date(int(y), int(m), int(d))
    except ValueError:
        return None


def _shift_months(anchor: dt.date, delta_months: int) -> dt.date:
    total = (anchor.year * 12 + (anchor.month - 1)) + int(delta_months)
    y, m0 = divmod(total, 12)
    m = m0 + 1
    d = min(anchor.day, calendar.monthrange(y, m)[1])
    return dt.date(y, m, d)


def _parse_date_string(text: str) -> dt.date | None:
    if not text:
        return None
    m = _ISO_DATE_RE.search(text)
    if m:
        return _safe_date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
    m = _DMY_DATE_RE.search(text)
    if m:
        mo = _MONTH_MAP.get(m.group(2).lower())
        if mo:
            return _safe_date(int(m.group(3)), mo, int(m.group(1)))
    m = _MDY_DATE_RE.search(text)
    if m:
        mo = _MONTH_MAP.get(m.group(1).lower())
        if mo:
            return _safe_date(int(m.group(3)), mo, int(m.group(2)))
    return None


def _extract_event_date(record: dict) -> dt.date | None:
    """Resolve canonical calendar anchor date from structured event header or explicit Unix timestamp."""
    txt = str(record.get("text", "") or "")
    first_chunk = txt[:320]
    m = _EVENT_HEADER_DATE_RE.search(first_chunk)
    if m:
        for grp in m.groups():
            if grp:
                parsed = _parse_date_string(grp)
                if parsed is not None:
                    return parsed
    obs = record.get("observed_at")
    if isinstance(obs, (int, float)):
        val = float(obs)
        # Explicit Unix seconds (2000..2100) or milliseconds (never default wall-clock ns or turn indices 0..10000)
        if 946684800.0 <= val <= 4102444800.0:
            return dt.datetime.fromtimestamp(val, tz=dt.timezone.utc).date()
        if 946684800000.0 <= val <= 4102444800000.0:
            return dt.datetime.fromtimestamp(val / 1000.0, tz=dt.timezone.utc).date()
    return None


def _parse_query_ref_date(query_text: str) -> dt.date | None:
    """Extract optional reference date from standard query headers (`Current Date:`, `Current time:`, etc.)."""
    if not query_text:
        return None
    m = _QUERY_REF_DATE_RE.search(query_text)
    if not m:
        return None
    return _parse_date_string(m.group(1))


def _parse_small_int(tok: str) -> int | None:
    s = tok.strip().lower()
    if s.isdigit():
        v = int(s)
        return v if 0 < v <= 365 else None
    return _NUM_WORD_MAP.get(s)


def _fmt_date(d: dt.date) -> str:
    return f"{d.isoformat()} ({_DOW_SHORT[d.weekday()]})"


def _fmt_month(d: dt.date) -> str:
    return f"{_MONTH_NAMES[d.month]} {d.year}"


def _resolve_relative_dates(text: str, anchor: dt.date) -> list[str]:
    """Deterministically resolve unambiguous relative time expressions in `text` relative to `anchor`."""
    if not text or anchor is None:
        return []
    # Strip leading metadata bracket/header so we only scan spoken content
    body = _EVENT_HEADER_DATE_RE.sub(" ", text, count=1)
    low = body.lower()
    notes: list[str] = []

    def _add(note: str):
        if note not in notes and len(notes) < 4:
            notes.append(note)

    if re.search(r"\bthe\s+day\s+before\s+yesterday\b|前天", low):
        _add(f"day_before_yesterday={_fmt_date(anchor - dt.timedelta(days=2))}")
    elif re.search(r"\byesterday\b|昨天|昨日", low):
        _add(f"yesterday={_fmt_date(anchor - dt.timedelta(days=1))}")

    if re.search(r"\btomorrow\b|明天|明日", low):
        _add(f"tomorrow={_fmt_date(anchor + dt.timedelta(days=1))}")

    if re.search(r"\b(?:today|tonight|this\s+(?:morning|afternoon|evening))\b|今天|今晚", low):
        _add(f"today={_fmt_date(anchor)}")

    for m in re.finditer(
        r"\b(\d+|a|an|one|two|couple\s+of|three|four|five|six|seven|eight|nine|ten)\s+days?\s+ago\b",
        low,
    ):
        n = _parse_small_int(m.group(1))
        if n is not None:
            _add(f"{m.group(0)}={_fmt_date(anchor - dt.timedelta(days=n))}")
    for m in re.finditer(r"(\d+)\s*天前", body):
        n = _parse_small_int(m.group(1))
        if n is not None:
            _add(f"{n}天前={_fmt_date(anchor - dt.timedelta(days=n))}")

    for m in re.finditer(
        r"\bin\s+(\d+|a|an|one|two|three|four|five|six|seven|eight|nine|ten)\s+days?\b",
        low,
    ):
        n = _parse_small_int(m.group(1))
        if n is not None:
            _add(f"{m.group(0)}={_fmt_date(anchor + dt.timedelta(days=n))}")

    for m in re.finditer(
        r"\b(\d+|a|an|one|two|couple\s+of|three|four|five|six|seven|eight)\s+weeks?\s+ago\b",
        low,
    ):
        n = _parse_small_int(m.group(1))
        if n is not None:
            _add(f"{m.group(0)}={_fmt_date(anchor - dt.timedelta(days=7 * n))}")
    for m in re.finditer(r"(\d+)\s*(?:週|周|星期)前", body):
        n = _parse_small_int(m.group(1))
        if n is not None:
            _add(f"{n}週前={_fmt_date(anchor - dt.timedelta(days=7 * n))}")

    if re.search(r"\b(?:last|past)\s+week\b|上週|上周|上星期", low):
        d_prev = anchor - dt.timedelta(days=7)
        _add(f"last_week=week_of_{d_prev.isoformat()} ({_fmt_month(d_prev)})")
    if re.search(r"\bnext\s+week\b|下週|下周|下星期", low):
        d_next = anchor + dt.timedelta(days=7)
        _add(f"next_week=week_of_{d_next.isoformat()} ({_fmt_month(d_next)})")

    if re.search(r"\bthis\s+month\b|這個月|这个月|本月", low):
        _add(f"this_month={_fmt_month(anchor)}")
    if re.search(r"\blast\s+month\b|上個月|上个月|上月", low):
        _add(f"last_month={_fmt_month(_shift_months(anchor, -1))}")
    if re.search(r"\bnext\s+month\b|下個月|下个月|下月", low):
        _add(f"next_month={_fmt_month(_shift_months(anchor, 1))}")

    for m in re.finditer(
        r"\b(\d+|a|an|one|two|couple\s+of|three|four|five|six|seven|eight|nine|ten)\s+months?\s+ago\b",
        low,
    ):
        n = _parse_small_int(m.group(1))
        if n is not None:
            _add(f"{m.group(0)}={_fmt_month(_shift_months(anchor, -n))}")

    if re.search(r"\blast\s+year\b|去年", low):
        _add(f"last_year={anchor.year - 1}")
    if re.search(r"\bnext\s+year\b|明年", low):
        _add(f"next_year={anchor.year + 1}")
    if re.search(r"\bthis\s+year\b|今年", low):
        _add(f"this_year={anchor.year}")

    for m in re.finditer(
        r"\b(last|this\s+past|the\s+previous|next|this\s+coming)\s+(monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b",
        low,
    ):
        qual, day_name = m.group(1), m.group(2)
        target_wd = _WEEKDAY_MAP[day_name]
        if qual.startswith(("next", "this coming")):
            diff = (target_wd - anchor.weekday()) % 7
            diff = 7 if diff == 0 else diff
            _add(f"{m.group(0)}={_fmt_date(anchor + dt.timedelta(days=diff))}")
        else:
            diff = (anchor.weekday() - target_wd) % 7
            diff = 7 if diff == 0 else diff
            _add(f"{m.group(0)}={_fmt_date(anchor - dt.timedelta(days=diff))}")

    if re.search(r"\b(?:last|this\s+past)\s+weekend\b|上週末|上周末", low):
        days_since_sun = (anchor.weekday() - 6) % 7
        days_since_sun = 7 if days_since_sun == 0 else days_since_sun
        sun = anchor - dt.timedelta(days=days_since_sun)
        sat = sun - dt.timedelta(days=1)
        _add(f"last_weekend={sat.isoformat()}..{sun.isoformat()}")
    if re.search(r"\b(?:next|this\s+coming)\s+weekend\b|下週末|下周末", low):
        days_to_sat = (5 - anchor.weekday()) % 7
        days_to_sat = 7 if days_to_sat == 0 else days_to_sat
        sat = anchor + dt.timedelta(days=days_to_sat)
        sun = sat + dt.timedelta(days=1)
        _add(f"next_weekend={sat.isoformat()}..{sun.isoformat()}")

    return notes


def format_event_recall_line(
    rec: dict,
    *,
    query_ref_date: dt.date | None = None,
    override_text: str | None = None,
) -> str:
    """Canonical V20-v3 event recall line with explicit calendar date, query offset, and resolved relative dates."""
    txt = (rec.get("text", "") if override_text is None else override_text).strip()
    eid = rec.get("event_id", rec.get("id", 0))
    role = rec.get("source_role", "user")
    rev = rec.get("revision", 0)
    parts = [f"event:{eid}"]
    ev_date = _extract_event_date(rec)
    if ev_date is not None:
        parts.append(f"date={_fmt_date(ev_date)}")
        if query_ref_date is not None:
            delta_d = (ev_date - query_ref_date).days
            parts.append(f"offset={delta_d:+d}d")
        rel_notes = _resolve_relative_dates(txt, ev_date)
        if rel_notes:
            parts.append('resolved="' + "; ".join(rel_notes) + '"')
    parts.append(f"role={role}")
    parts.append(f"rev={rev}")
    return f"[{' '.join(parts)}] {txt}"


def _extract_session_key(rec: dict) -> str:
    """Group events belonging to the same session for multi-session coverage balancing."""
    txt = str(rec.get("text", "") or "")
    m = _SESSION_KEY_RE.search(txt[:200])
    if m:
        snum = m.group(1) or m.group(2)
        return f"session:{snum}"
    ev_date = _extract_event_date(rec)
    if ev_date is not None:
        return f"date:{ev_date.isoformat()}"
    return f"ev:{rec.get('event_id', 0)}"


def _classify_query_intent(query_text: str) -> dict[str, bool]:
    cleaned = _clean_query_text(query_text or "")
    return {
        "is_aggregation": bool(_AGGREGATION_INTENT_RE.search(cleaned)),
        "is_temporal": bool(_TEMPORAL_INTENT_RE.search(cleaned)),
        "is_preference": bool(_PREFERENCE_INTENT_RE.search(cleaned)),
    }


def _extract_subclauses(query_text: str) -> list[str]:
    """Split comparative / dual-target / temporal-interval queries into 2 focused sub-clauses (<0.5 ms)."""
    cleaned = _clean_query_text(query_text or "")
    if not cleaned:
        return []
    patterns = (
        r"(?i)\bbetween\s+(?:the\s+(?:day|time|date)\s+)?(.{4,120}?)\s+and\s+(?:the\s+(?:day|time|date)\s+)?(.{4,120}?)(?:\?|$)",
        r"(?i)\b(?:do|did|does|are|were|have)\s+(.{2,60}?)\s+and\s+(.{2,60}?)\s+(?:both\s+)?(?:have\s+in\s+common|share|both\b)",
        r"(?i)\bcompare\s+(.{3,80}?)\s+(?:and|with|vs\.?|versus)\s+(.{3,80}?)(?:\?|$)",
        r"(?i)\b(?:happened\s+first|came\s+first|was\s+earlier|occurred\s+first)[^a-z0-9]{1,6}(.{4,100}?)\s+or\s+(.{4,100}?)(?:\?|$)",
        r"(?i)\b(?:did\s+i|have\s+i)\s+(.{4,100}?)\s+before\s+(?:or\s+after\s+)?(.{4,100}?)(?:\?|$)",
    )
    for pat in patterns:
        m = re.search(pat, cleaned)
        if m:
            c1, c2 = m.group(1).strip(" ,.;:?!"), m.group(2).strip(" ,.;:?!")
            if len(_salient_terms(c1, is_query=False)) >= 1 and len(_salient_terms(c2, is_query=False)) >= 1:
                return [c1, c2]
    return []


def _compact_event_text(text: str, query_terms: set[str], query_stems: set[str], max_chars: int = 900) -> str:
    """When packing many multi-session chunks into a tight token budget, keep header + query-relevant lines."""
    if len(text) <= max_chars or "\n" not in text:
        return text
    lines = text.splitlines()
    if len(lines) <= 3:
        return text[:max_chars]
    keep = {0}  # Always preserve session/date header line
    scored_lines = []
    for idx in range(1, len(lines)):
        ltoks = _salient_terms(lines[idx], is_query=False)
        hits = sum(1 for t in ltoks if t in query_terms or _light_stem(t) in query_stems)
        if hits > 0:
            scored_lines.append((hits, idx))
    scored_lines.sort(reverse=True)
    for _, idx in scored_lines[:4]:
        keep.add(idx)
        if idx - 1 >= 1:
            keep.add(idx - 1)
        if idx + 1 < len(lines):
            keep.add(idx + 1)
    if len(keep) == 1:
        keep.add(1)
        if len(lines) > 2:
            keep.add(2)
    out_lines = []
    total = 0
    prev = -1
    for idx in sorted(keep):
        if prev >= 0 and idx > prev + 1:
            out_lines.append("...")
        piece = lines[idx]
        if total + len(piece) > max_chars and len(out_lines) >= 2:
            piece = piece[: max(120, max_chars - total)]
            out_lines.append(piece)
            break
        out_lines.append(piece)
        total += len(piece) + 1
        prev = idx
    return "\n".join(out_lines)


def _read_safetensors_header(raw: bytes) -> dict:
    if len(raw) < 8:
        raise ValueError("Invalid safetensors payload: too short")
    header_len = struct.unpack("<Q", raw[:8])[0]
    if 8 + header_len > len(raw):
        raise ValueError("Invalid safetensors payload: truncated header")
    return json.loads(raw[8 : 8 + header_len].decode("utf-8"))


def components_for(model):
    base = model.model
    text = getattr(base, "language_model", base)
    if getattr(text, "memory_v20", None) is None:
        raise ValueError("Load Inkling with text_config.v20_memory_enabled=True")
    return text.memory_v20


def freeze_backbone(model, stage: str = "encoder"):
    model.requires_grad_(False)
    components = components_for(model)
    components.train_stage(stage)
    return components


def _device(module) -> torch.device:
    return next(module.parameters()).device


def _image(obj) -> Image.Image:
    if isinstance(obj, Image.Image):
        return obj
    with Image.open(io.BytesIO(obj)) as image:
        return image.copy()


def _state_to_blobs(state: torch.Tensor, fast_heads: int) -> tuple[bytes, bytes]:
    cpu = state.detach().to(device="cpu", dtype=torch.float16).contiguous()
    fast_blob = save({"m_fast": cpu[:fast_heads].contiguous()})
    slow_blob = save({"m_slow": cpu[fast_heads:].contiguous()})
    return fast_blob, slow_blob


def _blobs_to_state(fast_blob: bytes | None, slow_blob: bytes | None, shape, fast_heads: int, device) -> torch.Tensor:
    if fast_blob is None or slow_blob is None:
        return torch.zeros(shape, device=device, dtype=torch.float32)
    m_fast = load(fast_blob)["m_fast"].to(device=device, dtype=torch.float32)
    m_slow = load(slow_blob)["m_slow"].to(device=device, dtype=torch.float32)
    full = torch.cat((m_fast, m_slow), dim=0)
    if tuple(full.shape) != tuple(shape):
        raise ValueError(f"Stored state shape {tuple(full.shape)} disagrees with model state shape {tuple(shape)}")
    return full


def _turn_hash(role: str, text: str, image_bytes=()) -> str:
    h = hashlib.sha256()
    h.update(role.encode("utf-8"))
    h.update(b"\x00")
    h.update(text.encode("utf-8"))
    for raw in image_bytes:
        h.update(b"\x01")
        h.update(hashlib.sha256(raw).digest())
    return h.hexdigest()


@torch.no_grad()
def _source_parts(model, processor, text: str, images=()):
    """Canonical stem order: normed text embeddings followed by post-projector visual features."""
    embedding = model.get_input_embeddings()
    device = _device(embedding)
    parts, spans = [], []
    offset = 0
    if text:
        ids = processor.tokenizer(text, add_special_tokens=False, return_tensors="pt")[
            "input_ids"
        ].to(device)
        if ids.shape[1]:
            parts.append(embedding(ids)[0])
            offset = ids.shape[1]
            spans.append({"kind": "text", "start": 0, "end": offset})
    for i, obj in enumerate(images):
        image = _image(obj)
        inp = processor.image_processor(images=[image], return_tensors="pt")
        tower = model.model.vision_tower
        params = next(tower.parameters())
        grid = inp["image_grid_thw"]
        pixels = inp["pixel_values"].to(device=params.device, dtype=params.dtype)
        features = model.get_image_features(
            pixels, grid, return_dict=True
        ).pooler_output[0]
        parts.append(features.to(device=device, dtype=embedding.weight.dtype))
        cell = processor.image_processor.size
        spans.append(
            {
                "kind": "image",
                "image": i,
                "start": offset,
                "end": offset + len(features),
                "grid": grid[0].tolist(),
                "width": image.width,
                "height": image.height,
                "cell_width": cell["width"],
                "cell_height": cell["height"],
            }
        )
        offset += len(features)
    if not parts:
        raise ValueError("An event or query needs at least one text or image token")
    return torch.cat(parts, dim=0), spans


def _source_geometry(processor, text: str, images=()):
    end = (
        len(processor.tokenizer(text, add_special_tokens=False)["input_ids"])
        if text
        else 0
    )
    spans = [{"kind": "text", "start": 0, "end": end}] if end else []
    cell = processor.image_processor.size
    for i, data in enumerate(images):
        with Image.open(io.BytesIO(data)) as im:
            width, height = im.size
        rows = math.ceil(height / cell["height"])
        cols = math.ceil(width / cell["width"])
        spans.append(
            {
                "kind": "image",
                "image": i,
                "start": end,
                "end": end + rows * cols,
                "grid": [1, rows, cols],
                "width": width,
                "height": height,
                "cell_width": cell["width"],
                "cell_height": cell["height"],
            }
        )
        end += rows * cols
    if not end:
        raise ValueError("An event needs at least one text or image token")
    return spans


class SourceEvidenceError(LookupError):
    """A source-bound request failed evidence verification before emitting any answer token."""

    def __init__(self, grounding: dict):
        self.grounding = dict(grounding)
        self.status = self.grounding["status"]
        self.reason = self.grounding["reason"]
        self.evidence_ids = list(self.grounding.get("evidence_ids", ()))
        super().__init__(self.reason)


class _NativeImageBinding:
    """Request-local proof that retrieved visual vectors occupied their exact native token positions."""

    def __init__(self, ctx, targets):
        self.ctx = ctx
        self.targets = targets  # list of (start_pos, event_id, features)
        self.seen = [set() for _ in targets]
        self.consumed = False

    @torch.no_grad()
    def observe(self, embedded, image_mask, position_ids, cache):
        past = int(cache.get_seq_length()) if cache is not None else 0
        if self.consumed and past > 0:
            return
        if past == 0 and (position_ids is None or int(position_ids.min()) == 0):
            self.seen = [set() for _ in self.targets]
            self.consumed = False
            self.ctx.grounding["native_visual_consumed"] = False
        batch, length = embedded.shape[:2]
        pos = (
            torch.arange(past, past + length, device=embedded.device)
            if position_ids is None
            else position_ids.to(embedded.device)
        )
        pos = pos.reshape(-1, length).expand(batch, -1)
        for j, (first, _, features) in enumerate(self.targets):
            mask = (pos >= first) & (pos < first + len(features))
            cols = mask[0].nonzero().flatten()
            if not len(cols) and not bool(mask.any()):
                continue
            if not torch.equal(mask, mask[0:1].expand_as(mask)):
                self._mismatch()
            offsets = pos[0, cols] - first
            if image_mask is None or not bool(image_mask[:, cols, 0].all()):
                self._mismatch()
            expected = features.to(embedded).index_select(0, offsets)
            if not torch.equal(pos[:, cols], pos[0:1, cols].expand(batch, -1)) or not torch.equal(
                embedded[:, cols], expected.unsqueeze(0).expand(batch, -1, -1)
            ):
                self._mismatch()
            self.seen[j].update(offsets.tolist())
        self.consumed = all(
            len(done) == len(features)
            for done, (_, _, features) in zip(self.seen, self.targets)
        )
        self.ctx.grounding["native_visual_consumed"] = self.consumed

    def _mismatch(self):
        self.consumed = False
        self.ctx.grounding["native_visual_consumed"] = False
        raise SourceEvidenceError(
            dict(
                self.ctx.grounding,
                status="insufficient_evidence",
                reason="native_image_mismatch",
            )
        )


class V20EvidenceContext:
    """Static-shape, CUDA-graph-safe request memory session for Inkling2 Loop V20."""

    def __init__(
        self,
        *,
        state_tensor: torch.Tensor,
        active: bool = True,
        absence_code: int = -1,
        scope: dict | None = None,
        grounding: dict | None = None,
        trace: list | None = None,
        recall_text: str = "",
        channel_a_enabled: bool = True,
        requires_source_validation: bool = False,
    ):
        self.state_tensor = state_tensor.detach().float()
        if self.state_tensor.ndim == 3:
            self.state_tensor = self.state_tensor.unsqueeze(0)
        self.active = bool(active)
        self.absence_code = int(absence_code)
        self.scope = dict(scope or {})
        self.grounding = dict(grounding or {})
        self.trace = list(trace or [])
        self.recall_text = recall_text
        self.channel_a_enabled = bool(channel_a_enabled)
        self.requires_source_validation = bool(requires_source_validation)
        self.loop_num_passes: int | None = None
        self.cache_namespace = uuid4().hex
        self._native_binding: _NativeImageBinding | None = None

    def bind_loop_num_passes(self, count: int):
        if self.loop_num_passes is not None and self.loop_num_passes != count:
            raise ValueError(
                "Changing loop_num_passes requires a fresh V20 evidence context and KV cache"
            )
        self.loop_num_passes = count

    def state_inputs(self, batch_size: int, device: torch.device):
        """Return static-shape tensors (state, active_mask, absence_codes) for CUDA-graph-safe readout."""
        st = self.state_tensor.to(device=device, dtype=torch.float32)
        if st.shape[0] == 1 and batch_size > 1:
            st = st.expand(batch_size, -1, -1, -1)
        active_val = 1.0 if self.active else 0.0
        active_mask = torch.full((batch_size, 1, 1), active_val, device=device, dtype=torch.float32)
        absence_codes = (
            torch.full((batch_size,), self.absence_code, device=device, dtype=torch.long)
            if self.absence_code >= 0
            else None
        )
        return st, active_mask, absence_codes

    def validate_source_for_answer(self, *, allow_pending: bool = True) -> dict:
        if not self.requires_source_validation:
            return dict(self.grounding)
        if self.grounding.get("status") == "insufficient_evidence":
            raise SourceEvidenceError(self.grounding)
        if self.grounding.get("requires_native_image"):
            consumed = bool(getattr(self._native_binding, "consumed", False))
            if not consumed and not allow_pending:
                self.grounding.update(
                    status="insufficient_evidence",
                    reason="native_visual_input_required",
                )
                raise SourceEvidenceError(self.grounding)
        return dict(self.grounding)


def _resolve_source(store: EventStoreV20, ref, snapshot: int, budget: int):
    path = []
    current = ref
    while len(path) < budget:
        if type(current) is int:
            eid = current
        else:
            owners = store.lookup_reference(current, revision=snapshot)
            if len(owners) != 1:
                return path, "ambiguous_reference" if owners else "missing_reference"
            eid = owners[0]
        if eid in path:
            return path, "reference_cycle"
        try:
            meta = store.get(eid, revision=snapshot, include_images=False)
        except KeyError:
            return path, "missing_reference"
        path.append(eid)
        links = record_links(
            meta,
            directory=(not isinstance(current, int) and current[0] == "directory"),
        )
        if len(links) > 1:
            return path, "ambiguous_redirect"
        if not links:
            if not isinstance(current, int) and current[0] == "directory":
                return path, "missing_redirect"
            return path, None
        current = links[0]
    return path, "reference_budget_exhausted"


def _resolve_relation(store: EventStoreV20, spec: dict, snapshot: int, budget: int):
    predicates = spec["predicates"] if "predicates" in spec else [spec["predicate"]]
    subject = spec.get("subject")
    witnesses, seen, path, edges_read = [], set(), [], 0
    for predicate in predicates:
        pair = (subject, predicate)
        if pair in seen:
            return path, [], witnesses, "reference_cycle"
        seen.add(pair)
        if edges_read >= budget:
            return path, [], witnesses, "reference_budget_exhausted"
        ans = store.find_relations(subject, predicate, revision=snapshot, limit=budget - edges_read)
        edges = [e for e in ans["edges"] if e["origin"] == "asserted"]
        edges_read += len(ans["edges"])
        if ans["status"] in ("conflict", "incomplete") or not edges:
            witnesses.extend(ans["edges"])
            reason = {
                "conflict": "conflicting_relations",
                "incomplete": "reference_budget_exhausted",
            }.get(ans["status"], "unconfirmed_relation" if ans["edges"] else "missing_relation")
            return path, [], witnesses, reason
        edge = edges[0]
        witnesses.append(edge)
        if edge["source_event_id"] not in path:
            path.append(edge["source_event_id"])
        subject = edge["object"]
    if "terminal_kind" in spec:
        terminal, reason = _resolve_source(
            store, normalize_reference((spec["terminal_kind"], subject)), snapshot, budget - edges_read
        )
        return (
            list(dict.fromkeys(path + terminal)),
            terminal[-1:] if not reason else [],
            witnesses,
            reason,
        )
    return path, path[-1:], witnesses, None


def _extract_turn_parts(message: dict):
    content = message.get("content", "")
    if isinstance(content, str):
        return content, []
    texts, images = [], []
    for part in content:
        if not isinstance(part, dict):
            continue
        if part.get("type") == "text":
            texts.append(part.get("text", ""))
        elif part.get("type") == "image":
            img = part.get("image")
            if isinstance(img, bytes):
                images.append(img)
            elif isinstance(img, Image.Image):
                buf = io.BytesIO()
                img.save(buf, format="PNG")
                images.append(buf.getvalue())
    return "\n".join(t for t in texts if t), images


class InklingV20Memory:
    """High-level V20 persistent memory runtime for Inkling2 Loop checkpoints."""

    def __init__(self, model, processor, store: EventStoreV20, *, stem_id: str):
        self.model = model
        self.processor = processor
        self.store = store
        self.stem_id = stem_id
        self.components = components_for(model)
        ns = self.components.neural_state
        self._state_shape = (ns.state_heads, ns.state_key_dim, ns.state_value_dim)
        self._fast_heads = ns.fast_heads

    def view(self, *, branch: str | None = None, valid_at=...):
        return InklingV20Memory(
            self.model,
            self.processor,
            self.store.view(branch=branch, valid_at=valid_at),
            stem_id=self.stem_id,
        )

    def close(self):
        self.store.close()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()

    @torch.no_grad()
    def _encode_record(self, record: dict) -> dict:
        features = record.get("feature_blobs", ())
        if not features:
            states, spans = _source_parts(
                self.model, self.processor, record.get("text", ""), record.get("images", ())
            )
        else:
            pieces, spans = (
                _source_parts(self.model, self.processor, record.get("text", ""), ())
                if record.get("text")
                else (None, [])
            )
            parts = [] if pieces is None else [pieces]
            for i, blob in enumerate(features):
                desc = next(
                    s
                    for s in record["spans"]
                    if s.get("kind") == "projected_image" and s["index"] == i
                )
                if desc.get("stem_id") != self.stem_id:
                    raise ValueError("Projected-only evidence belongs to a different stem_id")
                feat = load(blob)["features"]
                parts.append(feat.to(device=_device(self.components), dtype=self.components.encoder.stem_in.weight.dtype))
                spans.append(desc)
            states = torch.cat(parts, dim=0)
        return self.components.encode_event(states.to(_device(self.components)), spans)

    @torch.no_grad()
    def neural_state(
        self,
        *,
        revision: int | None = None,
        max_replay_events: int = 128,
        persist: bool = False,
    ) -> tuple[torch.Tensor, int]:
        """Load latest branch neural state checkpoint <= revision and replay pending events."""
        snap = self.store.snapshot() if revision is None else revision
        marks = self.store.watermarks(snap)
        target_cursor = marks["source_cursor"]
        dev = _device(self.components)
        ckpt_cursor, fast_blob, slow_blob = self.store.load_state_checkpoint(target_cursor)
        state = _blobs_to_state(fast_blob, slow_blob, self._state_shape, self._fast_heads, dev)

        cursor = ckpt_cursor
        replayed = 0
        while cursor < target_cursor and replayed < max_replay_events:
            page = self.store.events(
                revision=snap, after=cursor, limit=min(32, max_replay_events - replayed)
            )
            if not page["event_ids"]:
                break
            for eid in page["event_ids"]:
                rec = self.store.get(eid, revision=snap, include_images=True)
                enc = self._encode_record(rec)
                # Online streaming populates ALL multi-timescale heads (fast working + slow long-horizon)
                state = self.components.advance_state(
                    state, enc["contextual"], stem_states=enc.get("stem"), target="both"
                )
                cursor = eid
                replayed += 1
                if persist and (replayed % _CHECKPOINT_INTERVAL == 0 or cursor == target_cursor):
                    fb, sb = _state_to_blobs(state, self._fast_heads)
                    self.store.save_state_checkpoint(cursor, fb, sb)
            if page["next_after"] is None:
                break
        if persist and replayed > 0:
            fb, sb = _state_to_blobs(state, self._fast_heads)
            self.store.save_state_checkpoint(cursor, fb, sb)
        return state, cursor

    def has_latent_state(self, *, revision: int | None = None) -> bool:
        """Return True when this branch carries non-empty latent memory (from events OR loaded .safetensors)."""
        snap = self.store.snapshot() if revision is None else revision
        marks = self.store.watermarks(snap)
        if marks["source_cursor"] > 0:
            return True
        return self.store.has_latent_base_state()

    @torch.no_grad()
    def drain_state(self, *, max_events: int = 128, revision: int | None = None) -> dict:
        snap = self.store.snapshot() if revision is None else revision
        _, cursor = self.neural_state(revision=snap, max_replay_events=max_events, persist=True)
        marks = self.store.watermarks(snap)
        return {
            **marks,
            "state_cursor": cursor,
            "has_latent_state": bool(cursor > 0 or self.store.has_latent_base_state()),
            "complete": cursor == marks["source_cursor"],
        }

    @torch.no_grad()
    def export_state_bytes(
        self,
        *,
        revision: int | None = None,
        dtype: str = "float16",
        drain: bool = True,
    ) -> tuple[bytes, dict]:
        """Serialize ONLY the portable latent memory state (m_fast, m_slow) to safetensors bytes (ZERO raw text!)."""
        dtype_map = {
            "float16": torch.float16,
            "fp16": torch.float16,
            "bfloat16": torch.bfloat16,
            "bf16": torch.bfloat16,
            "float32": torch.float32,
            "fp32": torch.float32,
        }
        if dtype not in dtype_map:
            raise ValueError(f"Unsupported state dtype {dtype!r}; expected float16, bfloat16, or float32")
        snap = self.store.snapshot() if revision is None else revision
        if drain:
            while True:
                dr = self.drain_state(max_events=256, revision=snap)
                if dr["complete"]:
                    break
        marks = self.store.watermarks(snap)
        state, cursor = self.neural_state(revision=snap, max_replay_events=0, persist=False)
        if not bool(torch.isfinite(state).all()):
            raise ValueError("Refusing to export non-finite latent memory state")
        cpu = state.detach().to(device="cpu", dtype=dtype_map[dtype]).contiguous()
        m_fast = cpu[: self._fast_heads].contiguous()
        m_slow = cpu[self._fast_heads :].contiguous()
        saved_at = dt.datetime.now(dt.timezone.utc).isoformat()
        state_digest = hashlib.sha256(state.detach().to(device="cpu", dtype=torch.float32).contiguous().numpy().tobytes()).hexdigest()
        header_meta = {
            "format": _PORTABLE_STATE_FORMAT,
            "stem_id": str(self.stem_id),
            "state_keyspace_id": str(self.store.state_keyspace_id),
            "state_shape": json.dumps(list(self._state_shape)),
            "fast_heads": str(self._fast_heads),
            "state_cursor": str(cursor),
            "source_count": str(marks["source_count"]),
            "bank_id": str(self.store.bank_id),
            "branch": str(self.store.branch),
            "dtype": dtype,
            "state_digest": state_digest,
            "saved_at": saved_at,
            "contains_raw_transcript": "false",
        }
        raw = save({"m_fast": m_fast, "m_slow": m_slow}, metadata=header_meta)
        info = {
            "format": _PORTABLE_STATE_FORMAT,
            "bytes": len(raw),
            "sha256": hashlib.sha256(raw).hexdigest(),
            "state_digest": state_digest,
            "stem_id": self.stem_id,
            "state_keyspace_id": self.store.state_keyspace_id,
            "state_shape": list(self._state_shape),
            "fast_heads": self._fast_heads,
            "state_cursor": cursor,
            "source_count": marks["source_count"],
            "dtype": dtype,
            "saved_at": saved_at,
            "contains_raw_transcript": False,
        }
        return raw, info

    @torch.no_grad()
    def save_state_safetensors(
        self,
        path,
        *,
        revision: int | None = None,
        dtype: str = "float16",
        drain: bool = True,
    ) -> dict:
        """Save portable standalone .safetensors latent memory snapshot (zero conversation text stored)."""
        target = Path(path)
        target.parent.mkdir(parents=True, exist_ok=True)
        raw, info = self.export_state_bytes(revision=revision, dtype=dtype, drain=drain)
        tmp = target.with_name(f".{target.name}.{uuid4().hex[:8]}.tmp")
        tmp.write_bytes(raw)
        tmp.replace(target)
        return {**info, "path": str(target)}

    @torch.no_grad()
    def import_state_bytes(
        self,
        raw: bytes,
        *,
        strict_keyspace: bool = True,
        clear_existing_events: bool = False,
    ) -> dict:
        """Load portable .safetensors latent memory state into this bank (works even with 0 raw events!)."""
        header = _read_safetensors_header(raw)
        meta = header.get("__metadata__") or {}
        if meta.get("format") != _PORTABLE_STATE_FORMAT:
            raise ValueError(f"Unsupported portable V20 state format: {meta.get('format')!r}")
        if strict_keyspace:
            if meta.get("stem_id") != self.stem_id:
                raise ValueError("Portable state stem_id disagrees with loaded V20 checkpoint")
            if meta.get("state_keyspace_id") != self.store.state_keyspace_id:
                raise ValueError("Portable state state_keyspace_id disagrees with loaded V20 checkpoint")
        tensors = load(raw)
        if "m_fast" not in tensors or "m_slow" not in tensors:
            raise ValueError("Portable V20 state file must contain 'm_fast' and 'm_slow' tensors")
        m_fast = tensors["m_fast"].detach().to(device="cpu", dtype=torch.float32).contiguous()
        m_slow = tensors["m_slow"].detach().to(device="cpu", dtype=torch.float32).contiguous()
        full = torch.cat((m_fast, m_slow), dim=0)
        if tuple(full.shape) != tuple(self._state_shape) or int(m_fast.shape[0]) != int(self._fast_heads):
            raise ValueError(
                f"Portable state shape {tuple(full.shape)} (fast={m_fast.shape[0]}) "
                f"disagrees with model shape {self._state_shape} (fast={self._fast_heads})"
            )
        if not bool(torch.isfinite(full).all()):
            raise ValueError("Portable state contains non-finite values")
        fb, sb = _state_to_blobs(full, self._fast_heads)
        load_meta = {
            "format": _PORTABLE_STATE_FORMAT,
            "loaded_at": dt.datetime.now(dt.timezone.utc).isoformat(),
            "source_meta": meta,
            "sha256": hashlib.sha256(raw).hexdigest(),
        }
        cleared = None
        if clear_existing_events:
            cleared = self.store.clear_transcript_keep_latent(fb, sb, metadata=load_meta)
        else:
            self.store.save_latent_base_state(fb, sb, metadata=load_meta, clear_checkpoints=True)
        marks = self.store.watermarks()
        state_digest = hashlib.sha256(full.numpy().tobytes()).hexdigest()
        return {
            "status": "loaded",
            "bank": self.store.bank_id,
            "branch": self.store.branch,
            "state_shape": list(self._state_shape),
            "fast_heads": self._fast_heads,
            "state_digest": state_digest,
            "sha256": load_meta["sha256"],
            "source_count": marks["source_count"],
            "has_latent_state": True,
            "cleared_events": cleared["removed_events"] if cleared else 0,
            "source_meta": meta,
        }

    @torch.no_grad()
    def load_state_safetensors(
        self,
        path,
        *,
        strict_keyspace: bool = True,
        clear_existing_events: bool = False,
    ) -> dict:
        """Load a portable .safetensors memory state file into this bank."""
        src = Path(path)
        if not src.is_file():
            raise FileNotFoundError(src)
        res = self.import_state_bytes(
            src.read_bytes(),
            strict_keyspace=strict_keyspace,
            clear_existing_events=clear_existing_events,
        )
        return {**res, "path": str(src)}

    @torch.no_grad()
    def clear_transcript(self, *, revision: int | None = None) -> dict:
        """Freeze current latent neural state and purge 100% of raw conversation records from this bank."""
        snap = self.store.snapshot() if revision is None else revision
        while True:
            dr = self.drain_state(max_events=256, revision=snap)
            if dr["complete"]:
                break
        state, cursor = self.neural_state(revision=snap, max_replay_events=0, persist=False)
        fb, sb = _state_to_blobs(state, self._fast_heads)
        state_digest = hashlib.sha256(
            state.detach().to(device="cpu", dtype=torch.float32).contiguous().numpy().tobytes()
        ).hexdigest()
        res = self.store.clear_transcript_keep_latent(
            fb,
            sb,
            metadata={
                "format": _PORTABLE_STATE_FORMAT,
                "detached_at": dt.datetime.now(dt.timezone.utc).isoformat(),
                "previous_cursor": cursor,
                "state_digest": state_digest,
            },
        )
        return {**res, "state_digest": state_digest}

    @torch.no_grad()
    def remember(
        self,
        *,
        occurrence_id: str,
        text: str = "",
        images=(),
        spans=(),
        source_role: str = "user",
        observed_at: int | None = None,
        valid_time=None,
        turn_hash: str = "",
        expected_parent: int | None = None,
        relations=(),
        defer_index: bool = False,
        commit_slow: bool = False,
    ) -> int:
        images = tuple(images)
        if any(not isinstance(img, bytes) for img in images):
            raise TypeError("remember() accepts original encoded image bytes")
        if defer_index:
            return self.store.append(
                occurrence_id=occurrence_id,
                text=text,
                images=images,
                spans=[*_source_geometry(self.processor, text, images), *spans],
                source_role=source_role,
                observed_at=observed_at,
                valid_time=valid_time,
                turn_hash=turn_hash,
                expected_parent=expected_parent,
                relations=relations,
            )

        states, geom = _source_parts(self.model, self.processor, text, images)
        enc = self.components.encode_event(states.to(_device(self.components)), geom)
        eid = self.store.append(
            occurrence_id=occurrence_id,
            text=text,
            images=images,
            spans=[*geom, *spans],
            key=enc["key"].tolist(),
            region_keys=enc["regions"].tolist(),
            region_meta=enc["region_meta"],
            source_role=source_role,
            observed_at=observed_at,
            valid_time=valid_time,
            turn_hash=turn_hash,
            expected_parent=expected_parent,
            relations=relations,
        )
        # Advance branch two-timescale neural state (idempotent if eid already checkpointed)
        ckpt_cursor, fast_blob, slow_blob = self.store.load_state_checkpoint(eid)
        if ckpt_cursor == eid:
            return eid
        parent = int(self.store.get(eid, include_images=False)["parent"])
        dev = _device(self.components)
        if ckpt_cursor < parent:
            parent_rev = int(self.store.get(parent, include_images=False)["revision"])
            state, _ = self.neural_state(revision=parent_rev, persist=True)
        else:
            state = _blobs_to_state(fast_blob, slow_blob, self._state_shape, self._fast_heads, dev)
        state = self.components.advance_state(
            state, enc["contextual"], stem_states=enc.get("stem"), target="both"
        )
        fb, sb = _state_to_blobs(state, self._fast_heads)
        self.store.save_state_checkpoint(eid, fb, sb)
        return eid

    @torch.no_grad()
    def index_page(self, *, revision: int | None = None, after: int = 0, limit: int = 128) -> dict:
        def encode(record):
            enc = self._encode_record(record)
            return {
                "key": enc["key"].tolist(),
                "region_keys": enc["regions"].tolist(),
                "region_meta": enc["region_meta"],
            }

        page = self.store.rebuild(encode, revision=revision, after=after, limit=limit)
        st = self.drain_state(max_events=limit)
        return {**page, "neural_state": st}

    @torch.no_grad()
    def retrieve_multihop(
        self,
        *,
        text: str = "",
        query_images=(),
        revision: int | None = None,
        k: int = 6,
        max_hops: int = 2,
        mode: str = "fast",
        candidate_budget: int = 256,
        event_ids=(),
        source_reference=None,
        relation_query=None,
        require_source: str | None = None,
        use_neural_state: bool = True,
        enable_crop_zoom: bool = True,
        zoom_threshold: float = 0.65,
        expand_neighbors: int = 1,
    ) -> dict:
        """Pre-prefill 1-3 hop router (<5 ms): resolves exact locators or runs adaptive 5-route + hop reformulation."""
        snap = self.store.snapshot() if revision is None else revision
        state_tensor, state_cursor = (
            self.neural_state(revision=snap, persist=False)
            if use_neural_state
            else (self.components.neural_state.zero_state(device=_device(self.components)), 0)
        )
        refs = []
        if source_reference is not None:
            refs = [normalize_reference(source_reference)]
        elif require_source != "off" and text:
            refs = query_references(text)

        event_ids = tuple(dict.fromkeys(event_ids))
        required = None if require_source == "off" else require_source
        if required is None and require_source != "off" and (refs or event_ids or relation_query is not None):
            if re.search(
                r"\b(?:photographs?|photos?|pictures?|images?)\b|照片|圖片|图片|圖像|图像|影像",
                text,
                re.I,
            ):
                required = "image"
            elif refs or relation_query is not None:
                required = "event"

        grounding = {
            "required": required,
            "status": "pending" if required else "not_required",
            "reason": None,
            "revision": snap,
            "bank_id": self.store.bank_id,
            "branch": self.store.branch,
            "valid_at": self.store.valid_at,
            "source_reference": {"kind": refs[0][0], "key": refs[0][1]} if len(refs) == 1 else None,
            "path": [],
            "target_event_ids": [],
            "evidence_ids": [],
            "visual_event_ids": [],
            "card_ids": [],
            "crops": [],
            "requires_native_image": False,
            "native_visual_consumed": False,
            "source_identity": "explicit"
            if (refs or event_ids or relation_query is not None)
            else "semantic_candidates",
        }
        trace = []

        # Path A: Explicit locator / relation / event_ids
        if refs or event_ids or relation_query is not None:
            if relation_query is not None:
                path, targets, witnesses, reason = _resolve_relation(
                    self.store, relation_query, snap, candidate_budget
                )
                grounding["relations"] = witnesses
            elif refs:
                if len(refs) > 1:
                    path, targets, reason = [], [], "multiple_references"
                else:
                    path, reason = _resolve_source(self.store, refs[0], snap, candidate_budget)
                    targets = path[-1:] if reason is None else []
                    if targets and event_ids and targets[0] not in event_ids:
                        reason = "source_reference_mismatch"
            else:
                path = targets = list(event_ids)
                reason = None

            if reason is None:
                for eid in targets:
                    try:
                        rec = self.store.get(eid, revision=snap, include_images=False)
                    except KeyError:
                        reason = "missing_reference"
                        break
                    if required == "image" and not (rec["image_digests"] or rec["feature_digests"]):
                        reason = "missing_image"
                        break

            grounding.update(path=list(path), target_event_ids=list(targets), reason=reason)
            if reason is not None:
                grounding["status"] = "insufficient_evidence"
                raise SourceEvidenceError(grounding)

            selected_ids = list(dict.fromkeys(path))[:k]
            records = [self.store.get(eid, revision=snap, include_images=True) for eid in selected_ids]
            visual_ids = [r["event_id"] for r in records if r["images"] or r["feature_blobs"]]
            grounding.update(
                status="grounded",
                evidence_ids=selected_ids,
                visual_event_ids=visual_ids,
                requires_native_image=bool(required == "image" or visual_ids),
            )
            trace.append({"hop": 1, "action": "explicit_resolve", "evidence_ids": selected_ids})
            return {
                "revision": snap,
                "state_tensor": state_tensor,
                "state_cursor": state_cursor,
                "records": records,
                "neighbor_records": [],
                "cards": [],
                "crops": [],
                "grounding": grounding,
                "trace": trace,
                "absence_code": -1 if records else 2,
            }

        # Path B: Pre-prefill neural 1-3 hop adaptive retrieval with query-intent coverage & session balancing
        q_states, q_spans = _source_parts(self.model, self.processor, text, query_images)
        q_pack = self.components.encode_query(
            q_states.to(_device(self.components)),
            q_spans,
            state=state_tensor if use_neural_state else None,
        )
        route_w = q_pack["route_weights"].tolist()
        has_q_img = q_pack["has_query_image"]
        pure_region = bool(has_q_img and len(text.strip()) < 48)

        intent = _classify_query_intent(text) if (text and not pure_region) else {
            "is_aggregation": False, "is_temporal": False, "is_preference": False
        }
        subclauses = _extract_subclauses(text) if (text and not pure_region) else []
        marks = self.store.watermarks(snap)
        visible_events = int(marks.get("source_count", 0))
        eff_k = int(k)
        if not pure_region and visible_events >= 16:
            if intent["is_aggregation"] or subclauses:
                eff_k = min(18, max(eff_k, 14))
            elif intent["is_temporal"] or intent["is_preference"]:
                eff_k = min(16, max(eff_k, 12))

        selected_order: list[int] = []
        hit_meta: dict[int, dict] = {}
        session_counts: Counter = Counter()
        rec_meta_cache: dict[int, dict] = {}

        def _get_rec_light(eid: int) -> dict:
            rec = rec_meta_cache.get(eid)
            if rec is None:
                rec = self.store.get(eid, revision=snap, include_images=False)
                rec_meta_cache[eid] = rec
            return rec

        q_cls = q_pack["q_cls"]
        q_sem = q_pack["q_sem"]
        zoom_query = q_pack["zoom_query"]
        zoom_prob = float(q_pack["zoom_prob"].item())
        num_hops = max(1, min(int(max_hops), 3))
        if pure_region or eff_k <= 2:
            num_hops = 1
        hop_bridge_terms: list[str] = []
        base_salient = set(_salient_terms(text, is_query=True)) if text else set()

        for hop in range(1, num_hops + 1):
            remaining = eff_k - len(selected_order)
            if remaining <= 0:
                break
            # Explicit per-hop slot budget so Hop 2 / Hop 3 always execute and bring in bridge events
            if hop < num_hops and remaining >= 2:
                hop_k = max(1, math.ceil(remaining * 0.6))
            else:
                hop_k = remaining

            hop_terms = ()
            if hop == 1:
                if text:
                    hop_terms = [text]
            elif hop_bridge_terms:
                # Combine original query context with newly discovered Hop-(h-1) salient bridge terms
                hop_terms = [text, " ".join(hop_bridge_terms[:24])] if text else [" ".join(hop_bridge_terms[:24])]
            elif text:
                hop_terms = [text]

            pool_k = min(max(hop_k * 3, 24), 48) if not pure_region else max(hop_k, 4)
            res = self.store.search(
                q_sem.tolist(),
                k=pool_k,
                mode=mode,
                revision=snap,
                terms=hop_terms,
                region_query=q_pack["q_regions"].tolist() if hop == 1 else None,
                state_query=q_pack["q_state"].tolist() if (hop == 1 and q_pack["q_state"] is not None) else None,
                route_weights=route_w,
                pure_region_mode=pure_region if hop == 1 else False,
                candidate_budget=max(64, candidate_budget),
                exclude_event_ids=set(hit_meta) if hop > 1 else None,
            )

            # Clause-split dual-target interleaving in Hop 1 (e.g., "between A and B", "both X and Y in common")
            candidate_hits = list(res["hits"])
            if hop == 1 and subclauses and not pure_region:
                sub_lists = []
                for sc_text in subclauses[:2]:
                    sub_res = self.store.search(
                        q_sem.tolist(),
                        k=max(6, eff_k // 2),
                        mode=mode,
                        revision=snap,
                        terms=[sc_text],
                        region_query=None,
                        state_query=None,
                        route_weights=route_w,
                        pure_region_mode=False,
                        candidate_budget=max(64, candidate_budget),
                    )
                    sub_lists.append(sub_res["hits"])
                # Interleave full-query hits and both sub-clause hit lists (deduplicated) so neither target starves
                interleaved = []
                seen_cand = set()
                max_len = max([len(candidate_hits)] + [len(sl) for sl in sub_lists])
                for idx_c in range(max_len):
                    for lst in (candidate_hits, *sub_lists):
                        if idx_c < len(lst):
                            h_item = lst[idx_c]
                            eid_c = h_item["event_id"]
                            if eid_c not in seen_cand:
                                seen_cand.add(eid_c)
                                interleaved.append(h_item)
                candidate_hits = interleaved

            # Determine chunk-length-aware per-session coverage cap so multi-chunk sessions never starve other sessions
            use_session_div = (
                not pure_region
                and len(candidate_hits) > hop_k
                and (intent["is_aggregation"] or intent["is_temporal"] or intent["is_preference"] or visible_events >= 24)
            )
            hop_ids = []
            if use_session_div:
                sample_lens = [len(_get_rec_light(h["event_id"]).get("text", "")) for h in candidate_hits[:12]]
                med_len = sorted(sample_lens)[len(sample_lens) // 2] if sample_lens else 0
                pass_caps = (1, 2, 1000) if med_len > 500 else ((2, 4, 1000) if (intent["is_aggregation"] or intent["is_temporal"]) else (3, 1000))
                for cap in pass_caps:
                    if len(hop_ids) >= hop_k or len(selected_order) >= eff_k:
                        break
                    for h in candidate_hits:
                        eid = h["event_id"]
                        if eid in hit_meta:
                            continue
                        skey = _extract_session_key(_get_rec_light(eid))
                        if session_counts[skey] >= cap:
                            continue
                        hit_meta[eid] = h
                        session_counts[skey] += 1
                        selected_order.append(eid)
                        hop_ids.append(eid)
                        if len(hop_ids) >= hop_k or len(selected_order) >= eff_k:
                            break
            else:
                for h in candidate_hits:
                    eid = h["event_id"]
                    if eid not in hit_meta:
                        hit_meta[eid] = h
                        if len(hop_ids) < hop_k and len(selected_order) < eff_k:
                            skey = _extract_session_key(_get_rec_light(eid))
                            session_counts[skey] += 1
                            selected_order.append(eid)
                            hop_ids.append(eid)

            # Follow explicit relation links attached to newly discovered hop events
            for eid in list(hop_ids):
                if len(selected_order) >= eff_k:
                    break
                rec = _get_rec_light(eid)
                for link in record_links(rec):
                    if len(selected_order) >= eff_k:
                        break
                    target_eids = [link] if isinstance(link, int) else self.store.lookup_reference(link, revision=snap)
                    for teid in target_eids:
                        if teid not in hit_meta and len(selected_order) < eff_k:
                            hit_meta[teid] = {"event_id": teid, "score": 0.99, "via": "relation_link"}
                            selected_order.append(teid)
                            hop_ids.append(teid)
            trace.append(
                {
                    "hop": hop,
                    "ranking": res["ranking"],
                    "route_weights": [round(x, 4) for x in route_w],
                    "hits": [h["event_id"] for h in res["hits"][: max(hop_k, 8)]],
                    "selected": list(hop_ids),
                    "scanned": res["scanned"],
                }
            )
            if hop < num_hops and hop_ids and len(selected_order) < eff_k:
                # Neural hop reformulation (<1 ms on GPU, zero LLM prefill!) + lexical bridge term extraction
                hop_key_vecs = []
                new_bridge = []
                for eid in hop_ids[:6]:
                    kd = self.store.get_key(eid, revision=snap)
                    if kd is not None:
                        hop_key_vecs.append(kd["key"])
                    rec = _get_rec_light(eid)
                    for term in _salient_terms(rec.get("text", "")):
                        if term not in base_salient and term not in new_bridge:
                            new_bridge.append(term)
                hop_bridge_terms = new_bridge[:24]
                if hop_key_vecs:
                    hk = torch.tensor(hop_key_vecs, device=_device(self.components), dtype=torch.float32)
                    ref = self.components.reformulate_hop(q_cls, hk)
                    q_cls, q_sem = ref["q_cls"], ref["q_sem"]
                    zoom_query, zoom_prob = ref["zoom_query"], float(ref["zoom_prob"].item())

        records = [self.store.get(eid, revision=snap, include_images=True) for eid in selected_order]
        active_cards = self.store.list_cards(status="active", revision=snap, limit=8)

        # Adjacent-turn neighbor expansion for short single-turn dialogue events (skip on already-chunked long records)
        neighbor_records: list[dict] = []
        if expand_neighbors > 0 and records and not pure_region:
            seen_eids = set(selected_order)
            max_neighbors = max(8, 2 * len(records))
            for rec in records:
                if len(neighbor_records) >= max_neighbors:
                    break
                if rec.get("images") or len(rec.get("text", "")) > 500:
                    continue
                for neid in self.store.get_neighbors(rec["event_id"], window=expand_neighbors, revision=snap):
                    if neid in seen_eids or len(neighbor_records) >= max_neighbors:
                        continue
                    nrec = self.store.get(neid, revision=snap, include_images=False)
                    if nrec.get("image_digests") or nrec.get("feature_digests"):
                        continue
                    ntxt = nrec.get("text", "").strip()
                    if not ntxt or len(ntxt) > 500:
                        continue
                    seen_eids.add(neid)
                    neighbor_records.append(nrec)

        # Single-prefill 2D visual crop zoom selection (if high-confidence local region matched)
        crops = []
        if enable_crop_zoom:
            zq_list = zoom_query.tolist()
            for rec in records:
                if not rec["images"]:
                    continue
                kd = self.store.get_key(rec["event_id"], revision=snap)
                if not kd or not kd["regions"]:
                    continue
                best_box, best_idx, best_score = None, 0, -2.0
                for vec, meta in zip(kd["regions"], kd["region_meta"]):
                    if meta.get("kind") != "image" or meta.get("scale") == "1x1":
                        continue
                    sc = sum(a * b for a, b in zip(zq_list, vec))
                    if sc > best_score:
                        best_score = sc
                        best_box = meta.get("norm_box")
                        best_idx = int(meta.get("image_index", 0))
                if best_box is not None and (zoom_prob >= zoom_threshold or has_q_img):
                    im = _image(rec["images"][best_idx])
                    w, h = im.size
                    x0 = max(0, math.floor(best_box[0] * w))
                    y0 = max(0, math.floor(best_box[1] * h))
                    x1 = min(w, math.ceil(best_box[2] * w))
                    y1 = min(h, math.ceil(best_box[3] * h))
                    if x1 > x0 and y1 > y0 and not (x0 == 0 and y0 == 0 and x1 == w and y1 == h):
                        buf = io.BytesIO()
                        im.crop((x0, y0, x1, y1)).save(buf, format="PNG")
                        crops.append(
                            {
                                "event_id": rec["event_id"],
                                "image_index": best_idx,
                                "norm_box": best_box,
                                "pixel_box": [x0, y0, x1, y1],
                                "bytes": buf.getvalue(),
                            }
                        )

        visual_ids = [r["event_id"] for r in records if r["images"] or r["feature_blobs"]]
        if required == "image" and not visual_ids:
            grounding.update(status="insufficient_evidence", reason="no_visual_candidate")
            raise SourceEvidenceError(grounding)

        grounding.update(
            status="grounded" if (records or active_cards or not required) else "insufficient_evidence",
            evidence_ids=[r["event_id"] for r in records],
            visual_event_ids=visual_ids,
            card_ids=[c["card_id"] for c in active_cards],
            crops=[{k: v for k, v in c.items() if k != "bytes"} for c in crops],
            requires_native_image=bool(required == "image" or visual_ids),
        )
        has_latent = bool(use_neural_state and (state_cursor > 0 or self.store.has_latent_base_state()))
        absence_code = -1 if (records or active_cards or has_latent) else 2
        return {
            "revision": snap,
            "state_tensor": state_tensor,
            "state_cursor": state_cursor,
            "has_latent_state": has_latent,
            "records": records,
            "neighbor_records": neighbor_records,
            "cards": active_cards,
            "crops": crops,
            "grounding": grounding,
            "trace": trace,
            "absence_code": absence_code,
        }

    def _format_recall_block(
        self,
        records: list[dict],
        cards: list[dict],
        max_recall_tokens: int,
        *,
        neighbor_records: list[dict] = (),
        query_text: str = "",
    ) -> str:
        if not records and not cards:
            return ""
        tok = self.processor.tokenizer
        card_lines = [
            f"[card:{card['card_id']} {card['card_type']} {card['subject']}.{card['predicate']}] {card['content']}"
            for card in cards
        ]
        query_ref_date = _parse_query_ref_date(query_text)
        q_salient = _salient_terms(query_text, is_query=True) if query_text else []
        q_terms = set(q_salient)
        q_stems = {_light_stem(t) for t in q_salient}

        def _tok_len(s: str) -> int:
            return len(tok(s, add_special_tokens=False)["input_ids"])

        header = "\n".join(["<v20_recall>", *card_lines, "</v20_recall>"])
        cur_len = _tok_len(header)
        budget = max(32, int(max_recall_tokens)) - 6

        # Pack in RELEVANCE-RANK order first so high-event-id Rank #1 hits are NEVER truncated when sorting chronologically!
        # When packing many long multi-session chunks, compact verbose secondary chunks so all distinct sessions fit.
        included: dict[int, tuple[dict, str]] = {}
        total_core = len(records)
        for rank_idx, rec in enumerate(records):
            eid = int(rec["event_id"])
            raw_txt = rec.get("text", "").strip()
            if eid in included or not raw_txt:
                continue
            line = format_event_recall_line(rec, query_ref_date=query_ref_date) + "\n"
            add_toks = _tok_len(line)
            remaining_hits = max(1, total_core - rank_idx)
            remaining_budget = max(0, budget - cur_len)
            if (
                included
                and (cur_len + add_toks > budget or (remaining_hits >= 4 and add_toks > max(260, int(remaining_budget * 0.40))))
                and len(raw_txt) > 900
                and "\n" in raw_txt
            ):
                compacted = _compact_event_text(raw_txt, q_terms, q_stems, max_chars=820)
                c_line = format_event_recall_line(rec, query_ref_date=query_ref_date, override_text=compacted) + "\n"
                c_toks = _tok_len(c_line)
                if c_toks < add_toks:
                    line, add_toks = c_line, c_toks
            if not included or cur_len + add_toks <= budget:
                included[eid] = (rec, line.rstrip("\n"))
                cur_len += add_toks

        if neighbor_records and cur_len < budget - 10:
            for nrec in neighbor_records:
                neid = int(nrec["event_id"])
                if neid in included or not nrec.get("text", "").strip():
                    continue
                line = format_event_recall_line(nrec, query_ref_date=query_ref_date) + "\n"
                add_toks = _tok_len(line)
                if cur_len + add_toks <= budget:
                    included[neid] = (nrec, line.rstrip("\n"))
                    cur_len += add_toks

        # Render the surviving within-budget events strictly chronologically (event_id ASC)
        lines = ["<v20_recall>", *card_lines]
        for eid in sorted(included.keys()):
            lines.append(included[eid][1])
        lines.append("</v20_recall>")
        block = "\n".join(lines)

        ids = tok(block, add_special_tokens=False)["input_ids"]
        if len(ids) > max_recall_tokens:
            trimmed = tok.decode(ids[: max(16, max_recall_tokens - 6)], skip_special_tokens=False)
            block = trimmed + "\n</v20_recall>"
        return block

    @torch.no_grad()
    def prepare_generation(
        self,
        messages: list[dict],
        *,
        text: str | None = None,
        reasoning_effort: str = "none",
        loop_num_passes: int | None = None,
        channel_a_enabled: bool = True,
        use_neural_state: bool = True,
        max_recall_tokens: int = 1536,
        **retrieval_options,
    ):
        """Single-prefill RadixCache-friendly preparation: splices <v20_recall> + native images at final user turn."""
        if not messages or messages[-1].get("role") != "user":
            raise ValueError("prepare_generation requires messages ending with a user turn")

        last_text, last_images = _extract_turn_parts(messages[-1])
        query_text = last_text if text is None else text

        explicit_grounding = bool(
            retrieval_options.get("event_ids")
            or retrieval_options.get("source_reference") is not None
            or retrieval_options.get("relation_query") is not None
            or retrieval_options.get("require_source") in ("event", "image")
        )
        if not channel_a_enabled and not explicit_grounding:
            # Pure-Latent Channel-B fast path: skip Channel-A index search and read directly from NeuralStateV20!
            snap = (
                self.store.snapshot()
                if retrieval_options.get("revision") is None
                else retrieval_options["revision"]
            )
            state_tensor, state_cursor = (
                self.neural_state(revision=snap, persist=False)
                if use_neural_state
                else (self.components.neural_state.zero_state(device=_device(self.components)), 0)
            )
            has_latent = bool(use_neural_state and (state_cursor > 0 or self.store.has_latent_base_state()))
            bundle = {
                "revision": snap,
                "state_tensor": state_tensor,
                "state_cursor": state_cursor,
                "has_latent_state": has_latent,
                "records": [],
                "neighbor_records": [],
                "cards": [],
                "crops": [],
                "grounding": {
                    "required": None,
                    "status": "not_required",
                    "reason": None,
                    "revision": snap,
                    "bank_id": self.store.bank_id,
                    "branch": self.store.branch,
                    "valid_at": self.store.valid_at,
                    "source_reference": None,
                    "path": [],
                    "target_event_ids": [],
                    "evidence_ids": [],
                    "visual_event_ids": [],
                    "card_ids": [],
                    "crops": [],
                    "requires_native_image": False,
                    "native_visual_consumed": False,
                    "source_identity": "pure_latent_state",
                },
                "trace": [
                    {
                        "hop": 0,
                        "action": "pure_latent_state",
                        "state_cursor": state_cursor,
                        "has_latent_state": has_latent,
                    }
                ],
                "absence_code": -1 if has_latent else 2,
            }
        else:
            bundle = self.retrieve_multihop(
                text=query_text,
                query_images=last_images,
                use_neural_state=use_neural_state,
                **retrieval_options,
            )
        recall_text = (
            self._format_recall_block(
                bundle["records"],
                bundle["cards"],
                max_recall_tokens,
                neighbor_records=bundle.get("neighbor_records", ()),
                query_text=query_text,
            )
            if channel_a_enabled
            else ""
        )

        # Preserve messages[:-1] untouched so SGLang RadixCache hits >95% on multi-turn history!
        inputs_messages = list(messages)
        user_msg = dict(inputs_messages[-1])
        orig_content = user_msg.get("content", "")
        if isinstance(orig_content, str):
            content_parts = [{"type": "text", "text": orig_content}]
        else:
            content_parts = list(orig_content)

        prefix_parts = []
        retrieved_images = []  # (event_id, PIL.Image, label)
        if channel_a_enabled:
            if recall_text:
                prefix_parts.append({"type": "text", "text": recall_text + "\n"})
            for rec in bundle["records"]:
                for idx, raw in enumerate(rec.get("images", ())):
                    retrieved_images.append(
                        (rec["event_id"], _image(raw), f"Archived event {rec['event_id']}, image {idx + 1}:")
                    )
            for crop in bundle["crops"]:
                retrieved_images.append(
                    (
                        crop["event_id"],
                        _image(crop["bytes"]),
                        f"Zoomed region of event {crop['event_id']} box {crop['pixel_box']}:",
                    )
                )
            for _, im, label in retrieved_images:
                prefix_parts.append({"type": "text", "text": label})
                prefix_parts.append({"type": "image", "image": im})

        if prefix_parts:
            user_msg["content"] = prefix_parts + content_parts
            inputs_messages[-1] = user_msg

        device = _device(self.model.get_input_embeddings())
        batch = self.processor.apply_chat_template(
            inputs_messages,
            tokenize=True,
            add_generation_prompt=True,
            return_tensors="pt",
            return_dict=True,
            reasoning_effort=reasoning_effort,
        )
        inputs = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in batch.items()}

        # Precompute visual features once and bind native image verification if images were injected
        native_binding_targets = []
        if "pixel_values" in inputs and "image_grid_thw" in inputs:
            grids = inputs["image_grid_thw"].cpu().tolist()
            counts = [math.prod(g) for g in grids]
            token_id = self.model.config.image_token_id
            ids = inputs["input_ids"][0]
            positions = (ids == token_id).nonzero().flatten()
            patches = inputs.pop("pixel_values").split(counts)
            param = next(self.model.model.vision_tower.parameters())
            proj_dtype = self.model.get_input_embeddings().weight.dtype
            vectors = []
            for i in range(len(grids)):
                enc = self.model.get_image_features(
                    patches[i].to(device=param.device, dtype=param.dtype),
                    inputs["image_grid_thw"][i : i + 1],
                    return_dict=True,
                )
                vectors.append(enc.pooler_output[0].to(device=device, dtype=proj_dtype))
            from transformers.modeling_outputs import BaseModelOutputWithPooling

            inputs["mm_encoder_outputs"] = {
                "image": BaseModelOutputWithPooling(pooler_output=tuple(vectors))
            }
            if retrieved_images:
                # Preceding history images come before the final user turn's injected retrieved images
                prior_imgs = sum(
                    1
                    for m in inputs_messages[:-1]
                    if isinstance(m.get("content"), list)
                    for p in m["content"]
                    if isinstance(p, dict) and p.get("type") == "image"
                )
                groups = positions.split([len(v) for v in vectors])
                for j, (eid, _, _) in enumerate(retrieved_images):
                    img_slot_idx = prior_imgs + j
                    if img_slot_idx < len(groups):
                        slots = groups[img_slot_idx]
                        native_binding_targets.append(
                            (int(slots[0]), eid, vectors[img_slot_idx].detach().clone())
                        )

        scope = {
            "bank": self.store.bank_id,
            "branch": self.store.branch,
            "valid_at": self.store.valid_at,
            "revision": bundle["revision"],
            "index_keyspace_id": self.store.index_keyspace_id,
            "state_keyspace_id": self.store.state_keyspace_id,
            "state_cursor": bundle["state_cursor"],
        }
        ctx = V20EvidenceContext(
            state_tensor=bundle["state_tensor"],
            active=use_neural_state,
            absence_code=bundle["absence_code"],
            scope=scope,
            grounding=bundle["grounding"],
            trace=bundle["trace"],
            recall_text=recall_text,
            channel_a_enabled=channel_a_enabled,
            requires_source_validation=bool(bundle["grounding"].get("required")),
        )
        if loop_num_passes is not None:
            ctx.bind_loop_num_passes(int(loop_num_passes))
        if native_binding_targets:
            ctx._native_binding = _NativeImageBinding(ctx, native_binding_targets)
        return inputs, ctx


class AutoSessionV20:
    """Zero-config conversational memory manager with prefix-diff ingestion and RP swipe/edit auto-forking."""

    def __init__(self, memory: InklingV20Memory):
        self.memory = memory

    def sync_conversation(self, messages: list[dict], *, auto_fork: bool = True) -> dict:
        """Align incoming OpenAI messages with current branch; fork cleanly on edits/swipes, ingest new turns."""
        turns = []
        for msg in messages:
            role = msg.get("role", "user")
            if role == "system":
                continue
            txt, imgs = _extract_turn_parts(msg)
            if not txt.strip() and not imgs:
                continue
            turns.append((role, txt, imgs, _turn_hash(role, txt, imgs)))

        lineage = self.memory.store.branch_turn_lineage()
        common = 0
        for (_, h_stored), (_, _, _, h_in) in zip(lineage, turns):
            if h_stored != h_in:
                break
            common += 1

        forked_branch = None
        if common < len(lineage):
            if not auto_fork:
                raise ValueError(
                    f"Incoming conversation diverged from branch {self.memory.store.branch!r} at turn {common}"
                )
            fork_event_id = lineage[common - 1][0] if common > 0 else 0
            forked_branch = f"auto-{uuid4().hex[:8]}"
            self.memory.store.fork(forked_branch, from_event_id=fork_event_id)
            old_store = self.memory.store
            self.memory.store = old_store.view(branch=forked_branch)
            old_store.close()

        committed = []
        for idx in range(common, len(turns)):
            role, txt, imgs, th = turns[idx]
            occ_id = f"turn-{idx:05d}-{th[:12]}"
            eid = self.memory.remember(
                occurrence_id=occ_id,
                text=txt,
                images=imgs,
                source_role=role,
                turn_hash=th,
            )
            committed.append(eid)

        return {
            "branch": self.memory.store.branch,
            "forked_branch": forked_branch,
            "matched_prefix_turns": common,
            "committed_event_ids": committed,
        }

    def commit_assistant_reply(self, text: str, *, images=(), turn_index: int | None = None) -> int:
        imgs = tuple(images)
        th = _turn_hash("assistant", text, imgs)
        idx = turn_index if turn_index is not None else len(self.memory.store.branch_turn_lineage())
        return self.memory.remember(
            occurrence_id=f"turn-{idx:05d}-{th[:12]}",
            text=text,
            images=imgs,
            source_role="assistant",
            turn_hash=th,
        )


class SleeperV20:
    """Non-destructive dual-queue background consolidator with verified cards and M_slow replay."""

    def __init__(self, memory: InklingV20Memory):
        self.memory = memory

    def consolidate_step(
        self,
        extractor_fn,
        *,
        max_events: int = 16,
        awake_check=None,
    ) -> dict:
        """Process un-slept new/review events via structured extractor_fn, verify quotes, and replay into M_slow."""
        prog = self.memory.store.get_sleep_progress()
        snap = self.memory.store.snapshot()
        new_cursor = prog["new_cursor"]
        review_cursor = prog["review_cursor"]
        review_end = prog["review_end"]

        if review_cursor >= review_end and new_cursor > 0:
            review_cursor = 0
            review_end = new_cursor

        processed, created_cards, activated_cards, replayed_slow = 0, [], [], 0
        existing_cards = self.memory.store.list_cards(status="active", revision=snap, limit=64)

        page = self.memory.store.events(revision=snap, after=new_cursor, limit=max_events)
        for eid in page["event_ids"]:
            if awake_check is not None and awake_check():
                break
            rec = self.memory.store.get(eid, revision=snap, include_images=False)
            new_cursor = eid
            # Only consolidate user/tool/observation sources, never raw assistant hallucinations
            if rec.get("source_role") == "assistant":
                continue
            processed += 1
            proposals = extractor_fn(rec, existing_cards) or []
            for prop in proposals:
                quote = str(prop.get("source_quote", ""))
                if not quote or quote not in rec.get("text", ""):
                    continue
                card_type = prop.get("card_type", "fact")
                status = "active" if card_type == "fact" else "pending"
                cid = self.memory.store.add_card(
                    card_type=card_type,
                    subject=prop["subject"],
                    predicate=prop["predicate"],
                    content=prop["content"],
                    source_event_ids=[eid],
                    source_quote=quote,
                    status=status,
                    valid_from=prop.get("valid_from"),
                    valid_to=prop.get("valid_to"),
                    supersedes_id=prop.get("supersedes_id"),
                )
                created_cards.append(cid)
                if status == "active":
                    activated_cards.append(cid)
                    existing_cards.append(
                        {
                            "card_id": cid,
                            "card_type": card_type,
                            "subject": prop["subject"],
                            "predicate": prop["predicate"],
                            "content": prop["content"],
                        }
                    )

        if activated_cards:
            replayed_slow = self.replay_slow_state(activated_cards)

        self.memory.store.set_sleep_progress(
            new_cursor=new_cursor, review_cursor=review_cursor, review_end=review_end
        )
        return {
            "processed_events": processed,
            "created_cards": created_cards,
            "activated_cards": activated_cards,
            "replayed_slow": replayed_slow,
            "new_cursor": new_cursor,
        }

    def validate_and_activate(self, card_id: int, *, positive_passed: bool, negative_passed: bool, details: dict | None = None) -> str:
        """Promote a pending skill/procedure card only if both positive and negative controls pass."""
        status = "active" if (positive_passed and negative_passed) else "rejected"
        self.memory.store.update_card_status(
            card_id,
            status,
            validation={
                "positive_passed": bool(positive_passed),
                "negative_passed": bool(negative_passed),
                **(details or {}),
            },
        )
        if status == "active":
            self.replay_slow_state([card_id])
        return status

    @torch.no_grad()
    def replay_slow_state(self, card_ids: list[int]) -> int:
        """Write verified consolidated cards into M_slow (heads fast_heads..state_heads-1)."""
        if not card_ids:
            return 0
        cards = {
            c["card_id"]: c
            for c in self.memory.store.list_cards(status="active", limit=512)
        }
        snap = self.memory.store.snapshot()
        state, cursor = self.memory.neural_state(revision=snap, persist=False)
        replayed = 0
        for cid in card_ids:
            card = cards.get(cid)
            if card is None:
                continue
            card_text = f"[{card['card_type']}] {card['subject']} {card['predicate']}: {card['content']}"
            states, spans = _source_parts(self.memory.model, self.memory.processor, card_text, ())
            enc = self.memory.components.encode_event(states.to(_device(self.memory.components)), spans)
            state = self.memory.components.advance_state(
                state, enc["contextual"], stem_states=enc.get("stem"), target="slow"
            )
            replayed += 1
        if replayed > 0:
            fb, sb = _state_to_blobs(state, self.memory._fast_heads)
            self.memory.store.save_state_checkpoint(cursor, fb, sb)
        return replayed


class V20LatentSession:
    """MemT-style portable latent-memory session supporting standalone .safetensors save/load with zero raw history."""

    def __init__(
        self,
        memory: InklingV20Memory,
        *,
        loop_num_passes: int | None = None,
        reasoning_effort: str = "none",
    ):
        self.memory = memory
        self.messages: list[dict] = []
        self.loop_num_passes = (
            int(loop_num_passes)
            if loop_num_passes is not None
            else int(getattr(memory.model.config.text_config, "loop_num_passes", 5))
        )
        self.reasoning_effort = reasoning_effort

    @classmethod
    def from_state(
        cls,
        model,
        processor,
        state_path,
        *,
        store_path,
        bank_id: str | None = None,
        checkpoint_dir=None,
        branch: str = "main",
        strict_keyspace: bool = True,
        loop_num_passes: int | None = None,
        reasoning_effort: str = "none",
    ) -> "V20LatentSession":
        """Restore a fresh session strictly from a standalone .safetensors state file (0 raw transcript messages!)."""
        bid = bank_id or f"latent-{uuid4().hex[:10]}"
        mem = open_checkpoint_memory(
            model,
            processor,
            store_path,
            bank_id=bid,
            checkpoint_dir=checkpoint_dir,
            branch=branch,
        )
        mem.load_state_safetensors(
            state_path,
            strict_keyspace=strict_keyspace,
            clear_existing_events=True,
        )
        return cls(mem, loop_num_passes=loop_num_passes, reasoning_effort=reasoning_effort)

    @property
    def raw_event_count(self) -> int:
        return int(self.memory.store.watermarks()["source_count"])

    @property
    def has_latent_state(self) -> bool:
        return self.memory.has_latent_state()

    def remember_turn(self, role: str, text: str, *, images=(), observed_at: int | None = None) -> int:
        th = _turn_hash(role, text, images)
        occ_id = f"sess-{uuid4().hex[:10]}-{th[:12]}"
        return self.memory.remember(
            occurrence_id=occ_id,
            text=text,
            images=images,
            source_role=role,
            observed_at=observed_at,
            turn_hash=th,
        )

    @torch.no_grad()
    def chat(
        self,
        prompt: str,
        *,
        channel_a_enabled: bool = False,
        commit_to_memory: bool = False,
        clear_context: bool = False,
        max_new_tokens: int = 256,
        do_sample: bool = False,
        **retrieval_options,
    ) -> str:
        """Answer using loaded latent memory (default pure-latent with 0 raw history) or hybrid A+B."""
        turn_messages = [*self.messages, {"role": "user", "content": prompt}]
        inputs, ctx = self.memory.prepare_generation(
            turn_messages,
            channel_a_enabled=channel_a_enabled,
            use_neural_state=True,
            loop_num_passes=self.loop_num_passes,
            reasoning_effort=self.reasoning_effort,
            **retrieval_options,
        )
        gen_ids = self.memory.model.generate(
            **inputs,
            memory_context=ctx,
            loop_num_passes=self.loop_num_passes,
            max_new_tokens=max_new_tokens,
            do_sample=do_sample,
        )
        reply = self.memory.processor.tokenizer.decode(
            gen_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
        ).strip()
        if commit_to_memory:
            self.remember_turn("user", prompt)
            self.remember_turn("assistant", reply)
        if clear_context:
            self.messages.clear()
        else:
            self.messages.append({"role": "user", "content": prompt})
            self.messages.append({"role": "assistant", "content": reply})
        return reply

    def save_state(self, path, *, dtype: str = "float16") -> dict:
        return self.memory.save_state_safetensors(path, dtype=dtype, drain=True)

    def clear_transcript(self) -> dict:
        self.messages.clear()
        return self.memory.clear_transcript()

    def close(self):
        self.memory.close()

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()


def open_checkpoint_memory(
    model,
    processor,
    path,
    *,
    bank_id: str,
    checkpoint_dir=None,
    branch: str = "main",
    valid_at: int | None = None,
) -> InklingV20Memory:
    """Attach a persistent on-disk V20 bank to an exported checkpoint with strict stem/shard verification."""
    from transformers.utils.hub import cached_file

    source = checkpoint_dir if checkpoint_dir is not None else model.config.name_or_path
    if not source:
        raise ValueError("Supply the V20 checkpoint directory or Hub model ID")
    revision = getattr(model.config, "_commit_hash", None)

    def resolve(name: str) -> Path:
        return Path(cached_file(str(source), name, revision=revision))

    manifest = json.loads(resolve("v20_export.json").read_bytes())
    stem_id = manifest.get("stem_id")
    keyspace = manifest.get("keyspace_id")
    index_ks = manifest.get("index_keyspace_id")
    state_ks = manifest.get("state_keyspace_id")
    if (
        not stem_id
        or stem_id != getattr(model.config, "v20_stem_id", None)
        or keyspace != getattr(model.config, "v20_keyspace_id", None)
        or index_ks != getattr(model.config, "v20_index_keyspace_id", None)
        or state_ks != getattr(model.config, "v20_state_keyspace_id", None)
    ):
        raise ValueError("Checkpoint manifest and loaded model config disagree on V20 stem/keyspace identity")

    name = "model-v20-memory.safetensors"
    data = resolve(name).read_bytes()
    if hashlib.sha256(data).hexdigest() != manifest["files"][name]:
        raise ValueError("Embedded V20 memory shard SHA-256 mismatch")

    prefix = "model.language_model.memory_v20."
    stored = load(data)
    if any(not k.startswith(prefix) or t.dtype != torch.float32 for k, t in stored.items()):
        raise ValueError("Invalid embedded V20 memory tensor")
    state = {k[len(prefix) :]: t for k, t in stored.items()}
    if hashlib.sha256(save(state)).hexdigest() != manifest["memory_tensors_sha256"]:
        raise ValueError("Embedded V20 memory tensor digest mismatch")

    components = components_for(model)
    components.float().load_state_dict(state, strict=True)
    model.eval()
    ns = components.neural_state
    store = EventStoreV20(
        path,
        bank_id=bank_id,
        index_keyspace_id=index_ks,
        state_keyspace_id=state_ks,
        branch=branch,
        valid_at=valid_at,
        dimension=components.key_dim,
        region_dimension=components.region_dim,
        state_shape=(ns.state_heads, ns.state_key_dim, ns.state_value_dim),
        fast_heads=ns.fast_heads,
    )
    return InklingV20Memory(model, processor, store, stem_id=stem_id)