File size: 91,130 Bytes
b8ea052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Deterministic parsers for reviewed structured PVR contract checks.

The generic detector stack is intentionally not used to infer dial sectors,
checkbox identities, or other fixed-layout state.  Each adapter below is
scoped by case family and consumes the reviewed decision-rule parameters.
It returns the same atomic-result shape as the formal evaluator and fails
closed with ``unknown`` when its required geometry or evidence is missing.
"""

from __future__ import annotations

import math
from pathlib import Path
from typing import Any, Mapping

import cv2
import numpy as np
from PIL import Image, ImageChops

from pvr_eval.core.schema import AtomicCheckSpec


def _clamp(value: float) -> float:
    return max(0.0, min(1.0, float(value)))


def _result(
    spec: AtomicCheckSpec,
    *,
    score: float,
    confidence: float,
    evidence: Mapping[str, Any],
    status: str | None = None,
) -> dict[str, Any]:
    score = _clamp(score)
    normalized_evidence = dict(evidence)
    if spec.role == "penalty":
        normalized_evidence.setdefault("penalty_semantics", "violation_severity")
    if status is None:
        if spec.role == "penalty":
            status = "triggered" if score >= 0.85 else "partial_trigger" if score >= 0.35 else "clean"
        else:
            status = "pass" if score >= 0.85 else "partial" if score >= 0.35 else "fail"
    return {
        "id": spec.check_id,
        "dimension": spec.dimension,
        "checker": "structured_contract_parser:pvr_structured_contract_v1",
        "weight": spec.weight,
        "role": spec.role,
        "hard_fail": spec.hard_fail,
        "status": status,
        "score": score,
        "confidence": _clamp(confidence),
        "evidence": normalized_evidence,
    }


def _unknown(spec: AtomicCheckSpec, reason: str, **evidence: Any) -> dict[str, Any]:
    return _result(
        spec,
        score=0.0,
        confidence=0.0,
        status="unknown",
        evidence={"reason": reason, **evidence},
    )


def _open_gray(path: Path) -> np.ndarray:
    with Image.open(path) as image:
        return np.asarray(image.convert("L"), dtype=np.float32)


def _scaled_point(point: tuple[float, float], shape: tuple[int, int], base: float = 1024.0) -> tuple[float, float]:
    height, width = shape
    return point[0] * width / base, point[1] * height / base


def _scaled_box(box: tuple[float, float, float, float], size: tuple[int, int], base: float = 1024.0) -> tuple[int, int, int, int]:
    width, height = size
    x0, y0, x1, y1 = box
    return (
        max(0, min(width, int(round(x0 * width / base)))),
        max(0, min(height, int(round(y0 * height / base)))),
        max(0, min(width, int(round(x1 * width / base)))),
        max(0, min(height, int(round(y1 * height / base)))),
    )


def _ratio_box(box: tuple[float, float, float, float], size: tuple[int, int]) -> tuple[int, int, int, int]:
    width, height = size
    x0, y0, x1, y1 = box
    return (
        max(0, min(width, int(round(x0 * width)))),
        max(0, min(height, int(round(y0 * height)))),
        max(0, min(width, int(round(x1 * width)))),
        max(0, min(height, int(round(y1 * height)))),
    )


def _diff_metrics(input_path: Path, pred_path: Path, box: tuple[int, int, int, int] | None = None) -> dict[str, float]:
    with Image.open(input_path).convert("RGB") as before, Image.open(pred_path).convert("RGB") as after:
        if after.size != before.size:
            after = after.resize(before.size, Image.Resampling.BILINEAR)
        if box is not None:
            before = before.crop(box)
            after = after.crop(box)
        diff = np.asarray(ImageChops.difference(before, after).convert("L"), dtype=np.float32)
    if not diff.size:
        return {"mean_absolute_error": 1.0, "changed_24": 1.0, "changed_48": 1.0}
    return {
        "mean_absolute_error": float(diff.mean() / 255.0),
        "changed_24": float((diff >= 24).mean()),
        "changed_48": float((diff >= 48).mean()),
    }


def _best_dark_line_angle(
    gray: np.ndarray,
    center: tuple[float, float],
    angle_min: float,
    angle_max: float,
    r0: float,
    r1: float,
    *,
    width: int = 1,
    step: float = 1.0,
) -> tuple[float, float, list[float]]:
    darkness = np.clip((125.0 - gray) / 125.0, 0.0, 1.0)
    height, image_width = darkness.shape
    best_angle, best_score, best_profile = angle_min, -1.0, []
    samples = max(12, int(max(1.0, r1 - r0) * 1.4))
    for angle in np.arange(angle_min, angle_max + 1e-6, step):
        rad = math.radians(float(angle))
        dx, dy = math.cos(rad), math.sin(rad)
        px, py = -dy, dx
        profile: list[float] = []
        for radius in np.linspace(r0, r1, samples):
            values = []
            for offset in range(-width, width + 1):
                xx = int(round(center[0] + dx * radius + px * offset))
                yy = int(round(center[1] + dy * radius + py * offset))
                if 0 <= xx < image_width and 0 <= yy < height:
                    values.append(float(darkness[yy, xx]))
            profile.append(float(np.mean(values)) if values else 0.0)
        score = float(np.mean(profile)) if profile else -1.0
        if score > best_score:
            best_angle, best_score, best_profile = float(angle), score, profile
    return best_angle, best_score, best_profile


def _decision_type(spec: AtomicCheckSpec) -> str:
    rule = spec.params.get("decision_rule", {}) if isinstance(spec.params, dict) else {}
    return str(rule.get("type") or "") if isinstance(rule, Mapping) else ""


def _decision_params(spec: AtomicCheckSpec) -> dict[str, Any]:
    rule = spec.params.get("decision_rule", {}) if isinstance(spec.params, dict) else {}
    nested = rule.get("parameters", {}) if isinstance(rule, Mapping) else {}
    return dict(nested) if isinstance(nested, Mapping) else {}


def _open_rgb_pair(input_path: Path, pred_path: Path) -> tuple[np.ndarray, np.ndarray]:
    with Image.open(input_path).convert("RGB") as image:
        before = np.asarray(image)
    with Image.open(pred_path).convert("RGB") as image:
        if image.size != (before.shape[1], before.shape[0]):
            image = image.resize((before.shape[1], before.shape[0]), Image.Resampling.BILINEAR)
        after = np.asarray(image)
    return before, after


def _hsv(rgb: np.ndarray) -> np.ndarray:
    return cv2.cvtColor(rgb.astype(np.uint8), cv2.COLOR_RGB2HSV)


def _color_mask(rgb: np.ndarray, color: str) -> np.ndarray:
    """Conservative HSV masks used only inside case-specific ROIs."""

    hsv = _hsv(rgb)
    h, s, v = [hsv[..., index] for index in range(3)]
    if color == "blue":
        return (h >= 92) & (h <= 132) & (s >= 45) & (v >= 55)
    if color == "cyan":
        return (h >= 78) & (h <= 105) & (s >= 55) & (v >= 55)
    if color == "green":
        return (h >= 36) & (h <= 92) & (s >= 55) & (v >= 45)
    if color == "yellow":
        return (h >= 18) & (h <= 38) & (s >= 75) & (v >= 90)
    if color == "red":
        return ((h <= 10) | (h >= 170)) & (s >= 80) & (v >= 55)
    if color == "pink":
        return ((h <= 12) | (h >= 165)) & (s >= 35) & (s <= 190) & (v >= 105)
    if color == "gray":
        return (s <= 45) & (v >= 45) & (v <= 185)
    if color == "white":
        return (s <= 78) & (v >= 165)
    if color == "dark":
        return v <= 72
    raise ValueError(f"unsupported structured color: {color}")


def _components(mask: np.ndarray, *, min_area: int = 20, max_area: int | None = None) -> list[dict[str, Any]]:
    binary = (mask.astype(np.uint8) * 255)
    count, _, stats, centroids = cv2.connectedComponentsWithStats(binary, connectivity=8)
    items: list[dict[str, Any]] = []
    for index in range(1, count):
        x, y, width, height, area = [int(value) for value in stats[index]]
        if area < min_area or (max_area is not None and area > max_area):
            continue
        items.append(
            {
                "bbox": [x, y, x + width, y + height],
                "centroid": [round(float(centroids[index][0]), 2), round(float(centroids[index][1]), 2)],
                "area": area,
            }
        )
    return sorted(items, key=lambda item: item["area"], reverse=True)


def _crop_mask(mask: np.ndarray, box: tuple[int, int, int, int]) -> np.ndarray:
    x0, y0, x1, y1 = box
    return mask[y0:y1, x0:x1]


def _mask_fraction(mask: np.ndarray, box: tuple[int, int, int, int]) -> float:
    crop = _crop_mask(mask, box)
    return float(crop.mean()) if crop.size else 0.0


def _changed_mask(before: np.ndarray, after: np.ndarray, threshold: float = 42.0) -> np.ndarray:
    delta = np.linalg.norm(before.astype(np.float32) - after.astype(np.float32), axis=2)
    return delta >= threshold


def _edge_change_fraction(
    before: np.ndarray,
    after: np.ndarray,
    box: tuple[int, int, int, int],
    *,
    ignore: np.ndarray | None = None,
) -> float:
    x0, y0, x1, y1 = box
    a = cv2.cvtColor(before[y0:y1, x0:x1], cv2.COLOR_RGB2GRAY)
    b = cv2.cvtColor(after[y0:y1, x0:x1], cv2.COLOR_RGB2GRAY)
    if not a.size or a.shape != b.shape:
        return 1.0
    ea = cv2.Canny(a, 70, 150) > 0
    eb = cv2.Canny(b, 70, 150) > 0
    changed = ea ^ eb
    valid = np.ones_like(changed, dtype=bool)
    if ignore is not None:
        local = ignore[y0:y1, x0:x1]
        if local.shape == valid.shape:
            valid &= ~local
    return float((changed & valid).sum() / max(1, valid.sum()))


def _edge_f1(
    before: np.ndarray,
    after: np.ndarray,
    box: tuple[int, int, int, int],
    *,
    ignore: np.ndarray | None = None,
    tolerance: int = 3,
) -> float:
    """Tolerance-aware structural edge agreement for registered scenes."""

    x0, y0, x1, y1 = box
    a = cv2.Canny(cv2.cvtColor(before[y0:y1, x0:x1], cv2.COLOR_RGB2GRAY), 70, 150) > 0
    b = cv2.Canny(cv2.cvtColor(after[y0:y1, x0:x1], cv2.COLOR_RGB2GRAY), 70, 150) > 0
    if not a.size or a.shape != b.shape:
        return 0.0
    valid = np.ones_like(a, dtype=bool)
    if ignore is not None:
        local = ignore[y0:y1, x0:x1]
        if local.shape == valid.shape:
            valid &= ~local
    kernel = np.ones((2 * tolerance + 1, 2 * tolerance + 1), np.uint8)
    a_dilated = cv2.dilate(a.astype(np.uint8), kernel).astype(bool)
    b_dilated = cv2.dilate(b.astype(np.uint8), kernel).astype(bool)
    a_count, b_count = int((a & valid).sum()), int((b & valid).sum())
    if a_count == 0 or b_count == 0:
        return 1.0 if a_count == b_count else 0.0
    recall = float((a & b_dilated & valid).sum() / a_count)
    precision = float((b & a_dilated & valid).sum() / b_count)
    return 2.0 * recall * precision / max(1e-8, recall + precision)


def _ocr_texts(observations: Mapping[str, Any], check_id: str, role: str = "pred") -> list[str]:
    scoped = observations.get("ocr_by_check", {}) if isinstance(observations, Mapping) else {}
    bucket = scoped.get(check_id, {}) if isinstance(scoped, Mapping) else {}
    values = bucket.get(role, []) if isinstance(bucket, Mapping) else []
    return [str(item.get("text") or "") for item in values if isinstance(item, Mapping)]


def _detections(observations: Mapping[str, Any], check_id: str, role: str = "pred") -> list[dict[str, Any]]:
    scoped = observations.get("detections_by_check", {}) if isinstance(observations, Mapping) else {}
    bucket = scoped.get(check_id, {}) if isinstance(scoped, Mapping) else {}
    values = bucket.get(role, []) if isinstance(bucket, Mapping) else []
    return [dict(item) for item in values if isinstance(item, Mapping)]


def _center(box: list[float] | tuple[float, ...]) -> tuple[float, float]:
    return (float(box[0]) + float(box[2])) / 2.0, (float(box[1]) + float(box[3])) / 2.0


def _inside(point: tuple[float, float], box: tuple[int, int, int, int]) -> bool:
    return box[0] <= point[0] <= box[2] and box[1] <= point[1] <= box[3]


def _score_threshold(value: float, pass_value: float, partial_value: float, *, higher: bool = True) -> float:
    if higher:
        return 1.0 if value >= pass_value else 0.5 if value >= partial_value else 0.0
    return 1.0 if value <= pass_value else 0.5 if value <= partial_value else 0.0


def _gauge_result(spec: AtomicCheckSpec, input_path: Path, pred_path: Path) -> dict[str, Any]:
    before, after = _open_gray(input_path), _open_gray(pred_path)
    if before.shape != after.shape:
        after = np.asarray(Image.fromarray(after.astype(np.uint8)).resize((before.shape[1], before.shape[0])), dtype=np.float32)
    scale = min(before.shape) / 1024.0
    center = _scaled_point((546.0, 542.0), before.shape)
    in_angle, in_strength, in_profile = _best_dark_line_angle(before, center, 85, 175, 18 * scale, 125 * scale)
    out_angle, out_strength, out_profile = _best_dark_line_angle(after, center, 85, 175, 18 * scale, 125 * scale)
    rule = _decision_type(spec)
    base_evidence = {
        "parser": "lower_gauge_radial_parser_v2",
        "pivot_xy": [round(center[0], 2), round(center[1], 2)],
        "input_angle_degrees": round(in_angle, 2),
        "output_angle_degrees": round(out_angle, 2),
        "angle_delta_degrees": round(out_angle - in_angle, 2),
        "input_line_strength": round(in_strength, 4),
        "output_line_strength": round(out_strength, 4),
    }
    size = (before.shape[1], before.shape[0])
    lower_box = _scaled_box((410, 455, 670, 720), size)
    upper_box = _scaled_box((350, 145, 700, 485), size)
    full_box = _scaled_box((205, 115, 815, 815), size)
    lower_diff = _diff_metrics(input_path, pred_path, lower_box)
    upper_diff = _diff_metrics(input_path, pred_path, upper_box)
    full_diff = _diff_metrics(input_path, pred_path, full_box)

    if rule == "angular_sector_containment":
        # The reviewed comfort sector is the lower-dial wedge bounded by the
        # 40 and 60 tick rays.  The tolerance band is deliberately wider than
        # the hard pass interval so boundary edits become partial, not false.
        pass_low, pass_high = 98.0, 132.0
        partial_low, partial_high = 92.0, 140.0
        score = 1.0 if pass_low <= out_angle <= pass_high else 0.5 if partial_low <= out_angle <= partial_high else 0.0
        return _result(spec, score=score, confidence=min(0.95, 0.55 + out_strength), evidence={
            **base_evidence,
            "comfort_sector_degrees": [pass_low, pass_high],
            "partial_tolerance_degrees": [partial_low, partial_high],
            "target_roi_change": lower_diff,
        })

    if rule == "source_corridor_vacancy":
        old_dark = float(np.mean(in_profile)) if in_profile else 0.0
        residual = float(np.mean(out_profile)) if out_profile else 1.0
        residual_ratio = residual / max(old_dark, 1e-6)
        moved = abs(out_angle - in_angle) >= 5.0
        score = 1.0 if moved and residual_ratio <= 0.35 else 0.5 if moved and residual_ratio <= 0.65 else 0.0
        return _result(spec, score=score, confidence=0.78, evidence={
            **base_evidence,
            "old_ray_residual_darkness_ratio": round(residual_ratio, 4),
            "thresholds": {"pass_max": 0.35, "partial_max": 0.65, "minimum_angle_move": 5.0},
        })

    if rule == "pivot_shaft_connectivity":
        profile = np.asarray(out_profile, dtype=np.float32)
        if not profile.size:
            return _unknown(spec, "missing_output_needle_profile", **base_evidence)
        connected_fraction = float((profile >= 0.12).mean())
        initial_fraction = float((profile[: max(3, len(profile) // 8)] >= 0.10).mean())
        score = 1.0 if connected_fraction >= 0.72 and initial_fraction >= 0.65 else 0.5 if connected_fraction >= 0.5 and initial_fraction >= 0.35 else 0.0
        return _result(spec, score=score, confidence=0.74, evidence={
            **base_evidence,
            "connected_profile_fraction": round(connected_fraction, 4),
            "pivot_neighborhood_connected_fraction": round(initial_fraction, 4),
        })

    if rule == "needle_instance_preservation":
        score = 1.0 if upper_diff["changed_48"] <= 0.004 else 0.5 if upper_diff["changed_48"] <= 0.012 else 0.0
        return _result(spec, score=score, confidence=0.82, evidence={**base_evidence, "upper_needle_registered_diff": upper_diff})

    if rule == "dial_graphics_preservation":
        score = 1.0 if upper_diff["changed_24"] <= 0.015 else 0.5 if upper_diff["changed_24"] <= 0.04 else 0.0
        return _result(spec, score=score, confidence=0.72, evidence={**base_evidence, "dial_graphics_proxy_diff": upper_diff})

    if rule == "registered_invariant_region_preservation":
        score = 1.0 if full_diff["changed_48"] <= 0.02 else 0.5 if full_diff["changed_48"] <= 0.05 else 0.0
        return _result(spec, score=score, confidence=0.78, evidence={**base_evidence, "gauge_hardware_registered_diff": full_diff})

    if rule == "needle_shape_integrity":
        profile = np.asarray(out_profile, dtype=np.float32)
        if not profile.size:
            return _unknown(spec, "missing_output_needle_profile", **base_evidence)
        active = profile >= 0.12
        gap_fraction = float((~active).mean())
        score = 1.0 if out_strength >= 0.18 and gap_fraction <= 0.28 else 0.5 if out_strength >= 0.12 and gap_fraction <= 0.48 else 0.0
        return _result(spec, score=score, confidence=0.7, evidence={
            **base_evidence,
            "shaft_gap_fraction": round(gap_fraction, 4),
            "shape_thresholds": {"pass_strength_min": 0.18, "pass_gap_max": 0.28},
        })
    return _unknown(spec, "unsupported_gauge_rule", source_rule_type=rule)


def _red_pivot(
    rgb: np.ndarray,
    expected: tuple[float, float] | None = None,
) -> tuple[float, float] | None:
    height, width = rgb.shape[:2]
    r, g, b = [rgb[..., index].astype(np.int16) for index in range(3)]
    mask = (r > 85) & (r > g + 18) & (r > b + 12)
    yy, xx = np.where(mask)
    if expected is not None:
        radius = min(height, width) * 0.065
        keep = (xx - expected[0]) ** 2 + (yy - expected[1]) ** 2 <= radius ** 2
        xx, yy = xx[keep], yy[keep]
    else:
        keep = (
            (yy > height * 0.30) & (yy < height * 0.72) &
            (xx > width * 0.28) & (xx < width * 0.72)
        )
        xx, yy = xx[keep], yy[keep]
    if len(xx) < 12:
        return None
    return float(np.median(xx)), float(np.median(yy))


def _watch_result(spec: AtomicCheckSpec, input_path: Path, pred_path: Path, observations: Mapping[str, Any]) -> dict[str, Any]:
    with Image.open(input_path).convert("RGB") as image:
        before_rgb = np.asarray(image)
    with Image.open(pred_path).convert("RGB") as image:
        after_image = image.resize((before_rgb.shape[1], before_rgb.shape[0]), Image.Resampling.BILINEAR)
        after_rgb = np.asarray(after_image)
    before = np.dot(before_rgb[..., :3], [0.299, 0.587, 0.114]).astype(np.float32)
    after = np.dot(after_rgb[..., :3], [0.299, 0.587, 0.114]).astype(np.float32)
    expected_center = _scaled_point((501.5, 537.0), before.shape)
    center = _red_pivot(before_rgb, expected_center) or expected_center
    output_center = _red_pivot(after_rgb, expected_center) or expected_center
    radius = min(before.shape) * 0.22
    hour_in, hour_strength_in, _ = _best_dark_line_angle(before, center, 155, 285, radius * 0.12, radius * 0.65, width=2)
    hour_out, hour_strength_out, _ = _best_dark_line_angle(after, output_center, 155, 285, radius * 0.12, radius * 0.65, width=2)
    minute_in, minute_strength_in, _ = _best_dark_line_angle(before, center, -35, 75, radius * 0.25, radius * 0.95, width=2)
    minute_out, minute_strength_out, _ = _best_dark_line_angle(after, output_center, -35, 75, radius * 0.25, radius * 0.95, width=2)
    rule = _decision_type(spec)
    parameters = _decision_params(spec)
    base = {
        "parser": "watch_registered_hand_parser_v2",
        "input_pivot_xy": [round(center[0], 2), round(center[1], 2)],
        "output_pivot_xy": [round(output_center[0], 2), round(output_center[1], 2)],
        "hour_angles": [round(hour_in, 2), round(hour_out, 2)],
        "minute_angles": [round(minute_in, 2), round(minute_out, 2)],
        "hour_strengths": [round(hour_strength_in, 4), round(hour_strength_out, 4)],
        "minute_strengths": [round(minute_strength_in, 4), round(minute_strength_out, 4)],
    }
    if rule == "clockwise_hour_hand_delta":
        expected = float(parameters.get("expected_clockwise_delta_degrees", 60.0))
        delta = (hour_out - hour_in) % 360.0
        error = min(abs(delta - expected), abs((360.0 - delta) - expected))
        pass_tolerance = float(parameters.get("pass_tolerance_degrees", 8.0))
        partial_tolerance = float(parameters.get("partial_tolerance_degrees", 15.0))
        score = 1.0 if error <= pass_tolerance else 0.5 if error <= partial_tolerance else 0.0
        return _result(spec, score=score, confidence=min(0.88, 0.5 + min(hour_strength_in, hour_strength_out)), evidence={
            **base, "clockwise_delta_degrees": round(delta, 2), "absolute_delta_error": round(error, 2),
            "thresholds": {"expected": expected, "pass_tolerance": pass_tolerance, "partial_tolerance": partial_tolerance},
        })
    if rule == "minute_hand_angle_invariance":
        delta = abs(minute_out - minute_in)
        pass_tolerance = float(parameters.get("pass_tolerance_degrees", 4.0))
        partial_tolerance = float(parameters.get("partial_tolerance_degrees", 8.0))
        score = 1.0 if delta <= pass_tolerance else 0.5 if delta <= partial_tolerance else 0.0
        return _result(spec, score=score, confidence=min(0.9, 0.55 + min(minute_strength_in, minute_strength_out)), evidence={
            **base, "absolute_minute_delta_degrees": round(delta, 2),
            "thresholds": {"pass_tolerance": pass_tolerance, "partial_tolerance": partial_tolerance},
        })
    if rule == "expected_date_digit_transition":
        expected = str(parameters.get("expected_output_text", "24"))
        texts: list[str] = []
        scoped = observations.get("ocr_by_check", {}) if isinstance(observations, Mapping) else {}
        bucket = scoped.get(spec.check_id, {}) if isinstance(scoped, Mapping) else {}
        for item in bucket.get("pred", []) if isinstance(bucket, Mapping) else []:
            if isinstance(item, Mapping):
                texts.append(str(item.get("text") or ""))
        normalized = ["".join(ch for ch in text if ch.isdigit()) for text in texts]
        digit_texts = [text for text in normalized if text]
        exact = any(expected in text for text in digit_texts)
        bbox = parameters.get("tight_bbox", [548, 456, 582, 483])
        if not (isinstance(bbox, (list, tuple)) and len(bbox) == 4):
            return _unknown(spec, "missing_date_window_bbox", ocr_texts=texts)
        crop_diff = _diff_metrics(input_path, pred_path, tuple(int(value) for value in bbox))
        date_evidence = {
            **base, "ocr_texts": texts, "ocr_digit_texts": digit_texts,
            "expected_output_text": expected, "date_window_bbox": list(bbox),
            "date_window_diff": crop_diff,
        }
        if exact:
            return _result(spec, score=1.0, confidence=0.9, evidence=date_evidence)
        if digit_texts:
            return _result(spec, score=0.0, confidence=0.75, evidence=date_evidence)
        return _unknown(spec, "date_ocr_inconclusive", **date_evidence)
    dial_box = _ratio_box((0.16, 0.17, 0.84, 0.78), (before.shape[1], before.shape[0]))
    dial_diff = _diff_metrics(input_path, pred_path, dial_box)
    pivot_shift = math.dist(center, output_center) / max(1.0, radius * 2.0)
    if rule == "watch_structure_relocation_violation":
        pass_max = float(parameters.get("pass_max_invariant_changed_fraction", 0.10))
        partial_max = float(parameters.get("partial_max_invariant_changed_fraction", 0.22))
        violation = 0.0 if dial_diff["changed_48"] <= pass_max and pivot_shift <= 0.03 else 0.5 if dial_diff["changed_48"] <= partial_max else 1.0
        return _result(spec, score=violation, confidence=0.78, evidence={**base, "dial_invariant_diff": dial_diff, "normalized_pivot_shift": pivot_shift})
    if rule == "non_target_component_integrity_violation":
        changed = dial_diff["changed_48"]
        violation = 0.0 if changed <= 0.10 else 0.5 if changed <= 0.22 else 1.0
        return _result(spec, score=violation, confidence=0.72, evidence={**base, "non_target_dial_diff": dial_diff})
    return _unknown(spec, "unsupported_watch_rule", source_rule_type=rule)


_BOARD_GRID = (0.107, 0.058, 0.814, 0.604)


def _board_cell(name: str, size: tuple[int, int]) -> tuple[int, int, int, int]:
    column = ord(name[0].upper()) - ord("A")
    row = int(name[1]) - 1
    x0, y0, x1, y1 = _BOARD_GRID
    cell_w = (x1 - x0) / 5.0
    cell_h = (y1 - y0) / 5.0
    # Row 1 is at the bottom of the photographed board.
    top = y1 - (row + 1) * cell_h
    bottom = y1 - row * cell_h
    return _ratio_box((x0 + column * cell_w, top, x0 + (column + 1) * cell_w, bottom), size)


def _board_piece_presence(mask: np.ndarray, box: tuple[int, int, int, int]) -> dict[str, Any]:
    x0, y0, x1, y1 = box
    width, height = x1 - x0, y1 - y0
    inner = (
        x0 + int(width * 0.22),
        y0 + int(height * 0.16),
        x1 - int(width * 0.22),
        y1 - int(height * 0.14),
    )
    crop = _crop_mask(mask, inner)
    area = int(crop.sum())
    return {"cell_bbox": list(box), "inner_bbox": list(inner), "mask_area": area, "present": area >= 180}


def _board_game_result(spec: AtomicCheckSpec, input_path: Path, pred_path: Path) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    rule = _decision_type(spec)
    blue = _color_mask(after, "blue")
    blue = cv2.morphologyEx(blue.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)).astype(bool)
    dark = _color_mask(after, "dark")
    base = {"parser": "registered_board_grid_parser_v1", "board_grid_bbox": list(_ratio_box(_BOARD_GRID, size))}

    if rule == "target_cell_mask_containment":
        e5 = _board_piece_presence(blue, _board_cell("E5", size))
        score = _score_threshold(float(e5["mask_area"]), 350.0, 180.0)
        return _result(spec, score=score, confidence=0.9, evidence={**base, "target_cell": "E5", **e5})

    if rule == "source_cell_vacated":
        a1 = _board_piece_presence(blue, _board_cell("A1", size))
        score = 1.0 if not a1["present"] else 0.0
        return _result(spec, score=score, confidence=0.9, evidence={**base, "source_cell": "A1", **a1})

    if rule == "ordered_dotted_route_match":
        # Remove pawn-sized blue components; only thin dots/segments may prove
        # the requested route.  A pawn sitting on a waypoint is not route
        # evidence.
        route = blue.copy()
        for component in _components(blue, min_area=20):
            if component["area"] >= 500:
                x0, y0, x1, y1 = component["bbox"]
                route[max(0, y0 - 4):min(route.shape[0], y1 + 4), max(0, x0 - 4):min(route.shape[1], x1 + 4)] = False
        waypoints = ["A1", "B1", "B3", "D3", "E5"]
        centers = [_center(_board_cell(cell, size)) for cell in waypoints]
        radius = max(4, int((size[0] * (_BOARD_GRID[2] - _BOARD_GRID[0]) / 5.0) * 0.18))
        segment_hits: list[float] = []
        for start, end in zip(centers, centers[1:]):
            samples = []
            distance = max(1.0, math.dist(start, end))
            for index in range(max(8, int(distance / max(2, radius // 2)))):
                alpha = index / max(1, max(8, int(distance / max(2, radius // 2))) - 1)
                x = int(round(start[0] * (1 - alpha) + end[0] * alpha))
                y = int(round(start[1] * (1 - alpha) + end[1] * alpha))
                crop = route[max(0, y-radius):min(route.shape[0], y+radius+1), max(0, x-radius):min(route.shape[1], x+radius+1)]
                samples.append(bool(crop.any()))
            segment_hits.append(float(np.mean(samples)) if samples else 0.0)
        coverage = float(np.mean(segment_hits)) if segment_hits else 0.0
        components = _components(route, min_area=8, max_area=500)
        minimum_dashes = int(_decision_params(spec).get("minimum_visible_dash_count", 4))
        score = 1.0 if coverage >= 0.85 and len(components) >= minimum_dashes else 0.5 if coverage >= 0.4 else 0.0
        return _result(spec, score=score, confidence=0.82, evidence={
            **base,
            "waypoints": waypoints,
            "segment_coverage": [round(value, 4) for value in segment_hits],
            "aggregate_segment_coverage": round(coverage, 4),
            "visible_route_component_count": len(components),
            "minimum_visible_dash_count": minimum_dashes,
        })

    if rule == "two_instance_cell_preservation":
        expected = _decision_params(spec).get("expected_cells", ["C2", "C3"])
        metrics = {cell: _board_piece_presence(dark, _board_cell(str(cell), size)) for cell in expected}
        present = sum(bool(item["present"]) for item in metrics.values())
        severity = 0.0 if present == len(metrics) else 0.5 if present else 1.0
        return _result(spec, score=severity, confidence=0.84, evidence={**base, "expected_cells": expected, "cell_metrics": metrics})

    if rule == "card_content_preservation":
        box = _ratio_box((0.10, 0.665, 0.79, 0.945), size)
        diff = _diff_metrics(input_path, pred_path, box)
        severity = 0.0 if diff["changed_48"] <= 0.015 else 0.5 if diff["changed_48"] <= 0.05 else 1.0
        return _result(spec, score=severity, confidence=0.88, evidence={**base, "instruction_card_bbox": list(box), "registered_diff": diff})

    if rule == "grid_and_labels_intact":
        box = _ratio_box((0.07, 0.035, 0.82, 0.66), size)
        changed = _edge_change_fraction(before, after, box)
        severity = 0.0 if changed <= 0.018 else 0.5 if changed <= 0.045 else 1.0
        return _result(spec, score=severity, confidence=0.8, evidence={**base, "grid_and_label_bbox": list(box), "edge_change_fraction": changed})

    if rule == "tray_and_contents_preserved":
        box = _ratio_box((0.80, 0.35, 1.0, 0.84), size)
        diff = _diff_metrics(input_path, pred_path, box)
        severity = 0.0 if diff["changed_48"] <= 0.025 else 0.5 if diff["changed_48"] <= 0.08 else 1.0
        return _result(spec, score=severity, confidence=0.84, evidence={**base, "tray_bbox": list(box), "registered_diff": diff})

    if rule == "exact_board_instance_count":
        grid = _ratio_box(_BOARD_GRID, size)
        local = _crop_mask(blue, grid)
        components = [item for item in _components(local, min_area=180) if item["area"] >= 300]
        required = int(_decision_params(spec).get("required_count", 1))
        count = len(components)
        severity = 0.0 if count == required else 0.5 if abs(count - required) == 1 else 1.0
        return _result(spec, score=severity, confidence=0.86, evidence={
            **base, "required_count": required, "detected_board_blue_instance_count": count,
            "component_evidence": components, "board_grid_bbox": list(grid),
        })
    return _unknown(spec, "unsupported_board_game_rule", source_rule_type=rule)


def _kanban_card_mask(rgb: np.ndarray) -> np.ndarray:
    hsv = _hsv(rgb)
    h, s, v = [hsv[..., index] for index in range(3)]
    mask = (h >= 18) & (h <= 112) & (s >= 34) & (v >= 105)
    # Sticky-note colour blocks are much larger than handwriting strokes.
    return cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((9, 9), np.uint8)).astype(bool)


def _kanban_cards(mask: np.ndarray, box: tuple[int, int, int, int]) -> list[dict[str, Any]]:
    x0, y0, x1, y1 = box
    local = _crop_mask(mask, box)
    items = []
    for component in _components(local, min_area=max(120, int(local.size * 0.0015))):
        bx0, by0, bx1, by1 = component["bbox"]
        width, height = bx1 - bx0, by1 - by0
        if width < 15 or height < 15 or width / max(height, 1) > 2.3 or height / max(width, 1) > 2.3:
            continue
        items.append({
            **component,
            "bbox": [bx0 + x0, by0 + y0, bx1 + x0, by1 + y0],
            "centroid": [component["centroid"][0] + x0, component["centroid"][1] + y0],
        })
    return items


def _normalized_words(texts: list[str]) -> set[str]:
    words: set[str] = set()
    for text in texts:
        token = "".join(character.lower() if character.isalnum() else " " for character in text)
        words.update(word for word in token.split() if len(word) >= 3)
    return words


def _kanban_result(
    spec: AtomicCheckSpec,
    input_path: Path,
    pred_path: Path,
    observations: Mapping[str, Any],
) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    input_cards_mask, output_cards_mask = _kanban_card_mask(before), _kanban_card_mask(after)
    todo = _ratio_box((0.055, 0.18, 0.405, 0.79), size)
    progress = _ratio_box((0.405, 0.18, 0.765, 0.79), size)
    done = _ratio_box((0.765, 0.18, 0.985, 0.79), size)
    input_counts = {
        "todo": len(_kanban_cards(input_cards_mask, todo)),
        "in_progress": len(_kanban_cards(input_cards_mask, progress)),
        "done": len(_kanban_cards(input_cards_mask, done)),
    }
    output_cards = {
        "todo": _kanban_cards(output_cards_mask, todo),
        "in_progress": _kanban_cards(output_cards_mask, progress),
        "done": _kanban_cards(output_cards_mask, done),
    }
    output_counts = {key: len(value) for key, value in output_cards.items()}
    rule = _decision_type(spec)
    base = {
        "parser": "kanban_color_card_and_text_parser_v1",
        "column_bboxes": {"todo": list(todo), "in_progress": list(progress), "done": list(done)},
        "input_card_counts": input_counts,
        "output_card_counts": output_counts,
    }
    if rule == "source_instance_vacancy":
        column = "in_progress" if "progress" in spec.check_id else "todo"
        source_box = progress if column == "in_progress" else todo
        before_fraction = _mask_fraction(input_cards_mask, source_box)
        after_fraction = _mask_fraction(output_cards_mask, source_box)
        reduction = 1.0 - after_fraction / max(before_fraction, 1e-6)
        score = _score_threshold(reduction, 0.70, 0.35)
        return _result(spec, score=score, confidence=0.88, evidence={
            **base, "source_column": column, "input_color_occupancy": before_fraction,
            "output_color_occupancy": after_fraction, "occupancy_reduction": reduction,
        })
    if rule == "all_source_instances_in_destination":
        expected = int(_decision_params(spec).get("expected_final_distinct_card_count", 8))
        count = output_counts["done"]
        score = 1.0 if count == expected else 0.5 if count >= max(1, expected - 2) else 0.0
        return _result(spec, score=score, confidence=0.86, evidence={
            **base, "expected_final_distinct_card_count": expected,
            "detected_done_cards": output_cards["done"],
        })
    if rule in {"card_text_identity_preservation", "identity_loss_penalty"}:
        input_words = _normalized_words(_ocr_texts(observations, spec.check_id, "input"))
        output_words = _normalized_words(_ocr_texts(observations, spec.check_id, "pred"))
        ignored = {"todo", "done", "progress", "task"}
        input_words -= ignored
        output_words -= ignored
        if len(input_words) < 3:
            return _unknown(spec, "kanban_ocr_identity_inconclusive", **base, input_words=sorted(input_words), output_words=sorted(output_words))
        recall = len(input_words & output_words) / len(input_words)
        identity_score = _score_threshold(recall, 0.8, 0.5)
        score = (1.0 - identity_score) if rule == "identity_loss_penalty" else identity_score
        return _result(spec, score=score, confidence=0.72, evidence={
            **base, "input_identity_words": sorted(input_words), "output_identity_words": sorted(output_words),
            "identity_word_recall": recall,
        })
    if rule == "structural_invariant_preservation":
        ignore = cv2.dilate((input_cards_mask | output_cards_mask).astype(np.uint8), np.ones((17, 17), np.uint8)).astype(bool)
        board = _ratio_box((0.02, 0.11, 0.99, 0.82), size)
        edge_change = _edge_change_fraction(before, after, board, ignore=ignore)
        severity = 0.0 if edge_change <= 0.018 else 0.5 if edge_change <= 0.05 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "protected_board_bbox": list(board), "edge_change_fraction_excluding_cards": edge_change})
    if rule == "unrequested_annotation_penalty":
        input_words = _normalized_words(_ocr_texts(observations, spec.check_id, "input"))
        output_words = _normalized_words(_ocr_texts(observations, spec.check_id, "pred"))
        if len(input_words) < 3 or len(output_words) < 3:
            return _unknown(
                spec,
                "kanban_annotation_ocr_inconclusive",
                **base,
                input_words=sorted(input_words),
                output_words=sorted(output_words),
            )
        ignore = cv2.dilate((input_cards_mask | output_cards_mask).astype(np.uint8), np.ones((15, 15), np.uint8)).astype(bool)
        board = _ratio_box((0.04, 0.13, 0.99, 0.80), size)
        changed = _changed_mask(before, after, 64.0) & ~ignore
        x0, y0, x1, y1 = board
        components = _components(changed[y0:y1, x0:x1], min_area=max(20, int(before.shape[0] * before.shape[1] * 0.00004)))
        significant = [item for item in components if item["area"] >= 40]
        ignored_words = {"todo", "done", "progress"}
        new_words = sorted(output_words - input_words - ignored_words)
        severity = 0.0 if not new_words and not significant else 0.5 if len(new_words) <= 1 else 1.0
        return _result(spec, score=severity, confidence=0.74, evidence={
            **base, "unexplained_changed_component_count": len(significant),
            "unexplained_changed_components": significant[:12], "protected_board_bbox": list(board),
            "new_ocr_words": new_words,
        })
    return _unknown(spec, "unsupported_kanban_rule", source_rule_type=rule)


def _pill_components(
    after: np.ndarray,
    changed: np.ndarray,
    organizer: tuple[int, int, int, int],
    color: str,
    domain: np.ndarray | None = None,
    *,
    zones: Mapping[str, np.ndarray] | None = None,
) -> list[dict[str, Any]]:
    if color == "pink":
        # The movable pills range from pale peach to dark red capsules.  The
        # generic pink mask intentionally excludes saturated red, but doing so
        # here made red capsules disappear from the sorting decision.
        hsv = _hsv(after)
        h, s, v = [hsv[..., index] for index in range(3)]
        color_mask = ((h <= 18) | (h >= 165)) & (s >= 35) & (v >= 65)
    else:
        color_mask = _color_mask(after, color)
    mask = color_mask & changed
    if domain is not None and domain.shape == mask.shape:
        mask &= domain
    mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)).astype(bool)
    x0, y0, x1, y1 = organizer
    local = mask[y0:y1, x0:x1]
    minimum = max(40, int(after.shape[0] * after.shape[1] * 0.00008))
    items = []
    count, labels, stats, centroids = cv2.connectedComponentsWithStats(
        (local.astype(np.uint8) * 255), connectivity=8
    )
    for index in range(1, count):
        bx0, by0, width, height, area = [int(value) for value in stats[index]]
        bx1, by1 = bx0 + width, by0 + height
        if area < minimum or area > int(local.size * 0.08):
            continue
        width, height = bx1 - bx0, by1 - by0
        fill = area / max(1, width * height)
        aspect = width / max(1, height)
        if width < 8 or height < 8 or width > 90 or height > 90:
            continue
        if not 0.42 <= aspect <= 2.4 or fill < 0.32:
            continue
        component_mask = labels == index
        overlap_by_zone: dict[str, float] = {}
        for zone_name, zone_mask in (zones or {}).items():
            if zone_mask.shape != mask.shape:
                continue
            zone_local = zone_mask[y0:y1, x0:x1]
            overlap_by_zone[zone_name] = round(
                float((component_mask & zone_local).sum() / max(1, area)), 4
            )
        item = {
            "bbox": [bx0 + x0, by0 + y0, bx1 + x0, by1 + y0],
            "centroid": [round(float(centroids[index][0] + x0), 2), round(float(centroids[index][1] + y0), 2)],
            "area": area,
        }
        if overlap_by_zone:
            item["zone_overlap_fraction"] = overlap_by_zone
        items.append(item)
    return items


def _visual_pill_registered_zones(before: np.ndarray) -> tuple[dict[str, np.ndarray], dict[str, Any]]:
    """Return reviewed, mutually exclusive organizer-column geometry.

    The source photograph has a strong warm cast: the visually cyan evening
    column has HSV hue 32--51 rather than the generic cyan range.  Deriving the
    zones from broad HSV masks therefore either erased the cyan column or
    swallowed the beige tablecloth.  These normalized quadrilaterals register
    the two columns in the reviewed source view; colour statistics are used as
    a fail-closed identity check, not as the region generator.
    """

    height, width = before.shape[:2]
    normalized = {
        "yellow": ((0.218, 0.267), (0.291, 0.229), (0.501, 0.629), (0.417, 0.657)),
        "cyan": ((0.291, 0.229), (0.333, 0.207), (0.565, 0.589), (0.501, 0.629)),
    }
    masks: dict[str, np.ndarray] = {}
    polygons: dict[str, list[list[int]]] = {}
    for name, points in normalized.items():
        polygon = np.asarray(
            [[int(round(x * width)), int(round(y * height))] for x, y in points],
            dtype=np.int32,
        )
        mask = np.zeros((height, width), dtype=np.uint8)
        cv2.fillPoly(mask, [polygon], 1)
        masks[name] = mask.astype(bool)
        polygons[name] = polygon.tolist()

    # Even a shared one-pixel polygon edge must not make an assignment both
    # correct and wrong.  Give the reviewed divider itself to neither column.
    overlap = masks["yellow"] & masks["cyan"]
    masks["yellow"] &= ~overlap
    masks["cyan"] &= ~overlap

    hsv = _hsv(before)
    h, s = hsv[..., 0], hsv[..., 1]
    yellow_identity = (h >= 20) & (h <= 30) & (s >= 50)
    # Covers both neutralized warm-cyan pixels in this photograph and ordinary
    # cyan pixels in synthetic regression fixtures.
    cyan_identity = (h >= 32) & (h <= 105) & (s >= 35)
    yellow_fraction = float((yellow_identity & masks["yellow"]).sum() / max(1, masks["yellow"].sum()))
    cyan_fraction = float((cyan_identity & masks["cyan"]).sum() / max(1, masks["cyan"].sum()))
    identity_valid = yellow_fraction >= 0.15 and cyan_fraction >= 0.15
    evidence = {
        "zone_geometry": "reviewed_registered_two_column_quadrilaterals_v2",
        "zone_polygons": polygons,
        "yellow_identity_fraction": round(yellow_fraction, 4),
        "cyan_identity_fraction": round(cyan_fraction, 4),
        "zone_overlap_pixels_after_exclusion": int((masks["yellow"] & masks["cyan"]).sum()),
        "zone_identity_valid": identity_valid,
    }
    return masks, evidence


def _visual_pill_result(
    spec: AtomicCheckSpec,
    input_path: Path,
    pred_path: Path,
    observations: Mapping[str, Any],
) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    changed = _changed_mask(before, after, 34.0)
    zones, zone_evidence = _visual_pill_registered_zones(before)
    yellow_zone, cyan_zone = zones["yellow"], zones["cyan"]
    pill_domain = yellow_zone | cyan_zone
    zone_y, zone_x = np.where(pill_domain)
    padding = max(4, int(round(min(size) * 0.008)))
    organizer = (
        max(0, int(zone_x.min()) - padding),
        max(0, int(zone_y.min()) - padding),
        min(size[0], int(zone_x.max()) + padding + 1),
        min(size[1], int(zone_y.max()) + padding + 1),
    )
    whites = _pill_components(after, changed, organizer, "white", pill_domain, zones=zones)
    pinks = _pill_components(after, changed, organizer, "pink", pill_domain, zones=zones)
    rule = _decision_type(spec)
    base = {
        "parser": "registered_visual_pill_color_zone_parser_v2",
        "organizer_bbox": list(organizer),
        "new_white_components": whites,
        "new_pink_components": pinks,
        **zone_evidence,
    }
    if rule == "source_instance_vacancy":
        source = _ratio_box((0.025, 0.34, 0.31, 0.66), size)
        input_pink = _mask_fraction(_color_mask(before, "pink"), source)
        output_pink = _mask_fraction(_color_mask(after, "pink"), source)
        reduction = 1.0 - output_pink / max(input_pink, 1e-6)
        detector_hits = []
        for item in _detections(observations, spec.check_id):
            bbox = item.get("bbox_xyxy") or item.get("bbox")
            if isinstance(bbox, (list, tuple)) and len(bbox) == 4 and _inside(_center(bbox), source):
                detector_hits.append(item)
        if detector_hits:
            score = 0.0
        else:
            score = _score_threshold(reduction, 0.78, 0.45)
        return _result(spec, score=score, confidence=0.8, evidence={
            **base, "source_bbox": list(source), "input_pink_fraction": input_pink,
            "output_pink_fraction": output_pink, "pink_occupancy_reduction": reduction,
            "remaining_detector_hits": detector_hits,
        })
    if rule == "exclusive_color_zone_containment":
        if not zone_evidence["zone_identity_valid"]:
            return _unknown(spec, "registered_pill_zone_identity_inconclusive", **base)
        components = whites if "white" in spec.check_id else pinks
        target_name = "yellow" if "white" in spec.check_id else "cyan"
        wrong_name = "cyan" if "white" in spec.check_id else "yellow"
        containment_min = float(_decision_params(spec).get("mask_containment_min", 0.8))
        assignments = []
        correct = 0
        for item in components:
            overlaps = item.get("zone_overlap_fraction", {})
            target_fraction = float(overlaps.get(target_name, 0.0))
            wrong_fraction = float(overlaps.get(wrong_name, 0.0))
            in_target = target_fraction >= containment_min
            in_wrong = wrong_fraction > (1.0 - containment_min)
            assignments.append({
                **item,
                "target_zone": target_name,
                "wrong_zone": wrong_name,
                "target_mask_containment": target_fraction,
                "wrong_mask_containment": wrong_fraction,
                "in_target_zone": in_target,
                "in_wrong_zone": in_wrong,
            })
            correct += int(in_target and not in_wrong)
        if not components:
            return _unknown(spec, "insufficient_color_pill_components", **base, component_count=len(components))
        ratio = correct / len(components)
        score = _score_threshold(ratio, 0.95, 0.55)
        return _result(spec, score=score, confidence=0.8, evidence={
            **base, "assignment_count": len(components), "correct_assignment_count": correct,
            "correct_assignment_fraction": ratio, "mask_containment_min": containment_min,
            "target_zone": target_name, "wrong_zone": wrong_name, "assignments": assignments,
        })
    if rule == "translucent_lid_depth_plausibility":
        return _unknown(
            spec,
            "translucent_depth_requires_calibrated_optical_model",
            **base,
            note="Colour-zone containment is measurable, but image-only lid depth ordering is not safely inferred by this parser.",
        )
    if rule == "multi_entity_integrity":
        rois = {
            "black_case": _ratio_box((0.30, 0.075, 0.58, 0.27), size),
            "blood_pressure_cuff": _ratio_box((0.53, 0.15, 0.99, 0.62), size),
            "glasses": _ratio_box((0.47, 0.63, 0.86, 0.98), size),
            "cable": _ratio_box((0.58, 0.46, 1.0, 0.98), size),
        }
        metrics = {name: _diff_metrics(input_path, pred_path, box) for name, box in rois.items()}
        changed_max = max(item["changed_48"] for item in metrics.values())
        severity = 0.0 if changed_max <= 0.035 else 0.5 if changed_max <= 0.10 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "entity_rois": {key: list(value) for key, value in rois.items()}, "registered_diff_by_entity": metrics})
    if rule == "protected_roi_exact_preservation":
        rois = {
            # Inner pack regions avoid the adjacent loose-pill source pile and
            # the organizer corner; those are intentionally mutable.
            "white_blister": _ratio_box((0.18, 0.61, 0.43, 0.77), size),
            "pink_blister": _ratio_box((0.20, 0.79, 0.55, 0.98), size),
        }
        metrics = {name: _diff_metrics(input_path, pred_path, box) for name, box in rois.items()}
        edge_f1 = {name: _edge_f1(before, after, box, tolerance=4) for name, box in rois.items()}
        minimum = min(edge_f1.values())
        severity = 0.0 if minimum >= 0.88 else 0.5 if minimum >= 0.72 else 1.0
        return _result(spec, score=severity, confidence=0.84, evidence={**base, "protected_rois": {key: list(value) for key, value in rois.items()}, "registered_diff_by_roi": metrics, "tolerant_edge_f1_by_roi": edge_f1})
    if rule == "paired_text_legibility_preservation":
        input_words = _normalized_words(_ocr_texts(observations, spec.check_id, "input"))
        output_words = _normalized_words(_ocr_texts(observations, spec.check_id, "pred"))
        if len(input_words) < 3:
            return _unknown(spec, "organizer_ocr_inconclusive", **base, input_words=sorted(input_words), output_words=sorted(output_words))
        recall = len(input_words & output_words) / len(input_words)
        severity = 0.0 if recall >= 0.9 else 0.5 if recall >= 0.65 else 1.0
        return _result(spec, score=severity, confidence=0.7, evidence={**base, "input_words": sorted(input_words), "output_words": sorted(output_words), "token_recall": recall})
    if rule == "count_conservation_and_structure_invariance":
        # Exact conservation is only scored when both colour families yield a
        # stable component roster.  Otherwise fail closed instead of turning a
        # weak small-object count into a penalty.
        structure_box = _ratio_box((0.22, 0.16, 0.70, 0.77), size)
        edge_change = _edge_change_fraction(before, after, structure_box, ignore=cv2.dilate(changed.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool))
        return _unknown(
            spec,
            "pill_count_conservation_roster_not_calibrated",
            **base,
            organizer_structure_edge_change=edge_change,
            note="Structure evidence is available, but the composite penalty also requires exact small-pill conservation.",
        )
    return _unknown(spec, "unsupported_visual_pill_rule", source_rule_type=rule)


def _parameter_box(values: Any, size: tuple[int, int]) -> tuple[int, int, int, int] | None:
    if not isinstance(values, (list, tuple)) or len(values) != 4:
        return None
    box = [float(value) for value in values]
    width, height = size
    if max(box[0], box[2]) <= 1.0 and max(box[1], box[3]) <= 1.0:
        return _ratio_box(tuple(box), size)
    # Resolved plans for this case were annotated directly on the 900px
    # source.  Scale only when an artifact is evaluated at another size.
    base = 900.0
    return (
        max(0, min(width, int(round(box[0] * width / base)))),
        max(0, min(height, int(round(box[1] * height / base)))),
        max(0, min(width, int(round(box[2] * width / base)))),
        max(0, min(height, int(round(box[3] * height / base)))),
    )


_PARKING_SLOTS = {
    "slot_1": (34.8 / 900.0, 156.8 / 900.0, 207.6 / 900.0, 403.5 / 900.0),
    "slot_2": (232.3 / 900.0, 156.8 / 900.0, 394.8 / 900.0, 403.5 / 900.0),
    "slot_3": (464.5 / 900.0, 156.8 / 900.0, 625.6 / 900.0, 403.5 / 900.0),
    "slot_4": (670.6 / 900.0, 156.8 / 900.0, 856.5 / 900.0, 403.5 / 900.0),
}


def _expanded_box(box: tuple[int, int, int, int], amount: int, size: tuple[int, int]) -> tuple[int, int, int, int]:
    width, height = size
    return max(0, box[0] - amount), max(0, box[1] - amount), min(width, box[2] + amount), min(height, box[3] + amount)


def _parking_color_component(
    after: np.ndarray,
    changed: np.ndarray,
    color: str,
    search_box: tuple[int, int, int, int],
) -> dict[str, Any] | None:
    mask = _color_mask(after, color) & cv2.dilate(changed.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool)
    x0, y0, x1, y1 = search_box
    items = _components(mask[y0:y1, x0:x1], min_area=55)
    if not items:
        return None
    item = items[0]
    bx0, by0, bx1, by1 = item["bbox"]
    # Vehicles in the rectified parking slots are vertically oriented.  Long
    # horizontal/diagonal coloured components are painted slot markings, not
    # vehicle bodies.
    if (by1 - by0) < (bx1 - bx0) * 1.12:
        return None
    return {
        **item,
        "bbox": [bx0 + x0, by0 + y0, bx1 + x0, by1 + y0],
        "centroid": [item["centroid"][0] + x0, item["centroid"][1] + y0],
    }


def _bbox_containment(inner: list[float], outer: tuple[int, int, int, int]) -> float:
    ix0, iy0 = max(float(inner[0]), outer[0]), max(float(inner[1]), outer[1])
    ix1, iy1 = min(float(inner[2]), outer[2]), min(float(inner[3]), outer[3])
    intersection = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
    area = max(1.0, (float(inner[2]) - float(inner[0])) * (float(inner[3]) - float(inner[1])))
    return intersection / area


def _parking_result(spec: AtomicCheckSpec, input_path: Path, pred_path: Path) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    changed = _changed_mask(before, after, 45.0)
    rule = _decision_type(spec)
    parameters = _decision_params(spec)
    slot_boxes = {name: _ratio_box(ratio, size) for name, ratio in _PARKING_SLOTS.items()}
    base = {"parser": "registered_parking_color_change_parser_v1", "slot_bboxes": {key: list(value) for key, value in slot_boxes.items()}}
    if rule in {"assigned_vehicle_slot_predicate", "accessible_vehicle_slot_predicate"}:
        slot_name = str(parameters.get("slot") or "")
        slot = _parameter_box(parameters.get("slot_bbox"), size) or slot_boxes.get(slot_name)
        if slot is None:
            return _unknown(spec, "missing_parking_slot_geometry", **base)
        expected = str(parameters.get("expected_color") or "").lower().replace("grey", "gray")
        expand = int(round(float(parameters.get("slot_expand_px_for_detection", 28)) * size[0] / 900.0))
        candidate = _parking_color_component(after, changed, expected, _expanded_box(slot, expand, size))
        if candidate is None:
            return _result(spec, score=0.0, confidence=0.84, evidence={**base, "slot": slot_name, "expected_color": expected, "candidate": None})
        containment = _bbox_containment(candidate["bbox"], slot)
        pass_min = float(parameters.get("pass_mask_containment", 0.85))
        partial_min = float(parameters.get("partial_mask_containment", 0.65))
        area_threshold = max(55, int(float(parameters.get("min_vehicle_area_px", 1800)) * float(parameters.get("min_color_ratio", 0.1)) * size[0] * size[1] / 810000.0))
        score = _score_threshold(containment, pass_min, partial_min) if candidate["area"] >= area_threshold else 0.0
        symbol_evidence: dict[str, Any] = {}
        if rule == "accessible_vehicle_slot_predicate":
            bx0, by0, bx1, by1 = [int(value) for value in candidate["bbox"]]
            white_changed = (_color_mask(after, "white") & changed)[by0:by1, bx0:bx1]
            symbol_pixels = int(white_changed.sum())
            symbol_evidence = {"vehicle_white_symbol_changed_pixels": symbol_pixels, "symbol_minimum_pixels": 45}
            if symbol_pixels < 45:
                score = min(score, 0.5 if symbol_pixels >= 20 else 0.0)
        return _result(spec, score=score, confidence=0.84, evidence={
            **base, "slot": slot_name, "expected_color": expected, "candidate": candidate,
            "bbox_containment": containment, "thresholds": {"pass": pass_min, "partial": partial_min, "minimum_color_area": area_threshold},
            **symbol_evidence,
        })
    if rule == "any_assigned_vehicle_boundary_violation":
        assignment = parameters.get("assignment", {}) if isinstance(parameters.get("assignment"), Mapping) else {}
        details = []
        violations = []
        for identity, slot_name in assignment.items():
            color = "blue" if "blue" in str(identity) else str(identity).replace("grey", "gray")
            slot = slot_boxes.get(str(slot_name))
            if slot is None:
                continue
            candidate = _parking_color_component(after, changed, color, _expanded_box(slot, int(35 * size[0] / 900), size))
            containment = _bbox_containment(candidate["bbox"], slot) if candidate else 0.0
            item = {"identity": identity, "slot": slot_name, "candidate": candidate, "containment": containment}
            details.append(item)
            if candidate is None or containment < float(parameters.get("min_mask_containment", 0.85)):
                violations.append(item)
        severity = 0.0 if not violations else 0.5 if len(violations) == 1 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "assignment_results": details, "violations": violations})
    if rule == "audit_only_required_identity_count":
        counts = {}
        scene = _ratio_box((0.0, 0.12, 1.0, 0.72), size)
        for identity in (parameters.get("required_identity_counts") or {}):
            color = "blue" if "blue" in str(identity) else str(identity).split("_")[0].replace("grey", "gray")
            candidate = _parking_color_component(after, changed, color, scene)
            counts[str(identity)] = 1 if candidate else 0
        return _result(spec, score=0.0, confidence=0.75, status="clean", evidence={
            **base, "audit_only": True, "automatic_penalty_enabled": False,
            "observed_identity_presence": counts, "note":"Reported for audit only; contract explicitly disables automatic penalty.",
        })
    if rule == "occlusion_aware_marking_preservation":
        protected = _parameter_box(parameters.get("protected_bbox"), size) or _ratio_box((0.02, 0.15, 0.97, 0.48), size)
        vehicle_change = cv2.dilate(changed.astype(np.uint8), np.ones((17, 17), np.uint8)).astype(bool)
        edge_change = _edge_change_fraction(before, after, protected, ignore=vehicle_change)
        return _result(spec, score=0.0, confidence=0.72, status="clean", evidence={
            **base, "audit_only": True, "automatic_penalty_enabled": False,
            "protected_bbox": list(protected), "unexplained_edge_change_fraction": edge_change,
        })
    return _unknown(spec, "unsupported_parking_rule", source_rule_type=rule)


_LAUNDRY_OBJECT_TOKENS = {
    "white_t_shirt": ("t-shirt", "t shirt"),
    "blue_jeans": ("jeans", "denim"),
    "red_sweater": ("sweater",),
    "beige_towel": ("towel",),
    "white_blouse": ("blouse", "lace"),
    "grey_scarf": ("scarf", "fringe"),
}


def _detection_candidates_for_tokens(
    items: list[dict[str, Any]],
    tokens: tuple[str, ...],
) -> list[dict[str, Any]]:
    candidates: list[dict[str, Any]] = []
    for item in items:
        query = str(item.get("query_text", "")).lower()
        label = str(item.get("label", "")).lower()
        query_match = any(token in query for token in tokens)
        label_match = any(token in label for token in tokens)
        if (query_match or label_match) and float(item.get("score", 0.0) or 0.0) >= 0.10:
            bbox = item.get("bbox_xyxy") or item.get("bbox")
            if isinstance(bbox, (list, tuple)) and len(bbox) == 4:
                candidates.append({**item, "_query_token_match": query_match})
    return candidates


def _best_detection_for_tokens(
    items: list[dict[str, Any]],
    tokens: tuple[str, ...],
    *,
    preferred_zone: tuple[int, int, int, int] | None = None,
) -> tuple[dict[str, Any] | None, dict[str, Any]]:
    candidates = _detection_candidates_for_tokens(items, tokens)
    eligible = candidates
    inside_candidates: list[dict[str, Any]] = []
    if preferred_zone is not None:
        inside_candidates = [
            item for item in candidates
            if _inside(_center(item.get("bbox_xyxy") or item.get("bbox")), preferred_zone)
        ]
        if inside_candidates:
            eligible = inside_candidates

    def rank(item: Mapping[str, Any]) -> tuple[int, int, float]:
        policy = str(item.get("query_policy") or "")
        backend = str(item.get("backend") or "")
        preferred_backend = (
            backend == "grounding_dino" if policy == "dino_long_query"
            else backend in {"yoloe_text", "yolo_world_text"} if policy == "yolo_short_query"
            else False
        )
        return (
            int(bool(item.get("_query_token_match"))),
            int(preferred_backend),
            float(item.get("score", 0.0) or 0.0),
        )

    selected = max(eligible, key=rank, default=None)
    if selected is not None:
        selected = {key: value for key, value in selected.items() if not key.startswith("_")}
    audit = {
        "candidate_count": len(candidates),
        "inside_target_candidate_count": len(inside_candidates),
        "used_zone_arbitration": bool(preferred_zone is not None and inside_candidates),
        "selected_backend": str(selected.get("backend") or "") if selected else "",
        "selection_policy": "query-token-match_then_query-policy_backend_then_score_with_target-zone_preference",
    }
    return selected, audit


def _laundry_result(
    spec: AtomicCheckSpec,
    input_path: Path,
    pred_path: Path,
    observations: Mapping[str, Any],
) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    zones = {
        "cold": _ratio_box((0.00, 0.19, 0.34, 0.69), size),
        "warm": _ratio_box((0.30, 0.19, 0.70, 0.69), size),
        "delicate": _ratio_box((0.66, 0.19, 1.00, 0.69), size),
    }
    rule = _decision_type(spec)
    parameters = _decision_params(spec)
    detections = _detections(observations, spec.check_id)
    base = {"parser": "laundry_detector_zone_and_registered_background_parser_v1", "basket_zones": {key: list(value) for key, value in zones.items()}}
    if rule == "required_pair_in_target_zone":
        target = "cold" if "cold" in spec.check_id else "warm" if "warm" in spec.check_id else "delicate"
        required = [str(item) for item in parameters.get("required_objects", [])]
        matches = []
        missing = []
        for object_id in required:
            candidate, arbitration = _best_detection_for_tokens(
                detections,
                _LAUNDRY_OBJECT_TOKENS.get(object_id, (object_id.replace("_", " "),)),
                preferred_zone=zones[target],
            )
            if candidate is None:
                missing.append(object_id)
                continue
            bbox = candidate.get("bbox_xyxy") or candidate.get("bbox")
            matches.append({
                "object_id": object_id,
                "detection": candidate,
                "inside_target": _inside(_center(bbox), zones[target]),
                "detector_arbitration": arbitration,
            })
        if missing:
            return _unknown(spec, "laundry_required_item_detection_incomplete", **base, target_basket=target, missing_objects=missing, matched_objects=matches)
        correct = sum(bool(item["inside_target"]) for item in matches)
        score = 1.0 if correct == len(required) else 0.5 if correct else 0.0
        return _result(spec, score=score, confidence=0.76, evidence={**base, "target_basket": target, "required_objects": required, "matched_objects": matches})
    if rule == "all_sources_vacated_no_forbidden_zone_instances":
        source = _ratio_box((0.0, 0.67, 1.0, 0.98), size)
        before_gray = cv2.cvtColor(before, cv2.COLOR_RGB2GRAY)
        after_gray = cv2.cvtColor(after, cv2.COLOR_RGB2GRAY)
        x0, y0, x1, y1 = source
        before_edges = cv2.Canny(before_gray[y0:y1, x0:x1], 70, 150) > 0
        after_edges = cv2.Canny(after_gray[y0:y1, x0:x1], 70, 150) > 0
        before_density = float(before_edges.mean()) if before_edges.size else 0.0
        after_density = float(after_edges.mean()) if after_edges.size else 1.0
        reduction = 1.0 - after_density / max(before_density, 1e-6)
        remaining = []
        for item in detections:
            bbox = item.get("bbox_xyxy") or item.get("bbox")
            if isinstance(bbox, (list, tuple)) and len(bbox) == 4 and _inside(_center(bbox), source):
                remaining.append(item)
        severity = 1.0 if remaining else 0.0 if reduction >= 0.45 and after_density <= 0.035 else 0.5 if reduction >= 0.2 else 1.0
        return _result(spec, score=severity, confidence=0.78, evidence={
            **base, "source_table_bbox": list(source), "input_edge_density": before_density,
            "output_edge_density": after_density, "edge_density_reduction": reduction,
            "remaining_detector_hits": remaining,
        })
    if rule == "all_required_text_and_icons_intact":
        texts = " ".join(_ocr_texts(observations, spec.check_id, "pred")).upper()
        required = ["COLD", "WARM", "DELICATE"]
        hits = {token: token in texts for token in required}
        if not texts.strip():
            return _unknown(spec, "laundry_label_ocr_inconclusive", **base, required_tokens=required)
        count = sum(hits.values())
        severity = 0.0 if count == 3 else 0.5 if count >= 2 else 1.0
        return _result(spec, score=severity, confidence=0.74, evidence={**base, "ocr_text": texts, "required_token_hits": hits})
    if rule == "all_item_attributes_preserved":
        roster = {}
        arbitration = {}
        for object_id, tokens in _LAUNDRY_OBJECT_TOKENS.items():
            roster[object_id], arbitration[object_id] = _best_detection_for_tokens(detections, tokens)
        missing = [key for key, value in roster.items() if value is None]
        if missing:
            return _unknown(
                spec, "laundry_output_identity_roster_incomplete", **base,
                missing_identities=missing, identity_roster=roster,
                detector_arbitration=arbitration,
            )
        return _result(spec, score=0.0, confidence=0.7, status="clean", evidence={
            **base, "expected_count": 6, "identity_roster": roster,
            "detector_arbitration": arbitration,
            "note":"All six query-specific identities have distinct output evidence; appearance thresholds remain visible in detector provenance.",
        })
    if rule == "invariant_region_preserved":
        background = _ratio_box((0.0, 0.0, 1.0, 0.20), size)
        diff = _diff_metrics(input_path, pred_path, background)
        severity = 0.0 if diff["changed_48"] <= 0.025 else 0.5 if diff["changed_48"] <= 0.07 else 1.0
        return _result(spec, score=severity, confidence=0.84, evidence={**base, "background_bbox": list(background), "registered_diff": diff})
    return _unknown(spec, "unsupported_laundry_rule", source_rule_type=rule)


def _medication_cells(size: tuple[int, int]) -> tuple[list[tuple[int, int, int, int]], list[tuple[int, int, int, int]]]:
    x0, x1 = 0.17, 0.90
    edges = np.linspace(x0, x1, 8)
    am = [_ratio_box((float(edges[index]), 0.405, float(edges[index + 1]), 0.515), size) for index in range(7)]
    pm = [_ratio_box((float(edges[index]), 0.545, float(edges[index + 1]), 0.675), size) for index in range(7)]
    return am, pm


def _cell_color_area(after: np.ndarray, changed: np.ndarray, box: tuple[int, int, int, int], color: str) -> int:
    return int(_crop_mask(_color_mask(after, color) & changed, box).sum())


def _medication_result(
    spec: AtomicCheckSpec,
    input_path: Path,
    pred_path: Path,
    observations: Mapping[str, Any],
) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    changed = _changed_mask(before, after, 32.0)
    am_cells, pm_cells = _medication_cells(size)
    separate = _ratio_box((0.72, 0.145, 0.965, 0.30), size)
    scale = before.shape[0] * before.shape[1] / (1024.0 * 1024.0)
    presence = max(14, int(26 * scale))
    am_metrics = [
        {color: _cell_color_area(after, changed, box, color) for color in ("white", "yellow", "blue", "red")}
        for box in am_cells
    ]
    pm_metrics = [
        {color: _cell_color_area(after, changed, box, color) for color in ("white", "yellow", "blue", "red")}
        for box in pm_cells
    ]
    rule = _decision_type(spec)
    base = {
        "parser": "registered_medication_grid_color_delta_parser_v1",
        "am_cell_bboxes": [list(box) for box in am_cells],
        "pm_cell_bboxes": [list(box) for box in pm_cells],
        "am_color_areas": am_metrics,
        "pm_color_areas": pm_metrics,
        "presence_threshold_pixels": presence,
    }
    if rule == "seven_slot_exact_pair_count":
        correct = sum(item["white"] >= presence and item["yellow"] >= presence and item["blue"] < presence and item["red"] < presence for item in am_metrics)
        partial_min = int(_decision_params(spec).get("minimum_correct_slots_for_partial", 4))
        score = 1.0 if correct == 7 else 0.5 if correct >= partial_min else 0.0
        return _result(spec, score=score, confidence=0.88, evidence={**base, "correct_am_slots": correct, "required_slots": 7})
    if rule == "seven_slot_exact_single_count":
        correct = sum(item["blue"] >= presence and item["white"] < presence and item["yellow"] < presence and item["red"] < presence for item in pm_metrics)
        partial_min = int(_decision_params(spec).get("minimum_correct_slots_for_partial", 4))
        score = 1.0 if correct == 7 else 0.5 if correct >= partial_min else 0.0
        return _result(spec, score=score, confidence=0.88, evidence={**base, "correct_pm_slots": correct, "required_slots": 7})
    if rule == "exact_container_count_with_purity":
        red_local = _crop_mask(_color_mask(after, "red") & changed, separate)
        red_components = _components(red_local, min_area=max(10, int(18 * scale)), max_area=max(5000, int(red_local.size * 0.25)))
        other_area = sum(_cell_color_area(after, changed, separate, color) for color in ("white", "yellow", "blue"))
        required = int(_decision_params(spec).get("required_red_capsules", 7))
        count = len(red_components)
        score = 1.0 if count == required and other_area < presence else 0.5 if count >= max(1, required - 2) and other_area < presence * 2 else 0.0
        return _result(spec, score=score, confidence=0.84, evidence={
            **base, "separate_container_bbox": list(separate), "red_component_count": count,
            "required_red_capsules": required, "red_components": red_components,
            "other_pill_color_area": other_area,
        })
    if rule == "all_instances_intact_and_stationary":
        bottles = _ratio_box((0.065, 0.045, 0.67, 0.27), size)
        diff = _diff_metrics(input_path, pred_path, bottles)
        severity = 0.0 if diff["changed_48"] <= 0.02 else 0.5 if diff["changed_48"] <= 0.06 else 1.0
        return _result(spec, score=severity, confidence=0.86, evidence={**base, "bottle_row_bbox": list(bottles), "registered_diff": diff})
    if rule == "registered_card_preservation":
        card = _ratio_box((0.24, 0.70, 0.72, 0.94), size)
        diff = _diff_metrics(input_path, pred_path, card)
        edge_f1 = _edge_f1(before, after, card, tolerance=4)
        severity = 0.0 if edge_f1 >= 0.88 else 0.5 if edge_f1 >= 0.72 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "schedule_card_bbox": list(card), "registered_diff": diff, "tolerant_edge_f1": edge_f1})
    if rule == "all_required_labels_legible_and_aligned":
        texts = " ".join(_ocr_texts(observations, spec.check_id, "pred")).upper()
        required = [str(item).upper() for item in _decision_params(spec).get("required_tokens", [])]
        hits = {token: token in texts for token in required}
        if not texts.strip():
            return _unknown(spec, "medication_label_ocr_inconclusive", **base, required_tokens=required)
        fraction = sum(hits.values()) / max(1, len(hits))
        severity = 0.0 if fraction >= 0.9 else 0.5 if fraction >= 0.65 else 1.0
        return _result(spec, score=severity, confidence=0.72, evidence={**base, "ocr_text": texts, "required_token_hits": hits, "token_recall": fraction})
    if rule == "allowed_type_by_row":
        wrong_am = sum(item["blue"] >= presence or item["red"] >= presence for item in am_metrics)
        wrong_pm = sum(item["white"] >= presence or item["yellow"] >= presence or item["red"] >= presence for item in pm_metrics)
        severity = 0.0 if wrong_am + wrong_pm == 0 else 0.5 if wrong_am + wrong_pm <= 2 else 1.0
        return _result(spec, score=severity, confidence=0.88, evidence={**base, "wrong_am_slots": wrong_am, "wrong_pm_slots": wrong_pm})
    if rule == "invariant_background_preservation":
        mutable = np.zeros(changed.shape, dtype=bool)
        for box in [*am_cells, *pm_cells, separate]:
            x0, y0, x1, y1 = box
            mutable[y0:y1, x0:x1] = True
        valid = ~cv2.dilate(mutable.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool)
        fraction = float((changed & valid).sum() / max(1, valid.sum()))
        edge_f1 = _edge_f1(before, after, (0, 0, size[0], size[1]), ignore=~valid, tolerance=4)
        severity = 0.0 if edge_f1 >= 0.92 else 0.5 if edge_f1 >= 0.80 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "significant_background_change_fraction": fraction, "tolerant_background_edge_f1": edge_f1})
    return _unknown(spec, "unsupported_medication_rule", source_rule_type=rule)


def _line_occupancy(mask: np.ndarray, start: tuple[float, float], end: tuple[float, float], *, width: int = 3) -> float:
    height, image_width = mask.shape
    distance = max(1, int(math.dist(start, end)))
    hits = []
    for index in range(distance + 1):
        alpha = index / distance
        x = int(round(start[0] * (1 - alpha) + end[0] * alpha))
        y = int(round(start[1] * (1 - alpha) + end[1] * alpha))
        crop = mask[max(0, y-width):min(height, y+width+1), max(0, x-width):min(image_width, x+width+1)]
        hits.append(bool(crop.any()))
    return float(np.mean(hits)) if hits else 0.0


def _fluid_surface_y(mask: np.ndarray, box: tuple[int, int, int, int]) -> float | None:
    x0, y0, x1, y1 = box
    local = mask[y0:y1, x0:x1]
    values = []
    for column in range(local.shape[1]):
        ys = np.flatnonzero(local[:, column])
        if ys.size:
            values.append(float(ys[0] + y0))
    return float(np.median(values)) if len(values) >= max(3, local.shape[1] // 6) else None


def _fluid_result(spec: AtomicCheckSpec, input_path: Path, pred_path: Path, observations: Mapping[str, Any]) -> dict[str, Any]:
    before, after = _open_rgb_pair(input_path, pred_path)
    size = (before.shape[1], before.shape[0])
    before_blue = _color_mask(before, "blue") | _color_mask(before, "cyan")
    after_blue = _color_mask(after, "blue") | _color_mask(after, "cyan")
    rule = _decision_type(spec)
    reservoir = _ratio_box((0.035, 0.125, 0.19, 0.355), size)
    bottle_boxes = {
        "A": _ratio_box((0.455, 0.59, 0.57, 0.82), size),
        "B": _ratio_box((0.63, 0.59, 0.75, 0.82), size),
        "C": _ratio_box((0.81, 0.59, 0.94, 0.82), size),
    }
    x = {"A": size[0] * 0.515, "B": size[0] * 0.695, "C": size[0] * 0.875}
    y_main = size[1] * 0.25
    upper_segments = {
        "main_left": ((size[0] * 0.19, y_main), (size[0] * 0.30, y_main)),
        "main_right": ((size[0] * 0.42, y_main), (size[0] * 0.87, y_main)),
        **{f"upper_{key}": ((value, y_main), (value, size[1] * 0.327)) for key, value in x.items()},
    }
    lower_segments = {
        "lower_A": ((x["A"], size[1] * 0.45), (x["A"], size[1] * 0.555)),
        "lower_B": ((x["B"], size[1] * 0.45), (x["B"], size[1] * 0.555)),
        "lower_C": ((x["C"], size[1] * 0.45), (x["C"], size[1] * 0.555)),
    }
    base = {
        "parser": "registered_lab_fluid_network_parser_v1",
        "reservoir_bbox": list(reservoir),
        "bottle_bboxes": {key: list(value) for key, value in bottle_boxes.items()},
        "overlay_geometry": {
            "segments": {
                **{key: [*start, *end] for key, (start, end) in upper_segments.items()},
                **{key: [*start, *end] for key, (start, end) in lower_segments.items()},
            }
        },
    }
    if rule == "fluid_level_drop":
        input_y, output_y = _fluid_surface_y(before_blue, reservoir), _fluid_surface_y(after_blue, reservoir)
        if input_y is None or output_y is None:
            return _unknown(spec, "reservoir_surface_not_detected", **base, input_surface_y=input_y, output_surface_y=output_y)
        drop = (output_y - input_y) / max(1.0, reservoir[3] - reservoir[1])
        parameters = _decision_params(spec)
        score = _score_threshold(drop, float(parameters.get("pass_min_drop_fraction", 0.05)), float(parameters.get("minimum_detectable_drop_fraction", 0.01)))
        return _result(spec, score=score, confidence=0.9, evidence={**base, "input_surface_y": input_y, "output_surface_y": output_y, "drop_fraction_of_reservoir_height": drop})
    if rule == "required_tube_network_fill":
        occupancies = {name: _line_occupancy(after_blue, start, end, width=max(2, int(size[0] * 0.004))) for name, (start, end) in upper_segments.items()}
        aggregate = float(np.mean(list(occupancies.values())))
        minimum = min(occupancies.values())
        parameters = _decision_params(spec)
        score = 1.0 if minimum >= float(parameters.get("pass_segment_occupancy", 0.9)) else 0.5 if aggregate >= float(parameters.get("partial_aggregate_occupancy", 0.6)) else 0.0
        return _result(spec, score=score, confidence=0.88, evidence={**base, "segment_occupancies": occupancies, "minimum_segment_occupancy": minimum, "aggregate_occupancy": aggregate})
    if rule == "paired_lower_path_and_container_fill":
        tube = {name: _line_occupancy(after_blue, *segment, width=max(2, int(size[0] * 0.004))) for name, segment in lower_segments.items() if name != "lower_C"}
        bottle = {key: _mask_fraction(after_blue, box) for key, box in bottle_boxes.items() if key in {"A", "B"}}
        tube_min = min(tube.values())
        bottle_min = min(bottle.values())
        parameters = _decision_params(spec)
        passed = tube_min >= float(parameters.get("tube_pass_occupancy", 0.9)) and bottle_min >= float(parameters.get("minimum_bottle_fluid_area_fraction", 0.02))
        partial = tube_min >= 0.55 and bottle_min >= 0.01
        return _result(spec, score=1.0 if passed else 0.5 if partial else 0.0, confidence=0.9, evidence={**base, "lower_tube_occupancies": tube, "bottle_blue_fractions": bottle})
    if rule == "paired_level_equality":
        levels = {key: _fluid_surface_y(after_blue, bottle_boxes[key]) for key in ("A", "B")}
        if any(value is None for value in levels.values()):
            return _unknown(spec, "paired_bottle_surface_not_detected", **base, levels=levels)
        difference = abs(float(levels["A"]) - float(levels["B"]))
        relative = difference / max(1.0, before.shape[0])
        parameters = _decision_params(spec)
        score = 1.0 if difference <= float(parameters.get("absolute_pass_tolerance_pixels", 2)) or relative <= float(parameters.get("relative_pass_tolerance", 0.005)) else 0.5 if relative <= float(parameters.get("partial_max_relative_difference", 0.05)) else 0.0
        return _result(spec, score=score, confidence=0.9, evidence={**base, "surface_levels_y": levels, "absolute_difference_pixels": difference, "relative_difference": relative})
    if rule == "forbidden_blue_fluid_overlap":
        tube_occupancy = _line_occupancy(after_blue, *lower_segments["lower_C"], width=max(2, int(size[0] * 0.004)))
        bottle_fraction = _mask_fraction(after_blue, bottle_boxes["C"])
        severity = 1.0 if tube_occupancy >= 0.3 or bottle_fraction >= 0.02 else 0.5 if tube_occupancy >= 0.08 or bottle_fraction >= 0.005 else 0.0
        return _result(spec, score=severity, confidence=0.92, evidence={**base, "forbidden_lower_c_tube_occupancy": tube_occupancy, "forbidden_bottle_c_blue_fraction": bottle_fraction})
    if rule == "multi_handle_pose_preservation":
        rois = {key: _ratio_box((value / size[0] - 0.055, 0.335, value / size[0] + 0.055, 0.445), size) for key, value in x.items()}
        ious = {}
        for key, box in rois.items():
            a, b = _crop_mask(before_blue, box), _crop_mask(after_blue, box)
            union = int((a | b).sum())
            ious[key] = float((a & b).sum() / max(1, union))
        minimum = min(ious.values())
        severity = 0.0 if minimum >= 0.82 else 0.5 if minimum >= 0.62 else 1.0
        return _result(spec, score=severity, confidence=0.86, evidence={**base, "valve_handle_mask_iou": ious})
    if rule == "ordered_label_preservation":
        labels = _ratio_box((0.44, 0.82, 0.94, 0.93), size)
        diff = _diff_metrics(input_path, pred_path, labels)
        edge_change = _edge_change_fraction(before, after, labels)
        texts = " ".join(_ocr_texts(observations, spec.check_id, "pred")).upper()
        ordered = all(token in texts for token in ("A", "B", "C")) if texts else None
        severity = 0.0 if edge_change <= 0.02 and ordered is not False else 0.5 if edge_change <= 0.05 else 1.0
        return _result(spec, score=severity, confidence=0.8, evidence={**base, "label_plate_bbox": list(labels), "registered_diff": diff, "edge_change_fraction": edge_change, "ocr_text": texts, "ordered_labels_detected": ordered})
    if rule == "invariant_structure_integrity":
        apparatus = _ratio_box((0.015, 0.01, 0.985, 0.92), size)
        mutable = cv2.dilate((before_blue | after_blue).astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool)
        edge_change = _edge_change_fraction(before, after, apparatus, ignore=mutable)
        severity = 0.0 if edge_change <= 0.012 else 0.5 if edge_change <= 0.035 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "apparatus_bbox": list(apparatus), "edge_change_excluding_fluid": edge_change})
    return _unknown(spec, "unsupported_fluid_rule", source_rule_type=rule)


_FLOW_CHECKBOXES = {
    "start_checkbox": (0.335, 0.135, 0.385, 0.205),
    "temp_high_checkbox": (0.315, 0.265, 0.365, 0.335),
    "battery_low_checkbox": (0.31, 0.405, 0.365, 0.48),
    "alert_tech_checkbox": (0.31, 0.59, 0.365, 0.66),
    "service_checkbox": (0.31, 0.72, 0.365, 0.79),
    "cool_down_checkbox": (0.735, 0.265, 0.79, 0.34),
    "recharge_checkbox": (0.745, 0.405, 0.805, 0.49),
    "ok_checkbox": (0.765, 0.67, 0.83, 0.755),
}


def _checkbox_delta(
    input_gray: np.ndarray,
    pred_gray: np.ndarray,
    box: tuple[int, int, int, int],
    *,
    output_color_mark: np.ndarray | None = None,
) -> dict[str, float]:
    x0, y0, x1, y1 = box
    before = input_gray[y0:y1, x0:x1]
    after = pred_gray[y0:y1, x0:x1]
    if not before.size or before.shape != after.shape:
        return {"changed_fraction": 1.0, "dark_fraction_gain": 0.0, "inside_mark_score": 0.0}
    border_x = max(1, int(before.shape[1] * 0.18))
    border_y = max(1, int(before.shape[0] * 0.18))
    before_inner = before[border_y:-border_y or None, border_x:-border_x or None]
    after_inner = after[border_y:-border_y or None, border_x:-border_x or None]
    delta = np.abs(before_inner - after_inner)
    changed = float((delta >= 24).mean())
    dark_gain = float((after_inner <= 100).mean() - (before_inner <= 100).mean())
    color_fraction = 0.0
    if output_color_mark is not None:
        color_inner = output_color_mark[y0:y1, x0:x1]
        color_inner = color_inner[border_y:-border_y or None, border_x:-border_x or None]
        color_fraction = float(color_inner.mean()) if color_inner.size else 0.0
    # Re-rendering can move an empty checkbox border and create a high raw
    # change fraction. A mark must add either colored ink or dark ink inside
    # the box; change alone is not sufficient evidence.
    dark_stroke_score = min(changed / 0.08, max(0.0, dark_gain) / 0.035)
    inside_score = max(color_fraction / 0.012, dark_stroke_score)
    return {
        "changed_fraction": changed,
        "dark_fraction_gain": dark_gain,
        "color_mark_fraction": color_fraction,
        "inside_mark_score": float(inside_score),
    }


def _flowchart_result(spec: AtomicCheckSpec, input_path: Path, pred_path: Path) -> dict[str, Any]:
    before_rgb, after_rgb = _open_rgb_pair(input_path, pred_path)
    before = cv2.cvtColor(before_rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
    after = cv2.cvtColor(after_rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
    output_color_mark = _color_mask(after_rgb, "green")
    size = (before.shape[1], before.shape[0])
    metrics = {
        zone_id: _checkbox_delta(
            before, after, _ratio_box(ratio, size), output_color_mark=output_color_mark,
        )
        for zone_id, ratio in _FLOW_CHECKBOXES.items()
    }
    rule = _decision_type(spec)
    base = {
        "parser": "registered_checkbox_delta_parser_v2",
        "checkbox_metrics": metrics,
        "checkbox_bboxes": {
            zone_id: list(_ratio_box(ratio, size))
            for zone_id, ratio in _FLOW_CHECKBOXES.items()
        },
    }
    if rule == "single_checkbox_mark_state":
        metric = metrics["start_checkbox"]
        score = 1.0 if metric["inside_mark_score"] >= 1.0 else 0.5 if metric["inside_mark_score"] >= 0.45 else 0.0
        return _result(spec, score=score, confidence=0.82, evidence={**base, "evaluated_zones": ["start_checkbox"]})
    if rule == "two_checkbox_completion_count":
        zones = ["temp_high_checkbox", "battery_low_checkbox"] if "condition" in spec.check_id else ["alert_tech_checkbox", "service_checkbox"]
        checked = sum(metrics[zone]["inside_mark_score"] >= 0.75 for zone in zones)
        score = 1.0 if checked == 2 else 0.5 if checked == 1 else 0.0
        return _result(spec, score=score, confidence=0.82, evidence={**base, "evaluated_zones": zones, "checked_count": checked, "required_count": 2})
    if rule == "all_forbidden_checkboxes_empty":
        zones = ["cool_down_checkbox", "recharge_checkbox", "ok_checkbox"]
        modified = [zone for zone in zones if metrics[zone]["inside_mark_score"] >= 0.45]
        severity = 1.0 if modified else 0.0
        return _result(spec, score=severity, confidence=0.84, evidence={**base, "evaluated_zones": zones, "modified_forbidden_zones": modified})

    checkbox_boxes = [_ratio_box(ratio, size) for ratio in _FLOW_CHECKBOXES.values()]
    if rule == "flowchart_structure_preservation":
        sheet = _ratio_box((0.18, 0.06, 0.86, 0.89), size)
        x0, y0, x1, y1 = sheet
        before_crop, after_crop = before[y0:y1, x0:x1], after[y0:y1, x0:x1]
        diff = np.abs(before_crop - after_crop)
        allowed = np.zeros(diff.shape, dtype=bool)
        for bx0, by0, bx1, by1 in checkbox_boxes:
            allowed[max(0, by0-y0):max(0, by1-y0), max(0, bx0-x0):max(0, bx1-x0)] = True
        changed = float(((diff >= 42) & ~allowed).sum() / max(1, (~allowed).sum()))
        severity = 0.0 if changed <= 0.02 else 0.5 if changed <= 0.06 else 1.0
        return _result(spec, score=severity, confidence=0.78, evidence={**base, "protected_structure_changed_fraction": changed, "thresholds": {"clean_max": 0.02, "partial_max": 0.06}})
    if rule == "inputs_card_integrity":
        card = _ratio_box((0.01, 0.23, 0.19, 0.51), size)
        diff = _diff_metrics(input_path, pred_path, card)
        severity = 0.0 if diff["changed_48"] <= 0.02 else 0.5 if diff["changed_48"] <= 0.06 else 1.0
        return _result(spec, score=severity, confidence=0.82, evidence={**base, "inputs_card_diff": diff})
    if rule == "multi_region_background_preservation":
        # Fixed camera view: cup, pen, clipboard rim and exposed wood are all
        # outside the mutable checkbox interiors.  Global high-threshold change
        # is a conservative guard; any large edit becomes a penalty.
        diff = _diff_metrics(input_path, pred_path)
        severity = 0.0 if diff["changed_48"] <= 0.035 else 0.5 if diff["changed_48"] <= 0.08 else 1.0
        return _result(spec, score=severity, confidence=0.75, evidence={**base, "global_registered_background_diff": diff})
    return _unknown(spec, "unsupported_flowchart_rule", source_rule_type=rule)


def evaluate_structured_contract_check(
    *,
    case_id: str,
    spec: AtomicCheckSpec,
    input_path: Path,
    pred_path: Path,
    observations: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    """Evaluate one supported structured check or return fail-closed unknown."""

    if not input_path.is_file() or not pred_path.is_file():
        return _unknown(spec, "missing_structured_parser_image", input=str(input_path), pred=str(pred_path))
    normalized = str(case_id).lower()
    if "gauge_comfort_state" in normalized:
        return _gauge_result(spec, input_path, pred_path)
    if "watch_time_delta" in normalized:
        return _watch_result(spec, input_path, pred_path, observations or {})
    if "kanban_all_done" in normalized:
        return _kanban_result(spec, input_path, pred_path, observations or {})
    if "visual_pill_sorting" in normalized:
        return _visual_pill_result(spec, input_path, pred_path, observations or {})
    if "board_game_move_state" in normalized:
        return _board_game_result(spec, input_path, pred_path)
    if "parking_lot_reassignment" in normalized:
        return _parking_result(spec, input_path, pred_path)
    if "laundry_sorting_basket" in normalized:
        return _laundry_result(spec, input_path, pred_path, observations or {})
    if "medication_organizer" in normalized:
        return _medication_result(spec, input_path, pred_path, observations or {})
    if "lab_tube_final_state" in normalized:
        return _fluid_result(spec, input_path, pred_path, observations or {})
    if "flowchart_execution_final_sheet" in normalized:
        return _flowchart_result(spec, input_path, pred_path)
    return _unknown(spec, "structured_case_adapter_not_implemented", case_id=case_id, source_rule_type=_decision_type(spec))