File size: 75,246 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
"""Deterministic lowering from reviewed predicate IR to executable programs.

The natural-language layer may propose a candidate, but this module is the
only promotion path for the six reviewed contract families.  It preserves
every parameter and region, selects only registered materializers, and emits
synthetic witnesses proving that decision parameters are live.
"""

from __future__ import annotations

from copy import deepcopy
import re
from typing import Any, Mapping, Sequence

from pvr_eval.contracts.change_spec import compile_change_spec
from pvr_eval.contracts.contract_obligations import (
    build_binding_witnesses,
    compile_parameter_bindings,
)
from pvr_eval.contracts.fact_producer_registry import (
    objective_obligation_producer,
    objective_producer_for_binding,
)
from pvr_eval.contracts.metric_profiles import (
    ARCHITECTURE_QUALITATIVE_FAILURE_CERTIFICATE_VERSION,
    ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION,
    ARTICULATED_ENTITY_PRESERVATION_PROFILE,
    HUMAN_POSE_PROFILE,
    LOCAL_CORRESPONDENCE_PROFILE,
    REGISTERED_ARCHITECTURE_PRESERVATION_EXECUTOR_VERSION,
    REGISTERED_ARCHITECTURE_PRESERVATION_PROFILE,
    articulated_entity_preservation_profile_parameters,
    registered_architecture_preservation_profile_parameters,
    registered_grid_structure_profile_parameters,
    support_contact_geometry_profile_parameters,
)
from pvr_eval.contracts.predicate_ir_candidate import (
    FAMILY_OPERATION_TEMPLATES,
    RULE_FAMILY_TARGETS,
    compile_predicate_ir_candidate,
    validate_predicate_ir_candidate,
)


LOWERED_FAMILIES = frozenset(FAMILY_OPERATION_TEMPLATES)
COMPOSITE_FAMILY = "contract_family_all_of"
LOWERER_VERSION = "pvr.reviewed_contract_lowerer.v12"
ALLOWED_EDIT_QUERY_SCOPE_POLICY = "reviewed_exclusion_clause_subject_intersection_v1"
ROSTER_ALLOWED_EDIT_QUERY_SCOPE_POLICY = "question_support_roster_queries_v1"
VERIFIED_GROUP_ROSTER_PROFILE = "verified_group_roster_assignment_v1"

# A source rule name alone is not a type.  These signatures prevent an LLM or
# stale resolver from attaching unrelated parameters to a registered family
# and receiving an executable status merely because the name is recognized.
RULE_REQUIRED_PARAMETERS: dict[str, frozenset[str]] = {
    "multi_region_strict_preservation": frozenset({"maximum_changed_pixel_fraction", "minimum_region_ssim"}),
    "architecture_and_decor_preservation": frozenset({"registration_residual_tolerance_pixels", "minimum_edge_preservation"}),
    "masked_entity_structure_preservation": frozenset({"minimum_major_part_match_rate", "major_parts"}),
    "instance_and_background_preservation": frozenset({"required_original_bird_match_rate", "maximum_background_changed_fraction"}),
    "masked_object_pose_and_appearance_preservation": frozenset({"minimum_robot_mask_iou", "maximum_centroid_shift_fraction_of_image_diagonal"}),
    "masked_environment_structure_preservation": frozenset({"minimum_invariant_region_ssim", "maximum_unexplained_change_area_fraction"}),
    "matched_instance_integrity": frozenset({"appearance_similarity_warning_threshold", "mask_shape_change_warning_threshold"}),
    "protected_subject_invariance": frozenset({"centroid_shift_max", "bbox_scale_ratio"}),
    "registered_structure_preservation": frozenset({"maximum_normalized_boundary_displacement", "compare_drawer_state"}),
    "multi_instance_furniture_preservation": frozenset({"minimum_mask_iou_after_registration", "require_equal_chair_count"}),
    "registered_object_pose_preservation": frozenset({"registered_mask_iou_min", "expected_instance_count"}),
    "all_landmarks_preserved": frozenset({"registered_mask_iou_min", "require_one_to_one_instance_matching"}),
    "movable_inventory_integrity": frozenset({"expected_counts", "appearance_embedding_similarity_min"}),
    "all_instances_strict_preservation": frozenset({"minimum_mask_iou_after_registration", "expected_magazine_count"}),
    "strict_person_instance_preservation": frozenset({"minimum_mask_iou_after_registration", "minimum_appearance_similarity"}),
    "all_furniture_structures_preserved": frozenset({"minimum_boundary_iou", "minimum_unaffected_feature_match_ratio"}),
    "architectural_structure_preservation": frozenset({"minimum_door_mask_iou", "minimum_wall_feature_similarity"}),
    "multi_region_invariant_preservation": frozenset({"minimum_man_mask_iou", "minimum_board_feature_inlier_ratio"}),
    "structure_and_tray_preservation": frozenset({"minimum_structural_line_correspondence", "minimum_tray_shape_iou"}),
    "relocated_object_in_air_zone": frozenset({"minimum_air_zone_containment", "maximum_solid_mask_overlap_for_pass"}),
    "categorized_group_completeness": frozenset({"expected_counts", "minimum_group_members_for_clear_group"}),
    "dual_category_grouping": frozenset({"personal_care_expected", "medical_expected"}),
    "document_group_completeness": frozenset({"expected_counts", "use_title_or_color_identity"}),
    "remote_pair_on_table_surface": frozenset({"required_instances", "minimum_mask_containment"}),
    "paired_relocation_beside_dispenser": frozenset({"destination_reference", "require_cart_and_chair"}),
    "same_unit_different_compartment_placement": frozenset({"pass_min_containment", "pass_max_tray_overlap"}),
    "supported_nonintersecting_placement": frozenset({
        "pass_max_support_gap_ratio",
        "partial_max_support_gap_ratio",
        "pass_min_supported_bottom_fraction",
        "fail_below_supported_bottom_fraction",
        "pass_max_structural_overlap",
        "partial_max_structural_overlap",
    }),
    "open_shelf_state_preserved": frozenset({"reference_state", "minimum_visible_recess_fraction"}),
    "flat_tabletop_structure_preserved": frozenset({"forbidden_surface_features", "minimum_forbidden_feature_confidence"}),
    "upright_group_arrangement": frozenset({"upright_angle_tolerance_degrees", "pass_min_upright_fraction"}),
}


def _mapping(value: Any) -> dict[str, Any]:
    return deepcopy(dict(value)) if isinstance(value, Mapping) else {}


def _list(value: Any) -> list[Any]:
    return list(value) if isinstance(value, (list, tuple)) else []


def _dedupe(values: Sequence[Any]) -> list[str]:
    result: list[str] = []
    seen: set[str] = set()
    for item in values:
        value = str(item or "").strip()
        if value and value not in seen:
            seen.add(value)
            result.append(value)
    return result


def _configure_verified_group_roster(
    parameters: dict[str, Any], reasons: list[str],
) -> None:
    """Promote a complete reviewed roster to shared group matching runtime config."""

    annotations = [
        item for item in _list(parameters.get("source_instance_annotations"))
        if isinstance(item, Mapping)
    ]
    expected_raw = parameters.get("source_roster_expected_counts")
    if not annotations or not isinstance(expected_raw, Mapping):
        return
    observed: dict[str, int] = {}
    instance_ids: set[str] = set()
    labels: list[str] = []
    animal_terms = {
        "animal", "bird", "birds", "cat", "deer", "doe", "dog", "fawn",
        "fox", "raccoon", "squirrel", "wildlife",
    }
    animal_roster = True
    for index, annotation in enumerate(annotations):
        group = str(annotation.get("group_id") or "").strip()
        instance_id = str(annotation.get("instance_id") or "").strip()
        if not group:
            reasons.append(f"verified_source_roster_group_missing:{index}")
            continue
        if not instance_id or instance_id in instance_ids:
            reasons.append(f"verified_source_roster_instance_id_invalid:{index}")
        instance_ids.add(instance_id)
        observed[group] = observed.get(group, 0) + 1
        label = str(annotation.get("label") or group).strip()
        if label.endswith("s") and not label.endswith("ss"):
            label = label[:-1]
        if label and label not in labels:
            labels.append(label)
        animal_roster = animal_roster and bool(
            set(re.findall(r"[a-z]+", f"{group} {label}".casefold())) & animal_terms
        )
    try:
        expected = {str(group): int(count) for group, count in expected_raw.items()}
    except (TypeError, ValueError):
        reasons.append("verified_source_roster_expected_counts_invalid")
        return
    if expected != observed:
        reasons.append("verified_source_roster_expected_counts_mismatch")
        return
    if parameters.get("source_roster_complete") is not True:
        reasons.append("verified_source_roster_not_declared_complete")
        return
    if str(parameters.get("source_inventory_provenance") or "") not in {
        "contract_source_annotations", "manual_source_annotations", "certified_source_inventory",
    }:
        reasons.append("verified_source_roster_provenance_uncertified")
        return

    distractor = "other animal" if animal_roster else "other object"
    parameters.setdefault("source_annotation_mask_profile", "fastsam_bbox_prompt_or_color_component_v2")
    parameters.setdefault("matching_classification_labels", [*labels, distractor])
    parameters.setdefault("matching_use_segmenter_proposals", True)
    parameters.setdefault("matching_segmenter_min_area_fraction", 0.00003)
    parameters.setdefault("matching_segmenter_max_area_fraction", 0.08)
    parameters.setdefault("matching_segmenter_max_proposals", 160)
    parameters.setdefault("matching_classification_minimum_margin", 0.0)
    parameters.setdefault("matching_classification_minimum_probability", 0.25)
    parameters.setdefault("minimum_match_confidence", 0.55)
    parameters.setdefault(
        "required_matching_features",
        ["verified group label", "appearance embedding", "relative size", "mask shape"],
    )
    parameters.setdefault("verified_roster_profile", VERIFIED_GROUP_ROSTER_PROFILE)
    question_support = parameters.get("question_support_roster")
    question_support_purpose = (
        str(question_support.get("purpose") or "")
        if isinstance(question_support, Mapping)
        else ""
    )
    parameters.setdefault(
        "verified_roster_assignment_mode",
        (
            "question_support_allowed_edit_coverage_v1"
            if "allowed_edit" in question_support_purpose
            else "identity_exact"
        ),
    )
    parameters.setdefault("verified_roster_expected_counts", expected)
    parameters.setdefault("verified_roster_minimum_area_ratio", 0.10)
    parameters.setdefault("verified_roster_maximum_area_ratio", 6.0)


_QUERY_STOPWORDS = frozenset(
    {
        "all", "and", "central", "every", "input", "output", "the", "with",
    }
)
_QUERY_PREPOSITIONS = frozenset(
    {"at", "beside", "by", "from", "in", "inside", "near", "on", "onto", "under", "with"}
)
_QUERY_STATE_WORDS = frozenset({"lying", "perched", "relocated", "resting", "standing", "upright"})


def _query_token(value: str) -> str:
    token = value.lower()
    return token[:-1] if token.endswith("s") and len(token) > 3 else token


def _semantic_query_head(query: str) -> str:
    tokens = [
        token for token in re.findall(r"[a-z0-9]+", query.lower())
        if token not in _QUERY_STOPWORDS
    ]
    for index, token in enumerate(tokens):
        if token in _QUERY_PREPOSITIONS:
            tokens = tokens[:index]
            break
    while tokens and tokens[-1] in _QUERY_STATE_WORDS:
        tokens.pop()
    return _query_token(tokens[-1]) if tokens else ""


def _explicit_mask_heads(text: str) -> set[str]:
    """Return entity words explicitly used to construct an edit mask."""

    heads: set[str] = set()
    for match in re.finditer(
        r"([a-z0-9]+(?:[ -]+[a-z0-9]+){0,4})[ -]+masks?\b",
        text.lower(),
    ):
        tokens = [
            token for token in re.findall(r"[a-z0-9]+", match.group(1))
            if token not in _QUERY_STOPWORDS
            and token not in {
                "allowed", "destination", "edit", "input", "matched", "movable",
                "original", "output", "relocated", "source",
            }
        ]
        heads.update(_query_token(token) for token in tokens[-2:])
    if re.search(r"\b(?:its|their)\s+masks?\b", text.lower()):
        for match in re.finditer(
            r"\bsegment\s+(?:the\s+)?(.+?)(?=\s+(?:and|from|in|inside|near|on|perched|with)\b|[,;.])",
            text.lower(),
        ):
            action_tokens = [
                token for token in re.findall(r"[a-z0-9]+", match.group(1))
                if token not in _QUERY_STOPWORDS and token not in {"every"}
            ]
            if action_tokens:
                heads.add(_query_token(action_tokens[-1]))
    if "animal" in heads:
        heads.update({"wildlife", "bird"})
    if "wildlife" in heads:
        heads.add("animal")
    return heads


def _allowed_edit_queries(
    region: Mapping[str, Any],
    *,
    subjects: Sequence[str],
    related_regions: Sequence[Mapping[str, Any]],
) -> list[str]:
    """Select only subject queries explicitly named as edit exclusions.

    Reviewed checks often use one broad ``object_queries`` list for both the
    protected scene and the editable foreground.  Copying that whole list to
    an allowed-edit mask can hide real damage (for example by subtracting the
    forest ground and rocks).  The editable query set is therefore derived
    from the exclusion clauses themselves.  If no reviewed subject matches,
    the region remains unsupported instead of inventing a foreground class.
    """

    texts = [str(region.get("query_or_rule") or "")]
    for other in related_regions:
        if other is region:
            continue
        rule = str(other.get("query_or_rule") or "")
        if re.search(r"\b(exclud\w*|minus|subtract\w*)\b", rule.lower()):
            texts.append(rule.split(";", 1)[0])
    explicit_heads: set[str] = set()
    for text in texts:
        explicit_heads.update(_explicit_mask_heads(text))

    reviewed_support = _dedupe(_list(region.get("reviewed_support_queries")))
    candidates = reviewed_support or _dedupe(subjects)
    selected: list[str] = []
    for subject in candidates:
        # Only a noun explicitly attached to a reviewed mask is eligible.
        # Merely appearing as an anchor ("bird on robot shoulder") must not
        # make the robot itself editable.
        head = _semantic_query_head(subject)
        reviewed_tokens = {
            _query_token(token)
            for token in re.findall(r"[a-z0-9]+", subject.lower())
            if token not in _QUERY_STOPWORDS
        }
        if (
            head in explicit_heads
            or bool(reviewed_support and reviewed_tokens.intersection(explicit_heads))
        ):
            selected.append(subject)
    return selected


def _scope_allowed_edit_regions(
    regions: list[dict[str, Any]], subjects: Sequence[str], *, roster_queries: Sequence[str] = (),
) -> None:
    """Remove protected/context queries from detector-backed edit masks."""

    for region in regions:
        if str(region.get("semantic_role") or "") != "allowed_edit_exclusion":
            continue
        materializer = region.get("materializer")
        if not isinstance(materializer, dict):
            continue
        if str(materializer.get("kind") or "") != "detector_segmenter":
            continue
        if roster_queries:
            materializer["queries"] = _dedupe(roster_queries)
            materializer["query_scope_policy"] = ROSTER_ALLOWED_EDIT_QUERY_SCOPE_POLICY
        else:
            materializer["queries"] = _allowed_edit_queries(
                region, subjects=subjects, related_regions=regions,
            )
            materializer["query_scope_policy"] = ALLOWED_EDIT_QUERY_SCOPE_POLICY


def _exclusion_parameter_requested(parameters: Mapping[str, Any]) -> bool:
    """Return whether a reviewed config explicitly requires an exclusion."""

    # Occlusion can be a destination-relation fact (for example a chair
    # legitimately hidden behind a cart) without authorizing pixels to be
    # removed from a preservation comparison.  Only mask/exemption wording
    # that actually requests subtraction activates the exclusion gate.
    return any(
        (
            str(key).casefold().startswith("exclude_")
            or "exemption" in str(key).casefold()
            or "allowed_mask" in str(key).casefold()
            or "occlusion_mask" in str(key).casefold()
        )
        and value not in (False, None, "", [], {})
        for key, value in parameters.items()
    )


def _append_parameter_allowed_edit_region(
    regions: list[dict[str, Any]], parameters: Mapping[str, Any], reasons: list[str],
    *, require_complete: bool,
) -> None:
    """Lower an exclusion config only from explicit reviewed object queries.

    A boolean such as ``exclude_verified_new_furniture_occlusion`` says that
    an exclusion is required, but it does not identify the pixels.  The
    objective executor therefore requires a separate ``allowed_edit_queries``
    list and refuses to invent one from protected subjects or sibling
    evidence. Semantic-fallback-only rules remain fallback candidates.
    """

    if not _exclusion_parameter_requested(parameters):
        return
    if any(region.get("semantic_role") == "allowed_edit_exclusion" for region in regions):
        return
    queries = _dedupe(_list(parameters.get("allowed_edit_queries")))
    if not queries:
        if require_complete:
            reasons.append("exclusion_operation_missing_allowed_edit_region_or_queries")
        return
    mask_phrases = [f"{query} masks" for query in queries]
    regions.append(
        {
            "region_id": "contract_allowed_edit_exclusion",
            "semantic_role": "allowed_edit_exclusion",
            "image_roles": ["pred"],
            "source_image": "pred",
            "proposal_method": "sam_mask",
            "query_or_rule": (
                "Union " + " and ".join(mask_phrases)
                + " as the allowed output occlusion."
            ),
            "reviewed_support_queries": queries,
            "materializer": {
                "kind": "detector_segmenter",
                "queries": queries,
                "selection_policy": "reviewed_query_topk_then_sam",
                "cardinality": "contract_defined",
                "region_rule": (
                    "Union " + " and ".join(mask_phrases)
                    + " as the allowed output occlusion."
                ),
            },
            "geometry_policy": "mask_or_polygon_required",
            "provenance": "derived from reviewed allowed_edit_queries operation config",
        }
    )


def _configure_multi_region_protected_regions(
    regions: list[dict[str, Any]], source_rule_type: str,
) -> None:
    """Make every named invariant ROI measurable for strict multi-region rules."""

    if source_rule_type != "multi_region_strict_preservation":
        return
    for region in regions:
        if region.get("semantic_role") in {
            "allowed_edit_exclusion", "comparison_context_exclusion",
        }:
            continue
        region["semantic_role"] = "protected_region"
        region["image_roles"] = ["input", "pred"]
        region["source_image"] = "both"


def _configure_registered_architecture_regions(
    regions: list[dict[str, Any]], parameters: Mapping[str, Any], reasons: list[str],
) -> None:
    """Compile one architecture/decor contract into strict component masks."""

    component_queries = _dedupe(_list(parameters.get("architecture_component_queries")))
    decor_queries = _dedupe(_list(parameters.get("tidy_decor_queries")))
    allowed_queries = _dedupe(_list(parameters.get("allowed_edit_queries")))
    for key, values in (
        ("architecture_component_queries", component_queries),
        ("tidy_decor_queries", decor_queries),
        ("allowed_edit_queries", allowed_queries),
    ):
        if not values:
            reasons.append(f"registered_architecture_{key}_missing")

    configured_roles: set[str] = set()
    for region in regions:
        region_id = str(region.get("region_id") or "")
        semantic_role = str(region.get("semantic_role") or "")
        lowered_id = region_id.casefold()
        component_role = ""
        queries: list[str] = []
        if semantic_role == "allowed_edit_exclusion" or "allowed" in lowered_id:
            component_role, queries = "allowed_edit", allowed_queries
            region["semantic_role"] = "allowed_edit_exclusion"
        elif "decor" in lowered_id:
            component_role, queries = "tidy_decor", decor_queries
            region["semantic_role"] = "context_region"
        elif semantic_role == "protected_region" or any(
            token in lowered_id for token in ("architecture", "structure", "invariant")
        ):
            component_role, queries = "major_structure", component_queries
            region["semantic_role"] = "protected_region"
        if not component_role:
            continue
        configured_roles.add(component_role)
        region["image_roles"] = ["input", "pred"]
        region["source_image"] = "both"
        region["materializer"] = {
            "kind": "architecture_region_parser",
            "profile": REGISTERED_ARCHITECTURE_PRESERVATION_PROFILE,
            "component_role": component_role,
            "queries": queries,
            "strict_component_masks": True,
            "selection_policy": "one_reviewed_query_top1_then_strict_mask",
            "geometry_policy": "strict_mask_union_with_component_certificate",
            "region_rule": str(region.get("query_or_rule") or ""),
        }
        region["geometry_policy"] = "strict_mask_union_with_component_certificate"
    for role in ("major_structure", "tidy_decor", "allowed_edit"):
        if role not in configured_roles:
            reasons.append(f"registered_architecture_region_missing:{role}")


def _append_explicit_comparison_context_exclusion(
    regions: list[dict[str, Any]], *, subjects: Sequence[str], roster_queries: Sequence[str],
) -> None:
    """Materialize non-question foreground explicitly excluded by the contract.

    For background-preservation questions, a fixed foreground anchor such as a
    robot may be outside the question while still being named in the reviewed
    ``full frame minus ... mask`` rule.  It is a comparison-context exclusion,
    never an editable roster member.
    """

    heads: set[str] = set()
    for region in regions:
        if str(region.get("semantic_role") or "") != "protected_region":
            continue
        rule = str(region.get("query_or_rule") or "")
        if re.search(r"\b(exclud\w*|minus|subtract\w*)\b", rule.lower()):
            heads.update(_explicit_mask_heads(rule))
    roster_heads = {_semantic_query_head(query) for query in roster_queries}
    if "animal" in roster_heads or any(
        re.search(r"\b(?:animal|bird|deer|doe|fawn|fox|raccoon|squirrel|wildlife)\b", query.lower())
        for query in roster_queries
    ):
        roster_heads.update({"animal", "wildlife"})
    queries = [
        subject for subject in _dedupe(subjects)
        if _semantic_query_head(subject) in heads
        and _semantic_query_head(subject) not in roster_heads
    ]
    if not queries:
        return
    regions.append(
        {
            "region_id": "question_context_exclusion",
            "semantic_role": "comparison_context_exclusion",
            "image_roles": ["input", "pred"],
            "source_image": "both",
            "proposal_method": "derived_from_reviewed_exclusion_clause",
            "query_or_rule": "Exclude only explicitly named non-question foreground from background comparison.",
            "materializer": {
                "kind": "detector_segmenter",
                "queries": queries,
                "selection_policy": "reviewed_query_topk_then_sam",
                "cardinality": "contract_defined",
                "query_scope_policy": "reviewed_comparison_context_exclusion_v1",
            },
            "geometry_policy": "mask_or_polygon_required",
            "provenance": "derived from reviewed protected-region exclusion clause",
        }
    )


def reviewed_region_policy_reasons(predicate: Mapping[str, Any]) -> list[str]:
    """Validate lowering policies whose semantics are not covered by JSON shape.

    A previously compiled predicate can remain schema-valid after the lowerer is
    fixed.  In particular, old allowed-edit masks copied every object query and
    could subtract protected background from the preservation comparison.  The
    compilation gate calls this validator so such stale artifacts cannot enter
    a new run silently.
    """

    provenance = _mapping(predicate.get("provenance"))
    if provenance.get("compiler") != "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate":
        return []
    regions = [
        deepcopy(dict(item))
        for item in _list(predicate.get("regions"))
        if isinstance(item, Mapping)
    ]
    subjects = _dedupe(
        str(item.get("identity_query") or "")
        for item in _list(predicate.get("subjects"))
        if isinstance(item, Mapping)
    )
    parameters = _mapping(predicate.get("parameters"))
    roster_queries = _dedupe(
        str(item.get("query_text") or "")
        for item in _list(parameters.get("source_instance_annotations"))
        if isinstance(item, Mapping)
    )
    reasons: list[str] = []
    capabilities = predicate.get("capability_versions") if isinstance(predicate.get("capability_versions"), Mapping) else {}
    if capabilities.get("lowerer") != LOWERER_VERSION:
        reasons.append("stale_reviewed_lowerer_version")
    if (
        parameters.get("articulated_entity_preservation_profile")
        == ARTICULATED_ENTITY_PRESERVATION_PROFILE
        and parameters.get("articulated_entity_preservation_executor_version")
        != ARTICULATED_ENTITY_PRESERVATION_EXECUTOR_VERSION
    ):
        reasons.append("stale_articulated_entity_preservation_executor_version")
    if parameters.get("registered_architecture_profile") == REGISTERED_ARCHITECTURE_PRESERVATION_PROFILE:
        if parameters.get("registered_architecture_executor_version") != (
            REGISTERED_ARCHITECTURE_PRESERVATION_EXECUTOR_VERSION
        ):
            reasons.append("stale_registered_architecture_executor_version")
        expected_by_role = {
            "major_structure": _dedupe(_list(parameters.get("architecture_component_queries"))),
            "tidy_decor": _dedupe(_list(parameters.get("tidy_decor_queries"))),
            "allowed_edit": _dedupe(_list(parameters.get("allowed_edit_queries"))),
        }
        seen_roles: set[str] = set()
        for region in regions:
            materializer = _mapping(region.get("materializer"))
            component_role = str(materializer.get("component_role") or "")
            if component_role not in expected_by_role:
                continue
            seen_roles.add(component_role)
            if materializer.get("kind") != "architecture_region_parser":
                reasons.append(f"registered_architecture_materializer_mismatch:{component_role}")
            if materializer.get("strict_component_masks") is not True:
                reasons.append(f"registered_architecture_strict_mask_policy_missing:{component_role}")
            if _dedupe(_list(materializer.get("queries"))) != expected_by_role[component_role]:
                reasons.append(f"registered_architecture_query_scope_mismatch:{component_role}")
        for component_role, expected in expected_by_role.items():
            if not expected or component_role not in seen_roles:
                reasons.append(f"registered_architecture_component_role_missing:{component_role}")
        if any(
            str(region.get("semantic_role") or "") == "comparison_context_exclusion"
            for region in regions
        ):
            reasons.append("registered_architecture_decor_must_not_be_comparison_exclusion")
    if (
        objective_obligation_producer(
            str(predicate.get("family") or ""),
            str(predicate.get("source_rule_type") or ""),
        )
        and _exclusion_parameter_requested(parameters)
        and not any(
            str(region.get("semantic_role") or "") == "allowed_edit_exclusion"
            for region in regions
        )
    ):
        reasons.append("exclusion_operation_missing_allowed_edit_region")
    for region in regions:
        if str(region.get("semantic_role") or "") != "allowed_edit_exclusion":
            continue
        materializer = _mapping(region.get("materializer"))
        if str(materializer.get("kind") or "") != "detector_segmenter":
            continue
        region_id = str(region.get("region_id") or "missing")
        expected_policy = (
            ROSTER_ALLOWED_EDIT_QUERY_SCOPE_POLICY
            if roster_queries else ALLOWED_EDIT_QUERY_SCOPE_POLICY
        )
        if materializer.get("query_scope_policy") != expected_policy:
            reasons.append(f"stale_allowed_edit_query_scope_policy:{region_id}")
            continue
        expected = roster_queries or _allowed_edit_queries(
            region, subjects=subjects, related_regions=regions,
        )
        actual = _dedupe(_list(materializer.get("queries")))
        if actual != expected:
            reasons.append(f"allowed_edit_query_scope_mismatch:{region_id}")
    return reasons


def reviewed_source_check_projection(check: Mapping[str, Any]) -> dict[str, Any]:
    """Reconstruct the exact check hashed before compiler artifacts were embedded."""

    source = deepcopy(dict(check))
    source.pop("predicate_ir_candidate", None)
    source.pop("executable_predicate", None)
    params = _mapping(source.get("params"))
    params.pop("predicate_ir_candidate", None)
    params.pop("executable_predicate", None)
    params.pop("require_executable_predicate", None)
    source["params"] = params
    return source


def reviewed_source_check_sha256(check: Mapping[str, Any]) -> str:
    """Return the canonical hash used by reviewed predicate artifacts."""

    candidate = compile_predicate_ir_candidate(reviewed_source_check_projection(check))
    return str(candidate.get("source_check_sha256") or "")


def _roles(region: Mapping[str, Any]) -> list[str]:
    explicit = _list(region.get("image_roles"))
    if explicit:
        return _dedupe(explicit)
    source = str(region.get("source_image") or region.get("image_role") or "pred").lower()
    if source in {"both", "input_pred", "input/output"}:
        return ["input", "pred"]
    if source in {"output", "prediction", "pred"}:
        return ["pred"]
    return ["input"]


def _special_vlm_replacement(region_id: str) -> tuple[str, list[str], str]:
    """Replace the four reviewed VLM boxes with deterministic backends."""

    if region_id == "airborne_flock_zone":
        return "derived_free_space_zone", ["robot", "ground", "tree trunk", "tree branch"], "air_above_solid_exclusions"
    if region_id == "central_walkway":
        return "planar_free_space_parser", ["rug", "open floor", "sofa", "TV stand"], "floor_corridor_between_furniture"
    if region_id == "map_pinboard":
        return "detector_segmenter", ["wall pinboard", "map board with pinned notes"], "top1_then_segment"
    if region_id == "house_structure_mask":
        return "architecture_region_parser", ["house walls", "windows", "eaves", "building facade"], "fixed_architecture_union"
    return "", [], ""


def _materialize_region(
    raw: Mapping[str, Any],
    *,
    subjects: Sequence[str],
) -> tuple[dict[str, Any], list[str]]:
    region = deepcopy(dict(raw))
    region_id = str(region.get("region_id") or region.get("id") or "").strip()
    method = str(region.get("proposal_method") or "").strip()
    query_or_rule = str(region.get("query_or_rule") or "").strip()
    roles = _roles(region)
    reasons: list[str] = []
    queries: list[str] = []
    raw_materializer = (
        region.get("materializer")
        if isinstance(region.get("materializer"), Mapping)
        else {}
    )
    reviewed_support_queries = _dedupe(
        _list(
            region.get("object_queries")
            or region.get("queries")
            or region.get("reviewed_support_queries")
            or raw_materializer.get("queries")
        )
    )
    materializer: dict[str, Any]

    if method in {"grounding_dino_box", "dino_box"}:
        queries = reviewed_support_queries or _dedupe(subjects)
        materializer = {
            "kind": "detector_segmenter",
            "queries": queries,
            "selection_policy": "reviewed_query_topk_then_sam",
            "cardinality": "contract_defined",
        }
    elif method == "sam_mask":
        # SAM is never invoked from prose alone.  The reviewed subject queries
        # are its explicit detector seed; the region rule only filters/merges.
        queries = reviewed_support_queries or _dedupe(subjects)
        materializer = {
            "kind": "detector_segmenter",
            "queries": queries,
            "seed": "check_scoped_detector_boxes",
            "selection_policy": "detector_seed_then_rule_filtered_sam",
            "region_rule": query_or_rule,
        }
        if not queries:
            reasons.append(f"region_seed_queries_missing:{region_id}")
    elif method == "change_mask":
        materializer = {
            "kind": "registered_change_derivation",
            "registration": "robust_static_background_alignment",
            "operation": "union_subtract_clip",
            "region_rule": query_or_rule,
        }
    elif method == "ocr_layout":
        materializer = {
            "kind": "ocr_container_layout",
            "ocr_scope": "full_frame_then_nearest_container",
            "region_rule": query_or_rule,
        }
    elif method == "existing_zone":
        materializer = {
            "kind": "anchor_relative_zone",
            "queries": ["water dispenser"],
            "geometry_policy": "anchor_side_polygon_with_forbidden_subtraction",
            "region_rule": query_or_rule,
        }
    elif method == "grid_parser":
        materializer = {
            "kind": "shelf_grid_parser",
            "queries": reviewed_support_queries or ["shelving unit", "shelf compartment"],
            "geometry_policy": "registered_rectified_compartment_grid",
            "region_rule": query_or_rule,
        }
    elif method == "vlm_region_box":
        kind, queries, policy = _special_vlm_replacement(region_id)
        if not kind:
            reasons.append(f"zero_vlm_materializer_missing:{region_id}")
            materializer = {"kind": "unsupported"}
        else:
            materializer = {
                "kind": kind,
                "queries": queries,
                "geometry_policy": policy,
                "region_rule": query_or_rule,
            }
    else:
        reasons.append(f"unregistered_region_materializer:{region_id}:{method or 'missing'}")
        materializer = {"kind": "unsupported"}

    semantic_role = "context_region"
    lowered_id = region_id.lower()
    if any(token in lowered_id for token in ("allowed", "edit", "exemption")):
        semantic_role = "allowed_edit_exclusion"
    elif any(token in lowered_id for token in ("destination", "target_compartment", "storage", "airborne", "table_top")):
        semantic_role = "destination_region"
    elif any(token in lowered_id for token in ("invariant", "preservation", "structure", "surface")):
        semantic_role = "protected_region"

    lowered = {
        "region_id": region_id,
        "semantic_role": semantic_role,
        "image_roles": roles,
        "source_image": "both" if set(roles) == {"input", "pred"} else roles[0],
        "proposal_method": method,
        "query_or_rule": query_or_rule,
        "materializer": materializer,
        "geometry_policy": str(materializer.get("geometry_policy") or "mask_or_polygon_required"),
        "provenance": "reviewed planned_regions",
    }
    if reviewed_support_queries:
        lowered["reviewed_support_queries"] = reviewed_support_queries
    return lowered, reasons


def _configure_registered_grid_structure_regions(
    regions: list[dict[str, Any]], subjects: Sequence[str],
) -> None:
    """Route a reviewed shelf structure through the shared grid parser."""

    shelf_queries = [
        value for value in _dedupe(subjects)
        if "shel" in value.casefold() and "unit" in value.casefold()
    ]
    if not shelf_queries:
        shelf_queries = [
            value for value in _dedupe(subjects)
            if "shel" in value.casefold()
        ][:1]
    for region in regions:
        if str(region.get("region_id") or "") != "shelving_unit_structure":
            continue
        region["image_roles"] = ["input", "pred"]
        region["source_image"] = "both"
        region["materializer"] = {
            "kind": "shelf_grid_parser",
            "queries": shelf_queries or ["shelving unit"],
            "geometry_policy": "registered_rectified_compartment_grid",
            "region_rule": str(region.get("query_or_rule") or ""),
            "profile": "registered_grid_structure_preservation_v1",
        }
        region["geometry_policy"] = "registered_rectified_compartment_grid"


def _operation(
    operation_id: str,
    kind: str,
    tool_family: str,
    image_roles: Sequence[str],
    *,
    depends_on: Sequence[str] = (),
    produces: Sequence[str] = (),
) -> dict[str, Any]:
    return {
        "id": operation_id,
        "kind": kind,
        "tool_family": tool_family,
        "image_roles": list(image_roles),
        "depends_on": list(depends_on),
        "parameters": {},
        "produces": list(produces),
    }


def _operations(families: Sequence[str], parameters: Mapping[str, Any] | None = None) -> list[dict[str, Any]]:
    parameters = parameters or {}
    local_facts_requested = any(
        key in parameters
        for key in ("max_rotation_change_degrees", "maximum_rotation_change_degrees", "minimum_local_feature_match_ratio")
    ) and bool(parameters.get("local_correspondence_profile"))
    needs_fixed = "fixed_location_entity_preservation" in families
    articulated_profile = (
        str(parameters.get("articulated_entity_preservation_profile") or "")
        == ARTICULATED_ENTITY_PRESERVATION_PROFILE
    )
    needs_region = articulated_profile or any(family in families for family in (
        "registered_invariant_region_preservation", "destination_membership", "registered_structural_state",
    ))
    needs_match = any(family in families for family in (
        "fixed_location_entity_preservation", "relocated_entity_integrity", "destination_membership",
    )) or bool(parameters.get("source_instance_annotations")) or local_facts_requested
    needs_registration = needs_fixed or any(family in families for family in (
        "registered_invariant_region_preservation", "registered_structural_state",
    )) or local_facts_requested
    needs_change = articulated_profile or "registered_invariant_region_preservation" in families
    needs_state = any(family in families for family in (
        "destination_membership", "registered_structural_state", "group_pose_arrangement",
    ))
    needs_attribute = any(family in families for family in (
        "fixed_location_entity_preservation", "relocated_entity_integrity", "group_pose_arrangement",
    ))

    operations = [
        _operation("detect_input", "object_detection", "detector", ("input",), produces=("input_boxes",)),
        _operation("detect_pred", "object_detection", "detector", ("pred",), produces=("pred_boxes",)),
        _operation("segment_input", "mask_refinement", "segmenter", ("input",), depends_on=("detect_input",), produces=("input_masks",)),
        _operation("segment_pred", "mask_refinement", "segmenter", ("pred",), depends_on=("detect_pred",), produces=("pred_masks",)),
    ]
    terminal: list[str] = ["segment_input", "segment_pred"]
    if needs_match:
        operations.append(_operation(
            "match_instances", "instance_matching", "matcher", ("input", "pred"),
            depends_on=("segment_input", "segment_pred"), produces=("instance_matches",),
        ))
        terminal.append("match_instances")
    if needs_registration:
        operations.append(_operation(
            "register_frames", "image_registration", "registration", ("input", "pred"),
            produces=("registered_transform", "registration_quality"),
        ))
        terminal.append("register_frames")
    if needs_region:
        region_deps = ("register_frames",) if needs_registration else ()
        operations.append(_operation(
            "materialize_regions", "region_resolution", "typed_region_materializer", ("input", "pred"),
            depends_on=region_deps, produces=("typed_regions", "materializer_status"),
        ))
        operations.append(_operation(
            "refine_region_geometry", "spatial_geometry", "segmenter", ("input", "pred"),
            depends_on=("materialize_regions",), produces=("region_masks", "zone_geometry"),
        ))
        terminal.append("refine_region_geometry")
    if needs_change:
        deps = ["register_frames"]
        if needs_region:
            deps.append("refine_region_geometry")
        operations.append(_operation(
            "measure_registered_change", "change_analysis", "change_analyzer", ("input", "pred"),
            depends_on=deps, produces=("change_metrics", "structure_metrics"),
        ))
        terminal.append("measure_registered_change")
    if needs_state:
        deps = ["segment_pred"] + (["refine_region_geometry"] if needs_region else [])
        operations.append(_operation(
            "parse_visual_state", "state_parsing", "state_parser", ("input", "pred"),
            depends_on=deps, produces=("state_facts", "pose_facts", "layout_facts"),
        ))
        terminal.append("parse_visual_state")
    if "destination_membership" in families:
        operations.append(_operation(
            "count_destination_instances", "counting", "checker_internal", ("pred",),
            depends_on=("segment_pred",), produces=("count_facts",),
        ))
        terminal.append("count_destination_instances")
    if needs_attribute:
        operations.append(_operation(
            "measure_visual_attributes", "visual_attribute", "attribute_parser", ("input", "pred"),
            depends_on=("segment_input", "segment_pred"), produces=("attribute_facts", "appearance_facts"),
        ))
        terminal.append("measure_visual_attributes")
    if "maximum_normalized_keypoint_error" in parameters:
        operations.append(_operation(
            "measure_human_pose", "pose_estimation", "human_pose_parser", ("input", "pred"),
            depends_on=("detect_input", "detect_pred"), produces=("human_pose_keypoints",),
        ))
        terminal.append("measure_human_pose")
    if local_facts_requested:
        operations.append(_operation(
            "measure_local_correspondence", "local_correspondence", "local_correspondence", ("input", "pred"),
            depends_on=("match_instances", "register_frames"),
            produces=("rotation_change_degrees", "local_feature_match_ratio", "local_correspondence_certificate"),
        ))
        terminal.append("measure_local_correspondence")
    if parameters.get("source_selector_profile"):
        operations.append(_operation(
            "select_allowed_edit_source", "source_instance_selection",
            "source_instance_selector", ("input",),
            depends_on=("segment_input",), produces=("source_selector_certificate",),
        ))
        terminal.append("select_allowed_edit_source")
    operations.append(_operation(
        "decide", "predicate_decision", "contract_metric_binding", ("input", "pred"),
        depends_on=tuple(dict.fromkeys(terminal)), produces=("check_result",),
    ))
    return operations


def _subject_spec(
    index: int,
    aliases: Sequence[str],
    *,
    expected_count: int = 1,
    provenance: str = "reviewed object_queries",
    subject_id: str = "",
    component_queries: Sequence[str] = (),
    part_schema: Mapping[str, Any] | None = None,
) -> dict[str, Any]:
    clean_aliases = _dedupe(aliases)
    spec: dict[str, Any] = {
        "id": subject_id or f"subject_{index + 1}",
        "identity_query": clean_aliases[0],
        "input_queries": clean_aliases,
        "output_queries": clean_aliases,
        "aliases": clean_aliases,
        "expected_count": max(1, int(expected_count)),
        "cardinality_mode": "exact",
        "provenance": provenance,
    }
    clean_components = _dedupe(component_queries)
    if clean_components:
        spec["component_queries"] = clean_components
    if isinstance(part_schema, Mapping) and part_schema:
        spec["part_schema"] = deepcopy(dict(part_schema))
    return spec


def _explicit_physical_subject_specs(
    subjects: Sequence[str], parameters: Mapping[str, Any],
) -> tuple[list[dict[str, Any]], list[str]] | None:
    """Compile optional contract-authored query-to-physical-slot ownership.

    ``object_queries`` are detector prompts, not an entity roster.  A contract
    may therefore group several prompts as aliases of one physical subject or
    attach an exact cardinality to one aggregate prompt.  Every authored query
    must be owned exactly once; malformed or lossy groupings block lowering.
    """

    raw_groups = parameters.get("physical_subject_groups")
    if raw_groups is None:
        return None
    if not isinstance(raw_groups, (list, tuple)) or not raw_groups:
        return [], ["physical_subject_groups_missing_or_invalid"]
    source_values = _dedupe(subjects)
    source_set = set(source_values)
    consumed: list[str] = []
    specs: list[dict[str, Any]] = []
    reasons: list[str] = []
    for index, raw in enumerate(raw_groups):
        if not isinstance(raw, Mapping):
            reasons.append(f"physical_subject_group_not_object:{index}")
            continue
        aliases = _dedupe(
            _list(raw.get("aliases"))
            or [raw.get("identity_query")]
        )
        unknown = sorted(set(aliases) - source_set)
        if not aliases:
            reasons.append(f"physical_subject_group_aliases_missing:{index}")
            continue
        if unknown:
            reasons.append(
                f"physical_subject_group_unreviewed_alias:{index}:" + ",".join(unknown)
            )
        duplicates = sorted(set(aliases) & set(consumed))
        if duplicates:
            reasons.append(
                f"physical_subject_query_multiply_owned:{index}:" + ",".join(duplicates)
            )
        try:
            expected_count = int(raw.get("expected_count", 1))
        except (TypeError, ValueError):
            expected_count = 0
        if expected_count < 1:
            reasons.append(f"physical_subject_expected_count_invalid:{index}")
            expected_count = 1
        consumed.extend(aliases)
        specs.append(
            _subject_spec(
                index,
                aliases,
                expected_count=expected_count,
                subject_id=str(raw.get("id") or ""),
                component_queries=_list(raw.get("component_queries")),
                part_schema=_mapping(raw.get("part_schema")),
                provenance="reviewed decision_rule.parameters.physical_subject_groups",
            )
        )
    unowned = [value for value in source_values if value not in set(consumed)]
    if unowned:
        reasons.append("physical_subject_queries_unowned:" + ",".join(unowned))
    return specs, reasons


def _inventory_subject_specs(
    subjects: Sequence[str], parameters: Mapping[str, Any],
) -> tuple[list[dict[str, Any]], list[str]]:
    """Turn aggregate inventory prompts into exact physical cardinalities."""

    expected_raw = parameters.get("expected_counts")
    if not isinstance(expected_raw, Mapping):
        return [], ["inventory_expected_counts_missing"]
    expected = {
        str(key): int(value)
        for key, value in expected_raw.items()
        if str(key) != "total"
        and isinstance(value, (int, float)) and not isinstance(value, bool)
        and int(value) > 0
    }
    values = _dedupe(subjects)
    category_queries: dict[str, list[str]] = {key: [] for key in expected}
    unmatched: list[str] = []
    for query in values:
        query_tokens = set(re.findall(r"[a-z0-9]+", query.casefold().replace("_", " ")))
        ranked: list[tuple[int, str]] = []
        for category in expected:
            category_tokens = {
                _query_token(token)
                for token in re.findall(r"[a-z0-9]+", category.casefold().replace("_", " "))
            }
            overlap = len(category_tokens & {_query_token(token) for token in query_tokens})
            if overlap:
                ranked.append((overlap, category))
        if ranked:
            ranked.sort(key=lambda row: (-row[0], row[1]))
            category_queries[ranked[0][1]].append(query)
        else:
            unmatched.append(query)

    empty_categories = [key for key, queries in category_queries.items() if not queries]
    if unmatched and len(empty_categories) == 1:
        category_queries[empty_categories[0]] = unmatched
        unmatched = []

    specs: list[dict[str, Any]] = []
    reasons: list[str] = []
    for category, count in expected.items():
        queries = category_queries.get(category, [])
        if not queries:
            reasons.append(f"inventory_category_queries_missing:{category}")
            continue
        if len(queries) == count:
            for query in queries:
                specs.append(
                    _subject_spec(
                        len(specs), [query],
                        provenance=(
                            "reviewed object_queries + "
                            "decision_rule.parameters.expected_counts"
                        ),
                    )
                )
        elif len(queries) == 1:
            specs.append(
                _subject_spec(
                    len(specs), queries,
                    expected_count=count,
                    provenance=(
                        "reviewed aggregate object_query + "
                        "decision_rule.parameters.expected_counts"
                    ),
                )
            )
        else:
            reasons.append(f"inventory_category_cardinality_ambiguous:{category}")
    if unmatched:
        reasons.append("inventory_queries_unassigned:" + ",".join(unmatched))
    expected_total = expected_raw.get("total")
    physical_total = sum(int(item["expected_count"]) for item in specs)
    if isinstance(expected_total, (int, float)) and int(expected_total) != physical_total:
        reasons.append(
            f"inventory_total_mismatch:expected={int(expected_total)}:compiled={physical_total}"
        )
    return specs, reasons


def _subject_specs(
    subjects: Sequence[str], source_rule_type: str, parameters: Mapping[str, Any],
) -> tuple[list[dict[str, Any]], list[str], list[str], list[str]]:
    values = _dedupe(subjects)
    context: list[str] = []
    component_queries: list[str] = []
    reasons: list[str] = []

    explicit = _explicit_physical_subject_specs(values, parameters)
    if explicit is not None:
        specs, explicit_reasons = explicit
        return specs, context, component_queries, explicit_reasons

    if source_rule_type == "strict_person_instance_preservation":
        specs = [
            _subject_spec(
                0, values,
                provenance="singular reviewed person rule; object_queries are aliases",
            )
        ] if values else []
        return specs, context, component_queries, reasons

    if source_rule_type == "all_instances_strict_preservation":
        magazine_queries = [
            value for value in values
            if "magazine" in {
                _query_token(token)
                for token in re.findall(r"[a-z0-9]+", value.casefold())
            }
        ]
        other_queries = [value for value in values if value not in set(magazine_queries)]
        specs: list[dict[str, Any]] = []
        expected_parts = parameters.get("expected_magazine_count")
        if magazine_queries:
            part_schema = {
                "kind": "stack_members",
                "entity_type": "magazine",
                "expected_count": int(expected_parts),
                "count_provenance": "decision_rule.parameters.expected_magazine_count",
            } if isinstance(expected_parts, (int, float)) else {}
            specs.append(
                _subject_spec(
                    len(specs), magazine_queries,
                    component_queries=magazine_queries,
                    part_schema=part_schema,
                    provenance="reviewed magazine-stack aliases",
                )
            )
        specs.extend(
            _subject_spec(len(specs) + index, [value])
            for index, value in enumerate(other_queries)
        )
        return specs, context, component_queries, reasons

    if source_rule_type == "movable_inventory_integrity":
        specs, inventory_reasons = _inventory_subject_specs(values, parameters)
        return specs, context, component_queries, inventory_reasons

    groups: list[list[str]] = [[item] for item in values]
    if source_rule_type == "relocated_object_in_air_zone":
        groups, context = ([values[:2]] if values else []), values[2:]
    elif source_rule_type == "remote_pair_on_table_surface":
        groups, context = [[item] for item in values[:2]], values[2:]
    elif source_rule_type == "paired_relocation_beside_dispenser":
        groups, context = [[item] for item in values[:2]], values[2:]
    elif source_rule_type == "same_unit_different_compartment_placement":
        groups, context = ([values[:1]] if values else []), values[1:]
    elif source_rule_type == "supported_nonintersecting_placement":
        groups, context = ([values[:1]] if values else []), values[1:]
    elif source_rule_type == "structure_and_tray_preservation":
        # These queries name components of one registered structural system,
        # not four independent physical instances.
        groups = [values] if values else []
    elif source_rule_type == "architecture_and_decor_preservation":
        component_queries = _dedupe(_list(parameters.get("architecture_component_queries")))
        decor_queries = _dedupe(_list(parameters.get("tidy_decor_queries")))
        aliases = component_queries + decor_queries
        specs = [
            _subject_spec(
                0,
                aliases,
                component_queries=aliases,
                part_schema={
                    "kind": "registered_architecture_and_decor_component_roster_v1",
                    "major_structure_queries": component_queries,
                    "tidy_decor_queries": decor_queries,
                    "count_provenance": "reviewed decision_rule.parameters component query rosters",
                },
                provenance="reviewed registered architecture/decor component system",
            )
        ] if aliases else []
        return specs, context, aliases, reasons
    elif source_rule_type == "upright_group_arrangement":
        # The first query names the aggregate group whose ownership/location
        # must be certified.  Remaining queries describe components to parse
        # *inside* that group; treating them as additional physical subjects
        # incorrectly made one binder row plus one binder spine the expected
        # roster and allowed unrelated shelf proposals into the pose metric.
        groups = [values[:1]] if values else []
        component_queries = values[1:]
    elif source_rule_type == "masked_entity_structure_preservation":
        # Detector prompts for head/torso/limbs describe components of one
        # articulated entity.  They are not five independent roster slots.
        root = min(values, key=lambda value: (len(value.split()), len(value))) if values else ""
        components = [value for value in values if value != root]
        required_parts = _dedupe(parameters.get("major_parts") or [])
        specs = [
            _subject_spec(
                0,
                [root],
                component_queries=components,
                part_schema={
                    "kind": "normalized_humanoid_six_part_support_v1",
                    "required_parts": required_parts,
                    "component_queries": components,
                    "count_provenance": "decision_rule.parameters.major_parts",
                },
                provenance="reviewed articulated root query + component schema",
            )
        ] if root else []
        return specs, context, components, reasons
    specs = [
        _subject_spec(index, aliases)
        for index, aliases in enumerate(groups) if aliases
    ]
    return specs, context, component_queries, reasons


def lower_reviewed_predicate(check: Mapping[str, Any]) -> dict[str, Any] | None:
    """Lower one of the 29 reviewed source rules, or return ``None``."""

    params = _mapping(check.get("params"))
    decision_rule = _mapping(params.get("decision_rule"))
    source_rule_type = str(decision_rule.get("type") or "").strip()
    if source_rule_type not in RULE_FAMILY_TARGETS:
        return None

    candidate_value = check.get("predicate_ir_candidate") or params.get("predicate_ir_candidate")
    candidate_source = reviewed_source_check_projection(check)
    candidate = _mapping(candidate_value) or compile_predicate_ir_candidate(candidate_source)
    candidate_validation = validate_predicate_ir_candidate(
        candidate,
        source_check=candidate_source,
    )
    # A generated candidate is cacheable only for the exact authored check.
    # Regenerate it deterministically after criteria, thresholds, regions, or
    # subject queries change; never let a schema-valid stale candidate force
    # the new check into an old predicate program.
    if "source_check_hash_mismatch" in candidate_validation.reasons:
        candidate = compile_predicate_ir_candidate(candidate_source)
        candidate_validation = validate_predicate_ir_candidate(
            candidate,
            source_check=candidate_source,
        )
    expected_families = list(RULE_FAMILY_TARGETS[source_rule_type])
    if [str(item) for item in candidate.get("target_families", [])] != expected_families:
        candidate = compile_predicate_ir_candidate(candidate_source)
        candidate_validation = validate_predicate_ir_candidate(
            candidate,
            source_check=candidate_source,
        )
    # Candidate IR is a cache, never authority.  A rule that gains a reviewed
    # deterministic lowering must not remain manual merely because an older
    # candidate recorded it as unmapped.
    if not candidate_validation.valid:
        regenerated = compile_predicate_ir_candidate(candidate_source)
        regenerated_validation = validate_predicate_ir_candidate(
            regenerated,
            source_check=candidate_source,
        )
        if regenerated_validation.valid:
            candidate = regenerated
            candidate_validation = regenerated_validation
    check_id = str(check.get("id") or check.get("check_id") or "").strip()
    families = [str(item) for item in candidate.get("target_families", [])]
    subjects = _dedupe(params.get("object_queries") or candidate.get("subjects") or [])
    reasons: list[str] = []
    if not candidate_validation.valid:
        reasons.extend("candidate_invalid:" + item for item in candidate_validation.reasons)
    if not families or any(family not in LOWERED_FAMILIES for family in families):
        reasons.append("candidate_family_not_lowerable")
    family = families[0] if len(families) == 1 else COMPOSITE_FAMILY

    regions: list[dict[str, Any]] = []
    for raw in _list(params.get("planned_regions")):
        if not isinstance(raw, Mapping):
            continue
        region, region_reasons = _materialize_region(raw, subjects=subjects)
        if (
            source_rule_type == "supported_nonintersecting_placement"
            and str((region.get("materializer") or {}).get("kind") or "")
            == "shelf_grid_parser"
        ):
            # Support is certified against an input/output registered grid,
            # even when the authored region names only the output cell.
            region["image_roles"] = ["input", "pred"]
            region["source_image"] = "both"
        regions.append(region)
        reasons.extend(region_reasons)
    source_parameters = _mapping(decision_rule.get("parameters"))
    runtime_parameters = deepcopy(source_parameters)
    if source_rule_type == "supported_nonintersecting_placement":
        runtime_parameters.update(support_contact_geometry_profile_parameters())
    if source_rule_type == "structure_and_tray_preservation":
        runtime_parameters.update(registered_grid_structure_profile_parameters())
        _configure_registered_grid_structure_regions(regions, subjects)
    if source_rule_type == "architecture_and_decor_preservation":
        runtime_parameters.update(registered_architecture_preservation_profile_parameters())
        _configure_registered_architecture_regions(regions, runtime_parameters, reasons)
    _configure_verified_group_roster(runtime_parameters, reasons)
    if source_rule_type == "masked_entity_structure_preservation":
        runtime_parameters.update(articulated_entity_preservation_profile_parameters())
        root_query = min(subjects, key=lambda value: (len(value.split()), len(value)))
        protected = next(
            (region for region in regions if region.get("semantic_role") == "protected_region"),
            None,
        )
        if isinstance(protected, dict):
            protected["image_roles"] = ["input", "pred"]
            protected["source_image"] = "both"
            protected["materializer"] = {
                "kind": "detector_segmenter",
                "queries": [root_query],
                "seed": "check_scoped_detector_boxes",
                "selection_policy": "top1_whole_entity_then_sam",
                "region_rule": str(protected.get("query_or_rule") or ""),
            }
        allowed = next(
            (region for region in regions if region.get("semantic_role") == "allowed_edit_exclusion"),
            None,
        )
        support_queries = _dedupe((allowed or {}).get("reviewed_support_queries") or [])
        selector_identity = _semantic_query_head(support_queries[0]) if support_queries else ""
        selector_text = " ".join(
            [str((allowed or {}).get("query_or_rule") or ""), *support_queries]
        ).casefold()
        anchor_part = (
            "viewer_right_shoulder" if "viewer" in selector_text and "right" in selector_text
            else "viewer_left_shoulder" if "viewer" in selector_text and "left" in selector_text
            else ""
        )
        if isinstance(allowed, dict) and selector_identity and anchor_part:
            allowed["image_roles"] = ["input"]
            allowed["source_image"] = "input"
            allowed["materializer"] = {
                "kind": "registered_change_derivation",
                "operation": "source_selector_registered_projection",
                "projection_policy": "source_mask_to_registered_comparison_v1",
                "source_selector_profile": "anchor_relative_source_instance_v1",
                "region_rule": str(allowed.get("query_or_rule") or ""),
            }
            runtime_parameters["source_selector_profile"] = "anchor_relative_source_instance_v1"
            runtime_parameters["source_selector"] = {
                "profile": "anchor_relative_source_instance_v1",
                "identity_queries": [selector_identity],
                "anchor_queries": [root_query],
                "anchor_part": anchor_part,
                "relation": "contact_or_near",
                "expected_count": 1,
                "minimum_identity_score": 0.05,
                "minimum_anchor_score": 0.10,
                "minimum_selection_margin": 0.12,
                "purpose": "allowed_edit_exclusion",
            }
        else:
            reasons.append("articulated_allowed_edit_source_selector_not_derivable")
    _configure_multi_region_protected_regions(regions, source_rule_type)
    _append_parameter_allowed_edit_region(
        regions,
        source_parameters,
        reasons,
        require_complete=bool(
            objective_obligation_producer(family, source_rule_type)
        ),
    )
    roster_queries = _dedupe(
        str(item.get("query_text") or "")
        for item in _list(source_parameters.get("source_instance_annotations"))
        if isinstance(item, Mapping)
    )
    _scope_allowed_edit_regions(regions, subjects, roster_queries=roster_queries)
    if source_rule_type != "architecture_and_decor_preservation":
        _append_explicit_comparison_context_exclusion(
            regions, subjects=subjects, roster_queries=roster_queries,
        )
    for region in regions:
        materializer = region.get("materializer")
        if (
            str(region.get("semantic_role") or "") == "allowed_edit_exclusion"
            and isinstance(materializer, Mapping)
            and str(materializer.get("kind") or "") == "detector_segmenter"
            and not materializer.get("queries")
        ):
            reasons.append(
                "allowed_edit_subject_queries_missing:"
                + str(region.get("region_id") or "missing")
            )

    required_parameters = RULE_REQUIRED_PARAMETERS.get(source_rule_type, frozenset())
    missing_required_parameters = sorted(required_parameters - set(source_parameters))
    if missing_required_parameters:
        reasons.append("source_rule_parameter_schema_mismatch:" + ",".join(missing_required_parameters))
    if "maximum_normalized_keypoint_error" in source_parameters:
        pose_profile = str(source_parameters.get("pose_profile") or "")
        if pose_profile != HUMAN_POSE_PROFILE:
            reasons.append("normalized_keypoint_error_requires_registered_pose_profile")
    local_facts_requested = any(
        key in source_parameters
        for key in ("max_rotation_change_degrees", "maximum_rotation_change_degrees", "minimum_local_feature_match_ratio")
    )
    local_profile = str(source_parameters.get("local_correspondence_profile") or "")
    if local_facts_requested and local_profile and local_profile != LOCAL_CORRESPONDENCE_PROFILE:
        reasons.append("local_correspondence_profile_unsupported")
    bindings = compile_parameter_bindings(source_parameters)
    for binding in bindings:
        if binding.get("consumer") == "decision_clause":
            objective_producer = objective_producer_for_binding(family, binding, runtime_parameters)
            if objective_producer:
                binding["producer"] = objective_producer
                binding["producer_mode"] = "objective"
            else:
                binding["producer"] = "reviewed_semantic_vlm"
                binding["producer_mode"] = "semantic_vlm"
                binding["source_text"] = (
                    "No registered deterministic runtime producer for reviewed parameter "
                    + str(binding.get("source_key") or binding.get("fact") or "")
                )
    if source_rule_type == "architecture_and_decor_preservation":
        fail_text = str(decision_rule.get("fail_condition") or "").casefold()
        broad_decor_failure = bool(
            "decor" in fail_text
            and any(token in fail_text for token in ("broad", "large-scale", "majority"))
        )
        if broad_decor_failure:
            bindings.append(
                {
                    "source_key": "derived:fail_condition:broad_tidy_decor_removal",
                    "consumer": "decision_clause",
                    "clause_id": "derived:architecture_broad_tidy_decor_removal",
                    "branch": "fail",
                    "fact": "tidy_decor_unmatched_fraction",
                    "op": "ge",
                    "expected": float(
                        runtime_parameters[
                            "architecture_broad_decor_removal_minimum_fraction"
                        ]
                    ),
                    "producer": "reviewed_typed_evidence_adapter",
                    "producer_mode": "objective",
                    "source_text": str(decision_rule.get("fail_condition") or ""),
                    "certificate_version": (
                        ARCHITECTURE_QUALITATIVE_FAILURE_CERTIFICATE_VERSION
                    ),
                    "threshold_provenance": (
                        "shared lexical certificate: broad removal means a strict "
                        "majority of the reviewed registered decor mask"
                    ),
                }
            )
    obligation_producer = objective_obligation_producer(family, source_rule_type)
    for obligation in _list(candidate.get("obligations")):
        if not isinstance(obligation, Mapping):
            continue
        branch = str(obligation.get("branch") or "pass")
        bindings.append(
            {
                "source_key": str(obligation.get("id") or ""),
                "consumer": "decision_clause",
                "clause_id": "obligation:" + str(obligation.get("id") or ""),
                "branch": branch,
                "fact": "obligation:" + str(obligation.get("id") or ""),
                "op": "eq",
                "expected": True,
                "source_text": str(obligation.get("source_text") or ""),
                # Free-form pass/fail prose is semantic by default.  Promotion
                # is allowed only through the runtime-aligned registry above,
                # after a rule-specific executor proves the exact branch from
                # complete objective measurements.
                "producer": obligation_producer or "reviewed_semantic_vlm",
                "producer_mode": "objective" if obligation_producer else "semantic_vlm",
            }
        )
    witnesses = build_binding_witnesses(bindings)
    if not witnesses or any(not bool(item.get("passed")) for item in witnesses):
        reasons.append("parameter_witness_failure")
    if not check_id:
        reasons.append("missing_check_id")
    if not subjects:
        reasons.append("missing_subject_queries")

    subject_specs, context_queries, component_queries, subject_reasons = _subject_specs(
        subjects, source_rule_type, runtime_parameters,
    )
    reasons.extend(subject_reasons)
    decision_bindings = [
        item for item in bindings if item.get("consumer") == "decision_clause"
    ]
    semantic_fact_requirements = [
        {
            "fact": str(item.get("fact") or ""),
            "clause_id": str(item.get("clause_id") or ""),
            "branch": str(item.get("branch") or "pass"),
            "source_text": str(item.get("source_text") or ""),
            "producer": str(item.get("producer") or ""),
        }
        for item in decision_bindings
        if item.get("producer_mode") == "semantic_vlm"
    ]
    predicate = {
        "schema_version": "pvr.executable_predicate.v1",
        "check_id": check_id,
        "status": "executable" if not reasons else "blocked_uncompiled",
        "family": family,
        "target_families": families,
        "source_rule_type": source_rule_type,
        "source_check_sha256": candidate.get("source_check_sha256"),
        "subjects": subject_specs,
        "context_queries": context_queries,
        "component_queries": component_queries,
        "regions": regions,
        "operations": _operations(families, runtime_parameters),
        "state_schema": {
            "unit": "typed_contract_obligation",
            "states": ["pass", "partial", "fail", "unknown"],
            "facts": sorted({str(item.get("fact")) for item in bindings if item.get("consumer") == "decision_clause"}),
        },
        "decision": {
            "aggregation": "ALL_OF" if len(families) > 1 else "SINGLE_FAMILY",
            "allowed_outcomes": ["pass", "partial", "fail", "unknown"],
            "unknown_policy": "missing_or_ambiguous_required_fact_is_unknown",
        },
        "parameters": deepcopy(runtime_parameters),
        "parameter_bindings": bindings,
        "fact_producers": [
            {
                "fact": str(item.get("fact") or ""),
                "clause_id": str(item.get("clause_id") or ""),
                "producer": str(item.get("producer") or ""),
                "mode": str(item.get("producer_mode") or ""),
            }
            for item in decision_bindings
        ],
        "semantic_fact_requirements": semantic_fact_requirements,
        "parameter_provenance": {
            str(item.get("source_key")): "reviewed decision_rule.parameters"
            for item in bindings if not str(item.get("source_key") or "").startswith(check_id + ":")
        } | {
            key: "derived:registered_support_contact_geometry_profile"
            for key in set(runtime_parameters) - set(source_parameters)
            if source_rule_type == "supported_nonintersecting_placement"
        } | {
            key: "derived:registered_grid_structure_preservation_profile"
            for key in set(runtime_parameters) - set(source_parameters)
            if source_rule_type == "structure_and_tray_preservation"
        } | {
            key: "derived:registered_architecture_preservation_profile"
            for key in set(runtime_parameters) - set(source_parameters)
            if source_rule_type == "architecture_and_decor_preservation"
        },
        "obligations": deepcopy(_list(candidate.get("obligations"))),
        "coverage_map": {
            "parameter_keys": list(source_parameters),
            "region_ids": [str(item.get("region_id") or "") for item in regions],
            "obligation_ids": [str(item.get("id") or "") for item in _list(candidate.get("obligations")) if isinstance(item, Mapping)],
        },
        "witness_results": witnesses,
        "capability_versions": {
            "lowerer": LOWERER_VERSION,
            "decision_evaluator": "pvr.contract_obligations.v1",
            "metric_binding": "pvr.contract_metric.v7",
            "fact_producer_registry": "pvr.runtime_fact_producers.v1",
            "semantic_fallback": "pvr.reviewed_semantic_vlm.v1",
        },
        "unmapped_contract_parameters": [],
        "reasons": list(dict.fromkeys(reasons)),
        "provenance": {
            "compiler": "pvr_eval.contracts.predicate_lowering.lower_reviewed_predicate",
            "candidate_schema": candidate.get("schema_version"),
            "conversion": "reviewed_golden_ir_then_deterministic_lowering",
        },
    }
    change_spec = compile_change_spec(predicate)
    if change_spec:
        predicate["change_spec"] = change_spec
        predicate["capability_versions"]["visual_change_spec"] = "pvr.visual_change_spec.v1"
    return predicate