File size: 148,060 Bytes
faff844
 
 
 
 
 
 
 
 
08bd7b1
 
faff844
 
 
c5cf11b
 
 
 
 
faff844
f235f15
1f150ac
 
 
ed4bc99
 
 
6e20261
 
 
0c43c01
 
ca49ff3
 
6b25656
 
ec68d6c
 
 
 
f3e7bb2
382909e
 
f3e7bb2
49fbc8a
 
 
 
faff844
 
475ee2f
 
 
 
 
 
 
 
26b7884
 
 
9fb03a6
 
475ee2f
 
08bd7b1
 
 
 
 
 
 
 
 
 
 
34a6c11
 
 
08bd7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
34a6c11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08bd7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34a6c11
08bd7b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52376e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e285a50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a002e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c884625
 
 
 
 
 
 
3300543
c884625
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f150ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f273880
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e20261
49fbc8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26b7884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fb03a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475ee2f
 
 
 
 
 
 
 
 
 
9fb03a6
 
475ee2f
 
 
 
 
6e20261
 
 
 
 
475ee2f
6e20261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c43c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b25656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c43c01
ca49ff3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e20261
ec68d6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3e7bb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475ee2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83d1413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aaac30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c69376b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed4bc99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faff844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d249bbb
 
 
 
 
 
 
 
 
dead914
 
d249bbb
 
 
 
 
 
 
 
 
dead914
d249bbb
 
 
 
 
 
dead914
d249bbb
 
 
 
 
dead914
d249bbb
 
 
 
 
dead914
d249bbb
 
 
 
dead914
d249bbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faff844
9fb03a6
 
 
 
 
 
 
 
 
 
 
 
 
faff844
 
 
 
 
 
 
 
 
 
c5cf11b
 
dead914
 
 
 
 
c5cf11b
dead914
 
 
c5cf11b
faff844
d249bbb
faff844
 
 
 
 
 
 
01274b0
c5cf11b
01274b0
 
c5cf11b
2ae9304
 
c5cf11b
 
c69376b
 
 
1f150ac
 
 
ed4bc99
 
 
f273880
 
 
 
f3e7bb2
 
9fb03a6
 
26b7884
475ee2f
382909e
f3e7bb2
 
 
c69376b
1f150ac
ed4bc99
f273880
6e20261
 
 
 
 
0c43c01
 
 
 
 
 
 
 
 
ca49ff3
 
 
 
 
 
 
 
 
6b25656
ca49ff3
 
 
6b25656
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec68d6c
f3e7bb2
ec68d6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475ee2f
 
ec68d6c
 
6aaac30
e83d3f1
 
26b7884
 
 
475ee2f
 
f3e7bb2
 
ec68d6c
 
6b25656
 
ca49ff3
 
0c43c01
 
6e20261
 
f273880
 
 
ed4bc99
 
e83d3f1
faff844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692132c
 
 
 
faff844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52376e
 
faff844
 
 
08bd7b1
c5cf11b
 
 
 
 
 
 
 
 
 
 
 
 
f52376e
08bd7b1
f52376e
 
 
 
 
 
 
6a002e2
c884625
f52376e
 
 
 
 
 
 
 
e285a50
 
 
 
 
 
 
 
6a002e2
 
 
 
 
 
 
 
 
c884625
 
 
 
 
 
 
 
 
83d1413
 
 
6aaac30
c69376b
 
1f150ac
 
 
 
 
 
 
 
 
c69376b
 
 
 
ed4bc99
 
 
 
 
 
f273880
 
 
 
 
 
 
6e20261
 
 
 
0c43c01
 
 
 
ca49ff3
 
 
 
6b25656
 
 
 
03490d9
 
ec68d6c
 
 
 
 
f3e7bb2
 
475ee2f
9fb03a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26b7884
f3e7bb2
 
 
475ee2f
ec68d6c
f3e7bb2
ec68d6c
 
 
f3e7bb2
 
475ee2f
26b7884
 
 
475ee2f
 
 
 
 
26b7884
03490d9
 
 
ec68d6c
 
26b7884
ec68d6c
 
 
f3e7bb2
09b8714
2bbf4d5
 
ec68d6c
03490d9
 
 
 
 
 
1f150ac
f273880
6b25656
 
05e0834
c69376b
 
 
 
05e0834
 
 
1f150ac
6b25656
c69376b
1f150ac
 
c69376b
 
 
ed4bc99
1f150ac
f273880
6b25656
1f150ac
 
ed4bc99
1f150ac
 
 
ed4bc99
 
 
 
 
 
6b25656
f273880
 
6e20261
 
f273880
 
 
6b25656
6e20261
 
 
0c43c01
6e20261
 
 
6b25656
0c43c01
 
 
6b25656
0c43c01
 
 
6b25656
ca49ff3
 
 
6b25656
ca49ff3
 
 
03490d9
6b25656
 
 
ec68d6c
 
6b25656
 
 
ec68d6c
 
 
 
 
 
 
 
 
26b7884
f3e7bb2
 
 
 
 
49fbc8a
 
 
 
 
 
 
 
26b7884
475ee2f
 
 
26b7884
 
475ee2f
 
 
26b7884
 
 
 
9fb03a6
26b7884
 
 
 
 
 
 
 
 
9fb03a6
26b7884
9fb03a6
 
 
26b7884
 
 
 
 
 
9fb03a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faff844
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
"""Verify a coverage.py JSON report covers the complete backend inventory.

Modules in the audited legacy baseline must not regress in covered statements
or branches. Every other production backend module must be fully covered.
"""
from __future__ import annotations

import json
import ast
import difflib
import hashlib
from pathlib import Path
import sys

# Support both the direct CLI and package imports used by gate tests.
if __package__ in (None, ""):
    sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from scripts.check_transport_coverage import transport_baseline, transport_layout

ROOT = Path(__file__).resolve().parents[1]
BASELINE_FILE = "quality/baselines/backend-coverage-debt.json"
READER_ARCHIVE_OLD_APP_SHA = "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca"
READER_ARCHIVE_NEW_APP_SHA = "6acee59dcd272f367340da70c2ec6c2a90e71b6076aa2318e10eb12b5e39235f"
READER_ARCHIVE_OLD_DEBT_SHA = "eac5463c1f64f29a551baf216433e950e939493fee855d001814786daad8a13a"
TYPING_NEW_APP_SHA = "02350a36d2f22c20ba82bfedae564b7b6186ec3d884952e9ccd33f3ed6122b98"
TYPING_OLD_DEBT_SHA = "0caa77489676631f9e8f23da7340c741e73b90ad0744ab9b20070b9a866d05d1"
TYPING_REVIEW_SHA = "4196e9f8f9aba299025107cd59bf9b0ef27528d8b5059cd8fa80b97c28116d82"
RANGE_OLD_APP_SHA = "febd804ffe83685d17f043e9a9a5d60bea4ac3b4399ffbef5527c10e3465f121"
RANGE_NEW_APP_SHA = "6bd515f891cb732fa701cc8b3042e6e927d8423869c836ae1f2719bcbecfb7f7"
RANGE_MODULE_SHA = "8d6eb60fb15bab4f303e3ff689ca083ad9fa49ef92c928b75bfdc9aea88ce825"
TERM_NEW_APP_SHA = "0c64e9323c7b7512f666d6ce69f151c33d8bef3d31c9b5c14fb14834eb6c94ed"
TERM_MODULE_SHA = "4d66ea84242625e56e6b387506050527fed6e557b813af34bc7986aaba76970d"
WARM_NEW_APP_SHA = "f9fe394346923e0d36f06908d7092a842330b5474b464c8a02dd46c12a6e8e8b"
WARM_MODULE_SHA = "b720d87c5fb86d2cac1fb1fc2c7933477e106af7689fff56e6217c446604ab6a"
SINGLE_NEW_APP_SHA = "c67201f73947c546f1ae2fdb5de59d97b0d730ae3b90d5c92ddea0ef1ed07a23"
SINGLE_MODULE_SHA = "8cdde250384a5b9900f664d376a5472693e98f77522937d138acead6068be411"
SEARCH_RELEASE_APP_SHA = "a97ac73340331b5c0e6e8d17149b541d758d25e7cb25841544f3fe9219548fb5"
SEARCH_RELEASE_TERM_SHA = "dc2251331033e4787f7a4edabdf8de6351b85b1c160fbf1b0392734ada9babbf"
SEARCH_RELEASE_DEBT_SHA = "d7bed3e96d3cbdc8dc20d9c8f5a92dbc96d4d0f6c2e45fb6237bad9c2c70bed5"
SEARCH_RELEASE_DIFF_SHA = "2155663554e77d4f3ffe4164a154b9c9d4c1ad216f5b7b37d3ba1a6b8e765b85"
SEARCH_SIGMA_APP_SHA = "cd78aa10d6202c71ce7c99bc7da06c0842bbe2adece90f60ff01347a1eafda02"
# A reviewed constant-only change keeps every sigma-layout coordinate intact.
SEARCH_SIGMA_VERSION_APP_SHA = "20f24996fd3366a6e3bb903fd959f26385fe02c16037793c59b51a953cd1c63f"
SEARCH_SIGMA_OLD_DEBT_SHA = "0326c931227ea305f66e2ca42108a288660d2b88e530bed6637a1f57d92618a3"
SEO_PATH_OLD_SHA = "4ce6a235f862a1281199ea5de4b9b8dccaa048254842fe278ddd3545dceb97e7"
SEO_PATH_NEW_SHA = "b263f903ae185449ee0e0c375a4d7529420ab673f9d9ceb2772d65d8b7a84615"
SEO_PATH_OLD_DEBT_SHA = "ddf16ced4e535becfb2d481ae655931b3d174e8b8aa028c07bc7b6a92cce99af"
SEO_PATH_OLD_ENTRY_SHA = "50d39238ff2b2d33e94b4d57b2cb6b7dabeeb8833381202d19e39e53bd2e500a"


PROXY_SAFETY_PARENT_DEBT_SHA = "c6faa63b2edc0c91d8139532d3640a266b3e345eb59d3b689cc72259bd1df944"
PROXY_SAFETY_OLD_APP_SHA = SEARCH_SIGMA_VERSION_APP_SHA
PROXY_SAFETY_NEW_APP_SHA = "5cecc3a293b0d98c684cf67b087300fceb445efe64f2c6bff705b09f03f3f466"
PROXY_SAFETY_OLD_STREAMS_SHA = "b13d42a2a4a80bd364dd2143bb9132e3fca831e38a9022b5ed339a17ba097c82"
PROXY_SAFETY_NEW_STREAMS_SHA = "1ea7166805ef52c2afb8ccd2da09c4c37a4aa22cd901fc5768552395659c9f55"
PROXY_SAFETY_NEW_RANGE_SHA = "966395157c044f254d0c0734231b6af55f1c63bb32e250ff037b644438a68367"
PROXY_SAFETY_APP_DIFF_SHA = "68416eb9c40727cbd188657b3a8409dc5c7c4569edbf58f500b0ff216d0da130"
PROXY_SAFETY_STREAMS_DIFF_SHA = "76ef2e037fee17c6f8aca062213455e9fd158f078fa9b92d670edc6049712a61"
BROWSE_NEW_APP_SHA = "64c479aea84f7b4b8b3f7fdacdc188d34e2c174aa2ee21748a20ba0d4b31211a"
BROWSE_MODULE_SHA = "78a1f1d3217e3d6b83573a1d311222cd9d1f66d735d10dc8c96bcee5bda92fa1"
BROWSE_PARENT_ENTRY_SHA = "ad7eca33e0ab4fa1ef3b23747417ecc0545feda00ebe0592aeb21c086cd88c41"
LIFESPAN_APP_SHA = "652c1576d8e3cb4802254205d4dd978b325966966af52972dea260e63e6d1ba0"
LIFESPAN_PARENT_DEBT_SHA = "f7cbc7bf0ccb5f60cfeb6b72cccb46291dce5f8b5d7fcd7f52fa1ab2889a5faa"


def migrate_retired_txt_app_baseline(root: Path, previous: dict[str, dict[str, object]],
                                     old_source: Path) -> dict[str, dict[str, object]]:
    """Translate one independently pinned baseline across the reviewed TXT deletion.

    Only deleted lines and arcs wholly inside them are retired. Later source
    edits are checked against the ordinary line and branch coverage ratchet.
    """
    old = old_source.read_bytes()
    if hashlib.sha256(old).hexdigest() != "144a94519c57fff1da752d26cb514f99fb7ffda7f068da06a726d842f3a61442":
        raise ValueError("unexpected source for retired TXT baseline")
    # The historical target remains a reviewed migration anchor even after
    # future app changes. Subsequent migrations must also use pinned anchors.
    anchor = (root / "scripts/coverage-anchors/retired-txt-app.py.snapshot").read_bytes()
    new = anchor
    if hashlib.sha256(new).hexdigest() != "b81421ba994354d34991af6ee181e6aba5b935c1eb300f242ab349a4e68036f2":
        raise ValueError("retired TXT baseline migration requires the reviewed target anchor")
    if "backend/app.py" not in previous:
        raise ValueError("previous baseline lacks backend/app.py")
    line_map: dict[int, int] = {}
    removed: set[int] = set()
    for op, start, end, new_start, _new_end in difflib.SequenceMatcher(
            None, old.decode().splitlines(), new.decode().splitlines(), autojunk=False).get_opcodes():
        if op == "equal":
            line_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        elif op == "delete":
            removed.update(range(start + 1, end + 1))
    # Both replacements remove only imports for the retired proxy.
    line_map.update({29: 28, 70: 69})
    random_target = (root / "scripts/coverage-anchors/retired-random-txt-app.py.snapshot").read_bytes()
    if hashlib.sha256(random_target).hexdigest() != "83276576ce2a1cfd439d8b901446a567b46eb49e99077ccf04a97dabfa5c22cd":
        raise ValueError("retired random TXT migration requires the reviewed target anchor")
    random_map: dict[int, int] = {}
    random_removed: set[int] = set()
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(
            None, anchor.decode().splitlines(), random_target.decode().splitlines(), autojunk=False).get_opcodes():
        if op == "equal":
            random_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        elif op == "delete":
            random_removed.update(range(start + 1, end + 1))
        elif op == "replace" and end - start == new_end - new_start == 1:
            # The global declaration and packed-index tuple lose TXT entries.
            random_map[start + 1] = new_start + 1
        else:
            raise ValueError("unexpected retired random TXT anchor change")
    stage_one_map = line_map
    line_map = {original: random_map[intermediate] for original, intermediate in stage_one_map.items()
                if intermediate in random_map}
    removed.update(original for original, intermediate in stage_one_map.items() if intermediate in random_removed)

    def line(number: int) -> int:
        sign = -1 if number < 0 else 1
        return sign * line_map[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline lines")
        mapped: list[int] = []
        for number in values:
            if number in line_map:
                mapped.append(line(number))
            elif number not in removed:
                raise ValueError(f"unmapped previous baseline line: {number}")
        return sorted(mapped)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline arcs")
        mapped: list[list[int]] = []
        for start, end in values:
            if abs(start) in line_map and abs(end) in line_map:
                mapped.append([line(start), line(end)])
            elif [start, end] == [1445, 1449]:
                # The old false branch fell into the removed TXT shutdown block;
                # it now falls through to the preserved bucket shutdown.
                mapped.append([random_map[1417], random_map[1421]])
            elif abs(start) not in removed:
                raise ValueError(f"unmapped previous baseline branch: {start}, {end}")
        return sorted(mapped)

    result = {name: dict(item) for name, item in previous.items()}
    entry = previous["backend/app.py"]
    covered_lines = lines(entry["lines"])
    covered_arcs = arcs(entry["arcs"])
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def migrate_folder_tree_app_baseline(root: Path, previous: dict[str, dict[str, object]],
                                     old_source: Path, new_source: Path, extracted_source: Path
                                     ) -> dict[str, dict[str, object]]:
    """Map a single reviewed extraction; moved coverage is guarded by 100% on the new module."""
    expected = (
        (old_source, "83276576ce2a1cfd439d8b901446a567b46eb49e99077ccf04a97dabfa5c22cd"),
        (new_source, "4a05aa049a763b52238aeb8a86621c9532555e55f0d9391de9f16afa49df0639"),
        (extracted_source, "95d04cfe5ad79e1cbe6218edeba4567c001f7961f199cfd04363123a1e391fd3"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("folder-tree coverage migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/folder_tree.py" in previous:
        raise ValueError("folder-tree coverage migration requires the original module inventory")
    old = old_source.read_text().splitlines()
    new = new_source.read_text().splitlines()
    line_map: dict[int, int] = {}
    moved: set[int] = set()
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            line_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
            if op == "replace":
                moved.update(range(start + 1, end + 1))
    if changes != [("insert", 34, 34, 34, 35), ("replace", 1234, 1281, 1235, 1236)]:
        raise ValueError("unexpected folder-tree source diff")

    def line(number: int) -> int:
        sign = -1 if number < 0 else 1
        return sign * line_map[abs(number)]

    def lines(values: object, *, missing: bool) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline lines")
        mapped: list[int] = []
        for number in values:
            if number in line_map:
                mapped.append(line(number))
            elif number not in moved or missing:
                raise ValueError(f"unmapped or uncovered extracted line: {number}")
        return sorted(mapped)

    def arcs(values: object, *, missing: bool) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline arcs")
        mapped: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if missing:
                    raise ValueError(f"uncovered extracted branch: {start}, {end}")
                continue
            if [start, end] == [1233, 1235]:
                mapped.append([1234, 1236])
            elif abs(start) in line_map and abs(end) in line_map:
                mapped.append([line(start), line(end)])
            else:
                raise ValueError(f"unmapped previous branch: {start}, {end}")
        return sorted(mapped)

    result = {name: dict(item) for name, item in previous.items()}
    entry = previous["backend/app.py"]
    covered_lines = lines(entry["lines"], missing=False)
    covered_arcs = arcs(entry["arcs"], missing=False)
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"], missing=True),
        "missing_arcs": arcs(entry["missing_arcs"], missing=True),
    }
    return result


def migrate_search_projection_app_baseline(previous: dict[str, dict[str, object]],
                                            old_source: Path, new_source: Path, extracted_source: Path
                                            ) -> dict[str, dict[str, object]]:
    """Map the reviewed projection extraction; the new module remains outside the debt."""
    expected = (
        (old_source, "4a05aa049a763b52238aeb8a86621c9532555e55f0d9391de9f16afa49df0639"),
        (new_source, "b73c5db076ae1dce7c8988fc30049d2c0120ffdf9b6d6b2fd02a4b97e726b3cb"),
        (extracted_source, "a5be97d44e9371c6cc91d7c5753f7f83c6fc64a288a779141ea35f4278324179"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("search-projection coverage migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/search_projection.py" in previous:
        raise ValueError("search-projection coverage migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    line_map: dict[int, int] = {}
    moved: set[int] = set()
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            line_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
            if op == "replace":
                moved.update(range(start + 1, end + 1))
    if changes != [("insert", 35, 35, 35, 36), ("replace", 622, 636, 623, 624),
                   ("replace", 639, 644, 627, 628)]:
        raise ValueError("unexpected search-projection source diff")

    def translate(number: int) -> int:
        return (-1 if number < 0 else 1) * line_map[abs(number)]

    def lines(values: object, *, missing: bool) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline lines")
        result: list[int] = []
        for number in values:
            if number in line_map:
                result.append(translate(number))
            elif number not in moved or missing:
                raise ValueError(f"unmapped or uncovered projection line: {number}")
        return sorted(result)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) not in line_map or abs(end) not in line_map:
                raise ValueError(f"unmapped projection branch: {start}, {end}")
            result.append([translate(start), translate(end)])
        return sorted(result)

    result = {name: dict(item) for name, item in previous.items()}
    entry = previous["backend/app.py"]
    covered_lines = lines(entry["lines"], missing=False)
    covered_arcs = arcs(entry["arcs"])
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def migrate_search_candidates_app_baseline(previous: dict[str, dict[str, object]],
                                            old_source: Path, new_source: Path, extracted_source: Path
                                            ) -> dict[str, dict[str, object]]:
    """Translate the pinned extraction, requiring complete coverage in the new module."""
    expected = (
        (old_source, "b73c5db076ae1dce7c8988fc30049d2c0120ffdf9b6d6b2fd02a4b97e726b3cb"),
        (new_source, "bd3de63841020bfc3c16f5015894ae39ff08c38e6a6d3bc03129e1b86ed91a84"),
        (extracted_source, "81dbe74b8142aed5447478e2a05c36150a5a2abf67f4aa0b55bc3d43b297cec4"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("search-candidates coverage migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/search_candidates.py" in previous:
        raise ValueError("search-candidates coverage migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    moved: set[int] = set()
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
            if op == "replace":
                moved.update(range(start + 1, end + 1))
    if changes != [("insert", 35, 35, 35, 36), ("insert", 263, 263, 264, 284),
                   ("replace", 264, 300, 285, 287)]:
        raise ValueError("unexpected search-candidates source diff")

    def translate(number: int) -> int:
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object, *, missing: bool) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline lines")
        result: list[int] = []
        for number in values:
            if number in mapping:
                result.append(translate(number))
            elif number not in moved or missing:
                raise ValueError(f"unmapped or uncovered candidate line: {number}")
        return sorted(result)

    def arcs(values: object, *, missing: bool) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if missing:
                    raise ValueError(f"uncovered candidate branch: {start}, {end}")
                if abs(end) not in moved:
                    raise ValueError(f"unexpected candidate branch endpoint: {start}, {end}")
                continue
            if abs(start) not in mapping or abs(end) not in mapping:
                raise ValueError(f"unmapped candidate branch: {start}, {end}")
            result.append([translate(start), translate(end)])
        return sorted(result)

    result = {name: dict(item) for name, item in previous.items()}
    entry = previous["backend/app.py"]
    covered_lines = lines(entry["lines"], missing=False)
    covered_arcs = arcs(entry["arcs"], missing=False)
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"], missing=True),
        "missing_arcs": arcs(entry["missing_arcs"], missing=True),
    }
    return result


def migrate_search_bootstrap_app_baseline(previous: dict[str, dict[str, object]],
                                           old_source: Path, new_source: Path, extracted_source: Path
                                           ) -> dict[str, dict[str, object]]:
    """Translate only the independently reviewed initial-payload extraction."""
    expected = (
        (old_source, "bd3de63841020bfc3c16f5015894ae39ff08c38e6a6d3bc03129e1b86ed91a84"),
        (new_source, "f9582d39a22dbe75c29422c58d978b586e5d38e483e51d75eefa906d25e3d713"),
        (extracted_source, "41fd419e58c036b00f35bc2e8c8fee12e757f748ef69b56560c2b059addfa24d"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("search-bootstrap coverage migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/search_bootstrap.py" in previous:
        raise ValueError("search-bootstrap coverage migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    moved: set[int] = set()
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
            if op == "replace":
                moved.update(range(start + 1, end + 1))
    if changes != [("insert", 35, 35, 35, 36), ("replace", 751, 756, 752, 765),
                   ("replace", 758, 777, 767, 769)]:
        raise ValueError("unexpected search-bootstrap source diff")

    def translate(number: int) -> int:
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object, *, missing: bool) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline lines")
        result: list[int] = []
        for number in values:
            if number in mapping:
                result.append(translate(number))
            elif number not in moved or missing:
                raise ValueError(f"unmapped or uncovered bootstrap line: {number}")
        return sorted(result)

    def arcs(values: object, *, missing: bool) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if missing:
                    raise ValueError(f"uncovered bootstrap branch: {start}, {end}")
                if abs(end) not in moved:
                    raise ValueError(f"unexpected bootstrap branch endpoint: {start}, {end}")
                continue
            if abs(start) not in mapping or abs(end) not in mapping:
                raise ValueError(f"unmapped bootstrap branch: {start}, {end}")
            result.append([translate(start), translate(end)])
        return sorted(result)

    result = {name: dict(item) for name, item in previous.items()}
    entry = previous["backend/app.py"]
    covered_lines = lines(entry["lines"], missing=False)
    covered_arcs = arcs(entry["arcs"], missing=False)
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"], missing=True),
        "missing_arcs": arcs(entry["missing_arcs"], missing=True),
    }
    return result


def migrate_reader_archive_app_baseline(previous: dict[str, dict[str, object]],
                                        old_source: Path, new_source: Path, extracted_source: Path
                                        ) -> dict[str, dict[str, object]]:
    """Translate only the reviewed reader-archive extraction.

    Lines and arcs of the moved validator leave backend/app.py; the new module
    must independently reach 100% statements and branches, so no coverage is lost.
    """
    expected = (
        (old_source, "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca"),
        (new_source, "6acee59dcd272f367340da70c2ec6c2a90e71b6076aa2318e10eb12b5e39235f"),
        (extracted_source, "9439528bdad3127c8c794489a7edbf940d7cac9a7341e7bc6e2ca09c2751bb24"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("reader-archive coverage migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/reader_archive.py" in previous:
        raise ValueError("reader-archive coverage migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    moved: set[int] = set()
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
            if op in ("delete", "replace"):
                moved.update(range(start + 1, end + 1))
    if changes != [("replace", 1656, 1666, 1656, 1660), ("replace", 1669, 1777, 1663, 1665)]:
        raise ValueError("unexpected reader-archive source diff")
    function_exit = -1669

    def translate(number: int) -> int:
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline lines")
        result: list[int] = []
        for number in values:
            if number in mapping:
                result.append(translate(number))
            elif number not in moved:
                raise ValueError(f"unmapped reader-archive line: {number}")
        return sorted(result)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid previous baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if abs(end) not in moved and end != function_exit:
                    raise ValueError(f"unexpected reader-archive branch endpoint: {start}, {end}")
                continue
            if abs(start) not in mapping or abs(end) not in mapping:
                raise ValueError(f"unmapped reader-archive branch: {start}, {end}")
            result.append([translate(start), translate(end)])
        return sorted(result)

    result = {name: dict(item) for name, item in previous.items()}
    entry = previous["backend/app.py"]
    covered_lines = lines(entry["lines"])
    covered_arcs = arcs(entry["arcs"])
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result



def migrate_folder_contents_app_baseline(previous: dict[str, dict[str, object]],
                                         old_source: Path, new_source: Path, extracted_source: Path
                                         ) -> dict[str, dict[str, object]]:
    """Carry every retained app coordinate across the pinned folder-content extraction.

    The new module must independently satisfy the ordinary 100% coverage gate,
    including previously uncovered branches moved from the legacy app.
    """
    expected = (
        (old_source, TYPING_NEW_APP_SHA),
        (new_source, "febd804ffe83685d17f043e9a9a5d60bea4ac3b4399ffbef5527c10e3465f121"),
        (extracted_source, "931758f2f2b76b4cbe51a00b3a5f408c48d9b4e42104476ee21cdd49a083b56d"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("folder-contents migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/folder_contents.py" in previous:
        raise ValueError("folder-contents migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("insert", 36, 36, 36, 37), ("replace", 1272, 1314, 1273, 1280)]:
        raise ValueError("unexpected folder-contents source diff")
    moved = set(range(1273, 1315))
    entry = previous["backend/app.py"]
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid folder-contents baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid folder-contents baseline counts")
    if (len(entry["lines"]) != len(set(entry["lines"]))
            or len(entry["missing_lines"]) != len(set(entry["missing_lines"]))
            or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]})
            or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]})
            or set(entry["lines"]) & set(entry["missing_lines"])
            or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}):
        raise ValueError("overlapping or duplicate folder-contents coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped folder-contents coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid folder-contents baseline lines")
        result: list[int] = []
        for value in values:
            if value in moved:
                continue
            result.append(translate(value))
        return sorted(result)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid folder-contents baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if abs(end) not in moved:
                    raise ValueError(f"unexpected folder-contents branch endpoint: {start}, {end}")
                continue
            result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines = lines(entry["lines"])
    covered_arcs = arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]),
        "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def migrate_seo_path_baseline(previous: dict[str, dict[str, object]], old_source: Path,
                              new_source: Path, parent_debt: Path) -> dict[str, dict[str, object]]:
    """Map the reviewed equivalent path predicate without retiring old coverage."""
    expected = ((old_source, SEO_PATH_OLD_SHA), (new_source, SEO_PATH_NEW_SHA),
                (parent_debt, SEO_PATH_OLD_DEBT_SHA))
    if any(not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("SEO path migration requires exact reviewed sources and baseline")
    old = old_source.read_text().splitlines()
    new = new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("replace", 137, 138, 137, 142)]:
        raise ValueError("unexpected SEO path source diff")
    mapping[138] = 140
    entry = previous.get("backend/seo.py")
    reviewed = json.loads(parent_debt.read_text()).get("backend/seo.py")
    if (not isinstance(entry, dict) or not isinstance(reviewed, dict) or
            hashlib.sha256(json.dumps(reviewed, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
            != SEO_PATH_OLD_ENTRY_SHA):
        raise ValueError("SEO path migration requires exact previous baseline")
    for covered, missing in (("lines", "missing_lines"), ("arcs", "missing_arcs")):
        convert = tuple if covered == "arcs" else int
        if (not {convert(value) for value in entry[covered]} <= {convert(value) for value in reviewed[covered]} or
                not {convert(value) for value in reviewed[missing]} <= {convert(value) for value in entry[missing]} or
                not {convert(value) for value in entry[missing]} <=
                {convert(value) for value in reviewed[covered] + reviewed[missing]}):
            raise ValueError("SEO path migration requires a reviewed baseline subset")
    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped SEO path coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]
    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid SEO path baseline lines")
        return sorted(translate(value) for value in values)
    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid SEO path baseline arcs")
        return sorted([[translate(start), translate(end)] for start, end in values])
    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    if entry["covered_lines"] != len(covered_lines) or entry["covered_branches"] != len(covered_arcs):
        raise ValueError("invalid SEO path baseline counts")
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/seo.py"] = {"covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
                                "lines": covered_lines, "arcs": covered_arcs,
                                "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"])}
    return result


def reviewed_browse_source(root: Path, source_sha: str) -> bool:
    """Permit only the exact browse extraction on the previously audited proxy layout."""
    if source_sha != BROWSE_NEW_APP_SHA:
        return False
    anchor = root / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot"
    module = root / "backend/search_browse.py"
    return (anchor.is_file() and module.is_file()
            and reviewed_proxy_safety_source(root, PROXY_SAFETY_NEW_APP_SHA)
            and hashlib.sha256(anchor.read_bytes()).hexdigest() == PROXY_SAFETY_NEW_APP_SHA
            and hashlib.sha256(module.read_bytes()).hexdigest() == BROWSE_MODULE_SHA)


def migrate_search_browse_baseline(previous: dict[str, dict[str, object]], old_source: Path,
                                   new_source: Path, extracted_source: Path) -> dict[str, dict[str, object]]:
    """Move audited browse paths only when the new module is independently 100% covered."""
    expected = ((old_source, PROXY_SAFETY_NEW_APP_SHA), (new_source, BROWSE_NEW_APP_SHA),
                (extracted_source, BROWSE_MODULE_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("search-browse migration requires exact reviewed sources")
    entry = previous.get("backend/app.py")
    if not isinstance(entry, dict) or "backend/search_browse.py" in previous:
        raise ValueError("search-browse migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    operations = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes()
    changes = [item for item in operations if item[0] != "equal"]
    if changes != [("insert", 42, 42, 42, 43), ("insert", 1027, 1027, 1028, 1044),
                   ("replace", 1097, 1131, 1114, 1126)]:
        raise ValueError("unexpected search-browse source diff")
    mapping = {index + 1: new_start + 1 + index - start
               for op, start, end, new_start, _ in operations if op == "equal"
               for index in range(start, end)}
    moved = set(range(1098, 1132))
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid search-browse baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid search-browse baseline counts")
    if (len(entry["lines"]) != len(set(entry["lines"]))
            or len(entry["missing_lines"]) != len(set(entry["missing_lines"]))
            or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]})
            or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]})
            or set(entry["lines"]) & set(entry["missing_lines"])
            or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}):
        raise ValueError("overlapping or duplicate search-browse coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped search-browse coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object, *, missing: bool) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid search-browse baseline lines")
        result: list[int] = []
        for value in values:
            if value in moved:
                if missing:
                    raise ValueError(f"uncovered search-browse extraction line: {value}")
                continue
            result.append(translate(value))
        return sorted(result)

    def arcs(values: object, *, missing: bool) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid search-browse baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if missing or abs(end) not in moved:
                    raise ValueError(f"uncovered or crossing search-browse branch: {start}, {end}")
                continue
            if (start, end) == (1097, 1098):
                result.append([translate(start), 1115])
            else:
                result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = lines(entry["lines"], missing=False), arcs(entry["arcs"], missing=False)
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"], missing=True),
        "missing_arcs": arcs(entry["missing_arcs"], missing=True),
    }
    return result


def reviewed_lifespan_source(root: Path, source_sha: str) -> bool:
    parent = root / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot"
    return (source_sha == LIFESPAN_APP_SHA and parent.is_file()
            and hashlib.sha256(parent.read_bytes()).hexdigest() == BROWSE_NEW_APP_SHA
            and reviewed_browse_source(root, BROWSE_NEW_APP_SHA))


def migrate_lifespan_baseline(previous: dict[str, dict[str, object]], old_source: Path,
                              new_source: Path) -> dict[str, dict[str, object]]:
    """Translate all parent coordinates; new code remains outside the debt."""
    if (hashlib.sha256(old_source.read_bytes()).hexdigest() != BROWSE_NEW_APP_SHA or
            hashlib.sha256(new_source.read_bytes()).hexdigest() != LIFESPAN_APP_SHA):
        raise ValueError("lifespan migration requires exact reviewed sources")
    operations = difflib.SequenceMatcher(None, old_source.read_text().splitlines(),
                                         new_source.read_text().splitlines(), autojunk=False).get_opcodes()
    if [op for op in operations if op[0] != "equal"] != [
            ("replace", 1335, 1336, 1335, 1356), ("insert", 1352, 1352, 1372, 1374)]:
        raise ValueError("unexpected lifespan source diff")
    mapping = {i + 1: new_start + 1 + i - start for op, start, end, new_start, _ in operations
               if op == "equal" for i in range(start, end)}
    # The old await is now the shielded await. Its incoming false branch
    # still targets creation of the close task instead.
    mapping[1336] = 1341
    entry = previous.get("backend/app.py")
    if not isinstance(entry, dict):
        raise ValueError("lifespan migration requires app baseline")
    for covered, missing, count in (("lines", "missing_lines", "covered_lines"),
                                    ("arcs", "missing_arcs", "covered_branches")):
        convert = tuple if covered == "arcs" else lambda x: x
        a, b = entry[covered], entry[missing]
        if (entry[count] != len(a) or len(a) != len({convert(x) for x in a}) or
                len(b) != len({convert(x) for x in b}) or
                {convert(x) for x in a} & {convert(x) for x in b}):
            raise ValueError("invalid lifespan baseline coordinates")
    def translate(n: int) -> int:
        if type(n) is not int or abs(n) not in mapping:
            raise ValueError(f"unmapped lifespan coordinate: {n}")
        return (-1 if n < 0 else 1) * mapping[abs(n)]
    def arcs(values: list) -> list:
        return sorted([[1332, 1337] if [a, b] == [1332, 1336]
                       else [translate(a), translate(b)] for a, b in values])
    result = {name: dict(value) for name, value in previous.items()}
    lines = sorted(translate(n) for n in entry["lines"])
    branches = arcs(entry["arcs"])
    result["backend/app.py"] = {"lines": lines, "arcs": branches,
        "missing_lines": sorted(translate(n) for n in entry["missing_lines"]),
        "missing_arcs": arcs(entry["missing_arcs"]),
        "covered_lines": len(lines), "covered_branches": len(branches)}
    return result


def lifespan_baseline_layout(debt: dict[str, dict[str, object]], parent: dict[str, dict[str, object]],
                             parent_source: Path, current_source: Path) -> str:
    """Recognize only coordinate inventories belonging unambiguously to a pinned layout."""
    current = migrate_lifespan_baseline(parent, parent_source, current_source)
    entry = debt.get("backend/app.py")
    if not isinstance(entry, dict):
        raise ValueError("lifespan baseline lacks app entry")
    def coordinates(item: dict[str, object]) -> tuple[set, set]:
        return (set(item["lines"]) | set(item["missing_lines"]),
                {tuple(arc) for arc in item["arcs"] + item["missing_arcs"]})
    lines, arcs = coordinates(entry)
    old_lines, old_arcs = coordinates(parent["backend/app.py"])
    new_lines, new_arcs = coordinates(current["backend/app.py"])
    # New-layout baselines may promote newly covered code, but may not
    # introduce unknown missing coordinates. Their covered coordinates may
    # include the reviewed new block.
    matches_old = lines <= old_lines and arcs <= old_arcs
    allowed_new_lines = new_lines | set(range(1337, 1357)) | {1373, 1374}
    matches_new = (lines <= allowed_new_lines and arcs <= (new_arcs | {
        (1339, 1340), (1344, 1345), (1344, 1346), (1346, 1347), (1346, 1339),
        (1349, 1350), (1349, 1351), (1373, 1374), (1373, -1295)}))
    if matches_old == matches_new:
        raise ValueError("ambiguous or unrecognized lifespan baseline layout")
    return "lifespan-parent" if matches_old else "current"


def historical_reader_range_module(path: Path) -> Path:
    """Use the immutable pre-fix module for the historical extraction proof."""
    if path.name != "reader_range_cache.py" or not path.is_file():
        return path
    if hashlib.sha256(path.read_bytes()).hexdigest() != PROXY_SAFETY_NEW_RANGE_SHA:
        return path
    root = path.parent.parent
    app = root / "backend/app.py"
    source_sha = hashlib.sha256(app.read_bytes()).hexdigest() if app.is_file() else ""
    anchor = root / "scripts/coverage-anchors/proxy-safety-old-range.py.snapshot"
    if ((reviewed_proxy_safety_source(root, source_sha) or reviewed_browse_source(root, source_sha)
         or reviewed_lifespan_source(root, source_sha)) and anchor.is_file()
            and hashlib.sha256(anchor.read_bytes()).hexdigest() == RANGE_MODULE_SHA):
        return anchor
    return path


def migrate_reader_range_app_baseline(previous: dict[str, dict[str, object]],
                                      old_source: Path, new_source: Path, extracted_source: Path
                                      ) -> dict[str, dict[str, object]]:
    """Translate the reviewed subrange move; the new module must be 100% covered."""
    expected = ((old_source, RANGE_OLD_APP_SHA), (new_source, RANGE_NEW_APP_SHA),
                (historical_reader_range_module(extracted_source), RANGE_MODULE_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("reader-range migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/reader_range_cache.py" in previous:
        raise ValueError("reader-range migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("insert", 55, 55, 55, 56), ("replace", 2866, 2894, 2867, 2872)]:
        raise ValueError("unexpected reader-range source diff")
    moved = set(range(2867, 2895))
    entry = previous["backend/app.py"]
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid reader-range baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid reader-range baseline counts")
    if (len(entry["lines"]) != len(set(entry["lines"]))
            or len(entry["missing_lines"]) != len(set(entry["missing_lines"]))
            or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]})
            or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]})
            or set(entry["lines"]) & set(entry["missing_lines"])
            or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}):
        raise ValueError("overlapping or duplicate reader-range coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped reader-range coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid reader-range baseline lines")
        return sorted(translate(value) for value in values if value not in moved)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid reader-range baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if abs(end) not in moved:
                    raise ValueError(f"unexpected reader-range branch endpoint: {start}, {end}")
                continue
            result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result
def migrate_search_term_app_baseline(previous: dict[str, dict[str, object]],
                                      old_source: Path, new_source: Path, extracted_source: Path
                                      ) -> dict[str, dict[str, object]]:
    """Translate the reviewed search-term move; the new module must be 100% covered."""
    expected = ((old_source, RANGE_NEW_APP_SHA), (new_source, TERM_NEW_APP_SHA),
                (extracted_source, TERM_MODULE_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("search-term migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/search_term_candidates.py" in previous:
        raise ValueError("search-term migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("insert", 39, 39, 39, 40), ("replace", 724, 780, 725, 732)]:
        raise ValueError("unexpected search-term source diff")
    moved = set(range(725, 781))
    entry = previous["backend/app.py"]
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid search-term baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid search-term baseline counts")
    if (len(entry["lines"]) != len(set(entry["lines"]))
            or len(entry["missing_lines"]) != len(set(entry["missing_lines"]))
            or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]})
            or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]})
            or set(entry["lines"]) & set(entry["missing_lines"])
            or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}):
        raise ValueError("overlapping or duplicate search-term coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped search-term coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid search-term baseline lines")
        return sorted(translate(value) for value in values if value not in moved)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid search-term baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if abs(end) not in moved:
                    raise ValueError(f"unexpected search-term branch endpoint: {start}, {end}")
                continue
            result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result
def migrate_single_term_app_baseline(previous: dict[str, dict[str, object]],
                                      old_source: Path, new_source: Path, extracted_source: Path
                                      ) -> dict[str, dict[str, object]]:
    """Translate the reviewed single-term move; the new module must be 100% covered."""
    expected = ((old_source, WARM_NEW_APP_SHA), (new_source, SINGLE_NEW_APP_SHA),
                (extracted_source, SINGLE_MODULE_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("single-term migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/single_term_marker.py" in previous:
        raise ValueError("single-term migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("replace", 41, 42, 41, 43), ("replace", 1128, 1184, 1129, 1137)]:
        raise ValueError("unexpected single-term source diff")
    moved = set(range(1129, 1185)) | {42}
    entry = previous["backend/app.py"]
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid single-term baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid single-term baseline counts")
    if (len(entry["lines"]) != len(set(entry["lines"]))
            or len(entry["missing_lines"]) != len(set(entry["missing_lines"]))
            or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]})
            or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]})
            or set(entry["lines"]) & set(entry["missing_lines"])
            or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}):
        raise ValueError("overlapping or duplicate single-term coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped single-term coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid single-term baseline lines")
        return sorted(translate(value) for value in values if value not in moved)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid single-term baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if [start, end] == [1077, 1129]:
                result.append([translate(start), 1130])
                continue
            if abs(start) in moved:
                if abs(end) not in moved:
                    raise ValueError(f"unexpected single-term branch endpoint: {start}, {end}")
                continue
            result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def migrate_download_warm_app_baseline(previous: dict[str, dict[str, object]],
                                      old_source: Path, new_source: Path, extracted_source: Path
                                      ) -> dict[str, dict[str, object]]:
    """Translate the reviewed download-warm move; the new module must be 100% covered."""
    expected = ((old_source, TERM_NEW_APP_SHA), (new_source, WARM_NEW_APP_SHA),
                (extracted_source, WARM_MODULE_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("download-warm migration requires exact reviewed sources")
    if "backend/app.py" not in previous or "backend/download_warm.py" in previous:
        raise ValueError("download-warm migration requires the original module inventory")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("insert", 35, 35, 35, 37), ("replace", 1238, 1253, 1240, 1241),
                   ("replace", 1256, 1268, 1244, 1248)]:
        raise ValueError("unexpected download-warm source diff")
    moved = set(range(1239, 1254)) | set(range(1257, 1269))
    entry = previous["backend/app.py"]
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid download-warm baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid download-warm baseline counts")
    if (len(entry["lines"]) != len(set(entry["lines"]))
            or len(entry["missing_lines"]) != len(set(entry["missing_lines"]))
            or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]})
            or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]})
            or set(entry["lines"]) & set(entry["missing_lines"])
            or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}):
        raise ValueError("overlapping or duplicate download-warm coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped download-warm coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid download-warm baseline lines")
        return sorted(translate(value) for value in values if value not in moved)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid download-warm baseline arcs")
        result: list[list[int]] = []
        for start, end in values:
            if abs(start) in moved:
                if abs(end) not in moved:
                    raise ValueError(f"unexpected download-warm branch endpoint: {start}, {end}")
                continue
            result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result



def search_release_mapping(old_source: Path, new_source: Path) -> dict[int, int]:
    """Map unchanged coordinates across the pinned search semantics change."""
    expected = ((old_source, SINGLE_NEW_APP_SHA), (new_source, SEARCH_RELEASE_APP_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("search-release migration requires exact reviewed sources")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    opcodes = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes()
    changes = [list(opcode) for opcode in opcodes if opcode[0] != "equal"]
    if hashlib.sha256(json.dumps(changes, separators=(",", ":")).encode()).hexdigest() != SEARCH_RELEASE_DIFF_SHA:
        raise ValueError("unexpected search-release source diff")
    return {index + 1: start_new + 1 + index - start
            for op, start, end, start_new, _ in opcodes if op == "equal"
            for index in range(start, end)}


def migrate_search_release_baseline(previous: dict[str, dict[str, object]],
                                    old_source: Path, new_source: Path,
                                    old_term: Path, new_term: Path) -> dict[str, dict[str, object]]:
    """Retire only changed coordinates and demand full replacement coverage.

    Unchanged lines and branches retain their prior status. Edited search
    code and the modified term-candidate module are absent from prior debt, so
    the regular ratchet requires every replacement statement and branch.
    """
    mapping = search_release_mapping(old_source, new_source)
    if (hashlib.sha256(old_term.read_bytes()).hexdigest() != SINGLE_MODULE_SHA or
            hashlib.sha256(new_term.read_bytes()).hexdigest() != SEARCH_RELEASE_TERM_SHA):
        raise ValueError("search-release migration requires exact reviewed term sources")
    if "backend/app.py" not in previous or "backend/search_term_candidates.py" in previous:
        raise ValueError("search-release migration requires original inventory")
    entry = previous["backend/app.py"]
    fields = ("lines", "missing_lines", "arcs", "missing_arcs")
    if not all(isinstance(entry.get(field), list) for field in fields):
        raise ValueError("invalid search-release baseline coordinates")
    if (entry.get("covered_lines") != len(entry["lines"])
            or entry.get("covered_branches") != len(entry["arcs"])):
        raise ValueError("invalid search-release baseline counts")
    old_count = len(old_source.read_text().splitlines())
    lines = entry["lines"] + entry["missing_lines"]
    arcs = entry["arcs"] + entry["missing_arcs"]
    if (any(type(value) is not int or not 1 <= value <= old_count for value in lines)
            or len(lines) != len(set(lines))
            or any(not isinstance(arc, list) or len(arc) != 2
                   or any(type(value) is not int or not 1 <= abs(value) <= old_count for value in arc)
                   for arc in arcs)
            or len(arcs) != len({tuple(arc) for arc in arcs})):
        raise ValueError("invalid or overlapping search-release coordinates")
    redirected = {(705, 707): (731, 735), (708, 710): (738, 740),
                  (1036, 1038): (1083, 1085), (1157, 1158): (1246, 1247)}

    def translate(number: int) -> int:
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def moved_lines(values: list[int]) -> list[int]:
        return sorted(translate(value) for value in values if value in mapping)

    def moved_arcs(values: list[list[int]]) -> list[list[int]]:
        result = []
        for start, end in values:
            replacement = redirected.get((start, end))
            if replacement is not None:
                result.append(list(replacement))
            elif abs(start) in mapping and abs(end) in mapping:
                result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = moved_lines(entry["lines"]), moved_arcs(entry["arcs"])
    # The former star-only dispatch was changed, not removed. Retain both
    # branches explicitly under the new wildcard-aware condition.
    if 992 in entry["lines"]:
        covered_lines.append(1033)
    if [992, 993] in entry["arcs"]:
        covered_arcs.append([1033, 1034])
    if [992, 997] in entry["arcs"]:
        covered_arcs.append([1033, 1038])
    covered_lines.sort()
    covered_arcs.sort()
    missing_lines, missing_arcs = moved_lines(entry["missing_lines"]), moved_arcs(entry["missing_arcs"])
    if (set(covered_lines) & set(missing_lines)
            or len(covered_lines + missing_lines) != len(set(covered_lines + missing_lines))
            or {tuple(arc) for arc in covered_arcs} & {tuple(arc) for arc in missing_arcs}
            or len(covered_arcs + missing_arcs) != len({tuple(arc) for arc in covered_arcs + missing_arcs})):
        raise ValueError("overlapping translated search-release coordinates")
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": missing_lines, "missing_arcs": missing_arcs,
    }
    return result


def migrate_search_sigma_baseline(previous: dict[str, dict[str, object]], old_source: Path,
                                  new_source: Path) -> dict[str, dict[str, object]]:
    """Translate the pinned contextual-sigma fallback; no old coverage is retired."""
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in (
            (old_source, SEARCH_RELEASE_APP_SHA), (new_source, SEARCH_SIGMA_APP_SHA))):
        raise ValueError("search-sigma migration requires exact reviewed sources")
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(
            None, old_source.read_text().splitlines(), new_source.read_text().splitlines(), autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("insert", 735, 735, 735, 740)]:
        raise ValueError("unexpected search-sigma source diff")
    entry = previous.get("backend/app.py")
    if not isinstance(entry, dict):
        raise ValueError("missing search-sigma application baseline")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped search-sigma coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid search-sigma baseline lines")
        return sorted(translate(value) for value in values)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid search-sigma baseline arcs")
        result = []
        for start, end in values:
            # The old index-fallback branch now enters the sigma condition.
            if (start, end) == (735, 737):
                result.append([translate(start), 740])
            else:
                result.append([translate(start), translate(end)])
        return sorted(result)

    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    if (entry.get("covered_lines") != len(covered_lines) or
            entry.get("covered_branches") != len(covered_arcs)):
        raise ValueError("invalid search-sigma baseline counts")
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {"covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
                                "lines": covered_lines, "arcs": covered_arcs,
                                "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"])}
    return result


def proxy_safety_mapping(old_source: Path, new_source: Path, *, streams: bool = False) -> dict[int, int]:
    """Translate every covered coordinate across the pinned transport fix."""
    expected = ((old_source, PROXY_SAFETY_OLD_STREAMS_SHA if streams else PROXY_SAFETY_OLD_APP_SHA),
                (new_source, PROXY_SAFETY_NEW_STREAMS_SHA if streams else PROXY_SAFETY_NEW_APP_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("proxy-safety migration requires exact reviewed sources")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    operations = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes()
    changes = [list(item) for item in operations if item[0] != "equal"]
    digest = hashlib.sha256(json.dumps(changes, separators=(",", ":")).encode()).hexdigest()
    if digest != (PROXY_SAFETY_STREAMS_DIFF_SHA if streams else PROXY_SAFETY_APP_DIFF_SHA):
        raise ValueError("unexpected proxy-safety source diff")
    mapping = {index + 1: new_start + 1 + index - start
               for op, start, end, new_start, _ in operations if op == "equal"
               for index in range(start, end)}
    # These lines only moved under a new ownership/cache-policy guard. The
    # earlier behavior and its covered branches remain mandatory.
    preserved = ({153: 160, 154: 161} if streams else {
        2356: 2360, 2357: 2361, 2358: 2362, 2359: 2364,
        2361: 2366, 2362: 2367, 2363: 2368, 2364: 2369, 2365: 2370,
        2399: 2438, 2400: 2439, 2401: 2440, 2402: 2441, 2403: 2442,
        2404: 2443, 2405: 2444, 2406: 2445, 2407: 2446, 2410: 2449,
        2411: 2450, 2412: 2451, 2413: 2452, 2414: 2453, 2415: 2454,
    })
    if set(preserved) & set(mapping):
        raise ValueError("proxy-safety explicit map overlaps unchanged source")
    for old_line, new_line in preserved.items():
        if old[old_line - 1].strip() != new[new_line - 1].strip() and not (
                streams and old_line in (153, 154)) and not (old_line == 2358 and not streams):
            raise ValueError("proxy-safety mapped behavior changed unexpectedly")
    mapping.update(preserved)
    return mapping


def migrate_proxy_safety_baseline(previous: dict[str, dict[str, object]], old_app: Path, new_app: Path,
                                  old_streams: Path, new_streams: Path) -> dict[str, dict[str, object]]:
    """Preserve prior lines/arcs and force all added transport code to be covered."""
    result = {name: dict(item) for name, item in previous.items()}
    for name, old_path, new_path, streams in (("backend/app.py", old_app, new_app, False),
                                               ("backend/proxy_streams.py", old_streams, new_streams, True)):
        mapping = proxy_safety_mapping(old_path, new_path, streams=streams)
        entry = previous.get(name)
        if not isinstance(entry, dict):
            raise ValueError("missing proxy-safety parent baseline")
        def translate(value: int) -> int:
            if type(value) is not int or abs(value) not in mapping:
                raise ValueError(f"unmapped proxy-safety coordinate: {value}")
            return (-1 if value < 0 else 1) * mapping[abs(value)]
        lines = sorted(translate(value) for value in entry["lines"])
        missing_lines = sorted(translate(value) for value in entry["missing_lines"])
        # The new cache-validation and overflow/early-response guards sit
        # between otherwise unchanged branches. Preserve those original paths
        # at their semantically equivalent new entry/exit points.
        redirected = ({(152, 153): (156, 157), (157, 168): (164, 170)} if streams else
                      {(2398, 2399): (2427, 2431), (2487, 2493): (2527, 2529)})
        def arc(start: int, end: int) -> list[int]:
            replacement = redirected.get((start, end))
            return list(replacement) if replacement is not None else [translate(start), translate(end)]
        arcs = sorted([arc(start, end) for start, end in entry["arcs"]])
        missing_arcs = sorted([arc(start, end) for start, end in entry["missing_arcs"]])
        if (entry["covered_lines"] != len(lines) or entry["covered_branches"] != len(arcs)
                or len(set(lines + missing_lines)) != len(lines) + len(missing_lines)
                or len({tuple(arc) for arc in arcs + missing_arcs}) != len(arcs) + len(missing_arcs)):
            raise ValueError("invalid or overlapping proxy-safety coordinates")
        result[name] = {"covered_lines": len(lines), "covered_branches": len(arcs),
                        "lines": lines, "missing_lines": missing_lines, "arcs": arcs, "missing_arcs": missing_arcs}
    return result


def reviewed_proxy_safety_source(root: Path, source_sha: str) -> bool:
    if source_sha != PROXY_SAFETY_NEW_APP_SHA:
        return False
    anchors = root / "scripts/coverage-anchors"
    expected = ((anchors / "proxy-safety-old-app.py.snapshot", PROXY_SAFETY_OLD_APP_SHA),
                (anchors / "proxy-safety-new-app.py.snapshot", PROXY_SAFETY_NEW_APP_SHA),
                (anchors / "proxy-safety-old-streams.py.snapshot", PROXY_SAFETY_OLD_STREAMS_SHA),
                (anchors / "proxy-safety-new-streams.py.snapshot", PROXY_SAFETY_NEW_STREAMS_SHA),
                (anchors / "proxy-safety-old-range.py.snapshot", RANGE_MODULE_SHA),
                (anchors / "proxy-safety-new-range.py.snapshot", PROXY_SAFETY_NEW_RANGE_SHA),
                (anchors / "proxy-safety-old-backend-coverage-debt.json", PROXY_SAFETY_PARENT_DEBT_SHA),
                (root / "backend/proxy_streams.py", PROXY_SAFETY_NEW_STREAMS_SHA),
                (root / "backend/reader_range_cache.py", PROXY_SAFETY_NEW_RANGE_SHA))
    return all(path.is_file() and hashlib.sha256(path.read_bytes()).hexdigest() == digest for path, digest in expected)


def migrate_native_postings_baseline(previous: dict[str, dict[str, object]],
                                     old_source: Path, new_source: Path) -> dict[str, dict[str, object]]:
    """Translate the reviewed posting-decoder wrapper without relaxing coverage."""
    expected = (
        (old_source, "dba3681ac430bc10a20235a3b06b676f4c481aae71404591a92afefbe559d4ba"),
        (new_source, "95d1c3fd9e41c0bb1cc875f349c611033fea50eb848b5b4ae2fb39bdc2cdeba5"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("native-postings coverage migration requires exact reviewed sources")
    entry = previous.get("backend/search_indexes.py")
    entry_bytes = json.dumps(entry, sort_keys=True, separators=(",", ":")).encode()
    if hashlib.sha256(entry_bytes).hexdigest() != "026965bf8ea2948ce608589c9e920b0b73e6d29d75bcd7ae97549cdcb03e0ae5":
        raise ValueError("native-postings coverage migration requires exact previous index baseline")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("replace", 13, 14, 13, 14), ("replace", 15, 16, 15, 19), ("insert", 41, 41, 44, 58)]:
        raise ValueError("unexpected native-postings source diff")
    # Import and optional-extension fallback retain the same coverage meaning.
    mapping.update({14: 14, 16: 16})

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped native-postings coverage coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid native-postings baseline lines")
        return sorted(translate(number) for number in values)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid native-postings baseline arcs")
        return sorted([[translate(start), translate(end)] for start, end in values])

    if not isinstance(entry, dict):
        raise ValueError("missing native-postings baseline")
    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/search_indexes.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def migrate_star_browse_app_baseline(previous: dict[str, dict[str, object]],
                                     old_source: Path, new_source: Path) -> dict[str, dict[str, object]]:
    """Translate only the reviewed all-star dispatch insertion, preserving every coordinate."""
    expected = (
        (old_source, "db91dcb900f0e4b22a31c62e75b14aec01a62cf7640b8e34fa57a11f53a12920"),
        (new_source, "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d"),
    )
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("star-browse migration requires exact reviewed sources")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("insert", 967, 967, 967, 974)]:
        raise ValueError("unexpected star-browse source diff")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped star-browse coverage coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid star-browse baseline lines")
        result = [translate(number) for number in values]
        if len(result) != len(set(result)):
            raise ValueError("duplicate star-browse baseline lines")
        return sorted(result)

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid star-browse baseline arcs")
        result = [[translate(start), translate(end)] for start, end in values]
        if len(result) != len({tuple(arc) for arc in result}):
            raise ValueError("duplicate star-browse baseline arcs")
        return sorted(result)

    entry = previous.get("backend/app.py")
    if not isinstance(entry, dict):
        raise ValueError("missing star-browse application baseline")
    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    if entry["covered_lines"] != len(covered_lines) or entry["covered_branches"] != len(covered_arcs):
        raise ValueError("invalid star-browse baseline counts")
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def migrate_pdf_limit_app_baseline(previous: dict[str, dict[str, object]],
                                   old_source: Path, new_source: Path) -> dict[str, dict[str, object]]:
    """Move reviewed coverage coordinates across the exact PDF-limit edit.

    Only the now-deleted bounded-range selection and its two obsolete branches
    are retired. Newly introduced PDF paths must be covered separately.
    """
    expected = ((old_source, "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d"),
                (new_source, "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca"))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("PDF limit migration requires exact reviewed sources")
    old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines()
    mapping: dict[int, int] = {}
    changes: list[tuple[str, int, int, int, int]] = []
    for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes():
        if op == "equal":
            mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)})
        else:
            changes.append((op, start, end, new_start, new_end))
    if changes != [("replace", 1624, 1627, 1624, 1627), ("replace", 2034, 2035, 2034, 2036),
                   ("insert", 2383, 2383, 2384, 2386), ("insert", 2450, 2450, 2453, 2454),
                   ("delete", 2458, 2459, 2462, 2462), ("delete", 2460, 2463, 2463, 2463),
                   ("replace", 2508, 2509, 2508, 2511)]:
        raise ValueError("unexpected PDF limit source diff")
    mapping[1627] = 1627  # Replaced import-time constant remains covered.
    # These exact statements and branches implemented the removed special
    # bounded-range ceiling; both new PDF paths are checked as new coverage.
    retired_lines = {2459, 2461, 2463}
    retired_arcs = {(2461, 2463), (2461, 2466)}
    entry = previous.get("backend/app.py")
    if not isinstance(entry, dict):
        raise ValueError("missing PDF limit application baseline")
    line_values = entry.get("lines"), entry.get("missing_lines")
    arc_values = entry.get("arcs"), entry.get("missing_arcs")
    if not all(isinstance(values, list) for values in (*line_values, *arc_values)):
        raise ValueError("invalid PDF limit baseline coordinates")
    if (set(line_values[0]) & set(line_values[1]) or
            {tuple(arc) for arc in arc_values[0]} & {tuple(arc) for arc in arc_values[1]}):
        raise ValueError("PDF limit baseline coordinates overlap")
    if (any(len(values) != len(set(values)) for values in line_values) or
            any(len(values) != len({tuple(arc) for arc in values}) for values in arc_values)):
        raise ValueError("duplicate PDF limit baseline coordinates")

    def translate(number: int) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped PDF limit coverage coordinate: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def lines(values: object, *, missing: bool = False) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid PDF limit baseline lines")
        if missing and retired_lines.intersection(values):
            raise ValueError("retired PDF limit lines cannot be baseline debt")
        result = [translate(number) for number in values if number not in retired_lines]
        if len(result) != len(set(result)):
            raise ValueError("duplicate PDF limit baseline lines")
        return sorted(result)

    def arcs(values: object, *, missing: bool = False) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid PDF limit baseline arcs")
        if missing and retired_arcs.intersection(map(tuple, values)):
            raise ValueError("retired PDF limit arcs cannot be baseline debt")
        result = [[translate(start), translate(end)] for start, end in values if (start, end) not in retired_arcs]
        if len(result) != len({tuple(arc) for arc in result}):
            raise ValueError("duplicate PDF limit baseline arcs")
        return sorted(result)

    if entry.get("covered_lines") != len(entry.get("lines", [])) or entry.get("covered_branches") != len(entry.get("arcs", [])):
        raise ValueError("invalid PDF limit baseline counts")
    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"], missing=True),
    }
    return result


GENERIC_CALLABLES = frozenset({"set", "dict", "list", "tuple", "frozenset", "OrderedDict", "defaultdict", "deque"})


class _TypingNormalizer(ast.NodeTransformer):
    """Erase annotations, casts and subscripted constructors; executable code stays intact."""

    def visit_arg(self, node: ast.arg) -> ast.arg:
        node.annotation = None
        return node

    def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
        self.generic_visit(node)
        node.returns = None
        return node

    def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> ast.AsyncFunctionDef:
        self.generic_visit(node)
        node.returns = None
        return node

    def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AST | None:
        self.generic_visit(node)
        if node.value is None:
            return None
        return ast.copy_location(ast.Assign(targets=[node.target], value=node.value), node)

    def visit_alias(self, node: ast.alias) -> ast.alias:
        if node.asname == node.name:
            node.asname = None
        return node

    def visit_Call(self, node: ast.Call) -> ast.AST:
        self.generic_visit(node)
        if isinstance(node.func, ast.Name) and node.func.id == "cast" and len(node.args) == 2 and not node.keywords:
            return node.args[1]
        if (isinstance(node.func, ast.Subscript) and isinstance(node.func.value, ast.Name)
                and node.func.value.id in GENERIC_CALLABLES):
            node.func = node.func.value
        return node


def _typing_statements(source: str) -> list[tuple[int, str, str]]:
    """Executable statements as (line, kind, structural signature) in source order."""
    tree = _TypingNormalizer().visit(ast.parse(source))
    result: list[tuple[int, str, str]] = []

    def signature(node: ast.stmt) -> str:
        fields = {name: getattr(node, name, None) for name in node._fields}
        for name, value in fields.items():
            if isinstance(value, list) and value and isinstance(value[0], (ast.stmt, ast.excepthandler)):
                fields[name] = []
        if "decorator_list" in fields:
            fields["decorator_list"] = []
        return ast.dump(type(node)(**fields), annotate_fields=False)

    def visit(body: list[ast.stmt]) -> None:
        for node in body:
            if isinstance(node, ast.Match):
                raise ValueError("unsupported match statement in typing migration")
            for decorator in getattr(node, "decorator_list", []):
                result.append((decorator.lineno, "decorator", ast.dump(decorator, annotate_fields=False)))
            result.append((node.lineno, type(node).__name__, signature(node)))
            for field in ("body", "orelse", "finalbody"):
                visit(getattr(node, field, None) or [])
            for handler in getattr(node, "handlers", None) or []:
                plain = ast.ExceptHandler(type=handler.type, name=handler.name, body=[])
                result.append((handler.lineno, "ExceptHandler", ast.dump(plain, annotate_fields=False)))
                visit(handler.body)

    visit(tree.body)
    return result


def typing_alignment(old_source: str, new_source: str
                     ) -> tuple[dict[int, int], dict[int, int], list[int], list[list[object]]]:
    """Align two sources statement by statement; only type-only insertions may change the shape."""
    old, new = _typing_statements(old_source), _typing_statements(new_source)
    lines: dict[int, int] = {}
    entries: dict[int, int] = {}
    added: list[int] = []
    review: list[list[object]] = []
    for op, a0, a1, b0, b1 in difflib.SequenceMatcher(None, [s[2] for s in old], [s[2] for s in new],
                                                      autojunk=False).get_opcodes():
        if op == "equal":
            for offset in range(a1 - a0):
                lines[old[a0 + offset][0]] = entries[old[a0 + offset][0]] = new[b0 + offset][0]
            continue
        olds, news = old[a0:a1], new[b0:b1]
        review.append([op, [[s[0], s[1]] for s in olds], [[s[0], s[1]] for s in news]])
        entry = b0
        for kop, k0, k1, m0, m1 in difflib.SequenceMatcher(None, [s[1] for s in olds], [s[1] for s in news],
                                                           autojunk=False).get_opcodes():
            if kop == "equal":
                for offset in range(k1 - k0):
                    lines[olds[k0 + offset][0]] = news[m0 + offset][0]
                    entries[olds[k0 + offset][0]] = new[entry][0]
                    entry = b0 + m0 + offset + 1
            elif kop == "insert":
                added.extend(s[0] for s in news[m0:m1])
            else:
                raise ValueError("typing edit changed statement kinds")
    return lines, entries, added, review


def migrate_backend_typing_app_baseline(previous: dict[str, dict[str, object]],
                                        old_source: Path, new_source: Path) -> dict[str, dict[str, object]]:
    """Translate coordinates across the reviewed annotation-only edit of backend/app.py."""
    expected = ((old_source, READER_ARCHIVE_NEW_APP_SHA), (new_source, TYPING_NEW_APP_SHA))
    if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected):
        raise ValueError("backend typing coverage migration requires exact reviewed sources")
    mapping, entries, added, review = typing_alignment(old_source.read_text(), new_source.read_text())
    digest = hashlib.sha256(json.dumps({"added": added, "review": review}, separators=(",", ":")).encode()).hexdigest()
    if digest != TYPING_REVIEW_SHA:
        raise ValueError("unexpected backend typing source diff")
    entry = previous.get("backend/app.py")
    if not isinstance(entry, dict):
        raise ValueError("missing backend typing application baseline")

    def line(number: object) -> int:
        if type(number) is not int or abs(number) not in mapping:
            raise ValueError(f"unmapped backend typing line: {number}")
        return (-1 if number < 0 else 1) * mapping[abs(number)]

    def target(number: object) -> int:
        if type(number) is int and number > 0 and number in entries:
            return entries[number]
        return line(number)

    def lines(values: object) -> list[int]:
        if not isinstance(values, list):
            raise ValueError("invalid backend typing baseline lines")
        result = sorted(line(number) for number in values)
        if len(result) != len(set(result)):
            raise ValueError("duplicate backend typing baseline lines")
        return result

    def arcs(values: object) -> list[list[int]]:
        if not isinstance(values, list):
            raise ValueError("invalid backend typing baseline arcs")
        result = sorted([line(start), target(end)] for start, end in values)
        if len(result) != len({tuple(arc) for arc in result}):
            raise ValueError("duplicate backend typing baseline arcs")
        return result

    covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"])
    if entry.get("covered_lines") != len(covered_lines) or entry.get("covered_branches") != len(covered_arcs):
        raise ValueError("invalid backend typing baseline counts")
    result = {name: dict(item) for name, item in previous.items()}
    result["backend/app.py"] = {
        "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs),
        "lines": covered_lines, "arcs": covered_arcs,
        "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]),
    }
    return result


def type_only_lines(path: Path) -> set[int]:
    """Only typing overload/protocol declarations are non-executable here."""
    source = path.read_text()
    tree = ast.parse(source)
    lines: set[int] = set()
    # coverage.py associates blank separators with the preceding overload or
    # Protocol method. Blank physical lines have no executable behavior.
    lines.update(index for index, line in enumerate(source.splitlines(), 1) if not line.strip())
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and any(
                isinstance(dec, ast.Name) and dec.id == "overload" for dec in node.decorator_list):
            lines.update(range(node.lineno, (node.end_lineno or node.lineno) + 1))
            lines.update(dec.lineno for dec in node.decorator_list)
        elif isinstance(node, ast.ClassDef) and any(
                isinstance(base, ast.Name) and base.id == "Protocol" for base in node.bases):
            lines.update(range(node.lineno, (node.end_lineno or node.lineno) + 1))
    return lines


def migrate_ci_baseline_to_lifespan_parent(root: Path, previous: dict) -> dict:
    """Replay the audited chain from the independently pinned CI baseline."""
    anchors = root / "scripts/coverage-anchors"
    anchor = anchors / "search-projection-old-backend-coverage-debt.json"
    if (hashlib.sha256(anchor.read_bytes()).hexdigest() !=
            "70e9311f50ba1407227de9ba42fd591d93826f92898d07873ce5f58cbebf2a29"
            or previous != json.loads(anchor.read_text())):
        raise ValueError("transport migration requires the independently pinned parent or CI debt")
    # Each existing translator checks its exact reviewed sources and preserves
    # covered/missing coordinates. Use only immutable snapshots, not live
    # canonical modules or current coverage reports.
    def source(name: str) -> Path:
        return anchors / (name + ".py.snapshot")
    steps = (
        (migrate_search_projection_app_baseline, source("search-projection-old-app"),
         source("search-projection-new-app"), source("search-projection-new-module")),
        (migrate_search_candidates_app_baseline, source("search-projection-new-app"),
         source("search-candidates-new-app"), source("search-candidates-new-module")),
        (migrate_search_bootstrap_app_baseline, source("search-candidates-new-app"),
         source("search-bootstrap-new-app"), source("search-bootstrap-new-module")),
        (migrate_native_postings_baseline, source("native-postings-old-index"), source("native-postings-new-index")),
        (migrate_star_browse_app_baseline, source("star-browse-old-app"), source("pdf-limit-old-app")),
        (migrate_pdf_limit_app_baseline, source("pdf-limit-old-app"), source("reader-archive-old-app")),
        (migrate_reader_archive_app_baseline, source("reader-archive-old-app"),
         source("reader-archive-new-app"), source("reader-archive-new-module")),
        (migrate_backend_typing_app_baseline, source("reader-archive-new-app"), source("backend-typing-new-app")),
        (migrate_folder_contents_app_baseline, source("backend-typing-new-app"),
         source("range-cache-old-app"), source("folder-contents-new-module")),
        (migrate_reader_range_app_baseline, source("range-cache-old-app"),
         source("term-candidates-old-app"), source("proxy-safety-old-range")),
        (migrate_search_term_app_baseline, source("term-candidates-old-app"),
         source("download-warm-old-app"), source("single-term-old-module")),
        (migrate_download_warm_app_baseline, source("download-warm-old-app"),
         source("single-term-old-app"), source("download-warm-new-module")),
        (migrate_single_term_app_baseline, source("single-term-old-app"),
         source("search-release-old-app"), source("search-release-old-term")),
        (migrate_search_release_baseline, source("search-release-old-app"), source("search-release-new-app"),
         source("search-release-old-term"), source("search-release-new-term")),
        (migrate_search_sigma_baseline, source("search-release-new-app"), source("search-sigma-new-app")),
        (migrate_seo_path_baseline, source("seo-path-old-seo"), source("seo-path-new-seo"),
         anchors / "seo-path-old-debt.json"),
        (migrate_proxy_safety_baseline, source("proxy-safety-old-app"), source("proxy-safety-new-app"),
         source("proxy-safety-old-streams"), source("proxy-safety-new-streams")),
        (migrate_search_browse_baseline, source("proxy-safety-new-app"),
         source("lifespan-parent-app"), source("search-browse-new-module")),
    )
    for migrate, *sources in steps:
        previous = migrate(previous, *sources)
    return previous


def coverage_debt_errors(baseline: dict, previous_baseline: dict) -> list[str]:
    """Require every prior exercised coordinate and forbid growing missing debt."""
    errors = []
    for path in sorted(set(baseline) - set(previous_baseline)):
        errors.append(f"backend coverage debt cannot grow: {path}")
    for path in sorted(set(baseline) & set(previous_baseline)):
        old, new = previous_baseline[path], baseline[path]
        if (new["covered_lines"] < old["covered_lines"] or new["covered_branches"] < old["covered_branches"]
                or not set(old["lines"]) <= set(new["lines"]) or not {
                    tuple(arc) for arc in old["arcs"]} <= {tuple(arc) for arc in new["arcs"]}
                or not set(new["missing_lines"]) <= set(old["missing_lines"])
                or not {tuple(arc) for arc in new["missing_arcs"]} <= {
                    tuple(arc) for arc in old["missing_arcs"]}):
            errors.append(f"backend coverage debt cannot remove prior exercised lines or arcs: {path}")
    return errors


def coverage_errors(root: Path, report: dict[str, object], baseline: dict[str, dict[str, object]],
                    previous_baseline: dict[str, dict[str, object]] | None = None, *,
                    baseline_layout: str = "current", previous_layout: str = "current") -> list[str]:
    if baseline_layout not in ("current", "lifespan-parent") or previous_layout not in ("current", "lifespan-parent"):
        raise ValueError("unknown coverage baseline layout")
    if baseline_layout == "lifespan-parent" or (previous_baseline is not None and previous_layout == "lifespan-parent"):
        app_source = root / "backend/app.py"
        if not app_source.is_file() or not reviewed_lifespan_source(root, hashlib.sha256(app_source.read_bytes()).hexdigest()):
            raise ValueError("lifespan parent layout requires reviewed target")
        anchor = root / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot"
        if baseline_layout == "lifespan-parent":
            baseline = migrate_lifespan_baseline(baseline, anchor, app_source)
        if previous_baseline is not None and previous_layout == "lifespan-parent":
            previous_baseline = migrate_lifespan_baseline(previous_baseline, anchor, app_source)
    meta = report.get("meta")
    if not isinstance(meta, dict) or meta.get("branch_coverage") is not True:
        return ["coverage JSON must include branch coverage"]
    files = report.get("files")
    if not isinstance(files, dict):
        return ["coverage JSON has no files"]
    sources = {path.relative_to(root).as_posix() for path in (root / "backend").rglob("*.py")
               if "__pycache__" not in path.relative_to(root).parts}
    sources.add("app.py")
    errors: list[str] = []
    transport = (root / 'backend/app.py').is_file() and transport_layout(root)
    if transport:
        # Independent files often resolve to the same historical inventory.
        # Validate its migration once per check, not once per equal copy. The
        # comparison stays in place; distinct inventories are always verified.
        same_baseline = (previous_baseline is not None and
                         json.dumps(previous_baseline, sort_keys=True) == json.dumps(baseline, sort_keys=True))
        baseline = transport_baseline(root, baseline)
        if same_baseline:
            previous_baseline = baseline
        elif previous_baseline is not None:
            previous_baseline = transport_baseline(root, previous_baseline)
    if previous_baseline is not None:
        errors.extend(coverage_debt_errors(baseline, previous_baseline))
    for path in sorted(set(baseline) - sources):
        errors.append(f"stale backend coverage debt entry: {path}")
    for path in sorted(sources):
        source_text = (root / path).read_text()
        if any(marker in source_text.lower() for marker in (
                "pragma: no cover", "pragma: no branch", "pragma: no mutate")):
            errors.append(f"coverage pragmas are forbidden in backend source: {path}")
        if path == "backend/app.py" and transport and path in baseline:
            # Source-pinned migration preserves the existing browse dispatch.
            # Refactor23 instead requires 100% for the entire app and all
            # extracted modules after validating the parent's dispatch ratchet.
            entry = baseline[path]
            if not {1062, 1063} <= set(entry['lines']) or not {
                    (1062, 1063), (1062, 1067)} <= {tuple(arc) for arc in entry['arcs']}:
                errors.append("star-browse coverage baseline must retain both dispatch branches")
        if path == "backend/app.py" and not transport and (root / "scripts/coverage-anchors/star-browse-old-app.py.snapshot").exists():
            source_sha = hashlib.sha256(source_text.encode()).hexdigest()
            pdf_anchor = root / "scripts/coverage-anchors/pdf-limit-old-app.py.snapshot"
            reviewed_pdf_source = pdf_anchor.exists() and hashlib.sha256(pdf_anchor.read_bytes()).hexdigest() == "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d"
            archive_anchor = root / "scripts/coverage-anchors/reader-archive-old-app.py.snapshot"
            reviewed_archive_source = (reviewed_pdf_source and archive_anchor.exists() and
                                       hashlib.sha256(archive_anchor.read_bytes()).hexdigest() == READER_ARCHIVE_OLD_APP_SHA)
            typing_anchor = root / "scripts/coverage-anchors/backend-typing-new-app.py.snapshot"
            reviewed_typing_source = (reviewed_archive_source and typing_anchor.exists() and
                                      hashlib.sha256(typing_anchor.read_bytes()).hexdigest() == TYPING_NEW_APP_SHA)
            folder_source = root / "backend/folder_contents.py"
            reviewed_folder_source = (reviewed_typing_source and folder_source.exists() and
                                      hashlib.sha256(folder_source.read_bytes()).hexdigest() ==
                                      "931758f2f2b76b4cbe51a00b3a5f408c48d9b4e42104476ee21cdd49a083b56d")
            sigma_source = root / "scripts/coverage-anchors/search-sigma-new-app.py.snapshot"
            sigma_debt = root / "scripts/coverage-anchors/search-sigma-old-debt.json"
            reviewed_browse = (reviewed_browse_source(root, source_sha) or
                               reviewed_lifespan_source(root, source_sha))
            reviewed_proxy = reviewed_proxy_safety_source(root, source_sha) or reviewed_browse
            reviewed_sigma = ((source_sha in (SEARCH_SIGMA_APP_SHA, SEARCH_SIGMA_VERSION_APP_SHA) or reviewed_proxy)
                              and sigma_source.exists() and sigma_debt.exists() and
                              hashlib.sha256(sigma_source.read_bytes()).hexdigest() == SEARCH_SIGMA_APP_SHA and
                              hashlib.sha256(sigma_debt.read_bytes()).hexdigest() == SEARCH_SIGMA_OLD_DEBT_SHA)
            release_source_sha = SEARCH_RELEASE_APP_SHA if reviewed_sigma else source_sha
            if source_sha != "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d" and not (
                    reviewed_pdf_source and source_sha == "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca") and not (
                    reviewed_archive_source and source_sha == READER_ARCHIVE_NEW_APP_SHA) and not (
                    reviewed_typing_source and source_sha == TYPING_NEW_APP_SHA) and not (
                    reviewed_folder_source and source_sha == RANGE_OLD_APP_SHA) and not (
                    reviewed_folder_source and source_sha == RANGE_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and
                    (root / "backend/reader_range_cache.py").exists() and
                    hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA) and not (
                    reviewed_folder_source and source_sha == TERM_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and
                    (root / "backend/reader_range_cache.py").exists() and
                    hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA and
                    (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and
                    (root / "backend/search_term_candidates.py").exists() and
                    hashlib.sha256((root / "backend/search_term_candidates.py").read_bytes()).hexdigest() == TERM_MODULE_SHA) and not (
                    reviewed_folder_source and source_sha == WARM_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and
                    (root / "backend/reader_range_cache.py").exists() and
                    hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA and
                    (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and
                    (root / "backend/search_term_candidates.py").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").read_bytes()).hexdigest() == TERM_MODULE_SHA and
                    (root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").read_bytes()).hexdigest() == TERM_NEW_APP_SHA and
                    (root / "backend/download_warm.py").exists() and
                    hashlib.sha256((root / "backend/download_warm.py").read_bytes()).hexdigest() == WARM_MODULE_SHA) and not (
                    reviewed_folder_source and source_sha == SINGLE_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and
                    (root / "backend/reader_range_cache.py").exists() and
                    hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA and
                    (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").read_bytes()).hexdigest() == TERM_MODULE_SHA and
                    (root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").read_bytes()).hexdigest() == TERM_NEW_APP_SHA and
                    (root / "backend/download_warm.py").exists() and
                    hashlib.sha256((root / "backend/download_warm.py").read_bytes()).hexdigest() == WARM_MODULE_SHA and
                    (root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").read_bytes()).hexdigest() == WARM_NEW_APP_SHA and
                    (root / "backend/search_term_candidates.py").exists() and
                    hashlib.sha256((root / "backend/search_term_candidates.py").read_bytes()).hexdigest() == SINGLE_MODULE_SHA) and not (
                    reviewed_folder_source and release_source_sha == SEARCH_RELEASE_APP_SHA and
                    (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and
                    (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").read_bytes()).hexdigest() == TERM_MODULE_SHA and
                    (root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").read_bytes()).hexdigest() == TERM_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").read_bytes()).hexdigest() == WARM_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/search-release-old-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/search-release-old-app.py.snapshot").read_bytes()).hexdigest() == SINGLE_NEW_APP_SHA and
                    (root / "scripts/coverage-anchors/search-release-new-app.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/search-release-new-app.py.snapshot").read_bytes()).hexdigest() == SEARCH_RELEASE_APP_SHA and
                    (root / "scripts/coverage-anchors/search-release-old-term.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/search-release-old-term.py.snapshot").read_bytes()).hexdigest() == SINGLE_MODULE_SHA and
                    (root / "scripts/coverage-anchors/search-release-new-term.py.snapshot").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/search-release-new-term.py.snapshot").read_bytes()).hexdigest() == SEARCH_RELEASE_TERM_SHA and
                    (root / "scripts/coverage-anchors/search-release-old-backend-coverage-debt.json").exists() and
                    hashlib.sha256((root / "scripts/coverage-anchors/search-release-old-backend-coverage-debt.json").read_bytes()).hexdigest() == SEARCH_RELEASE_DEBT_SHA and
                    (root / "backend/search_term_candidates.py").exists() and
                    hashlib.sha256((root / "backend/search_term_candidates.py").read_bytes()).hexdigest() == SEARCH_RELEASE_TERM_SHA and
                    (root / "backend/reader_range_cache.py").exists() and
                    (hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA
                     or reviewed_proxy) and
                    (root / "backend/download_warm.py").exists() and
                    hashlib.sha256((root / "backend/download_warm.py").read_bytes()).hexdigest() == WARM_MODULE_SHA):
                errors.append("star-browse coverage ratchet requires exact reviewed app source")
            else:
                entry = baseline.get(path, {})
                if reviewed_browse:
                    first, second, third = 1057, 1058, 1062
                elif reviewed_proxy:
                    first, second, third = 1040, 1041, 1045
                elif reviewed_sigma:
                    first, second, third = 1038, 1039, 1043
                elif source_sha == SEARCH_RELEASE_APP_SHA:
                    first, second, third = 1033, 1034, 1038
                elif source_sha == SINGLE_NEW_APP_SHA:
                    first, second, third = 992, 993, 997
                elif source_sha == WARM_NEW_APP_SHA:
                    first, second, third = 991, 992, 996
                elif source_sha == TERM_NEW_APP_SHA:
                    first, second, third = 989, 990, 994
                elif source_sha == RANGE_NEW_APP_SHA:
                    first, second, third = 1037, 1038, 1042
                elif source_sha == RANGE_OLD_APP_SHA:
                    first, second, third = 1036, 1037, 1041
                else:
                    first, second, third = (1035, 1036, 1040) if source_sha == TYPING_NEW_APP_SHA else (971, 972, 976)
                if not {first, second} <= set(entry.get("lines", [])) or not {
                        (first, second), (first, third)} <= {tuple(arc) for arc in entry.get("arcs", [])}:
                    errors.append("star-browse coverage baseline must retain both dispatch branches")
        item = files.get(path)
        if not isinstance(item, dict) or not isinstance(item.get("summary"), dict):
            errors.append(f"missing backend coverage report: {path}")
            continue
        summary = item["summary"]
        excluded = item.get("excluded_lines")
        if (not isinstance(excluded, list) or not all(isinstance(value, int) for value in excluded)
                or not set(excluded) <= type_only_lines(root / path)):
            errors.append(f"non-type-only coverage exclusions are forbidden: {path}")
        statements = summary.get("num_statements")
        branches = summary.get("num_branches")
        covered = summary.get("covered_lines")
        covered_branches = summary.get("covered_branches")
        executed_lines, missing_lines = item.get("executed_lines"), item.get("missing_lines")
        executed_arcs, missing_arcs = item.get("executed_branches"), item.get("missing_branches")
        if not all(isinstance(value, list) for value in (executed_lines, missing_lines, executed_arcs, missing_arcs)):
            errors.append(f"coverage JSON lacks detailed lines or branch arcs: {path}")
            continue
        if not all(isinstance(value, int) and value >= 0
                   for value in (statements, branches, covered, covered_branches)):
            errors.append(f"invalid backend coverage summary: {path}")
            continue
        if covered > statements or covered_branches > branches:
            errors.append(f"impossible backend coverage summary: {path}")
            continue
        if path in baseline:
            minimum = baseline[path]
            if set(minimum["lines"]) & set(minimum["missing_lines"]):
                errors.append(f"backend coverage baseline lines overlap: {path}")
            if {tuple(arc) for arc in minimum["arcs"]} & {tuple(arc) for arc in minimum["missing_arcs"]}:
                errors.append(f"backend coverage baseline branches overlap: {path}")
            if covered < minimum["covered_lines"] or covered_branches < minimum["covered_branches"]:
                errors.append(f"backend coverage regressed: {path}")
            if not set(map(int, minimum["lines"])) <= set(executed_lines):
                errors.append(f"previously covered lines not exercised: {path}")
            if not {tuple(arc) for arc in minimum["arcs"]} <= {tuple(arc) for arc in executed_arcs}:
                errors.append(f"previously covered branches not exercised: {path}")
            old_lines = set(minimum["lines"]) | set(minimum["missing_lines"])
            old_arcs = {tuple(arc) for arc in minimum["arcs"] + minimum["missing_arcs"]}
            if not set(missing_lines) <= old_lines:
                errors.append(f"new or changed backend lines lack tests: {path}")
            if not {tuple(arc) for arc in missing_arcs} <= old_arcs:
                errors.append(f"new or changed backend branches lack tests: {path}")
        elif covered != statements or covered_branches != branches:
            errors.append(f"new backend module requires 100% statements and branches: {path}")
    return errors


def main() -> int:
    if len(sys.argv) not in (2, 3, 4, 5):
        print("usage: python scripts/check_backend_coverage.py COVERAGE_JSON [BASELINE_DEBT_JSON [OLD_APP_SOURCE [FOLDER_TREE_OLD_APP_SOURCE]]]", file=sys.stderr)
        return 2
    report = json.loads(Path(sys.argv[1]).read_text())
    baseline = json.loads((ROOT / BASELINE_FILE).read_text())
    previous = json.loads(Path(sys.argv[2]).read_text()) if len(sys.argv) >= 3 else None
    if transport_layout(ROOT):
        try:
            if len(sys.argv) > 3:
                raise ValueError('transport layout accepts the pinned parent baseline only')
            errors = coverage_errors(ROOT, report, baseline, previous)
        except (KeyError, OSError, ValueError) as error:
            print(f'transport coverage migration failed: {error}', file=sys.stderr)
            return 1
        if errors:
            print('\n'.join(errors), file=sys.stderr)
            return 1
        print('Backend coverage inventory: pinned parent retained; changed code and new modules fully covered')
        return 0
    if len(sys.argv) >= 4 and previous is not None:
        previous = migrate_retired_txt_app_baseline(ROOT, previous, Path(sys.argv[3]))
    if len(sys.argv) == 5 and previous is not None:
        previous = migrate_folder_tree_app_baseline(ROOT, previous, Path(sys.argv[4]), ROOT / "backend/app.py",
                                                    ROOT / "backend/folder_tree.py")
    # A pinned old baseline can cross the audited folder-tree extraction only
    # when the exact source/anchor hashes match and no extracted line/arc was
    # previously uncovered. Normal same-revision baselines stay untouched.
    if len(sys.argv) == 3 and previous is not None:
        projection_migrated = False
        candidates_migrated = False
        anchor = ROOT / "scripts/coverage-anchors/folder-tree-old-backend-coverage-debt.json"
        if anchor.exists() and hashlib.sha256(anchor.read_bytes()).hexdigest() == "1417d624b79c06c77f4abe326f7bb9e60af34446af9873623a7d3d1efdbfddf9":
            anchored = json.loads(anchor.read_text())
            if previous == anchored:
                previous = migrate_folder_tree_app_baseline(
                    ROOT, previous, ROOT / "scripts/coverage-anchors/folder-tree-old-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/folder-tree-new-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/folder-tree-new-module.py.snapshot")
        projection = ROOT / "scripts/coverage-anchors/search-projection-old-backend-coverage-debt.json"
        if (projection.exists() and hashlib.sha256(projection.read_bytes()).hexdigest()
                == "70e9311f50ba1407227de9ba42fd591d93826f92898d07873ce5f58cbebf2a29"):
            if previous == json.loads(projection.read_text()):
                previous = migrate_search_projection_app_baseline(
                    previous, ROOT / "scripts/coverage-anchors/search-projection-old-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/search-projection-new-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/search-projection-new-module.py.snapshot")
                projection_migrated = True
        candidate = ROOT / "scripts/coverage-anchors/search-candidates-old-backend-coverage-debt.json"
        if (candidate.exists() and hashlib.sha256(candidate.read_bytes()).hexdigest()
                == "fd77ed345dee0c50314cc2ed7941e25f358bdbd4118ce7af308a5d1aa7046a8c"):
            if projection_migrated or previous == json.loads(candidate.read_text()):
                previous = migrate_search_candidates_app_baseline(
                    previous, ROOT / "scripts/coverage-anchors/search-projection-new-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/search-candidates-new-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/search-candidates-new-module.py.snapshot")
                candidates_migrated = True
        bootstrap = ROOT / "scripts/coverage-anchors/search-bootstrap-old-backend-coverage-debt.json"
        if (bootstrap.exists() and hashlib.sha256(bootstrap.read_bytes()).hexdigest()
                == "0313ee14bed3d7638251ff3252ae1f7a16409ed1f8ab97ee6dafa13497ab4eba"):
            if candidates_migrated or previous == json.loads(bootstrap.read_text()):
                previous = migrate_search_bootstrap_app_baseline(
                    previous, ROOT / "scripts/coverage-anchors/search-candidates-new-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/search-bootstrap-new-app.py.snapshot",
                    ROOT / "scripts/coverage-anchors/search-bootstrap-new-module.py.snapshot")
    native_anchor = ROOT / "scripts/coverage-anchors/native-postings-old-index.py.snapshot"
    if previous is not None and native_anchor.exists() and previous.get("backend/search_indexes.py") != baseline.get("backend/search_indexes.py"):
        previous = migrate_native_postings_baseline(previous, native_anchor, ROOT / "backend/search_indexes.py")
    star_anchor = ROOT / "scripts/coverage-anchors/star-browse-old-app.py.snapshot"
    pdf_anchor = ROOT / "scripts/coverage-anchors/pdf-limit-old-app.py.snapshot"
    pdf_baseline_anchor = ROOT / "scripts/coverage-anchors/pdf-limit-old-backend-coverage-debt.json"
    archive_old = ROOT / "scripts/coverage-anchors/reader-archive-old-app.py.snapshot"
    archive_new = ROOT / "scripts/coverage-anchors/reader-archive-new-app.py.snapshot"
    archive_module = ROOT / "scripts/coverage-anchors/reader-archive-new-module.py.snapshot"
    archive_debt = ROOT / "scripts/coverage-anchors/reader-archive-old-backend-coverage-debt.json"
    # The pre-extraction baseline already includes the star and PDF edits, so it
    # crosses only the reviewed reader-archive move; older baselines chain to it.
    direct_archive_baseline = (archive_debt.exists() and previous is not None and
                               hashlib.sha256(archive_debt.read_bytes()).hexdigest() == READER_ARCHIVE_OLD_DEBT_SHA and
                               previous == json.loads(archive_debt.read_text()))
    direct_pdf_baseline = (pdf_baseline_anchor.exists() and
                           hashlib.sha256(pdf_baseline_anchor.read_bytes()).hexdigest() == "1276a5ac7800edeb0c4b5af19df9215a75ad26cb4c4285e648023076c1bcbac2" and
                           previous is not None and previous.get("backend/app.py") ==
                           json.loads(pdf_baseline_anchor.read_text()).get("backend/app.py"))
    typing_new = ROOT / "scripts/coverage-anchors/backend-typing-new-app.py.snapshot"
    typing_debt = ROOT / "scripts/coverage-anchors/backend-typing-old-backend-coverage-debt.json"
    # A baseline already in post-extraction coordinates crosses only the typing edit.
    direct_typing_baseline = (typing_debt.exists() and previous is not None and
                              hashlib.sha256(typing_debt.read_bytes()).hexdigest() == TYPING_OLD_DEBT_SHA and
                              previous == json.loads(typing_debt.read_text()))
    # Only the exact typed-layout baseline can bypass older layout migrations.
    # Recognize its source-independent app entry so independently pinned and
    # same-parent comparisons work without accepting arbitrary coordinates.
    folder_parent_digest = "744882b25d160a5f6009033a43cd57d6568e8fb381e14b108ac9f8e5bd4a8b55"
    direct_folder_parent = (previous is not None and
                            hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True,
                                                      separators=(",", ":")).encode()).hexdigest() == folder_parent_digest)
    range_parent_digest = "aace013b131faa8de56b81f039bae24842a8f0d769977ea8b08b8daccffbf1f0"
    direct_range_parent = (previous is not None and
                           hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True,
                                                     separators=(",", ":")).encode()).hexdigest() == range_parent_digest)
    term_parent_digest = "c0e92d7bb0d9939662e84fc7c0b63c60a6ac2124491773a42c19303046ee58a5"
    direct_term_parent = (previous is not None and
                          hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True,
                                                    separators=(",", ":")).encode()).hexdigest() == term_parent_digest)
    warm_parent_digest = "fb53051c2f393bace1273912cc5a0fd609858756746b798bd84dd1fe2b7d9591"
    direct_warm_parent = (previous is not None and
                          hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True,
                                                    separators=(",", ":")).encode()).hexdigest() == warm_parent_digest)
    single_parent_digest = "af6016448274db1e2307c4c6a138718d8cb7ab9591e2f7779dd6d0ea4f17f668"
    direct_single_parent = (previous is not None and
                            hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True,
                                                      separators=(",", ":")).encode()).hexdigest() == single_parent_digest)
    # Same-source debt improvements stay in current coordinates. Running the
    # historical translators again would treat an exact parent as an old layout.
    release_old = ROOT / "scripts/coverage-anchors/search-release-old-app.py.snapshot"
    release_new = ROOT / "scripts/coverage-anchors/search-release-new-app.py.snapshot"
    release_debt = ROOT / "scripts/coverage-anchors/search-release-old-backend-coverage-debt.json"
    release_old_term = ROOT / "scripts/coverage-anchors/search-release-old-term.py.snapshot"
    release_new_term = ROOT / "scripts/coverage-anchors/search-release-new-term.py.snapshot"
    sigma_new = ROOT / "scripts/coverage-anchors/search-sigma-new-app.py.snapshot"
    sigma_debt = ROOT / "scripts/coverage-anchors/search-sigma-old-debt.json"
    current_sha = hashlib.sha256((ROOT / "backend/app.py").read_bytes()).hexdigest()
    lifespan_layout = reviewed_lifespan_source(ROOT, current_sha)
    # Parent-coordinate baseline is independently pinned. Current-coordinate
    # inputs are identified by explicit membership against that fixed layout,
    # never by comparing the two untrusted baseline arguments to one another.
    parent_debt_path = ROOT / "scripts/coverage-anchors/lifespan-parent-backend-coverage-debt.json"
    if lifespan_layout and (not parent_debt_path.is_file() or
            hashlib.sha256(parent_debt_path.read_bytes()).hexdigest() != LIFESPAN_PARENT_DEBT_SHA):
        print("lifespan parent debt anchor missing or tampered", file=sys.stderr)
        return 1
    parent_debt = json.loads(parent_debt_path.read_text()) if lifespan_layout else None
    baseline_layout = previous_layout = "current"
    if lifespan_layout:
        try:
            baseline_layout = lifespan_baseline_layout(baseline, parent_debt,
                ROOT / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot", ROOT / "backend/app.py")
            if previous is not None:
                try:
                    previous_layout = lifespan_baseline_layout(previous, parent_debt,
                        ROOT / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot", ROOT / "backend/app.py")
                except ValueError:
                    # Historical layouts must still pass the existing pinned
                    # translators; they are not assumed to be current.
                    previous_layout = "lifespan-parent"
                if previous_layout == "current":
                    # Historical translators below operate on parent coordinates.
                    # Same-layout inputs are compared separately at the end.
                    current_previous, previous = previous, None
                else:
                    current_previous = None
            else:
                current_previous = None
        except (KeyError, TypeError, ValueError) as error:
            print(f"lifespan baseline layout error: {error}", file=sys.stderr)
            return 1
    else:
        current_previous = None
    browse_layout = reviewed_browse_source(ROOT, current_sha) or lifespan_layout
    browse_target = (ROOT / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot"
                     if lifespan_layout else ROOT / "backend/app.py")
    proxy_layout = reviewed_proxy_safety_source(ROOT, current_sha) or browse_layout
    sigma_layout = (sigma_new.exists() and sigma_debt.exists() and
                    hashlib.sha256(sigma_new.read_bytes()).hexdigest() == SEARCH_SIGMA_APP_SHA and
                    hashlib.sha256(sigma_debt.read_bytes()).hexdigest() == SEARCH_SIGMA_OLD_DEBT_SHA and
                    (current_sha in (SEARCH_SIGMA_APP_SHA, SEARCH_SIGMA_VERSION_APP_SHA) or proxy_layout))
    release_layout = (release_old.exists() and release_new.exists() and
                      (sigma_layout or hashlib.sha256((ROOT / "backend/app.py").read_bytes()).hexdigest() == SEARCH_RELEASE_APP_SHA))
    direct_release_parent = (previous is not None and release_layout and release_debt.exists() and
                             hashlib.sha256(release_debt.read_bytes()).hexdigest() == SEARCH_RELEASE_DEBT_SHA and
                             previous.get("backend/app.py") == json.loads(release_debt.read_text()).get("backend/app.py"))
    direct_sigma_parent = (previous is not None and sigma_layout and
                           previous.get("backend/app.py") == json.loads(sigma_debt.read_text()).get("backend/app.py"))
    proxy_parent = ROOT / "scripts/coverage-anchors/proxy-safety-old-backend-coverage-debt.json"
    browse_direct_parent = (previous is not None and browse_layout and
                            hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True,
                                                      separators=(",", ":")).encode()).hexdigest() == BROWSE_PARENT_ENTRY_SHA)
    # A parent already at the reviewed sigma layout must not pass through the
    # older translators a second time, including older unaffected SEO debt.
    proxy_baseline = json.loads(proxy_parent.read_text()) if proxy_layout and proxy_parent.is_file() else {}
    direct_proxy_parent = (previous is not None and proxy_layout and all(
        previous.get(name) == proxy_baseline.get(name) for name in ("backend/app.py", "backend/proxy_streams.py")))
    current_release_parent = direct_sigma_parent or direct_proxy_parent or browse_direct_parent
    if previous is not None:
        parent_entry = previous.get("backend/app.py")
        parent_digest = hashlib.sha256(json.dumps(parent_entry, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
        # These exact fixtures exercise improvements in the new layout. Their
        # parent coordinates are already current, not inputs to a translator.
        current_release_parent = direct_sigma_parent or direct_proxy_parent or browse_direct_parent or (release_layout and parent_digest in (
            "e02a53f3222a025a886ec3415574f15bbd26fcc1283c2277920912082b171628",
            "16eec37e636ed6f7f3be140ad1bba5f43337b5181a3446156618c72071f9f40b",
            "3e74a5905c3f96bf9aef82f4eea281a5322981cbd70b0a0cf6e635bb5d1f6338",
        ))
        if parent_digest in ("e7183c108470275129c4b12f2ad9f8e7a3d572ad14d46a96109f65ad10331d99",
                              "0d241c8acac39f666a18b0f3da843320a98fe37ce59da7fab8a4c23bb9bb17e6",
                              "9f32a4a3f31ea8556c6f2295874203c17bf9c39c658ba3bd454302eb42d24477",
                              "3ef2aa68154c57eec732e9315b65e02bca8ac9a23570ee02b48c538bf5359858") or direct_release_parent or current_release_parent:
            direct_single_parent = True
            current_layout_parent = True
        else:
            current_layout_parent = False
    else:
        current_layout_parent = False
    if (previous is not None and star_anchor.exists() and previous.get("backend/app.py") != baseline.get("backend/app.py")
            and not direct_pdf_baseline and not direct_archive_baseline and not direct_typing_baseline
            and not direct_folder_parent and not direct_range_parent and not direct_term_parent and not direct_warm_parent
            and not direct_single_parent):
        try:
            # Historical migrations target their original immutable source,
            # never the later PDF edit.
            target = pdf_anchor if pdf_anchor.exists() else ROOT / "backend/app.py"
            previous = migrate_star_browse_app_baseline(previous, star_anchor, target)
        except ValueError as error:
            print(f"star-browse coverage migration failed: {error}", file=sys.stderr)
            return 1
    if (previous is not None and pdf_anchor.exists() and previous.get("backend/app.py") != baseline.get("backend/app.py")
            and not direct_archive_baseline and not direct_typing_baseline and not direct_folder_parent and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent):
        try:
            target = archive_old if archive_old.exists() else ROOT / "backend/app.py"
            previous = migrate_pdf_limit_app_baseline(previous, pdf_anchor, target)
        except ValueError as error:
            print(f"PDF limit coverage migration failed: {error}", file=sys.stderr)
            return 1
    archive_migrated = False
    if (previous is not None and archive_old.exists() and "backend/reader_archive.py" not in previous
            and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_typing_baseline
            and not direct_folder_parent and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent):
        try:
            previous = migrate_reader_archive_app_baseline(previous, archive_old, archive_new, archive_module)
            archive_migrated = True
        except ValueError as error:
            print(f"reader-archive coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and typing_new.exists() and (archive_migrated or direct_typing_baseline):
        try:
            previous = migrate_backend_typing_app_baseline(previous, archive_new, typing_new)
        except ValueError as error:
            print(f"backend typing coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent:
        try:
            previous = migrate_folder_contents_app_baseline(
                previous, typing_new, ROOT / "scripts/coverage-anchors/range-cache-old-app.py.snapshot",
                ROOT / "backend/folder_contents.py")
        except (OSError, ValueError) as error:
            print(f"folder-contents coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_term_parent and not direct_warm_parent and not direct_single_parent:
        try:
            previous = migrate_reader_range_app_baseline(
                previous, ROOT / "scripts/coverage-anchors/range-cache-old-app.py.snapshot",
                ROOT / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot", ROOT / "backend/reader_range_cache.py")
        except (OSError, ValueError) as error:
            print(f"reader-range coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_warm_parent and not direct_single_parent:
        try:
            previous = migrate_search_term_app_baseline(
                previous, ROOT / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot",
                ROOT / "scripts/coverage-anchors/download-warm-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/single-term-old-module.py.snapshot")
        except (OSError, ValueError) as error:
            print(f"search-term coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_single_parent:
        try:
            previous = migrate_download_warm_app_baseline(
                previous, ROOT / "scripts/coverage-anchors/download-warm-old-app.py.snapshot",
                ROOT / "scripts/coverage-anchors/single-term-old-app.py.snapshot", ROOT / "backend/download_warm.py")
        except (OSError, ValueError) as error:
            print(f"download-warm coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not current_layout_parent:
        try:
            previous = migrate_single_term_app_baseline(
                previous, ROOT / "scripts/coverage-anchors/single-term-old-app.py.snapshot",
                release_old if release_layout else ROOT / "backend/app.py",
                release_old_term if release_layout else ROOT / "backend/search_term_candidates.py")
        except (OSError, ValueError) as error:
            print(f"single-term coverage migration failed: {error}", file=sys.stderr)
            return 1
    if (previous is not None and release_layout and not current_release_parent
            and previous.get("backend/app.py") != baseline.get("backend/app.py")):
        try:
            if hashlib.sha256(release_debt.read_bytes()).hexdigest() != SEARCH_RELEASE_DEBT_SHA:
                raise ValueError("unexpected search-release parent baseline")
            previous = migrate_search_release_baseline(previous, release_old, release_new, release_old_term, release_new_term)
        except (OSError, ValueError) as error:
            print(f"search-release coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and sigma_layout and not direct_proxy_parent and not browse_direct_parent and previous.get("backend/app.py") != baseline.get("backend/app.py"):
        try:
            previous = migrate_search_sigma_baseline(previous, release_new, sigma_new)
        except (OSError, ValueError) as error:
            print(f"search-sigma coverage migration failed: {error}", file=sys.stderr)
            return 1
    seo_anchor = ROOT / "scripts/coverage-anchors/seo-path-old-seo.py.snapshot"
    if previous is not None and seo_anchor.exists() and previous.get("backend/seo.py") != baseline.get("backend/seo.py"):
        try:
            previous = migrate_seo_path_baseline(previous, seo_anchor, ROOT / "backend/seo.py",
                ROOT / "scripts/coverage-anchors/seo-path-old-debt.json")
        except (OSError, ValueError, KeyError) as error:
            print(f"SEO path coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and proxy_layout and not browse_direct_parent and previous.get("backend/app.py") != baseline.get("backend/app.py"):
        try:
            previous = migrate_proxy_safety_baseline(previous,
                ROOT / "scripts/coverage-anchors/proxy-safety-old-app.py.snapshot",
                ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot" if browse_layout else ROOT / "backend/app.py",
                ROOT / "scripts/coverage-anchors/proxy-safety-old-streams.py.snapshot", ROOT / "backend/proxy_streams.py")
        except (OSError, ValueError, KeyError) as error:
            print(f"proxy-safety coverage migration failed: {error}", file=sys.stderr)
            return 1
    if previous is not None and browse_layout:
        try:
            old_app = ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot"
            if previous.get("backend/app.py") != baseline.get("backend/app.py"):
                previous = migrate_search_browse_baseline(previous, old_app, browse_target,
                                                          ROOT / "backend/search_browse.py")
            else:
                # A same-layout baseline is supported, but cannot become its own
                # proof of coverage. Reconstruct the independently hash-pinned
                # pre-extraction parent and keep its full ratchet in force too.
                anchored = migrate_proxy_safety_baseline(proxy_baseline,
                    ROOT / "scripts/coverage-anchors/proxy-safety-old-app.py.snapshot", old_app,
                    ROOT / "scripts/coverage-anchors/proxy-safety-old-streams.py.snapshot",
                    ROOT / "backend/proxy_streams.py")
                anchored = migrate_search_browse_baseline(anchored, old_app, browse_target,
                                                           ROOT / "backend/search_browse.py")
                anchor_errors = coverage_errors(ROOT, report, baseline, anchored,
                    baseline_layout=baseline_layout,
                    previous_layout="lifespan-parent" if lifespan_layout else "current")
                if anchor_errors:
                    print("\n".join(anchor_errors), file=sys.stderr)
                    return 1
        except (OSError, ValueError, KeyError) as error:
            print(f"search-browse coverage migration failed: {error}", file=sys.stderr)
            return 1
    if lifespan_layout:
        try:
            # Always enforce the independently pinned historical chain, even
            # when no parent is supplied or both supplied debts are weakened.
            anchored = migrate_proxy_safety_baseline(proxy_baseline,
                ROOT / "scripts/coverage-anchors/proxy-safety-old-app.py.snapshot",
                ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot",
                ROOT / "scripts/coverage-anchors/proxy-safety-old-streams.py.snapshot",
                ROOT / "backend/proxy_streams.py")
            anchored = migrate_search_browse_baseline(anchored,
                ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot", browse_target,
                ROOT / "backend/search_browse.py")
            anchor_errors = coverage_errors(ROOT, report, baseline, anchored,
                baseline_layout=baseline_layout, previous_layout="lifespan-parent")
            anchor_errors += coverage_errors(ROOT, report, baseline, parent_debt,
                baseline_layout=baseline_layout, previous_layout="lifespan-parent")
            if anchor_errors:
                print("\n".join(anchor_errors), file=sys.stderr)
                return 1
        except (OSError, ValueError, KeyError) as error:
            print(f"lifespan historical coverage proof failed: {error}", file=sys.stderr)
            return 1
    if lifespan_layout and current_previous is not None:
        errors = coverage_errors(ROOT, report, baseline, current_previous,
                                 baseline_layout=baseline_layout, previous_layout="current")
    else:
        errors = coverage_errors(ROOT, report, baseline, previous,
            baseline_layout=baseline_layout,
            previous_layout="lifespan-parent" if lifespan_layout else "current")
    if errors:
        print("\n".join(errors), file=sys.stderr)
        return 1
    print("Backend coverage inventory: no regressions; new modules have 100% statements and branches")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())