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
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
"""Objective input/output instance matching for PVR tool evidence.

The matcher is deliberately model-agnostic.  Executors may provide CLIP crop
embeddings, while unit tests and CPU-only runs can omit them.  Detector label,
colour and shape evidence remain separately visible in every assignment so a
reviewer can tell why two instances were paired.
"""

from __future__ import annotations

from dataclasses import dataclass, field
import re
from typing import Any, Iterable, Mapping, Sequence

import numpy as np

from pvr_eval.agent.detector_fusion import semantic_class


MATCH_SCHEMA_VERSION = "pvr.instance_matches.v1"


@dataclass(frozen=True)
class MatchConfig:
    minimum_confidence: float = 0.55
    ambiguity_margin: float = 0.04
    semantic_weight: float = 0.30
    clip_weight: float = 0.40
    foreground_clip_weight: float = 0.20
    colour_weight: float = 0.20
    shape_weight: float = 0.10
    mask_shape_weight: float = 0.0
    spatial_weight: float = 0.0
    verified_roster_profile: str = ""
    verified_roster_assignment_mode: str = "identity_exact"
    verified_roster_expected_counts: Mapping[str, int] = field(default_factory=dict)
    verified_roster_minimum_area_ratio: float = 0.10
    verified_roster_maximum_area_ratio: float = 6.0
    identity_agnostic_target_coverage_profile: str = ""
    target_coverage_minimum_probability: float = 0.50
    target_coverage_minimum_margin: float = 0.15
    target_coverage_minimum_animal_probability: float = 0.75
    target_coverage_minimum_animal_margin: float = 0.50
    target_coverage_maximum_protected_overlap: float = 0.10
    target_coverage_neighborhood_fraction_of_diagonal: float = 0.08


VERIFIED_GROUP_ROSTER_PROFILE = "verified_group_roster_assignment_v1"
QUESTION_SUPPORT_COVERAGE_MODE = "question_support_allowed_edit_coverage_v1"
PROTECTED_SUBJECT_ROSTER_PROFILE = "protected_subject_roster_clearance_v1"
IDENTITY_AGNOSTIC_TARGET_COVERAGE_PROFILE = "identity_agnostic_target_animal_coverage_v1"


def _tokens(value: Any) -> set[str]:
    stop = {"a", "an", "the", "and", "or", "of", "on", "in", "at", "to", "with", "object", "item"}
    return {
        token
        for token in re.findall(r"[a-z0-9]+", str(value or "").lower().replace("grey", "gray"))
        if token not in stop
    }


def _normalise_group(value: Any) -> str:
    tokens = sorted(_tokens(str(value or "").replace("_", " ")))
    normalised = " ".join(tokens)
    if normalised.endswith("s") and not normalised.endswith("ss"):
        normalised = normalised[:-1]
    return normalised


def _verified_group(item: Mapping[str, Any], *, source: bool) -> str:
    values = (
        (item.get("group_id"), item.get("matching_class"), item.get("semantic_class"), item.get("label"))
        if source
        else (item.get("verified_roster_group"), item.get("predicted_class"), item.get("semantic_class"))
    )
    for value in values:
        group = _normalise_group(value)
        if group and group != "unknown":
            return group
    return ""


def _geometry_area(item: Mapping[str, Any]) -> float | None:
    mask = item.get("binary_mask")
    if isinstance(mask, np.ndarray) and mask.size:
        area = float(np.count_nonzero(mask))
        if area > 0:
            return area
    box = _bbox(item)
    if box is None:
        return None
    area = max(0.0, box[2] - box[0]) * max(0.0, box[3] - box[1])
    return area if area > 0 else None


def semantic_similarity(left: Mapping[str, Any], right: Mapping[str, Any]) -> float:
    """Conservative class compatibility in ``[0, 0.75]``.

    Identical query strings are detector requests, not independent proof that
    either crop belongs to that category.  The component is deliberately
    capped below one and matching is gated by the coarse semantic class.
    """

    left_class = str(left.get("semantic_class") or semantic_class(left))
    right_class = str(right.get("semantic_class") or semantic_class(right))
    if left_class != right_class:
        return 0.0

    left_tokens = _tokens(f"{left.get('label', '')} {left.get('query_text', '')}")
    right_tokens = _tokens(f"{right.get('label', '')} {right.get('query_text', '')}")
    if not left_tokens or not right_tokens:
        return 0.0
    overlap = len(left_tokens & right_tokens)
    union = len(left_tokens | right_tokens)
    if left_tokens <= right_tokens or right_tokens <= left_tokens:
        return 0.75
    return min(0.75, overlap / union) if overlap else 0.0


def cosine_similarity(left: np.ndarray | None, right: np.ndarray | None) -> float | None:
    if left is None or right is None or left.size == 0 or right.size == 0 or left.shape != right.shape:
        return None
    denominator = float(np.linalg.norm(left) * np.linalg.norm(right))
    if denominator <= 1e-12:
        return None
    # CLIP cosine may be negative.  Map it to a bounded confidence component.
    return float(np.clip((float(np.dot(left, right)) / denominator + 1.0) / 2.0, 0.0, 1.0))


def histogram_similarity(left: np.ndarray | None, right: np.ndarray | None) -> float | None:
    if left is None or right is None or left.size == 0 or right.size == 0 or left.shape != right.shape:
        return None
    left = np.asarray(left, dtype=np.float64)
    right = np.asarray(right, dtype=np.float64)
    left_sum, right_sum = float(left.sum()), float(right.sum())
    if left_sum <= 0 or right_sum <= 0:
        return None
    left, right = left / left_sum, right / right_sum
    return float(np.clip(np.minimum(left, right).sum(), 0.0, 1.0))


def _bbox(item: Mapping[str, Any]) -> list[float] | None:
    value = item.get("bbox") or item.get("bbox_xyxy")
    if isinstance(value, str):
        try:
            value = [float(part) for part in value.split(",")]
        except ValueError:
            return None
    if not isinstance(value, (list, tuple)) or len(value) != 4:
        return None
    try:
        return [float(part) for part in value]
    except (TypeError, ValueError):
        return None


def shape_similarity(left: Mapping[str, Any], right: Mapping[str, Any]) -> float | None:
    a, b = _bbox(left), _bbox(right)
    if a is None or b is None:
        return None
    aw, ah = max(1.0, a[2] - a[0]), max(1.0, a[3] - a[1])
    bw, bh = max(1.0, b[2] - b[0]), max(1.0, b[3] - b[1])
    aspect = min(aw / ah, bw / bh) / max(aw / ah, bw / bh)
    area = min(aw * ah, bw * bh) / max(aw * ah, bw * bh)
    return float(np.clip(0.65 * aspect + 0.35 * np.sqrt(area), 0.0, 1.0))


def mask_shape_similarity(left: Mapping[str, Any], right: Mapping[str, Any]) -> float | None:
    """Compare translation-invariant coarse mask shape statistics.

    Source and output instances may legitimately move, so raw image-coordinate
    mask IoU is not an identity feature.  Area ratio and bbox fill ratio retain
    useful silhouette evidence without rewarding the old location.
    """

    left_mask, right_mask = left.get("binary_mask"), right.get("binary_mask")
    left_box, right_box = _bbox(left), _bbox(right)
    if (
        not isinstance(left_mask, np.ndarray)
        or not isinstance(right_mask, np.ndarray)
        or left_mask.size == 0
        or right_mask.size == 0
        or left_box is None
        or right_box is None
    ):
        return None
    left_area, right_area = float(np.count_nonzero(left_mask)), float(np.count_nonzero(right_mask))
    if left_area <= 0 or right_area <= 0:
        return None
    left_box_area = max(1.0, (left_box[2] - left_box[0]) * (left_box[3] - left_box[1]))
    right_box_area = max(1.0, (right_box[2] - right_box[0]) * (right_box[3] - right_box[1]))
    area_score = min(left_area, right_area) / max(left_area, right_area)
    left_fill, right_fill = left_area / left_box_area, right_area / right_box_area
    fill_score = min(left_fill, right_fill) / max(left_fill, right_fill)
    return float(np.clip(0.60 * np.sqrt(area_score) + 0.40 * fill_score, 0.0, 1.0))


def spatial_similarity(left: Mapping[str, Any], right: Mapping[str, Any]) -> float | None:
    """Same-location similarity for checks that declare spatial invariance."""

    a, b = _bbox(left), _bbox(right)
    if a is None or b is None:
        return None
    ix0, iy0 = max(a[0], b[0]), max(a[1], b[1])
    ix1, iy1 = min(a[2], b[2]), min(a[3], b[3])
    intersection = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
    area_a = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
    area_b = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
    union = area_a + area_b - intersection
    iou = 0.0 if union <= 0 else intersection / union
    center_a = ((a[0] + a[2]) / 2.0, (a[1] + a[3]) / 2.0)
    center_b = ((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0)
    distance = float(np.hypot(center_a[0] - center_b[0], center_a[1] - center_b[1]))
    diagonal_a = float(np.hypot(a[2] - a[0], a[3] - a[1]))
    diagonal_b = float(np.hypot(b[2] - b[0], b[3] - b[1]))
    scale = max(1.0, (diagonal_a + diagonal_b) / 2.0)
    center_score = max(0.0, 1.0 - distance / (2.0 * scale))
    return float(np.clip(0.70 * iou + 0.30 * center_score, 0.0, 1.0))


def source_output_mask_iou(left: Mapping[str, Any], right: Mapping[str, Any]) -> float | None:
    left_mask, right_mask = left.get("binary_mask"), right.get("binary_mask")
    if not isinstance(left_mask, np.ndarray) or not isinstance(right_mask, np.ndarray):
        return None
    if left_mask.shape != right_mask.shape or left_mask.size == 0:
        return None
    intersection = int(np.logical_and(left_mask, right_mask).sum())
    union = int(np.logical_or(left_mask, right_mask).sum())
    return None if union <= 0 else intersection / union


def source_zone_output_overlap_ratio(left: Mapping[str, Any], right: Mapping[str, Any]) -> float | None:
    """Fraction of the output mask that remains in the input source mask."""

    left_mask, right_mask = left.get("binary_mask"), right.get("binary_mask")
    if not isinstance(left_mask, np.ndarray) or not isinstance(right_mask, np.ndarray):
        return None
    if left_mask.shape != right_mask.shape or left_mask.size == 0:
        return None
    output_area = int(np.count_nonzero(right_mask))
    if output_area <= 0:
        return None
    intersection = int(np.logical_and(left_mask, right_mask).sum())
    return intersection / output_area


def pair_similarity(
    left: Mapping[str, Any],
    right: Mapping[str, Any],
    *,
    config: MatchConfig,
) -> dict[str, Any]:
    components: dict[str, float | None] = {
        "semantic": semantic_similarity(left, right),
        "clip": cosine_similarity(left.get("clip_embedding"), right.get("clip_embedding")),
        "foreground_clip": cosine_similarity(
            left.get("foreground_clip_embedding"), right.get("foreground_clip_embedding")
        ),
        "colour": histogram_similarity(left.get("colour_histogram"), right.get("colour_histogram")),
        "shape": shape_similarity(left, right),
        "mask_shape": mask_shape_similarity(left, right),
        "spatial": spatial_similarity(left, right) if config.spatial_weight > 0 else None,
    }
    left_class = str(left.get("semantic_class") or semantic_class(left))
    right_class = str(right.get("semantic_class") or semantic_class(right))
    category_compatible = bool(left_class and right_class and left_class == right_class)
    weights = {
        "semantic": config.semantic_weight,
        "clip": config.clip_weight,
        "foreground_clip": config.foreground_clip_weight,
        "colour": config.colour_weight,
        "shape": config.shape_weight,
        "mask_shape": config.mask_shape_weight,
        "spatial": config.spatial_weight,
    }
    available = [(name, value) for name, value in components.items() if value is not None]
    denominator = sum(weights[name] for name, _ in available)
    score = 0.0 if denominator <= 0 else sum(weights[name] * float(value) for name, value in available) / denominator
    # A zero semantic overlap is a strong incompatibility signal.  Appearance
    # alone must not pair unrelated detector categories.
    if not category_compatible:
        score = 0.0
    return {
        "score": float(np.clip(score, 0.0, 1.0)),
        "category_compatible": category_compatible,
        "semantic_class": left_class if category_compatible else f"{left_class}!={right_class}",
        "components": {key: (None if value is None else round(float(value), 6)) for key, value in components.items()},
        "source_output_mask_iou": (
            None
            if (mask_iou := source_output_mask_iou(left, right)) is None
            else round(float(mask_iou), 6)
        ),
        "source_zone_output_overlap_ratio": (
            None
            if (source_overlap := source_zone_output_overlap_ratio(left, right)) is None
            else round(float(source_overlap), 6)
        ),
        "effective_weights": {name: weights[name] for name, _ in available},
    }


def _linear_assignment(scores: np.ndarray) -> list[tuple[int, int]]:
    if scores.size == 0:
        return []
    try:
        from scipy.optimize import linear_sum_assignment

        rows, columns = linear_sum_assignment(-scores)
        return list(zip(rows.tolist(), columns.tolist()))
    except Exception:
        # Deterministic fallback for minimal environments.  The production
        # server has SciPy, but tests should not depend on it.
        remaining_rows = set(range(scores.shape[0]))
        remaining_columns = set(range(scores.shape[1]))
        result: list[tuple[int, int]] = []
        while remaining_rows and remaining_columns:
            row, column = max(
                ((r, c) for r in remaining_rows for c in remaining_columns),
                key=lambda pair: (scores[pair], -pair[0], -pair[1]),
            )
            result.append((row, column))
            remaining_rows.remove(row)
            remaining_columns.remove(column)
        return result


def _public_instance(item: Mapping[str, Any], index: int) -> dict[str, Any]:
    public = {
        "instance_id": str(item.get("instance_id") or f"instance_{index:03d}"),
        "label": str(item.get("label") or ""),
        "query_text": str(item.get("query_text") or ""),
        "query_aliases": [str(value) for value in item.get("query_aliases", []) if str(value or "").strip()],
        "bbox_xyxy": _bbox(item),
        "detector_score": float(item.get("score") or 0.0),
        "detector_backend": str(item.get("detector_backend") or item.get("backend") or ""),
        "supporting_backends": str(item.get("supporting_backends") or ""),
        "semantic_class": str(item.get("semantic_class") or semantic_class(item)),
        "arbitration": str(item.get("arbitration") or ""),
        "mask_backend": str(item.get("mask_backend") or ""),
    }
    for key in (
        "group_id", "matching_class", "verified_roster_group", "predicted_class",
        "evidence_role", "proposal_source",
    ):
        if str(item.get(key) or "").strip():
            public[key] = str(item[key])
    encoded_mask = item.get("encoded_mask")
    if isinstance(encoded_mask, Mapping) and encoded_mask:
        public["encoded_mask"] = dict(encoded_mask)
    polygon = item.get("polygon")
    if isinstance(polygon, (list, tuple)) and polygon:
        public["polygon"] = list(polygon)
    target_coverage = item.get("target_coverage_evidence")
    if isinstance(target_coverage, Mapping) and target_coverage:
        public["target_coverage_evidence"] = dict(target_coverage)
    return public


def _same_physical_subject(left: Mapping[str, Any], right: Mapping[str, Any]) -> bool:
    """Conservatively identify two masks as proposals for one physical subject."""

    left_mask, right_mask = left.get("binary_mask"), right.get("binary_mask")
    if (
        isinstance(left_mask, np.ndarray)
        and isinstance(right_mask, np.ndarray)
        and left_mask.shape == right_mask.shape
        and left_mask.size
    ):
        intersection = int(np.logical_and(left_mask, right_mask).sum())
        smaller = min(int(left_mask.sum()), int(right_mask.sum()))
        return bool(smaller > 0 and intersection / smaller >= 0.70)
    left_box, right_box = _bbox(left), _bbox(right)
    if left_box is None or right_box is None:
        return False
    ix0, iy0 = max(left_box[0], right_box[0]), max(left_box[1], right_box[1])
    ix1, iy1 = min(left_box[2], right_box[2]), min(left_box[3], right_box[3])
    intersection = max(0.0, ix1 - ix0) * max(0.0, iy1 - iy0)
    left_area = max(0.0, left_box[2] - left_box[0]) * max(0.0, left_box[3] - left_box[1])
    right_area = max(0.0, right_box[2] - right_box[0]) * max(0.0, right_box[3] - right_box[1])
    union = left_area + right_area - intersection
    return bool(union > 0 and intersection / union >= 0.50)


def _physical_subject_components(items: Sequence[Mapping[str, Any]]) -> list[list[int]]:
    adjacency = {index: set() for index in range(len(items))}
    for left in range(len(items)):
        for right in range(left + 1, len(items)):
            if _same_physical_subject(items[left], items[right]):
                adjacency[left].add(right)
                adjacency[right].add(left)
    components: list[list[int]] = []
    remaining = set(adjacency)
    while remaining:
        stack = [remaining.pop()]
        component: list[int] = []
        while stack:
            index = stack.pop()
            component.append(index)
            for neighbor in adjacency[index]:
                if neighbor in remaining:
                    remaining.remove(neighbor)
                    stack.append(neighbor)
        components.append(sorted(component))
    return sorted(components, key=lambda value: (value[0] if value else -1))


def _bbox_edge_gap(left: Mapping[str, Any], right: Mapping[str, Any]) -> float | None:
    left_box, right_box = _bbox(left), _bbox(right)
    if left_box is None or right_box is None:
        return None
    dx = max(left_box[0] - right_box[2], right_box[0] - left_box[2], 0.0)
    dy = max(left_box[1] - right_box[3], right_box[1] - left_box[3], 0.0)
    return float(np.hypot(dx, dy))


def _mask_overlap_fraction(
    item: Mapping[str, Any], others: Sequence[Mapping[str, Any]],
) -> float | None:
    mask = item.get("binary_mask")
    if not isinstance(mask, np.ndarray) or mask.size == 0 or not mask.any():
        return None
    area = int(mask.sum())
    overlaps: list[float] = []
    for other in others:
        other_mask = other.get("binary_mask")
        if (
            isinstance(other_mask, np.ndarray)
            and other_mask.shape == mask.shape
            and other_mask.size
            and other_mask.any()
        ):
            overlaps.append(int(np.logical_and(mask, other_mask).sum()) / max(1, area))
    return max(overlaps, default=0.0)


def _dominant_target_neighbourhood(
    outputs: Sequence[Mapping[str, Any]],
    columns: Sequence[int],
    *,
    fraction_of_diagonal: float,
) -> dict[str, Any]:
    """Return a unique dominant seed component for coverage-only proposals.

    The seeds are already species-certified target masks.  Their dominant
    spatial component only scopes additional identity-agnostic proposals; it
    never creates an animal identity or replaces the original target masks.
    """

    distinct_columns: list[int] = []
    for component in _physical_subject_components([outputs[index] for index in columns]):
        candidates = [columns[index] for index in component]
        distinct_columns.append(max(candidates, key=lambda index: float(outputs[index].get("score") or 0.0)))
    masks = [outputs[index].get("binary_mask") for index in distinct_columns]
    shapes = {
        tuple(int(value) for value in mask.shape[:2])
        for mask in masks
        if isinstance(mask, np.ndarray) and mask.ndim >= 2 and mask.size
    }
    if len(shapes) != 1 or not distinct_columns:
        return {
            "status": "insufficient",
            "reason": "unique_image_shape_and_seed_targets_required",
            "seed_columns": distinct_columns,
        }
    height, width = next(iter(shapes))
    diagonal = float(np.hypot(width, height))
    threshold = max(1.0, float(fraction_of_diagonal) * diagonal)
    adjacency = {index: set() for index in range(len(distinct_columns))}
    for left in range(len(distinct_columns)):
        for right in range(left + 1, len(distinct_columns)):
            gap = _bbox_edge_gap(outputs[distinct_columns[left]], outputs[distinct_columns[right]])
            if gap is not None and gap <= threshold:
                adjacency[left].add(right)
                adjacency[right].add(left)
    components: list[list[int]] = []
    remaining = set(adjacency)
    while remaining:
        stack = [remaining.pop()]
        component: list[int] = []
        while stack:
            index = stack.pop()
            component.append(index)
            for neighbor in adjacency[index]:
                if neighbor in remaining:
                    remaining.remove(neighbor)
                    stack.append(neighbor)
        components.append(sorted(component))
    components.sort(key=lambda value: (-len(value), value[0]))
    if not components or (len(components) > 1 and len(components[0]) == len(components[1])):
        return {
            "status": "insufficient",
            "reason": "dominant_seed_component_ambiguous",
            "seed_columns": distinct_columns,
            "component_sizes": [len(value) for value in components],
            "neighbourhood_edge_gap_pixels": threshold,
        }
    dominant = [distinct_columns[index] for index in components[0]]
    return {
        "status": "ok",
        "reason": "",
        "seed_columns": distinct_columns,
        "dominant_seed_columns": dominant,
        "component_sizes": [len(value) for value in components],
        "neighbourhood_edge_gap_pixels": threshold,
        "image_shape": [height, width],
    }


def certify_protected_subject_roster(
    instances: Sequence[Mapping[str, Any]],
    expected_queries: Sequence[str],
) -> dict[str, Any]:
    """Certify one real, unique output mask for every protected subject.

    Detector and segmenter adapters may emit several overlapping proposals for
    one body.  Those proposals are one physical-subject component, not several
    subjects.  Two disjoint candidates for the same query remain ambiguous and
    fail closed.  A selected mask also cannot be reused for two query slots.
    """

    queries = [str(value).strip() for value in expected_queries if str(value).strip()]
    candidates = [
        item for item in instances
        if isinstance(item.get("binary_mask"), np.ndarray)
        and item["binary_mask"].size
        and bool(item["binary_mask"].any())
    ]
    assignments: list[dict[str, Any]] = []
    missing: list[str] = []
    ambiguous: list[dict[str, Any]] = []
    selected_instances: list[Mapping[str, Any]] = []
    for query in queries:
        query_group = _normalise_group(query)
        query_candidates = [
            item for item in candidates
            if _normalise_group(
                item.get("predicted_class")
                or item.get("verified_roster_group")
                or item.get("semantic_class")
                or item.get("label")
            ) == query_group
        ]
        components = _physical_subject_components(query_candidates)
        if not query_candidates:
            missing.append(query)
            continue
        if len(components) != 1:
            ambiguous.append({
                "query": query,
                "candidate_count": len(query_candidates),
                "physical_subject_component_count": len(components),
                "candidates": [
                    _public_instance(item, index)
                    for index, item in enumerate(query_candidates)
                ],
            })
            continue
        component_items = [query_candidates[index] for index in components[0]]
        selected = max(
            component_items,
            key=lambda item: (
                _geometry_area(item) or 0.0,
                float(item.get("score") or item.get("detector_score") or 0.0),
            ),
        )
        selected_instances.append(selected)
        assignments.append({
            "query": query,
            "candidate_count": len(query_candidates),
            "physical_subject_component_count": 1,
            "selected": _public_instance(selected, len(assignments)),
            "selection_policy": "largest_real_mask_within_one_physical_subject_component",
        })

    cross_query_duplicates: list[dict[str, str]] = []
    for left in range(len(selected_instances)):
        for right in range(left + 1, len(selected_instances)):
            if _same_physical_subject(selected_instances[left], selected_instances[right]):
                cross_query_duplicates.append({
                    "left_query": assignments[left]["query"],
                    "right_query": assignments[right]["query"],
                })
    complete = bool(queries) and not missing and not ambiguous and not cross_query_duplicates
    certificate = {
        "profile": PROTECTED_SUBJECT_ROSTER_PROFILE,
        "status": "ok" if complete else "insufficient",
        "complete": complete,
        "ambiguity_free": not ambiguous and not cross_query_duplicates,
        "identity_assignment_asserted": True,
        "expected_queries": queries,
        "assignment_count": len(assignments),
        "assignments": assignments,
        "missing_queries": missing,
        "ambiguous_queries": ambiguous,
        "cross_query_duplicate_subjects": cross_query_duplicates,
        "mask_requirement": "nonempty_real_instance_mask",
    }
    return {
        "status": certificate["status"],
        "reason": "" if complete else "protected_subject_roster_incomplete_or_ambiguous",
        "selected_instances": selected_instances if complete else [],
        "certificate": certificate,
    }


def certify_protected_subject_transition(
    source_instances: Sequence[Mapping[str, Any]],
    output_instances: Sequence[Mapping[str, Any]],
    expected_queries: Sequence[str],
    *,
    minimum_confidence: float = 0.45,
) -> dict[str, Any]:
    """Verify contract-prompted protected masks across input and output.

    The reviewed annotations provide identity and a stable prompt window, but
    never geometry: both sides must still materialize nonempty real masks.
    Appearance, colour, shape, and mask-shape agreement then verify that the
    output prompt did not silently segment background or another subject.
    """

    queries = [str(value).strip() for value in expected_queries if str(value).strip()]
    source_by_group: dict[str, list[Mapping[str, Any]]] = {}
    output_by_group: dict[str, list[Mapping[str, Any]]] = {}
    for item in source_instances:
        source_by_group.setdefault(_verified_group(item, source=True), []).append(item)
    for item in output_instances:
        output_by_group.setdefault(_verified_group(item, source=True), []).append(item)
    assignments: list[dict[str, Any]] = []
    selected: list[dict[str, Any]] = []
    missing: list[dict[str, Any]] = []
    config = MatchConfig(
        minimum_confidence=minimum_confidence,
        ambiguity_margin=0.0,
        semantic_weight=0.25,
        clip_weight=0.35,
        foreground_clip_weight=0.0,
        colour_weight=0.15,
        shape_weight=0.10,
        mask_shape_weight=0.15,
        spatial_weight=0.0,
    )
    for query in queries:
        group = _normalise_group(query)
        source_candidates = source_by_group.get(group, [])
        output_candidates = output_by_group.get(group, [])
        if len(source_candidates) != 1 or len(output_candidates) != 1:
            missing.append({
                "query": query,
                "source_candidate_count": len(source_candidates),
                "output_candidate_count": len(output_candidates),
                "reason": "exactly_one_prompted_real_mask_required_per_side",
            })
            continue
        source, output = source_candidates[0], output_candidates[0]
        evidence = pair_similarity(source, output, config=config)
        confidence = float(evidence["score"])
        if confidence < minimum_confidence:
            missing.append({
                "query": query,
                "source_candidate_count": 1,
                "output_candidate_count": 1,
                "confidence": round(confidence, 6),
                "reason": "protected_source_output_identity_below_minimum_confidence",
            })
            continue
        output_copy = dict(output)
        output_copy["label"] = query
        output_copy["query_text"] = query
        output_copy["semantic_class"] = query
        output_copy["predicted_class"] = query
        output_copy["verified_roster_group"] = query
        selected.append(output_copy)
        assignments.append({
            "query": query,
            "confidence": round(confidence, 6),
            "source": _public_instance(source, len(assignments)),
            "output": _public_instance(output_copy, len(assignments)),
            "components": evidence["components"],
            "source_output_mask_iou": evidence["source_output_mask_iou"],
            "selection_policy": "reviewed_prompt_real_mask_cross_image_identity_v1",
        })
    cross_query_duplicates: list[dict[str, str]] = []
    for left in range(len(selected)):
        for right in range(left + 1, len(selected)):
            if _same_physical_subject(selected[left], selected[right]):
                cross_query_duplicates.append({
                    "left_query": assignments[left]["query"],
                    "right_query": assignments[right]["query"],
                })
    complete = bool(queries) and not missing and not cross_query_duplicates
    certificate = {
        "profile": PROTECTED_SUBJECT_ROSTER_PROFILE,
        "status": "ok" if complete else "insufficient",
        "complete": complete,
        "ambiguity_free": not cross_query_duplicates,
        "identity_assignment_asserted": True,
        "expected_queries": queries,
        "assignment_count": len(assignments),
        "assignments": assignments,
        "missing_or_rejected_queries": missing,
        "missing_queries": [item["query"] for item in missing],
        "ambiguous_queries": [],
        "cross_query_duplicate_subjects": cross_query_duplicates,
        "mask_requirement": "nonempty_real_mask_on_input_and_output",
        "minimum_identity_confidence": minimum_confidence,
        "annotation_scope": "identity_and_prompt_window_not_geometry",
    }
    return {
        "status": certificate["status"],
        "reason": "" if complete else "protected_subject_transition_incomplete",
        "selected_instances": selected if complete else [],
        "certificate": certificate,
    }


def _match_verified_group_roster(
    inputs: list[Mapping[str, Any]],
    outputs: list[Mapping[str, Any]],
    *,
    config: MatchConfig,
    protected_instances: Sequence[Mapping[str, Any]] = (),
) -> dict[str, Any]:
    """Certify a reviewed source roster as output groups, not fake slot identities.

    Some questions need the union of all instances in a verified group (for
    example all birds as allowed-edit masks), while the identity of two
    same-colour members inside that group is immaterial.  This profile still
    requires mutually exclusive output group labels, plausible real mask
    areas, exact group cardinality, and a one-to-one assignment.  Ambiguity at
    the *group boundary* fails closed; swaps inside an already-certified group
    do not.
    """

    inferred: dict[str, list[int]] = {}
    for row, item in enumerate(inputs):
        group = _verified_group(item, source=True)
        inferred.setdefault(group, []).append(row)
    inferred_counts = {group: len(rows) for group, rows in inferred.items() if group}
    configured_counts = {
        _normalise_group(group): int(count)
        for group, count in config.verified_roster_expected_counts.items()
        if _normalise_group(group) and int(count) > 0
    }
    expected_counts = configured_counts or inferred_counts
    certificate_reasons: list[str] = []
    if "" in inferred:
        certificate_reasons.append("source_group_missing")
    if configured_counts and configured_counts != inferred_counts:
        certificate_reasons.append("configured_source_group_counts_mismatch")

    source_area_medians: dict[str, float] = {}
    pooled_source_areas: list[float] = []
    for group, rows in inferred.items():
        areas = [area for row in rows if (area := _geometry_area(inputs[row])) is not None]
        if areas:
            source_area_medians[group] = float(np.median(np.asarray(areas, dtype=np.float64)))
            pooled_source_areas.extend(areas)
    pooled_source_area_median = (
        float(np.median(np.asarray(pooled_source_areas, dtype=np.float64)))
        if pooled_source_areas
        else None
    )

    output_groups = [_verified_group(item, source=False) for item in outputs]
    plausible_by_group: dict[str, list[int]] = {group: [] for group in expected_counts}
    rejected_candidates: list[dict[str, Any]] = []
    identity_agnostic_candidates: list[int] = []
    identity_agnostic_audit: list[dict[str, Any]] = []
    output_area_ratios: dict[int, float | None] = {}
    for column, (item, group) in enumerate(zip(outputs, output_groups)):
        public = _public_instance(item, column)
        target_coverage = item.get("target_coverage_evidence")
        identity_agnostic = bool(
            group not in expected_counts
            and
            config.identity_agnostic_target_coverage_profile
            == IDENTITY_AGNOSTIC_TARGET_COVERAGE_PROFILE
            and isinstance(target_coverage, Mapping)
            and target_coverage.get("profile")
            == IDENTITY_AGNOSTIC_TARGET_COVERAGE_PROFILE
            and target_coverage.get("binary_status") == "candidate"
        )
        if identity_agnostic:
            output_area = _geometry_area(item)
            real_mask = item.get("binary_mask")
            has_real_mask = bool(
                isinstance(real_mask, np.ndarray)
                and real_mask.size
                and real_mask.any()
                and str(item.get("mask_backend") or "")
                and "fallback" not in str(item.get("mask_backend") or "").lower()
                and str(item.get("mask_backend") or "").lower() != "bbox"
            )
            ratio = (
                None
                if pooled_source_area_median is None or output_area is None
                else output_area / max(pooled_source_area_median, 1e-12)
            )
            output_area_ratios[column] = ratio
            target_probability = float(target_coverage.get("target_probability") or 0.0)
            target_margin = float(target_coverage.get("target_margin") or 0.0)
            animal_probability = float(target_coverage.get("animal_probability") or 0.0)
            animal_margin = float(target_coverage.get("animal_margin") or 0.0)
            protected_overlap = _mask_overlap_fraction(item, protected_instances)
            reasons: list[str] = []
            if not has_real_mask:
                reasons.append("real_non_bbox_mask_required")
            if ratio is None or not (
                config.verified_roster_minimum_area_ratio
                <= ratio
                <= config.verified_roster_maximum_area_ratio
            ):
                reasons.append("pooled_source_area_plausibility_out_of_range")
            target_gate = bool(
                target_probability >= config.target_coverage_minimum_probability
                and target_margin >= config.target_coverage_minimum_margin
            )
            animal_gate = bool(
                animal_probability >= config.target_coverage_minimum_animal_probability
                and animal_margin >= config.target_coverage_minimum_animal_margin
            )
            if not (target_gate or animal_gate):
                reasons.append("target_or_animal_binary_evidence_below_minimum")
            if protected_overlap is None:
                reasons.append("protected_overlap_mask_evidence_missing")
            elif protected_overlap > config.target_coverage_maximum_protected_overlap:
                reasons.append("protected_subject_overlap_exceeds_maximum")
            audit = {
                "output_index": column,
                "output": public,
                "binary_status": "candidate",
                "target_probability": round(target_probability, 6),
                "target_margin": round(target_margin, 6),
                "animal_probability": round(animal_probability, 6),
                "animal_margin": round(animal_margin, 6),
                "binary_acceptance_basis": (
                    "target_vs_distractor" if target_gate else "animal_vs_background"
                    if animal_gate else "none"
                ),
                "area_ratio_to_pooled_source_median": (
                    None if ratio is None else round(float(ratio), 6)
                ),
                "protected_subject_overlap_fraction": (
                    None if protected_overlap is None else round(float(protected_overlap), 6)
                ),
                "pre_neighbourhood_reasons": reasons,
            }
            identity_agnostic_audit.append(audit)
            if not reasons:
                identity_agnostic_candidates.append(column)
            else:
                rejected_candidates.append({
                    "output": public,
                    "group_id": "target_animal_identity_agnostic",
                    "rejection_reason": reasons[0],
                    "rejection_reasons": reasons,
                })
            continue
        if group not in expected_counts:
            rejected_candidates.append({
                "output": public,
                "group_id": group,
                "rejection_reason": "group_label_not_in_verified_roster",
            })
            continue
        source_median = source_area_medians.get(group)
        output_area = _geometry_area(item)
        ratio = (
            None
            if source_median is None or output_area is None or source_median <= 0
            else output_area / source_median
        )
        output_area_ratios[column] = ratio
        if ratio is None:
            rejected_candidates.append({
                "output": public,
                "group_id": group,
                "rejection_reason": "real_mask_or_bbox_area_missing",
            })
            continue
        if not (
            config.verified_roster_minimum_area_ratio
            <= ratio
            <= config.verified_roster_maximum_area_ratio
        ):
            rejected_candidates.append({
                "output": public,
                "group_id": group,
                "area_ratio_to_source_group_median": round(float(ratio), 6),
                "rejection_reason": "group_size_plausibility_out_of_range",
            })
            continue
        plausible_by_group[group].append(column)

    if config.verified_roster_assignment_mode == QUESTION_SUPPORT_COVERAGE_MODE:
        source_roster_complete = not certificate_reasons and inferred_counts == expected_counts
        base_provisional_output = sorted({
            column for columns in plausible_by_group.values() for column in columns
        })
        neighbourhood = _dominant_target_neighbourhood(
            outputs,
            base_provisional_output,
            fraction_of_diagonal=config.target_coverage_neighborhood_fraction_of_diagonal,
        )
        promoted_identity_agnostic: list[int] = []
        dominant_columns = list(neighbourhood.get("dominant_seed_columns", []))
        neighbourhood_threshold = float(
            neighbourhood.get("neighbourhood_edge_gap_pixels") or 0.0
        )
        audit_by_column = {
            int(item["output_index"]): item for item in identity_agnostic_audit
        }
        for column in identity_agnostic_candidates:
            gaps = [
                gap
                for seed in dominant_columns
                if (gap := _bbox_edge_gap(outputs[column], outputs[seed])) is not None
            ]
            minimum_gap = min(gaps) if gaps else None
            audit = audit_by_column[column]
            audit["minimum_gap_to_dominant_seed_pixels"] = (
                None if minimum_gap is None else round(float(minimum_gap), 6)
            )
            audit["neighbourhood_edge_gap_pixels"] = neighbourhood_threshold
            if neighbourhood.get("status") != "ok":
                audit["neighbourhood_status"] = "rejected"
                audit["neighbourhood_reason"] = str(neighbourhood.get("reason") or "")
                rejected_candidates.append({
                    "output": audit["output"],
                    "group_id": "target_animal_identity_agnostic",
                    "rejection_reason": "dominant_target_neighbourhood_incomplete",
                })
            elif minimum_gap is None or minimum_gap > neighbourhood_threshold:
                audit["neighbourhood_status"] = "rejected"
                audit["neighbourhood_reason"] = "outside_dominant_target_neighbourhood"
                rejected_candidates.append({
                    "output": audit["output"],
                    "group_id": "target_animal_identity_agnostic",
                    "rejection_reason": "outside_dominant_target_neighbourhood",
                    "minimum_gap_to_dominant_seed_pixels": audit[
                        "minimum_gap_to_dominant_seed_pixels"
                    ],
                })
            else:
                audit["neighbourhood_status"] = "accepted"
                audit["neighbourhood_reason"] = ""
                promoted_identity_agnostic.append(column)
        provisional_output = sorted({
            *base_provisional_output,
            *promoted_identity_agnostic,
        })
        identity_agnostic_set = set(promoted_identity_agnostic)
        accepted_output: list[int] = []
        duplicate_output_candidates: list[dict[str, Any]] = []
        output_boundary_ambiguous = False
        physical_components = _physical_subject_components(
            [outputs[column] for column in provisional_output]
        )
        for component in physical_components:
            columns = [provisional_output[index] for index in component]
            groups = {
                output_groups[column]
                for column in columns
                if column not in identity_agnostic_set
            }
            if len(groups) > 1:
                output_boundary_ambiguous = True
                certificate_reasons.append("output_group_boundary_overlap_ambiguous")
                duplicate_output_candidates.append({
                    "group_ids": sorted(groups),
                    "candidate_instance_ids": [
                        _public_instance(outputs[column], column)["instance_id"]
                        for column in columns
                    ],
                    "resolution": "rejected_cross_group_ambiguity",
                })
                continue
            selected = max(
                columns,
                key=lambda column: (
                    column not in identity_agnostic_set,
                    _geometry_area(outputs[column]) or 0.0,
                    float(outputs[column].get("score") or 0.0),
                ),
            )
            accepted_output.append(selected)
            if len(columns) > 1:
                duplicate_output_candidates.append({
                    "group_ids": sorted(groups) or ["target_animal_identity_agnostic"],
                    "candidate_instance_ids": [
                        _public_instance(outputs[column], column)["instance_id"]
                        for column in columns
                    ],
                    "selected_instance_id": _public_instance(outputs[selected], selected)["instance_id"],
                    "resolution": (
                        "collapsed_identity_agnostic_duplicate_into_species_certified_mask"
                        if selected not in identity_agnostic_set
                        and any(column in identity_agnostic_set for column in columns)
                        else "collapsed_same_target_physical_duplicate"
                    ),
                })
        accepted_output.sort()
        complete = source_roster_complete and not output_boundary_ambiguous
        status = "ok" if complete else "insufficient"
        reason = (
            ""
            if complete
            else "verified_output_roster_ambiguous"
            if output_boundary_ambiguous
            else "verified_source_roster_incomplete"
        )
        image_shapes = {
            tuple(int(value) for value in item["binary_mask"].shape[:2])
            for item in (*inputs, *outputs)
            if isinstance(item.get("binary_mask"), np.ndarray) and item["binary_mask"].ndim >= 2
        }
        input_public = [_public_instance(item, index) for index, item in enumerate(inputs)]
        output_public = [_public_instance(item, index) for index, item in enumerate(outputs)]
        accepted_public = [output_public[index] for index in accepted_output]
        return {
            "schema_version": MATCH_SCHEMA_VERSION,
            "status": status,
            "reason": reason,
            "matches": [],
            "ambiguous_pairs": [],
            "unmatched_input": [] if source_roster_complete else input_public,
            "unmatched_output": [
                item for index, item in enumerate(output_public) if index not in accepted_output
            ],
            "input_count": len(inputs),
            "output_count": len(outputs),
            "matched_count": 0,
            "input_instances": input_public,
            "output_instances": output_public,
            "allowed_edit_input_instances": input_public,
            "allowed_edit_output_instances": accepted_public,
            "image_shape": list(next(iter(image_shapes))) if len(image_shapes) == 1 else [],
            "candidate_score_matrix": [
                {
                    "output_instance_id": output_public[index]["instance_id"],
                    "output_group_id": (
                        "target_animal_identity_agnostic"
                        if index in identity_agnostic_set
                        else output_groups[index]
                    ),
                    "area_ratio_to_source_group_median": (
                        None
                        if output_area_ratios.get(index) is None
                        else round(float(output_area_ratios[index]), 6)
                    ),
                    "accepted_for_allowed_edit_coverage": index in accepted_output,
                }
                for index in range(len(outputs))
            ],
            "roster_assignment_certificate": {
                "profile": VERIFIED_GROUP_ROSTER_PROFILE,
                "assignment_mode": QUESTION_SUPPORT_COVERAGE_MODE,
                "status": status,
                "complete": complete,
                "source_roster_complete": source_roster_complete,
                "ambiguity_free": not output_boundary_ambiguous,
                "identity_assignment_asserted": False,
                "coverage_scope": (
                    "source_masks_plus_species_or_certified_identity_agnostic_target_masks"
                ),
                "expected_counts": expected_counts,
                "source_counts": inferred_counts,
                "matched_instance_ids": sorted(
                    item["instance_id"] for item in input_public if item["instance_id"]
                ),
                "allowed_output_instance_ids": [
                    item["instance_id"] for item in accepted_public
                ],
                "allowed_output_count": len(accepted_public),
                "minimum_area_ratio": config.verified_roster_minimum_area_ratio,
                "maximum_area_ratio": config.verified_roster_maximum_area_ratio,
                "identity_agnostic_target_coverage": {
                    "profile": config.identity_agnostic_target_coverage_profile,
                    "status": str(neighbourhood.get("status") or "not_requested"),
                    "identity_assignment_asserted": False,
                    "binary_classifier_scope": "target_animal_vs_protected_and_background",
                    "pooled_source_area_median": pooled_source_area_median,
                    "protected_subject_count": len(protected_instances),
                    "minimum_target_probability": config.target_coverage_minimum_probability,
                    "minimum_target_margin": config.target_coverage_minimum_margin,
                    "minimum_animal_probability": (
                        config.target_coverage_minimum_animal_probability
                    ),
                    "minimum_animal_margin": config.target_coverage_minimum_animal_margin,
                    "maximum_protected_overlap": (
                        config.target_coverage_maximum_protected_overlap
                    ),
                    "neighbourhood": neighbourhood,
                    "candidate_count": len(identity_agnostic_audit),
                    "promoted_candidate_count": len(promoted_identity_agnostic),
                    "accepted_after_physical_dedup_count": sum(
                        index in identity_agnostic_set for index in accepted_output
                    ),
                    "candidates": identity_agnostic_audit,
                },
                "rejected_candidates": rejected_candidates,
                "duplicate_output_candidates": duplicate_output_candidates,
                "reasons": certificate_reasons,
            },
            "thresholds": {
                "minimum_confidence": config.minimum_confidence,
                "ambiguity_margin": config.ambiguity_margin,
            },
        }

    pair_evidence: list[list[dict[str, Any]]] = []
    scores = np.zeros((len(inputs), len(outputs)), dtype=np.float64)
    candidate_matrix: list[dict[str, Any]] = []
    for row, left in enumerate(inputs):
        evidence_row: list[dict[str, Any]] = []
        source_group = _verified_group(left, source=True)
        for column, right in enumerate(outputs):
            evidence = pair_similarity(left, right, config=config)
            output_group = output_groups[column]
            group_compatible = bool(source_group and source_group == output_group)
            plausible = column in plausible_by_group.get(source_group, [])
            score = float(evidence["score"]) if group_compatible and plausible else 0.0
            scores[row, column] = score
            evidence_row.append(evidence)
            candidate_matrix.append({
                "input_instance_id": _public_instance(left, row)["instance_id"],
                "output_instance_id": _public_instance(right, column)["instance_id"],
                "source_group_id": source_group,
                "output_group_id": output_group,
                "group_compatible": group_compatible,
                "size_plausible": plausible,
                "area_ratio_to_source_group_median": (
                    None
                    if output_area_ratios.get(column) is None
                    else round(float(output_area_ratios[column]), 6)
                ),
                "score": round(score, 6),
                "components": evidence["components"],
                "rejection_reason": (
                    ""
                    if group_compatible and plausible
                    else "group_size_implausible" if group_compatible else "group_label_mismatch"
                ),
            })
        pair_evidence.append(evidence_row)

    matches: list[dict[str, Any]] = []
    ambiguous: list[dict[str, Any]] = []
    accepted_input: set[int] = set()
    accepted_output: set[int] = set()
    group_certificates: list[dict[str, Any]] = []
    for group, expected_count in expected_counts.items():
        rows = inferred.get(group, [])
        columns = plausible_by_group.get(group, [])
        group_reasons: list[str] = []
        if len(rows) != expected_count:
            group_reasons.append("source_group_cardinality_mismatch")
        if len(columns) < expected_count:
            group_reasons.append("output_group_candidates_missing")

        assignments: list[tuple[int, int]] = []
        if rows and columns:
            local_scores = scores[np.ix_(rows, columns)]
            assignments = [
                (rows[local_row], columns[local_column])
                for local_row, local_column in _linear_assignment(local_scores)
            ]
        selected_columns = {column for _, column in assignments}
        unselected_columns = [column for column in columns if column not in selected_columns]
        selected_scores = [float(scores[row, column]) for row, column in assignments]
        best_unselected = max(
            [0.0, *[float(scores[row, column]) for row in rows for column in unselected_columns]]
        )
        boundary_margin = (
            min(selected_scores) - best_unselected
            if len(assignments) == expected_count and selected_scores
            else float("-inf")
        )
        if selected_scores and min(selected_scores) < config.minimum_confidence:
            group_reasons.append("group_assignment_below_minimum_confidence")
        if len(columns) > expected_count and boundary_margin < config.ambiguity_margin:
            group_reasons.append("group_boundary_assignment_ambiguous")

        group_ok = not group_reasons and len(assignments) == expected_count
        for row, column in assignments:
            score = float(scores[row, column])
            row_alternatives = [
                float(scores[row, other]) for other in columns if other != column
            ]
            column_alternatives = [
                float(scores[other, column]) for other in rows if other != row
            ]
            individual_margin = score - max([0.0, *row_alternatives, *column_alternatives])
            selection_margin = score - best_unselected
            record = {
                "input": _public_instance(inputs[row], row),
                "output": _public_instance(outputs[column], column),
                "confidence": round(score, 6),
                "margin": round(selection_margin, 6),
                "individual_identity_margin": round(individual_margin, 6),
                "assignment_scope": "verified_group_set_not_individual_identity",
                "group_id": group,
                "area_ratio_to_source_group_median": round(float(output_area_ratios[column]), 6),
                **pair_evidence[row][column],
            }
            record["confidence"] = round(score, 6)
            if group_ok:
                matches.append(record)
                accepted_input.add(row)
                accepted_output.add(column)
            elif "group_boundary_assignment_ambiguous" in group_reasons:
                record["rejection_reason"] = "ambiguous_group_boundary"
                ambiguous.append(record)

        group_certificates.append({
            "group_id": group,
            "expected_count": expected_count,
            "source_count": len(rows),
            "plausible_output_count": len(columns),
            "rejected_output_count": sum(
                item.get("group_id") == group for item in rejected_candidates
            ),
            "selected_output_instance_ids": [
                _public_instance(outputs[column], column)["instance_id"]
                for _, column in assignments
            ],
            "minimum_selected_confidence": (
                None if not selected_scores else round(min(selected_scores), 6)
            ),
            "group_boundary_margin": (
                None if not np.isfinite(boundary_margin) else round(float(boundary_margin), 6)
            ),
            "complete": group_ok,
            "ambiguity_free": "group_boundary_assignment_ambiguous" not in group_reasons,
            "reasons": group_reasons,
        })

    complete = not certificate_reasons and len(accepted_input) == len(inputs)
    ambiguity_free = not ambiguous and all(row["ambiguity_free"] for row in group_certificates)
    if ambiguous:
        reason = "ambiguous_assignments"
    elif not complete:
        reason = "verified_roster_incomplete"
    else:
        reason = ""
    status = "ok" if complete and ambiguity_free else "insufficient"
    image_shapes = {
        tuple(int(value) for value in item["binary_mask"].shape[:2])
        for item in (*inputs, *outputs)
        if isinstance(item.get("binary_mask"), np.ndarray) and item["binary_mask"].ndim >= 2
    }
    return {
        "schema_version": MATCH_SCHEMA_VERSION,
        "status": status,
        "reason": reason,
        "matches": matches,
        "ambiguous_pairs": ambiguous,
        "unmatched_input": [
            _public_instance(item, index)
            for index, item in enumerate(inputs) if index not in accepted_input
        ],
        "unmatched_output": [
            _public_instance(item, index)
            for index, item in enumerate(outputs) if index not in accepted_output
        ],
        "input_count": len(inputs),
        "output_count": len(outputs),
        "matched_count": len(matches),
        "input_instances": [_public_instance(item, index) for index, item in enumerate(inputs)],
        "output_instances": [_public_instance(item, index) for index, item in enumerate(outputs)],
        "image_shape": list(next(iter(image_shapes))) if len(image_shapes) == 1 else [],
        "candidate_score_matrix": candidate_matrix,
        "roster_assignment_certificate": {
            "profile": VERIFIED_GROUP_ROSTER_PROFILE,
            "status": status,
            "complete": complete,
            "ambiguity_free": ambiguity_free,
            "expected_counts": expected_counts,
            "source_counts": inferred_counts,
            "minimum_area_ratio": config.verified_roster_minimum_area_ratio,
            "maximum_area_ratio": config.verified_roster_maximum_area_ratio,
            "groups": group_certificates,
            "rejected_candidates": rejected_candidates,
            "reasons": certificate_reasons,
        },
        "thresholds": {
            "minimum_confidence": config.minimum_confidence,
            "ambiguity_margin": config.ambiguity_margin,
        },
    }


def match_instances(
    input_instances: Sequence[Mapping[str, Any]],
    output_instances: Sequence[Mapping[str, Any]],
    *,
    config: MatchConfig | None = None,
    protected_instances: Sequence[Mapping[str, Any]] = (),
) -> dict[str, Any]:
    """Return one-to-one assignments and fail-closed ambiguity metadata."""

    cfg = config or MatchConfig()
    inputs, outputs = list(input_instances), list(output_instances)
    if not inputs:
        return {
            "schema_version": MATCH_SCHEMA_VERSION,
            "status": "insufficient",
            "reason": "no_input_instances",
            "matches": [],
            "unmatched_input": [],
            "unmatched_output": [_public_instance(item, index) for index, item in enumerate(outputs)],
        }
    if cfg.verified_roster_profile == VERIFIED_GROUP_ROSTER_PROFILE:
        return _match_verified_group_roster(
            inputs,
            outputs,
            config=cfg,
            protected_instances=protected_instances,
        )
    if not outputs:
        return {
            "schema_version": MATCH_SCHEMA_VERSION,
            "status": "ok",
            "reason": "no_output_instances",
            "matches": [],
            "unmatched_input": [_public_instance(item, index) for index, item in enumerate(inputs)],
            "unmatched_output": [],
            "ambiguous_pairs": [],
            "thresholds": {"minimum_confidence": cfg.minimum_confidence, "ambiguity_margin": cfg.ambiguity_margin},
        }

    pair_evidence: list[list[dict[str, Any]]] = []
    scores = np.zeros((len(inputs), len(outputs)), dtype=np.float64)
    for row, left in enumerate(inputs):
        evidence_row = []
        for column, right in enumerate(outputs):
            evidence = pair_similarity(left, right, config=cfg)
            evidence_row.append(evidence)
            scores[row, column] = evidence["score"]
        pair_evidence.append(evidence_row)

    matches, ambiguous = [], []
    accepted_input: set[int] = set()
    accepted_output: set[int] = set()
    for row, column in _linear_assignment(scores):
        score = float(scores[row, column])
        row_alternatives = [float(scores[row, j]) for j in range(scores.shape[1]) if j != column]
        column_alternatives = [float(scores[i, column]) for i in range(scores.shape[0]) if i != row]
        alternative = max([0.0, *row_alternatives, *column_alternatives])
        margin = score - alternative
        record = {
            "input": _public_instance(inputs[row], row),
            "output": _public_instance(outputs[column], column),
            "confidence": round(score, 6),
            "margin": round(margin, 6),
            **pair_evidence[row][column],
        }
        record["confidence"] = round(score, 6)
        if score < cfg.minimum_confidence:
            record["rejection_reason"] = (
                "semantic_class_mismatch" if not record.get("category_compatible", True) else "below_minimum_confidence"
            )
            continue
        if margin < cfg.ambiguity_margin:
            record["rejection_reason"] = "ambiguous_best_match"
            ambiguous.append(record)
            continue
        accepted_input.add(row)
        accepted_output.add(column)
        matches.append(record)

    status = "insufficient" if ambiguous else "ok"
    image_shapes = {
        tuple(int(value) for value in item["binary_mask"].shape[:2])
        for item in (*inputs, *outputs)
        if isinstance(item.get("binary_mask"), np.ndarray) and item["binary_mask"].ndim >= 2
    }
    pairwise_mask_iou = [
        {
            "input_instance_id": _public_instance(inputs[row], row)["instance_id"],
            "output_instance_id": _public_instance(outputs[column], column)["instance_id"],
            "source_output_mask_iou": evidence.get("source_output_mask_iou"),
            "source_zone_output_overlap_ratio": evidence.get("source_zone_output_overlap_ratio"),
        }
        for row, evidence_row in enumerate(pair_evidence)
        for column, evidence in enumerate(evidence_row)
        if evidence.get("source_output_mask_iou") is not None
    ]
    return {
        "schema_version": MATCH_SCHEMA_VERSION,
        "status": status,
        "reason": "ambiguous_assignments" if ambiguous else "",
        "matches": matches,
        "ambiguous_pairs": ambiguous,
        "unmatched_input": [_public_instance(item, index) for index, item in enumerate(inputs) if index not in accepted_input],
        "unmatched_output": [_public_instance(item, index) for index, item in enumerate(outputs) if index not in accepted_output],
        "input_count": len(inputs),
        "output_count": len(outputs),
        "matched_count": len(matches),
        "input_instances": [_public_instance(item, index) for index, item in enumerate(inputs)],
        "output_instances": [_public_instance(item, index) for index, item in enumerate(outputs)],
        "image_shape": list(next(iter(image_shapes))) if len(image_shapes) == 1 else [],
        "pairwise_source_output_mask_iou": pairwise_mask_iou,
        "thresholds": {"minimum_confidence": cfg.minimum_confidence, "ambiguity_margin": cfg.ambiguity_margin},
    }


def deduplicate_instances(
    items: Iterable[Mapping[str, Any]], *, iou_threshold: float = 0.75,
    preserve_nested_query_roles: bool = False,
) -> list[dict[str, Any]]:
    """Class-aware NMS for repeated fused detector/mask rows.

    Group-pose programs deliberately request an aggregate and its physical
    components.  Their boxes are nested by design, so callers may disable the
    smaller-box containment shortcut while retaining ordinary high-IoU NMS.
    """

    def iou(left: list[float], right: list[float]) -> float:
        x0, y0 = max(left[0], right[0]), max(left[1], right[1])
        x1, y1 = min(left[2], right[2]), min(left[3], right[3])
        intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
        union = max(0.0, left[2] - left[0]) * max(0.0, left[3] - left[1]) + max(0.0, right[2] - right[0]) * max(0.0, right[3] - right[1]) - intersection
        return 0.0 if union <= 0 else intersection / union

    def smaller_overlap(left: list[float], right: list[float]) -> float:
        x0, y0 = max(left[0], right[0]), max(left[1], right[1])
        x1, y1 = min(left[2], right[2]), min(left[3], right[3])
        intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
        left_area = max(0.0, left[2] - left[0]) * max(0.0, left[3] - left[1])
        right_area = max(0.0, right[2] - right[0]) * max(0.0, right[3] - right[1])
        denominator = min(left_area, right_area)
        return 0.0 if denominator <= 0 else intersection / denominator

    ordered = sorted((dict(item) for item in items if _bbox(item) is not None), key=lambda item: float(item.get("score") or 0.0), reverse=True)
    kept: list[dict[str, Any]] = []
    for item in ordered:
        duplicate = next((
            existing
            for existing in kept
            if
            (
                semantic_class(item) not in {"", "unknown"}
                and semantic_class(item) == semantic_class(existing)
                or semantic_similarity(item, existing) >= 0.5
            )
            and (
                iou(_bbox(item) or [], _bbox(existing) or []) >= iou_threshold
                or (
                    not preserve_nested_query_roles
                    and smaller_overlap(_bbox(item) or [], _bbox(existing) or []) >= 0.82
                )
            )
        ), None)
        if duplicate is not None:
            aliases = [
                *duplicate.get("query_aliases", []),
                duplicate.get("query_text", ""),
                *item.get("query_aliases", []),
                item.get("query_text", ""),
            ]
            duplicate["query_aliases"] = list(dict.fromkeys(str(value) for value in aliases if str(value or "").strip()))
            continue
        item["query_aliases"] = list(dict.fromkeys([
            *[str(value) for value in item.get("query_aliases", []) if str(value or "").strip()],
            str(item.get("query_text") or ""),
        ]))
        item.setdefault("instance_id", f"instance_{len(kept):03d}")
        kept.append(item)
    return kept