File size: 47,488 Bytes
15d1f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the auditable v5.1 Prompt/Certified-FMFS overlay.

This module deliberately leaves :mod:`eval.v5_sidecar` and all v5.0
artifacts frozen.  A v5.1 row is built offline from one dataset row and its
already-audited v5.0 sidecar row.  It adds two contracts:

``fmfs.prompt``
    Item-level, input-observable supervision.  Physical and annotation masks
    are aligned exactly with ``dimensions.items``.  Unknown or ambiguous
    items are omitted, never converted into model failures.

``fmfs.certified``
    A strict endpoint.  Automatic certification is intentionally restricted
    to three simple, complete prompt templates.  Unsupported feature graphs
    remain ``unknown`` rather than being over-claimed as manufacturable.

The overlay is evaluator metadata, not a model target or an intermediate DSL.
It never executes generated code and never rewrites the prompt or GT.
"""

from __future__ import annotations

import argparse
import copy
import hashlib
import json
import math
import os
import re
import tempfile
from collections import Counter, defaultdict, deque
from pathlib import Path
from typing import Any, Mapping, Sequence

try:
    from . import v5_sidecar as V5
except ImportError:  # direct script / external plugin import
    import v5_sidecar as V5


SCHEMA_VERSION = "edp-evaluator-sidecar-v5.1"
FMFS_VERSION = "fmfs-v5.1"
CERTIFICATE_SCOPE = "native_gt_dimension_manifest"

NUMBER_TOKEN = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)"
MM_UNIT_TOKEN = r"(?:mm|millimet(?:er|re)s?)"
PAIR_MEASUREMENT_RE = re.compile(
    rf"(?<![\w.])(?P<first>{NUMBER_TOKEN})\s*[x\u00d7]\s*"
    rf"(?P<second>{NUMBER_TOKEN})\s*(?P<unit>{MM_UNIT_TOKEN})\b",
    re.IGNORECASE,
)
# A dedicated, typed list recognizer is safer than a generic numeric-list
# regex: it cannot absorb counts such as "5 edges" or "2 holes".
SHARED_UNIT_LIST_RE = re.compile(
    rf"(?P<label>diameters?|radii)\s*\(?\s*"
    rf"(?P<values>{NUMBER_TOKEN}(?:\s*,\s*{NUMBER_TOKEN})+"
    rf"(?:\s*,?\s*(?:and|&)\s*{NUMBER_TOKEN})?)\s*"
    rf"(?P<unit>{MM_UNIT_TOKEN})\b\s*\)?",
    re.IGNORECASE,
)
SINGLE_MEASUREMENT_RE = re.compile(
    rf"(?<![\w.])(?P<value>{NUMBER_TOKEN})\s*"
    rf"(?P<unit>{MM_UNIT_TOKEN})\b",
    re.IGNORECASE,
)
NUMBER_RE = re.compile(NUMBER_TOKEN)
FEATURE_HEADER_RE = re.compile(
    r"(?:^|\s)(?P<header>The base solid:|A union feature:|A cut feature:)",
    re.IGNORECASE,
)
HASH_RE = re.compile(r"^[0-9a-f]{64}$")

LINEAR_TYPES = frozenset(
    {
        "profile_width",
        "profile_height",
        "bounding_box_width",
        "bounding_box_height",
        "cutout_width",
        "cutout_height",
        "extrusion_depth",
    }
)
CIRCULAR_TYPES = frozenset(
    {"profile_diameter", "cut_profile_diameter", "hole_diameter", "profile_radius"}
)


class V51SidecarError(ValueError):
    """Raised when provenance or a v5.1 schema contract is inconsistent."""


def _sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for block in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _text_sha256(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def _rounded(value: Any, digits: int = 9) -> float | None:
    try:
        result = float(value)
    except (TypeError, ValueError):
        return None
    if not math.isfinite(result):
        return None
    result = round(result, digits)
    return 0.0 if abs(result) < 0.5 * 10.0**-digits else result


def _user_prompt(row: Mapping[str, Any]) -> str:
    messages = row.get("messages", [])
    users = [
        message.get("content", "")
        for message in messages
        if isinstance(message, Mapping) and message.get("role") == "user"
    ] if isinstance(messages, list) else []
    return users[0] if len(users) == 1 and isinstance(users[0], str) else ""


def _feature_text(prompt: str) -> str:
    marker = "Feature description:"
    return prompt.split(marker, 1)[1].strip() if marker in prompt else prompt.strip()


def _normalise_space(text: str) -> str:
    return " ".join(text.split())


def _feature_scopes(text: str) -> list[dict[str, Any]]:
    matches = list(FEATURE_HEADER_RE.finditer(text))
    if not matches:
        return [
            {
                "id": "part:0",
                "operation": "part",
                "start": 0,
                "end": len(text),
                "text": text,
            }
        ]
    counts: Counter[str] = Counter()
    scopes: list[dict[str, Any]] = []
    for index, match in enumerate(matches):
        header = match.group("header").lower()
        operation = "base" if "base" in header else "union" if "union" in header else "cut"
        ordinal = counts[operation]
        counts[operation] += 1
        start = match.end()
        end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
        scopes.append(
            {
                "id": f"{operation}:{ordinal}",
                "operation": operation,
                "start": start,
                "end": end,
                "text": text[start:end].strip(),
            }
        )
    return scopes


def _scope_for_span(scopes: Sequence[Mapping[str, Any]], start: int) -> Mapping[str, Any]:
    for scope in scopes:
        if int(scope["start"]) <= start < int(scope["end"]):
            return scope
    return scopes[0]


def _profile_kind(scope_text: str) -> str:
    lower = scope_text.lower()
    if "circular plate" in lower:
        return "circle"
    if "square plate" in lower:
        return "square"
    if "rectangular plate" in lower:
        return "rectangle"
    if "rectilinear" in lower or "l-shaped" in lower:
        return "rectilinear"
    if "polygonal plate" in lower:
        return "polygon"
    return "unknown"


def _semantic_spec(
    text: str,
    scope: Mapping[str, Any],
    start: int,
    end: int,
    *,
    group_kind: str,
    component: int,
    list_label: str | None = None,
) -> dict[str, Any]:
    before = text[max(int(scope["start"]), start - 96) : start].lower()
    after = text[end : min(int(scope["end"]), end + 48)].lower()
    context = before + " " + after
    operation = str(scope["operation"])
    semantic_type: str | None = None
    axis: str | None = None
    family: str | None = None
    expected_position: str | None = None

    if group_kind == "shared_list":
        semantic_type = "hole_diameter" if str(list_label).lower().startswith("diameter") else "profile_radius"
    elif group_kind == "pair":
        if "cutout" in context:
            semantic_type = "cutout_width" if component == 1 else "cutout_height"
        elif "bounding box" in context:
            semantic_type = "bounding_box_width" if component == 1 else "bounding_box_height"
        elif "square plate" in before or "rectangular plate" in before:
            semantic_type = "profile_width" if component == 1 else "profile_height"
    else:
        if re.search(r"thickness\s+of\s*$", before) or "thickness" in before[-32:]:
            semantic_type = "extrusion_depth"
        elif re.match(r"\s*(?:mm\s+)?wide\b", after):
            semantic_type = "profile_width"
        elif re.match(r"\s*(?:mm\s+)?tall\b", after):
            semantic_type = "profile_height"
        elif re.search(r"(?:circular\s+holes?.*|hole\s+of\s+)diameter\s*$", before[-80:]):
            semantic_type = "hole_diameter"
        elif re.search(r"diameter\s*$", before):
            semantic_type = "cut_profile_diameter" if operation == "cut" else "profile_diameter"
        elif re.search(r"radius\s*$", before):
            semantic_type = "profile_radius"

    if semantic_type in LINEAR_TYPES:
        family = "linear"
        if semantic_type.endswith("width"):
            axis = "horizontal"
        elif semantic_type.endswith("height"):
            axis = "vertical"
        elif semantic_type == "extrusion_depth":
            axis = "horizontal"
    elif semantic_type in {"profile_diameter", "cut_profile_diameter", "hole_diameter"}:
        family = "diameter"
    elif semantic_type == "profile_radius":
        family = "radius"

    # The dataset's L-layout contract makes these positions deterministic for
    # the plain part and base profile.  Local union/cut feature orientation is
    # not encoded in text and therefore remains unknown.
    if semantic_type is not None and operation in {"part", "base"}:
        expected_position = "upper_right" if semantic_type == "extrusion_depth" else "upper_left"

    return {
        "state": "typed" if semantic_type is not None else "numeric_only",
        "type": semantic_type,
        "family": family,
        "axis": axis,
        "expected_view_position": expected_position,
        "feature_scope_id": scope["id"],
        "feature_operation": operation,
        "profile_kind": _profile_kind(str(scope["text"])),
    }


def _hole_multiplicity(text: str, start: int, scope: Mapping[str, Any]) -> tuple[int, str]:
    before = text[max(int(scope["start"]), start - 112) : start].lower()
    match = re.search(r"(\d+)\s+circular\s+holes?\s*,?\s*each\s+of\s+diameter\s*$", before)
    if match:
        return max(1, int(match.group(1))), "explicit_each"
    return 1, "single_mention"


def extract_typed_prompt_parameters(prompt: str) -> dict[str, Any]:
    """Extract typed millimetre values, including right-shared list units."""

    text = _feature_text(prompt)
    scopes = _feature_scopes(text)
    occupied: list[tuple[int, int]] = []
    raw: list[dict[str, Any]] = []
    group_index = 0

    def add_candidate(
        *,
        value_text: str,
        value_span: tuple[int, int],
        group_span: tuple[int, int],
        component: int,
        group_kind: str,
        unit_source: str,
        raw_group: str,
        list_label: str | None = None,
        expected_multiplicity: int = 1,
        multiplicity_source: str = "single_mention",
    ) -> None:
        value = _rounded(value_text)
        scope = _scope_for_span(scopes, value_span[0])
        semantic = _semantic_spec(
            text,
            scope,
            value_span[0],
            value_span[1],
            group_kind=group_kind,
            component=component,
            list_label=list_label,
        )
        reason_codes: list[str] = []
        physical_value = abs(float(value)) if value is not None and semantic["type"] == "extrusion_depth" else value
        if value is None or abs(float(value)) <= 1e-12:
            reason_codes.append("nonpositive_or_invalid_value")
        elif value < 0 and semantic["type"] != "extrusion_depth":
            reason_codes.append("negative_physical_length")
        raw.append(
            {
                "group_id": f"g{group_index:03d}",
                "component": component,
                "group_kind": group_kind,
                "signed_value_mm": value,
                "physical_value_mm": _rounded(physical_value),
                "unit": "mm",
                "unit_source": unit_source,
                "raw_group": raw_group,
                "span": [value_span[0], value_span[1]],
                "group_span": [group_span[0], group_span[1]],
                "context": text[max(0, group_span[0] - 40) : min(len(text), group_span[1] + 40)],
                "semantic": semantic,
                "expected_multiplicity": expected_multiplicity,
                "multiplicity_source": multiplicity_source,
                "reason_codes": reason_codes,
            }
        )

    for match in PAIR_MEASUREMENT_RE.finditer(text):
        occupied.append(match.span())
        for component, name in enumerate(("first", "second"), 1):
            add_candidate(
                value_text=match.group(name),
                value_span=match.span(name),
                group_span=match.span(),
                component=component,
                group_kind="pair",
                unit_source="group_suffix",
                raw_group=match.group(0),
            )
        group_index += 1

    for match in SHARED_UNIT_LIST_RE.finditer(text):
        if any(match.start() < right and match.end() > left for left, right in occupied):
            continue
        occupied.append(match.span())
        values_start = match.start("values")
        number_matches = list(NUMBER_RE.finditer(match.group("values")))
        label = match.group("label")
        for component, number in enumerate(number_matches, 1):
            absolute_span = (values_start + number.start(), values_start + number.end())
            add_candidate(
                value_text=number.group(0),
                value_span=absolute_span,
                group_span=match.span(),
                component=component,
                group_kind="shared_list",
                unit_source="right_shared",
                raw_group=match.group(0),
                list_label=label,
                expected_multiplicity=1,
                multiplicity_source="explicit_list_item",
            )
        group_index += 1

    for match in SINGLE_MEASUREMENT_RE.finditer(text):
        if any(match.start() < right and match.end() > left for left, right in occupied):
            continue
        scope = _scope_for_span(scopes, match.start())
        multiplicity, multiplicity_source = _hole_multiplicity(text, match.start(), scope)
        add_candidate(
            value_text=match.group("value"),
            value_span=match.span("value"),
            group_span=match.span(),
            component=1,
            group_kind="single",
            unit_source="explicit",
            raw_group=match.group(0),
            expected_multiplicity=multiplicity,
            multiplicity_source=multiplicity_source,
        )
        group_index += 1

    raw.sort(key=lambda item: (item["span"][0], item["component"]))
    for index, item in enumerate(raw):
        item["parameter_id"] = f"p{index:03d}"
    return {
        "status": "extracted" if raw else "unknown",
        "source": "typed_user_prompt_numeric_mentions",
        "feature_text_sha256": _text_sha256(text),
        "candidate_count": len(raw),
        "prompt_numbers_mm": [item["signed_value_mm"] for item in raw],
        "candidates": raw,
        "scope_count": len(scopes),
        "scopes": scopes,
        "reason_codes": [] if raw else ["no_explicit_mm_parameters"],
    }


def _dimension_orientation(dimension: Mapping[str, Any]) -> str | None:
    points = dimension.get("reference_points", {})
    first, second = points.get("defpoint2"), points.get("defpoint3")
    if not isinstance(first, Sequence) or not isinstance(second, Sequence):
        return None
    dx, dy = abs(float(second[0]) - float(first[0])), abs(float(second[1]) - float(first[1]))
    length = math.hypot(dx, dy)
    if length <= 1e-12:
        return None
    tolerance = math.sin(math.radians(5.0))
    if dy / length <= tolerance:
        return "horizontal"
    if dx / length <= tolerance:
        return "vertical"
    return "aligned"


def _point_segment_distance(point: Sequence[float], first: Sequence[float], second: Sequence[float]) -> float:
    px, py = float(point[0]), float(point[1])
    ax, ay = float(first[0]), float(first[1])
    bx, by = float(second[0]), float(second[1])
    dx, dy = bx - ax, by - ay
    denominator = dx * dx + dy * dy
    if denominator <= 1e-18:
        return math.hypot(px - ax, py - ay)
    fraction = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / denominator))
    return math.hypot(px - (ax + fraction * dx), py - (ay + fraction * dy))


def _distance_to_record(point: Sequence[float], record: Mapping[str, Any]) -> float | None:
    bounds = record.get("bbox")
    if not isinstance(bounds, Mapping):
        return None
    minimum, maximum = bounds.get("min"), bounds.get("max")
    if not isinstance(minimum, Sequence) or not isinstance(maximum, Sequence):
        return None
    entity_type = record.get("type")
    width = abs(float(maximum[0]) - float(minimum[0]))
    height = abs(float(maximum[1]) - float(minimum[1]))
    if entity_type == "LINE":
        if width <= 1e-9 or height <= 1e-9:
            return _point_segment_distance(point, minimum, maximum)
        # A diagonal cannot be reconstructed safely from bbox corners alone.
        return None
    if entity_type == "CIRCLE" and abs(width - height) <= max(1e-7, 1e-5 * max(width, height, 1.0)):
        centre = ((float(minimum[0]) + float(maximum[0])) / 2, (float(minimum[1]) + float(maximum[1])) / 2)
        radius = (width + height) / 4
        radial = math.dist((float(point[0]), float(point[1])), centre)
        return min(abs(radial - radius), radial)  # centre references are valid
    return None


def _dimension_geometry_bindings(base: Mapping[str, Any]) -> list[dict[str, Any]]:
    dimensions = list(base.get("dimensions", {}).get("items", []))
    entities = list(base.get("entities", {}).get("items", []))
    views = {int(item["index"]): item for item in base.get("views", {}).get("candidates", [])}
    results: list[dict[str, Any]] = []
    for dimension in dimensions:
        view_index = dimension.get("view_candidate_index")
        view = views.get(int(view_index)) if isinstance(view_index, int) else None
        candidate_records = [
            record
            for record in entities
            if record.get("view_candidate_index") == view_index
            and record.get("type") in {"LINE", "CIRCLE", "ARC"}
        ]
        family = "linear" if dimension.get("family") in {"linear", "aligned"} else dimension.get("family")
        refs = dimension.get("reference_points", {})
        names = ("defpoint2", "defpoint3") if family == "linear" else ("defpoint", "defpoint4")
        points = [refs[name] for name in names if isinstance(refs.get(name), Sequence)]
        diagonal = 1.0
        if isinstance(view, Mapping):
            bounds = view.get("geometry_bbox", {})
            diagonal = max(1.0, math.hypot(float(bounds.get("width", 0.0)), float(bounds.get("height", 0.0))))
        sigma = max(1e-6, 0.005 * diagonal)
        qualities: list[float] = []
        entity_indices: set[int] = set()
        distances: list[float] = []
        for point in points:
            choices = []
            for record in candidate_records:
                distance = _distance_to_record(point, record)
                if distance is not None and math.isfinite(distance):
                    choices.append((distance, int(record["index"])))
            if not choices:
                continue
            distance, entity_index = min(choices)
            distances.append(distance)
            qualities.append(math.exp(-distance / sigma))
            entity_indices.add(entity_index)
        quality = sum(qualities) / len(points) if points and len(qualities) == len(points) else 0.0
        geometry_state = "certified" if points and len(qualities) == len(points) and quality >= 0.90 else "unknown"
        view_state = "certified" if geometry_state == "certified" and view is not None else "heuristic" if view is not None else "unknown"
        results.append(
            {
                "geometry": {
                    "state": geometry_state,
                    "quality": _rounded(quality),
                    "entity_indices": sorted(entity_indices),
                    "reference_point_count": len(points),
                    "bound_reference_point_count": len(qualities),
                    "max_distance": _rounded(max(distances)) if distances else None,
                    "basis": "v5_bbox_primitive_reference_distance",
                },
                "view": {
                    "state": view_state,
                    "candidate_index": view_index,
                    "position": dimension.get("nearest_view_position"),
                    "role": dimension.get("nearest_view_role"),
                    "basis": "dimension_reference_geometry" if view_state == "certified" else "v5_binding_point_heuristic" if view_state == "heuristic" else None,
                },
                "orientation": _dimension_orientation(dimension),
            }
        )
    return results


def _normal_family(value: Any) -> str:
    return "linear" if str(value or "").lower() in {"linear", "aligned"} else str(value or "").lower()


def _value_matches(candidate: Mapping[str, Any], dimension: Mapping[str, Any]) -> tuple[bool, float | None, float | None]:
    value, target = candidate.get("physical_value_mm"), dimension.get("display_value")
    if not isinstance(value, (int, float)) or not isinstance(target, (int, float)):
        return False, None, None
    tolerance = max(0.05, 0.001 * abs(float(value)))
    error = abs(abs(float(target)) - abs(float(value)))
    return error <= tolerance, error, tolerance


def _compatible(
    candidate: Mapping[str, Any],
    dimension: Mapping[str, Any],
    binding: Mapping[str, Any],
) -> bool:
    semantic = candidate.get("semantic", {})
    if semantic.get("state") != "typed" or candidate.get("reason_codes"):
        return False
    if _normal_family(dimension.get("family")) != semantic.get("family"):
        return False
    matches, _, _ = _value_matches(candidate, dimension)
    if not matches or not dimension.get("reliable"):
        return False
    expected_position = semantic.get("expected_view_position")
    if expected_position is not None and binding.get("view", {}).get("position") != expected_position:
        return False
    expected_axis = semantic.get("axis")
    if expected_axis is not None and binding.get("orientation") != expected_axis:
        return False
    return binding.get("geometry", {}).get("state") == "certified"


def _maximum_slot_matching(
    candidate_indices: Sequence[int],
    edges: Mapping[int, Sequence[int]],
    candidates: Sequence[Mapping[str, Any]],
) -> dict[int, int] | None:
    slots: list[int] = []
    for candidate_index in candidate_indices:
        slots.extend([candidate_index] * int(candidates[candidate_index].get("expected_multiplicity", 1)))
    matched_dimension_to_slot: dict[int, int] = {}

    def augment(slot_index: int, visited: set[int]) -> bool:
        candidate_index = slots[slot_index]
        for dimension_index in sorted(edges.get(candidate_index, [])):
            if dimension_index in visited:
                continue
            visited.add(dimension_index)
            previous = matched_dimension_to_slot.get(dimension_index)
            if previous is None or augment(previous, visited):
                matched_dimension_to_slot[dimension_index] = slot_index
                return True
        return False

    for slot_index in range(len(slots)):
        if not augment(slot_index, set()):
            return None
    return {dimension_index: slots[slot_index] for dimension_index, slot_index in matched_dimension_to_slot.items()}


def _template_profile(text: str, category: Any) -> tuple[str | None, list[str], int | None]:
    compact = _normalise_space(text)
    value = rf"{NUMBER_TOKEN}\s*{MM_UNIT_TOKEN}"
    pair = rf"{NUMBER_TOKEN}\s*[x\u00d7]\s*{NUMBER_TOKEN}\s*{MM_UNIT_TOKEN}"
    thickness = rf"It is extruded to a thickness of {value}\."
    patterns = [
        (
            "simple_rectangular_prism_v1",
            rf"The part is a rectangular plate {value} wide and {value} tall\. {thickness}",
            "CONVEX_PLATE",
            3,
        ),
        (
            "simple_rectangular_prism_v1",
            rf"The part is a square plate {pair}\. {thickness}",
            "CONVEX_PLATE",
            3,
        ),
        (
            "simple_concentric_annulus_v1",
            rf"The part is a circular plate with diameter {value}, featuring a circular hole of diameter {value}\. {thickness}",
            "DISK_WITH_HOLES",
            3,
        ),
        (
            "simple_cylindrical_disk_v1",
            rf"The part is a circular plate with diameter {value}\. {thickness}",
            "DISK",
            2,
        ),
    ]
    for name, pattern, expected_category, count in patterns:
        if re.fullmatch(pattern, compact, re.IGNORECASE):
            reasons = [] if str(category or "").upper() == expected_category else ["category_not_supported_for_template"]
            return name, reasons, count
    return None, ["unsupported_completeness_template"], None


def _build_fmfs(
    base: Mapping[str, Any], parameters: dict[str, Any], feature_text: str
) -> dict[str, Any]:
    dimensions = list(base.get("dimensions", {}).get("items", []))
    candidates = list(parameters.get("candidates", []))
    bindings = _dimension_geometry_bindings(base)
    for index, dimension in enumerate(dimensions):
        dimension["v51_binding"] = bindings[index]

    edges: dict[int, list[int]] = {}
    for candidate_index, candidate in enumerate(candidates):
        compatible = [
            dimension_index
            for dimension_index, dimension in enumerate(dimensions)
            if _compatible(candidate, dimension, bindings[dimension_index])
        ]
        candidate["compatible_gt_dimension_indices"] = compatible
        edges[candidate_index] = compatible

    typed_nodes = [index for index, candidate in enumerate(candidates) if candidate.get("semantic", {}).get("state") == "typed" and not candidate.get("reason_codes")]
    dimension_to_candidates: defaultdict[int, list[int]] = defaultdict(list)
    for candidate_index in typed_nodes:
        for dimension_index in edges[candidate_index]:
            dimension_to_candidates[dimension_index].append(candidate_index)

    physical_mask = [False] * len(dimensions)
    annotation_mask = [False] * len(dimensions)
    items: list[dict[str, Any]] = []
    resolved_candidates: set[int] = set()
    visited_candidates: set[int] = set()
    ambiguous_candidates: set[int] = set()

    for seed in typed_nodes:
        if seed in visited_candidates or not edges[seed]:
            continue
        queue: deque[tuple[str, int]] = deque([("c", seed)])
        component_candidates: set[int] = set()
        component_dimensions: set[int] = set()
        while queue:
            kind, index = queue.popleft()
            if kind == "c":
                if index in component_candidates:
                    continue
                component_candidates.add(index)
                queue.extend(("d", value) for value in edges[index])
            else:
                if index in component_dimensions:
                    continue
                component_dimensions.add(index)
                queue.extend(("c", value) for value in dimension_to_candidates[index])
        visited_candidates.update(component_candidates)
        demand = sum(int(candidates[index].get("expected_multiplicity", 1)) for index in component_candidates)
        matching = _maximum_slot_matching(sorted(component_candidates), edges, candidates)
        complete = demand == len(component_dimensions) and matching is not None and len(matching) == demand
        if not complete:
            ambiguous_candidates.update(component_candidates)
            continue
        assignment_state = "unique" if len(component_candidates) == len(component_dimensions) == demand == 1 else "symmetric_group"
        component_parameter_ids = [candidates[index]["parameter_id"] for index in sorted(component_candidates)]
        semantic_types = sorted({str(candidates[index]["semantic"]["type"]) for index in component_candidates})
        annotation_ready = (
            len(semantic_types) == 1
            and all(
                candidates[index]["semantic"].get("expected_view_position") is not None
                and (
                    candidates[index]["semantic"].get("family") in {"diameter", "radius"}
                    or candidates[index]["semantic"].get("axis") is not None
                )
                for index in component_candidates
            )
        )
        group_id = "b" + hashlib.sha256(
            ("|".join(component_parameter_ids) + ":" + ",".join(map(str, sorted(component_dimensions)))).encode("utf-8")
        ).hexdigest()[:10]
        for dimension_index in sorted(component_dimensions):
            dimension = dimensions[dimension_index]
            binding = bindings[dimension_index]
            matched_candidate = matching.get(dimension_index) if matching else None
            source_candidate = candidates[matched_candidate] if matched_candidate is not None else candidates[min(component_candidates)]
            matches, value_error, tolerance = _value_matches(source_candidate, dimension)
            physical_mask[dimension_index] = True
            annotation_eligible = bool(
                annotation_ready
                and binding["geometry"]["state"] == "certified"
                and binding["view"]["state"] == "certified"
            )
            annotation_mask[dimension_index] = annotation_eligible
            items.append(
                {
                    "id": f"pf{len(items):03d}",
                    "gt_dimension_index": dimension_index,
                    "gt_dimension_id": dimension.get("id", f"d{dimension_index:03d}"),
                    "prompt_parameter_ids": component_parameter_ids,
                    "semantic_type": semantic_types[0] if len(semantic_types) == 1 else "symmetric_parameter_group",
                    "semantic_types": semantic_types,
                    "family": _normal_family(dimension.get("family")),
                    "value_mm": dimension.get("display_value"),
                    "physical_eligible": True,
                    "annotation_eligible": annotation_eligible,
                    "binding": {
                        "value": {
                            "state": "certified" if matches else "conflict",
                            "absolute_error_mm": _rounded(value_error),
                            "tolerance_mm": _rounded(tolerance),
                        },
                        "type": {
                            "state": "certified",
                            "expected": source_candidate["semantic"].get("family"),
                            "actual": _normal_family(dimension.get("family")),
                        },
                        "assignment": {
                            "state": assignment_state,
                            "group_id": group_id,
                            "candidate_dimension_indices": sorted(component_dimensions),
                            "demand": demand,
                        },
                        "view": binding["view"],
                        "geometry": binding["geometry"],
                    },
                    "reason_codes": [] if annotation_eligible else ["annotation_binding_not_certified"],
                }
            )
        resolved_candidates.update(component_candidates)

    template, template_reasons, expected_dimension_count = _template_profile(feature_text, base.get("category"))
    candidate_conflicts = {
        index for index, candidate in enumerate(candidates) if candidate.get("reason_codes")
    }
    if template is not None:
        candidate_conflicts.update(index for index in typed_nodes if index not in resolved_candidates)
    conflicting_ids = sorted(candidates[index]["parameter_id"] for index in candidate_conflicts)
    unresolved_ids = sorted(
        candidate["parameter_id"]
        for index, candidate in enumerate(candidates)
        if index not in resolved_candidates and index not in candidate_conflicts
    )
    unresolved_dimensions = [
        dimensions[index].get("id", f"d{index:03d}")
        for index, enabled in enumerate(physical_mask)
        if not enabled
    ]
    prompt_reasons: list[str] = []
    if not any(physical_mask):
        prompt_reasons.append("no_prompt_fmfs_physical_items")
    if not any(annotation_mask):
        prompt_reasons.append("no_prompt_fmfs_annotation_items")
    if ambiguous_candidates:
        prompt_reasons.append("ambiguous_parameter_dimension_assignment")
    if unresolved_ids:
        prompt_reasons.append("unresolved_prompt_parameters")
    if conflicting_ids:
        prompt_reasons.append("prompt_gt_conflict")

    reliable_count = sum(bool(item.get("reliable")) for item in dimensions)
    prompt_manifest = {
        "physical_eligible": any(physical_mask),
        "annotation_eligible": any(annotation_mask),
        "physical_item_mask": physical_mask,
        "annotation_item_mask": annotation_mask,
        "physical_item_count": sum(physical_mask),
        "annotation_item_count": sum(annotation_mask),
        "items": items,
        "unresolved_prompt_parameter_ids": unresolved_ids,
        "conflicting_prompt_parameter_ids": conflicting_ids,
        "unresolved_gt_dimension_ids": unresolved_dimensions,
        "coverage": {
            "physical_over_all_gt": _rounded(sum(physical_mask) / len(dimensions)) if dimensions else None,
            "physical_over_reliable_gt": _rounded(sum(physical_mask) / reliable_count) if reliable_count else None,
            "annotation_over_all_gt": _rounded(sum(annotation_mask) / len(dimensions)) if dimensions else None,
        },
        "reason_codes": prompt_reasons or ["ok"],
    }

    certified_reasons = list(template_reasons)
    if template is not None:
        if expected_dimension_count != len(dimensions):
            certified_reasons.append("template_dimension_count_mismatch")
        if not all(physical_mask) or not all(annotation_mask):
            certified_reasons.append("template_items_not_fully_bound")
        if conflicting_ids or unresolved_ids:
            certified_reasons.append("template_prompt_parameters_unresolved")
        if not all(bool(item.get("reliable")) for item in dimensions):
            certified_reasons.append("unreliable_gt_dimensions")
        if base.get("views", {}).get("status") != "ok" or base.get("views", {}).get("candidate_count") != 3:
            certified_reasons.append("three_view_contract_not_certified")
        if any(
            isinstance(candidate.get("signed_value_mm"), (int, float))
            and float(candidate["signed_value_mm"]) < 0
            for candidate in candidates
        ):
            certified_reasons.append("negative_template_parameter")
    eligible = bool(template is not None and not certified_reasons)
    if eligible:
        status = "certified"
        certified_reasons = ["ok"]
    elif template is None or "category_not_supported_for_template" in certified_reasons:
        status = "unknown"
    else:
        status = "conflict"
    certified_manifest = {
        "status": status,
        "eligible": eligible,
        "scope": CERTIFICATE_SCOPE,
        "completeness_profile": template,
        "physical_item_mask": list(physical_mask) if eligible else [False] * len(dimensions),
        "annotation_item_mask": list(annotation_mask) if eligible else [False] * len(dimensions),
        "item_ids": [item["id"] for item in items] if eligible else [],
        "unresolved_gt_dimension_ids": [] if eligible else unresolved_dimensions,
        "reason_codes": certified_reasons,
        "notes": (
            "Automatic certification covers only the declared native-GT dimension "
            "manifest for a supported complete template; it is not a STEP/B-Rep "
            "feature-tree completeness proof."
        ),
    }
    return {"version": FMFS_VERSION, "prompt": prompt_manifest, "certified": certified_manifest}


def build_v51_row(
    dataset_row: Mapping[str, Any],
    base_row: Mapping[str, Any],
    *,
    dataset_path: str | Path | None = None,
    dataset_sha256: str | None = None,
    base_sidecar_path: str | Path | None = None,
    base_sidecar_sha256: str | None = None,
) -> dict[str, Any]:
    part_id = str(dataset_row.get("id", "")).strip()
    if not part_id or part_id != str(base_row.get("id", "")).strip():
        raise V51SidecarError("dataset/base sidecar id mismatch")
    if base_row.get("schema_version") != V5.SCHEMA_VERSION:
        raise V51SidecarError(f"unsupported base schema {base_row.get('schema_version')!r}")
    for field in ("category", "tier"):
        if dataset_row.get(field) is not None and base_row.get(field) is not None and dataset_row.get(field) != base_row.get(field):
            raise V51SidecarError(f"{part_id}: dataset/base {field} mismatch")
    prompt = _user_prompt(dataset_row)
    prompt_hash = _text_sha256(prompt)
    expected_prompt_hash = base_row.get("source", {}).get("prompt_sha256")
    if not prompt or prompt_hash != expected_prompt_hash:
        raise V51SidecarError(f"{part_id}: prompt hash does not match base sidecar")
    if not isinstance(base_row.get("gt_dxf_sha256"), str) or not HASH_RE.fullmatch(base_row["gt_dxf_sha256"]):
        raise V51SidecarError(f"{part_id}: base sidecar has no valid GT hash")

    output = copy.deepcopy(dict(base_row))
    output["schema_version"] = SCHEMA_VERSION
    output["source"] = {
        **dict(base_row.get("source", {})),
        "dataset": str(Path(dataset_path).resolve()) if dataset_path is not None else None,
        "dataset_sha256": dataset_sha256,
        "base_sidecar": str(Path(base_sidecar_path).resolve()) if base_sidecar_path is not None else None,
        "base_sidecar_sha256": base_sidecar_sha256,
        "base_schema_version": V5.SCHEMA_VERSION,
        "prompt_sha256": prompt_hash,
        "base_gt_dxf_sha256": base_row["gt_dxf_sha256"],
    }
    output["parameters"] = extract_typed_prompt_parameters(prompt)
    output["fmfs"] = _build_fmfs(output, output["parameters"], _feature_text(prompt))
    output["eligibility"] = {
        **dict(base_row.get("eligibility", {})),
        "prompt_fmfs_physical": output["fmfs"]["prompt"]["physical_eligible"],
        "prompt_fmfs_annotation": output["fmfs"]["prompt"]["annotation_eligible"],
        "certified_fmfs": output["fmfs"]["certified"]["eligible"],
        "automatic_v51_reward": output["fmfs"]["prompt"]["physical_eligible"],
    }
    # Remove ambiguous v5.0 aliases so an old evaluator cannot silently treat a
    # partial Prompt-FMFS manifest as a strict all-GT endpoint.
    output["eligibility"].pop("fmfs", None)
    output["eligibility"].pop("automatic_v5_reward", None)
    return output


def _validate_hash(value: Any, label: str, path: Path, line_number: int) -> None:
    if not isinstance(value, str) or not HASH_RE.fullmatch(value):
        raise V51SidecarError(f"{path}:{line_number}: invalid {label}")


def _validate_loaded_row(row: Any, path: Path, line_number: int) -> dict[str, Any]:
    if not isinstance(row, dict):
        raise V51SidecarError(f"{path}:{line_number}: expected JSON object")
    if row.get("schema_version") != SCHEMA_VERSION:
        raise V51SidecarError(f"{path}:{line_number}: unsupported schema")
    part_id = str(row.get("id", "")).strip()
    if not part_id:
        raise V51SidecarError(f"{path}:{line_number}: missing id")
    source = row.get("source")
    if not isinstance(source, dict) or source.get("base_schema_version") != V5.SCHEMA_VERSION:
        raise V51SidecarError(f"{path}:{line_number}: invalid base provenance")
    for field in ("dataset_sha256", "base_sidecar_sha256", "prompt_sha256", "base_gt_dxf_sha256"):
        _validate_hash(source.get(field), f"source.{field}", path, line_number)
    if source["base_gt_dxf_sha256"] != row.get("gt_dxf_sha256"):
        raise V51SidecarError(f"{path}:{line_number}: GT hash binding mismatch")
    dimensions = row.get("dimensions", {}).get("items")
    fmfs = row.get("fmfs")
    if not isinstance(dimensions, list) or not isinstance(fmfs, dict) or fmfs.get("version") != FMFS_VERSION:
        raise V51SidecarError(f"{path}:{line_number}: invalid dimensions/FMFS contract")
    prompt, certified = fmfs.get("prompt"), fmfs.get("certified")
    if not isinstance(prompt, dict) or not isinstance(certified, dict):
        raise V51SidecarError(f"{path}:{line_number}: missing prompt/certified FMFS")
    for manifest_name, manifest in (("prompt", prompt), ("certified", certified)):
        for mask_name in ("physical_item_mask", "annotation_item_mask"):
            mask = manifest.get(mask_name)
            if not isinstance(mask, list) or len(mask) != len(dimensions) or any(type(value) is not bool for value in mask):
                raise V51SidecarError(f"{path}:{line_number}: invalid {manifest_name}.{mask_name}")
    physical_mask = prompt["physical_item_mask"]
    annotation_mask = prompt["annotation_item_mask"]
    if any(annotation and not physical for physical, annotation in zip(physical_mask, annotation_mask)):
        raise V51SidecarError(f"{path}:{line_number}: annotation mask exceeds physical mask")
    items = prompt.get("items")
    if not isinstance(items, list):
        raise V51SidecarError(f"{path}:{line_number}: prompt.items must be a list")
    seen_indices: set[int] = set()
    for item in items:
        if not isinstance(item, dict) or not isinstance(item.get("gt_dimension_index"), int):
            raise V51SidecarError(f"{path}:{line_number}: invalid Prompt-FMFS item")
        index = item["gt_dimension_index"]
        if index in seen_indices or not 0 <= index < len(dimensions):
            raise V51SidecarError(f"{path}:{line_number}: duplicate/out-of-range GT dimension index")
        seen_indices.add(index)
        assignment = item.get("binding", {}).get("assignment", {}).get("state")
        if assignment not in {"unique", "symmetric_group"} or not physical_mask[index]:
            raise V51SidecarError(f"{path}:{line_number}: unsafe Prompt-FMFS assignment")
        if annotation_mask[index]:
            binding = item.get("binding", {})
            if binding.get("view", {}).get("state") != "certified" or binding.get("geometry", {}).get("state") != "certified":
                raise V51SidecarError(f"{path}:{line_number}: annotation item lacks certified binding")
    if {index for index, enabled in enumerate(physical_mask) if enabled} != seen_indices:
        raise V51SidecarError(f"{path}:{line_number}: prompt item/mask mismatch")
    status = certified.get("status")
    if status not in {"certified", "conflict", "unknown"} or bool(certified.get("eligible")) != (status == "certified"):
        raise V51SidecarError(f"{path}:{line_number}: inconsistent certified status")
    if certified.get("eligible") and (
        not all(certified["physical_item_mask"]) or not all(certified["annotation_item_mask"])
    ):
        raise V51SidecarError(f"{path}:{line_number}: certified manifest is not complete")
    row["id"] = part_id
    return row


def load_sidecar_jsonl(path: str | Path) -> dict[str, dict[str, Any]]:
    source_path = Path(path)
    rows: dict[str, dict[str, Any]] = {}
    provenance: tuple[str, str] | None = None
    with source_path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                decoded = json.loads(line)
            except json.JSONDecodeError as error:
                raise V51SidecarError(f"{source_path}:{line_number}: {error}") from error
            row = _validate_loaded_row(decoded, source_path, line_number)
            if row["id"] in rows:
                raise V51SidecarError(f"{source_path}:{line_number}: duplicate id {row['id']}")
            current = (row["source"]["dataset_sha256"], row["source"]["base_sidecar_sha256"])
            if provenance is None:
                provenance = current
            elif current != provenance:
                raise V51SidecarError(f"{source_path}:{line_number}: mixed dataset/base provenance")
            rows[row["id"]] = row
    return rows


def _atomic_jsonl(path: Path, rows: Sequence[Mapping[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
    try:
        with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
            for row in rows:
                handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n")
            handle.flush()
            os.fsync(handle.fileno())
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.remove(temporary)


def build_sidecar_dataset(
    dataset_path: str | Path,
    base_sidecar_path: str | Path,
    output_path: str | Path,
) -> dict[str, Any]:
    dataset = Path(dataset_path).resolve()
    base_path = Path(base_sidecar_path).resolve()
    output = Path(output_path).resolve()
    dataset_hash, base_hash = _sha256(dataset), _sha256(base_path)
    dataset_rows: dict[str, dict[str, Any]] = {}
    with dataset.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                row = json.loads(line)
            except json.JSONDecodeError as error:
                raise V51SidecarError(f"{dataset}:{line_number}: {error}") from error
            if not isinstance(row, dict) or not str(row.get("id", "")).strip():
                raise V51SidecarError(f"{dataset}:{line_number}: invalid row/id")
            part_id = str(row["id"]).strip()
            if part_id in dataset_rows:
                raise V51SidecarError(f"{dataset}:{line_number}: duplicate id {part_id}")
            dataset_rows[part_id] = row
    base_rows = V5.load_sidecar_jsonl(base_path)
    if set(dataset_rows) != set(base_rows):
        missing_base = sorted(set(dataset_rows) - set(base_rows))
        missing_dataset = sorted(set(base_rows) - set(dataset_rows))
        raise V51SidecarError(
            f"dataset/base ID sets differ: missing_base={missing_base[:5]}, missing_dataset={missing_dataset[:5]}"
        )
    rows = [
        build_v51_row(
            dataset_rows[part_id],
            base_rows[part_id],
            dataset_path=dataset,
            dataset_sha256=dataset_hash,
            base_sidecar_path=base_path,
            base_sidecar_sha256=base_hash,
        )
        for part_id in dataset_rows
    ]
    _atomic_jsonl(output, rows)
    status_counts = Counter(row["fmfs"]["certified"]["status"] for row in rows)
    summary = {
        "schema_version": SCHEMA_VERSION,
        "dataset": str(dataset),
        "dataset_sha256": dataset_hash,
        "base_sidecar": str(base_path),
        "base_sidecar_sha256": base_hash,
        "output": str(output),
        "output_sha256": _sha256(output),
        "count": len(rows),
        "prompt_physical_eligible": sum(row["fmfs"]["prompt"]["physical_eligible"] for row in rows),
        "prompt_annotation_eligible": sum(row["fmfs"]["prompt"]["annotation_eligible"] for row in rows),
        "certified_status_counts": dict(sorted(status_counts.items())),
    }
    return summary


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset", type=Path, required=True)
    parser.add_argument("--base-sidecar", type=Path, required=True)
    parser.add_argument("--out", type=Path, required=True)
    args = parser.parse_args(argv)
    print(
        json.dumps(
            build_sidecar_dataset(args.dataset, args.base_sidecar, args.out),
            ensure_ascii=False,
            indent=2,
            sort_keys=True,
        )
    )
    return 0


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