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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
#!/usr/bin/env python3
"""Build an evaluator-only, auditable GT sidecar for the direct ezdxf task.

The sidecar is deliberately *not* a model target or an intermediate DSL.  It
only freezes facts that can be recovered from an existing dataset row and its
ground-truth DXF.  In particular, view roles and physical feature bindings are
never asserted when the DXF alone does not prove them: they are emitted as
heuristic hints with explicit audit flags.

Library API::

    build_sidecar_row(row, dataset_path=None) -> dict
    build_sidecar_dataset(dataset_path, output_path, limit=None, strict=False)
    load_sidecar_jsonl(path) -> dict[id, row]

CLI::

    python eval/v5_sidecar.py \
        --dataset code_datasets/physical_v1/eval_val.jsonl \
        --out results/metric_v5/eval_val_sidecar.jsonl \
        [--limit 32] [--strict]

``--strict`` applies to structural failures (missing/unreadable GT, malformed
dataset rows, duplicate IDs).  It intentionally does not fail merely because
a conservative inference is marked ``needs_audit``.
"""

from __future__ import annotations

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

import ezdxf
from ezdxf import bbox as ezdxf_bbox


SCHEMA_VERSION = "edp-evaluator-sidecar-v5.0"
REQUIRED_TOP_LEVEL_FIELDS = (
    "schema_version",
    "id",
    "category",
    "tier",
    "gt_dxf_sha256",
    "views",
    "dimensions",
    "fmfs",
    "parameters",
    "eligibility",
    "audit_flags",
)

# These bounded entity types are sufficient for the current GT corpus and are
# safe inputs to ezdxf.bbox.extents().  Unknown drawable types stay in the full
# inventory but do not silently influence view detection.
VIEW_GEOMETRY_TYPES = frozenset(
    {
        "LINE",
        "CIRCLE",
        "ARC",
        "LWPOLYLINE",
        "POLYLINE",
        "ELLIPSE",
        "SPLINE",
        "SOLID",
        "TRACE",
        "3DFACE",
    }
)
ANNOTATION_ENTITY_TYPES = frozenset(
    {"DIMENSION", "TEXT", "MTEXT", "LEADER", "MLEADER", "TOLERANCE"}
)
AUXILIARY_ENTITY_TYPES = frozenset(
    {"POINT", "XLINE", "RAY", "HATCH", "IMAGE", "WIPEOUT", "VIEWPORT"}
)

PAIR_MEASUREMENT_RE = re.compile(
    r"(?<![\w.])"
    r"(?P<first>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*"
    r"[x\u00d7]\s*"
    r"(?P<second>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*"
    r"(?P<unit>mm|millimet(?:er|re)s?)\b",
    re.IGNORECASE,
)
SINGLE_MEASUREMENT_RE = re.compile(
    r"(?<![\w.])"
    r"(?P<value>[+-]?(?:\d+(?:\.\d*)?|\.\d+))\s*"
    r"(?P<unit>mm|millimet(?:er|re)s?)\b",
    re.IGNORECASE,
)
NUMBER_RE = re.compile(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)")


class SidecarError(ValueError):
    """Raised for input failures that make a trustworthy sidecar impossible."""


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 _point2(value: Any) -> list[float] | None:
    try:
        x = _rounded(value.x)
        y = _rounded(value.y)
    except (AttributeError, TypeError):
        try:
            x = _rounded(value[0])
            y = _rounded(value[1])
        except (IndexError, TypeError):
            return None
    return [x, y] if x is not None and y is not None else None


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 _audit(
    flags: list[dict[str, Any]],
    code: str,
    severity: str,
    scope: str,
    message: str,
    **details: Any,
) -> None:
    item: dict[str, Any] = {
        "code": code,
        "severity": severity,
        "scope": scope,
        "message": message,
    }
    if details:
        item["details"] = details
    flags.append(item)


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


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


def _semantic_hint(text: str, start: int, end: int, *, pair: bool) -> str:
    before = text[max(0, start - 56) : start].lower()
    after = text[end : min(len(text), end + 28)].lower()
    context = before + " " + after
    if pair:
        if "bounding box" in before:
            return "bounding_box_extent_pair"
        if "cutout" in before:
            return "cutout_extent_pair"
        if "square" in before or "rectang" in before:
            return "planar_extent_pair"
        return "extent_pair"
    if "hole" in before[-48:] and re.search(r"diameter\s*$", before):
        return "hole_diameter"
    if re.search(r"diameter\s*$", before):
        return "diameter"
    if re.search(r"radius\s*$", before):
        return "radius"
    if re.search(r"thickness\s+of\s*$", before) or "thickness" in before[-28:]:
        return "extrusion_thickness"
    if re.match(r"\s*(?:mm\s+)?wide\b", after):
        return "width"
    if re.match(r"\s*(?:mm\s+)?tall\b", after):
        return "height"
    return "unknown"


def extract_prompt_parameters(prompt: str) -> dict[str, Any]:
    """Return traceable numeric millimetre mentions, not feature truth.

    Counts such as "six straight edges" and the 2D/3D wording are intentionally
    excluded.  ``A x B mm`` contributes two scalar candidates tied by one group
    ID.  The original sign is retained; magnitude matching is reported later
    but never rewrites the prompt.
    """

    text = _feature_text(prompt)
    occupied: list[tuple[int, int]] = []
    raw: list[dict[str, Any]] = []
    group_index = 0
    for match in PAIR_MEASUREMENT_RE.finditer(text):
        occupied.append(match.span())
        group_id = f"g{group_index:03d}"
        group_index += 1
        hint = _semantic_hint(text, match.start(), match.end(), pair=True)
        for component, name in enumerate(("first", "second"), 1):
            raw.append(
                {
                    "group_id": group_id,
                    "component": component,
                    "value": _rounded(match.group(name)),
                    "unit": "mm",
                    "semantic_hint": hint,
                    "raw_group": match.group(0),
                    "span": [match.start(), match.end()],
                    "context": text[max(0, match.start() - 40) : match.end() + 40],
                }
            )
    for match in SINGLE_MEASUREMENT_RE.finditer(text):
        if any(match.start() < end and match.end() > start for start, end in occupied):
            continue
        group_id = f"g{group_index:03d}"
        group_index += 1
        raw.append(
            {
                "group_id": group_id,
                "component": 1,
                "value": _rounded(match.group("value")),
                "unit": "mm",
                "semantic_hint": _semantic_hint(
                    text, match.start(), match.end(), pair=False
                ),
                "raw_group": match.group(0),
                "span": [match.start(), match.end()],
                "context": text[max(0, match.start() - 40) : match.end() + 40],
            }
        )
    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": "user_prompt_numeric_mentions",
        "feature_text_sha256": _text_sha256(text),
        "candidate_count": len(raw),
        "prompt_numbers_mm": [item["value"] for item in raw],
        "candidates": raw,
        "semantic_binding": "needs_audit" if raw else "unknown",
        "notes": (
            "Candidates are evaluator metadata only; semantic hints are not "
            "model targets and are not sufficient for a physical reward."
        ),
    }


def _parse_dimension_text(text: str) -> tuple[str, float | None]:
    raw = text or ""
    compact = raw.strip().replace(" ", "")
    lower = compact.lower()
    family = "linear"
    if lower.startswith("%%c") or compact.startswith(("\u00d8", "\u2205")):
        family = "diameter"
    elif lower.startswith("r"):
        family = "radius"
    cleaned = re.sub(r"%%[a-zA-Z]", "", compact)
    cleaned = cleaned.replace("\u00d8", "").replace("\u2205", "")
    cleaned = re.sub(r"^[Rr]", "", cleaned)
    match = NUMBER_RE.search(cleaned)
    return family, _rounded(match.group(0)) if match else None


def _dimension_family(dimtype: int, text: str) -> str:
    base = dimtype & 0x0F
    by_type = {
        0: "linear",
        1: "aligned",
        2: "angular",
        3: "diameter",
        4: "radius",
        5: "angular3",
        6: "ordinate",
    }
    family = by_type.get(base, f"type{base}")
    text_family, _ = _parse_dimension_text(text)
    if family not in {"linear", "aligned", "diameter", "radius"}:
        return text_family if text_family != "linear" else family
    return family


def _entity_bbox(entity: Any) -> tuple[dict[str, Any] | None, str]:
    try:
        bounds = ezdxf_bbox.extents([entity], fast=False)
        if not bounds.has_data:
            return None, "empty"
        minimum = _point2(bounds.extmin)
        maximum = _point2(bounds.extmax)
        if minimum is None or maximum is None:
            return None, "non_finite"
        return {
            "min": minimum,
            "max": maximum,
            "width": _rounded(maximum[0] - minimum[0]),
            "height": _rounded(maximum[1] - minimum[1]),
        }, "ok"
    except Exception as error:  # retained in the inventory for auditability
        return None, f"{type(error).__name__}: {error}"


def _dimension_record(entity: Any, index: int) -> dict[str, Any]:
    raw_dimtype = int(entity.dxf.dimtype) if entity.dxf.hasattr("dimtype") else 0
    text = str(entity.dxf.text) if entity.dxf.hasattr("text") else ""
    reference_points: dict[str, list[float]] = {}
    for name in ("defpoint", "defpoint2", "defpoint3", "defpoint4", "defpoint5"):
        if entity.dxf.hasattr(name):
            point = _point2(getattr(entity.dxf, name))
            if point is not None:
                reference_points[name] = point
    base = raw_dimtype & 0x0F
    if base in (0, 1) and {"defpoint2", "defpoint3"} <= reference_points.keys():
        first = reference_points["defpoint2"]
        second = reference_points["defpoint3"]
        binding = [_rounded((first[0] + second[0]) / 2), _rounded((first[1] + second[1]) / 2)]
    elif base in (3, 4) and "defpoint4" in reference_points:
        binding = list(reference_points["defpoint4"])
    else:
        binding = reference_points.get("defpoint")
    try:
        measurement_raw = entity.get_measurement()
        measurement = _rounded(measurement_raw)
    except Exception:
        measurement = None
    _, display_value = _parse_dimension_text(text)
    drawing_scale_ratio = (
        _rounded(display_value / measurement)
        if display_value is not None
        and measurement is not None
        and abs(measurement) > 1e-12
        else None
    )
    return {
        "id": f"d{index:03d}",
        "index": index,
        "handle": str(entity.dxf.handle) if entity.dxf.hasattr("handle") else None,
        "layer": str(entity.dxf.layer) if entity.dxf.hasattr("layer") else "0",
        "dimtype": raw_dimtype,
        "family": _dimension_family(raw_dimtype, text),
        "text": text,
        "display_value": display_value,
        "measurement": measurement,
        "definition_point": reference_points.get("defpoint"),
        "drawing_scale_ratio": drawing_scale_ratio,
        "binding_point": binding,
        "reference_points": reference_points,
        "view_candidate_index": None,
        "nearest_view_role": None,
        "nearest_view_position": None,
        "scale_consistent": None,
        "reliable": False,
        "reliability_reasons": [],
    }


def _layer_hint(name: str, linetype: str) -> str:
    token = f"{name} {linetype}".lower()
    if "hidden" in token or "dash" in token:
        return "hidden"
    if "center" in token or "centre" in token:
        return "center"
    if "dim" in token:
        return "dimension"
    return "visible_or_unknown"


def _extract_dxf(doc: Any, flags: list[dict[str, Any]]) -> dict[str, Any]:
    modelspace = list(doc.modelspace())
    type_counts: Counter[str] = Counter()
    layer_counts: Counter[str] = Counter()
    geometry_type_counts: Counter[str] = Counter()
    geometry_layer_counts: Counter[str] = Counter()
    entity_records: list[dict[str, Any]] = []
    geometry_records: list[dict[str, Any]] = []
    dimensions: list[dict[str, Any]] = []
    unknown_types: Counter[str] = Counter()

    for index, entity in enumerate(modelspace):
        entity_type = entity.dxftype()
        layer = str(entity.dxf.layer) if entity.dxf.hasattr("layer") else "0"
        type_counts[entity_type] += 1
        layer_counts[layer] += 1
        record: dict[str, Any] = {
            "index": index,
            "handle": str(entity.dxf.handle) if entity.dxf.hasattr("handle") else None,
            "type": entity_type,
            "layer": layer,
            "view_candidate_index": None,
        }
        if entity_type in VIEW_GEOMETRY_TYPES:
            bounds, bbox_status = _entity_bbox(entity)
            record["bbox"] = bounds
            record["bbox_status"] = bbox_status
            geometry_type_counts[entity_type] += 1
            geometry_layer_counts[layer] += 1
            if bounds is not None:
                geometry_records.append(record)
            else:
                _audit(
                    flags,
                    "geometry_bbox_failed",
                    "warning",
                    "entities",
                    "A supported geometry entity has no usable bounding box.",
                    entity_index=index,
                    entity_type=entity_type,
                    bbox_status=bbox_status,
                )
        elif entity_type == "DIMENSION":
            dimensions.append(_dimension_record(entity, len(dimensions)))
        elif entity_type not in ANNOTATION_ENTITY_TYPES | AUXILIARY_ENTITY_TYPES:
            unknown_types[entity_type] += 1
        entity_records.append(record)

    if unknown_types:
        _audit(
            flags,
            "unsupported_modelspace_entity_types",
            "warning",
            "entities",
            "Entity types outside the conservative view extractor were retained in the inventory.",
            counts=dict(sorted(unknown_types.items())),
        )

    layer_inventory: list[dict[str, Any]] = []
    known_layer_names = {str(layer.dxf.name) for layer in doc.layers}
    for name in sorted(known_layer_names | set(layer_counts), key=str.casefold):
        try:
            layer = doc.layers.get(name)
            linetype = str(layer.dxf.linetype)
            color = int(layer.dxf.color)
            is_on = bool(layer.is_on())
            is_frozen = bool(layer.is_frozen())
        except Exception:
            linetype, color, is_on, is_frozen = "unknown", None, None, None
        layer_inventory.append(
            {
                "name": name,
                "linetype": linetype,
                "color": color,
                "is_on": is_on,
                "is_frozen": is_frozen,
                "visibility_hint": _layer_hint(name, linetype),
                "modelspace_entity_count": layer_counts.get(name, 0),
                "view_geometry_entity_count": geometry_layer_counts.get(name, 0),
            }
        )

    return {
        "modelspace_entity_count": len(modelspace),
        "by_type": dict(sorted(type_counts.items())),
        "view_geometry_by_type": dict(sorted(geometry_type_counts.items())),
        "unsupported_by_type": dict(sorted(unknown_types.items())),
        "items": entity_records,
        "geometry_records": geometry_records,
        "layers": layer_inventory,
        "dimension_items": dimensions,
    }


def _merge_intervals(
    intervals: Iterable[tuple[float, float]], tolerance: float
) -> list[tuple[float, float]]:
    ordered = sorted((min(a, b), max(a, b)) for a, b in intervals)
    if not ordered:
        return []
    merged: list[list[float]] = [[ordered[0][0], ordered[0][1]]]
    for start, end in ordered[1:]:
        if start <= merged[-1][1] + tolerance:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return [(start, end) for start, end in merged]


def _axis_gaps(
    records: Sequence[dict[str, Any]], axis: int, tolerance: float
) -> list[dict[str, float]]:
    merged = _merge_intervals(
        (
            (record["bbox"]["min"][axis], record["bbox"]["max"][axis])
            for record in records
            if record.get("bbox") is not None
        ),
        tolerance,
    )
    return [
        {
            "low": _rounded(left[1]),
            "high": _rounded(right[0]),
            "width": _rounded(right[0] - left[1]),
            "cut": _rounded((left[1] + right[0]) / 2),
        }
        for left, right in zip(merged, merged[1:])
        if right[0] - left[1] > tolerance
    ]


def _cell_for_bbox(bounds: Mapping[str, Any], x_cut: float, y_cut: float) -> str | None:
    minimum, maximum = bounds["min"], bounds["max"]
    if maximum[0] <= x_cut:
        horizontal = "left"
    elif minimum[0] >= x_cut:
        horizontal = "right"
    else:
        return None
    if maximum[1] <= y_cut:
        vertical = "lower"
    elif minimum[1] >= y_cut:
        vertical = "upper"
    else:
        return None
    return f"{vertical}_{horizontal}"


def _cell_for_point(point: Sequence[float] | None, x_cut: float, y_cut: float) -> str | None:
    if point is None or len(point) < 2:
        return None
    horizontal = "left" if point[0] <= x_cut else "right"
    vertical = "lower" if point[1] <= y_cut else "upper"
    return f"{vertical}_{horizontal}"


def _union_bbox(records: Sequence[dict[str, Any]]) -> dict[str, Any]:
    min_x = min(record["bbox"]["min"][0] for record in records)
    min_y = min(record["bbox"]["min"][1] for record in records)
    max_x = max(record["bbox"]["max"][0] for record in records)
    max_y = max(record["bbox"]["max"][1] for record in records)
    return {
        "min": [_rounded(min_x), _rounded(min_y)],
        "max": [_rounded(max_x), _rounded(max_y)],
        "width": _rounded(max_x - min_x),
        "height": _rounded(max_y - min_y),
        "centroid": [_rounded((min_x + max_x) / 2), _rounded((min_y + max_y) / 2)],
    }


def _visibility_hint(layer: str) -> str:
    lower = layer.lower()
    if "hidden" in lower or "dash" in lower:
        return "hidden"
    if "center" in lower or "centre" in lower:
        return "center"
    return "visible_or_unknown"


def detect_view_candidates(
    geometry_records: Sequence[dict[str, Any]],
    flags: list[dict[str, Any]],
) -> dict[str, Any]:
    """Detect three spatial regions via two empty projection gaps.

    This is deterministic and invariant to entity order.  It does not use a
    learned classifier.  A standard upper-left/lower-left/upper-right layout
    receives front/top/right *hints* only; the role assignment remains an audit
    item because position alone is not geometric proof.
    """

    if not geometry_records:
        _audit(
            flags,
            "no_supported_view_geometry",
            "error",
            "views",
            "No bounded supported geometry is available for view detection.",
        )
        return {
            "status": "unknown",
            "method": "orthogonal_empty_gap_v1",
            "candidate_count": 0,
            "candidates": [],
            "split": None,
            "role_assignment": {"status": "unknown", "basis": None},
        }

    global_bbox = _union_bbox(geometry_records)
    diagonal = math.hypot(global_bbox["width"], global_bbox["height"])
    tolerance = max(1e-7, 1e-7 * max(diagonal, 1.0))
    x_gaps = _axis_gaps(geometry_records, 0, tolerance)
    y_gaps = _axis_gaps(geometry_records, 1, tolerance)
    expected_cells = {"upper_left", "lower_left", "upper_right"}
    proposals: list[dict[str, Any]] = []
    for x_gap in x_gaps:
        for y_gap in y_gaps:
            grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
            crossed = False
            for record in geometry_records:
                cell = _cell_for_bbox(record["bbox"], x_gap["cut"], y_gap["cut"])
                if cell is None:
                    crossed = True
                    break
                grouped[cell].append(record)
            occupied = set(grouped)
            if crossed or len(occupied) != 3:
                continue
            minimum_gap_ratio = min(x_gap["width"], y_gap["width"]) / max(diagonal, 1e-12)
            score = minimum_gap_ratio + (
                1.0 if occupied == expected_cells else 0.0
            )
            proposals.append(
                {
                    "score": score,
                    "x_gap": x_gap,
                    "y_gap": y_gap,
                    "grouped": grouped,
                    "occupied": occupied,
                    "minimum_gap_ratio": minimum_gap_ratio,
                }
            )
    if not proposals:
        _audit(
            flags,
            "view_split_not_found",
            "warning",
            "views",
            "No pair of empty x/y gaps produced exactly three occupied regions.",
            x_gap_count=len(x_gaps),
            y_gap_count=len(y_gaps),
        )
        return {
            "status": "unknown",
            "method": "orthogonal_empty_gap_v1",
            "global_geometry_bbox": global_bbox,
            "candidate_count": 0,
            "candidates": [],
            "split": None,
            "role_assignment": {"status": "unknown", "basis": None},
        }

    selected = sorted(
        proposals,
        key=lambda proposal: (
            -proposal["score"],
            proposal["x_gap"]["cut"],
            proposal["y_gap"]["cut"],
        ),
    )[0]
    conventional = selected["occupied"] == expected_cells
    status = (
        "ok"
        if conventional and selected["minimum_gap_ratio"] >= 0.005
        else "needs_audit"
    )
    if not conventional:
        _audit(
            flags,
            "nonstandard_three_region_layout",
            "warning",
            "views",
            "Three regions were found, but not in the dataset's common L layout.",
            occupied_cells=sorted(selected["occupied"]),
        )
    if selected["minimum_gap_ratio"] < 0.005:
        _audit(
            flags,
            "small_view_separation_gap",
            "warning",
            "views",
            "The smallest separating gap is below 0.5% of the drawing diagonal.",
            minimum_gap_ratio=_rounded(selected["minimum_gap_ratio"]),
        )

    role_by_cell = {
        "upper_left": "front_candidate",
        "lower_left": "top_candidate",
        "upper_right": "right_candidate",
    }
    position_order = {"upper_left": 0, "lower_left": 1, "upper_right": 2, "lower_right": 3}
    candidates: list[dict[str, Any]] = []
    record_to_candidate: dict[int, int] = {}
    for cell in sorted(selected["occupied"], key=lambda value: position_order[value]):
        records = selected["grouped"][cell]
        type_counts = Counter(record["type"] for record in records)
        layer_counts = Counter(record["layer"] for record in records)
        visibility_counts = Counter(_visibility_hint(record["layer"]) for record in records)
        candidate_index = len(candidates)
        for record in records:
            record_to_candidate[record["index"]] = candidate_index
        candidates.append(
            {
                "index": candidate_index,
                "position_hint": cell,
                "role_hint": role_by_cell.get(cell) if conventional else None,
                "name": (
                    role_by_cell[cell].removesuffix("_candidate")
                    if conventional and cell in role_by_cell
                    else f"view_{candidate_index}"
                ),
                "role_confidence": "heuristic" if conventional else "unknown",
                "geometry_bbox": _union_bbox(records),
                "bbox": [
                    *_union_bbox(records)["min"],
                    *_union_bbox(records)["max"],
                ],
                "entity_count": len(records),
                "entity_indices": sorted(record["index"] for record in records),
                "entity_types": dict(sorted(type_counts.items())),
                "layer_counts": dict(sorted(layer_counts.items())),
                "visibility_counts": dict(sorted(visibility_counts.items())),
                "dimension_indices": [],
            }
        )
    for record in geometry_records:
        record["view_candidate_index"] = record_to_candidate.get(record["index"])

    if conventional:
        _audit(
            flags,
            "view_roles_are_heuristic",
            "info",
            "views",
            "Front/top/right labels are positional hints and require an audited convention.",
        )
    return {
        "status": status,
        "method": "orthogonal_empty_gap_v1",
        "global_geometry_bbox": global_bbox,
        "candidate_count": len(candidates),
        "candidates": candidates,
        "split": {
            "x_cut": selected["x_gap"]["cut"],
            "y_cut": selected["y_gap"]["cut"],
            "x_gap": selected["x_gap"],
            "y_gap": selected["y_gap"],
            "minimum_gap_ratio": _rounded(selected["minimum_gap_ratio"]),
            "occupied_cells": sorted(selected["occupied"]),
        },
        "role_assignment": {
            "status": "needs_audit" if conventional else "unknown",
            "basis": "dataset_position_convention" if conventional else None,
            "mapping": role_by_cell if conventional else {},
        },
    }


def _attach_dimensions_to_views(
    dimensions: list[dict[str, Any]], views: dict[str, Any]
) -> None:
    split = views.get("split")
    if not split:
        return
    by_position = {
        candidate["position_hint"]: candidate
        for candidate in views.get("candidates", [])
    }
    for dimension in dimensions:
        cell = _cell_for_point(
            dimension.get("binding_point"), split["x_cut"], split["y_cut"]
        )
        candidate = by_position.get(cell)
        if candidate is None:
            continue
        dimension["view_candidate_index"] = candidate["index"]
        dimension["nearest_view_role"] = candidate.get("role_hint")
        dimension["nearest_view_position"] = candidate.get("position_hint")
        candidate["dimension_indices"].append(dimension["index"])


def _dimension_manifest(
    items: list[dict[str, Any]], flags: list[dict[str, Any]]
) -> dict[str, Any]:
    family_counts = Counter(item["family"] for item in items)
    unparsed = [item["index"] for item in items if item["display_value"] is None]
    invalid_measurements = [item["index"] for item in items if item["measurement"] is None]
    zero_conflicts = [
        item["index"]
        for item in items
        if item["measurement"] is not None
        and abs(item["measurement"]) <= 1e-12
        and item["display_value"] not in (None, 0.0)
    ]
    signatures: defaultdict[tuple[Any, ...], list[int]] = defaultdict(list)
    for item in items:
        signature = (
            item["family"],
            item["display_value"],
            tuple(item["binding_point"] or ()),
            tuple(item["definition_point"] or ()),
        )
        signatures[signature].append(item["index"])
    duplicate_groups = [indices for indices in signatures.values() if len(indices) > 1]
    ratios = [
        float(item["drawing_scale_ratio"])
        for item in items
        if isinstance(item.get("drawing_scale_ratio"), (int, float))
        and float(item["drawing_scale_ratio"]) > 0
    ]
    consensus_ratio = statistics.median(ratios) if ratios else None
    scale_qualities: list[float] = []
    for item in items:
        ratio = item.get("drawing_scale_ratio")
        if consensus_ratio is not None and isinstance(ratio, (int, float)) and ratio > 0:
            relative_log_error = abs(math.log(float(ratio) / consensus_ratio))
            item["scale_consistent"] = relative_log_error <= math.log1p(0.05)
            item["scale_quality"] = _rounded(math.exp(-relative_log_error / 0.05))
            scale_qualities.append(float(item["scale_quality"]))
        else:
            item["scale_consistent"] = False
            item["scale_quality"] = 0.0
        reasons: list[str] = []
        if item.get("family") not in {"linear", "aligned", "diameter", "radius"}:
            reasons.append("unsupported_dimension_family")
        if item.get("display_value") is None:
            reasons.append("missing_display_value")
        if item.get("measurement") is None or abs(float(item.get("measurement") or 0.0)) <= 1e-12:
            reasons.append("missing_or_zero_measurement")
        if item.get("binding_point") is None:
            reasons.append("missing_binding_point")
        if item.get("view_candidate_index") is None:
            reasons.append("view_binding_unknown")
        if not item["scale_consistent"]:
            reasons.append("drawing_scale_outlier")
        item["reliability_reasons"] = reasons
        item["reliable"] = not reasons
    if not items:
        _audit(
            flags,
            "no_native_dimensions",
            "warning",
            "dimensions",
            "The GT modelspace contains no native DIMENSION entities.",
        )
    if unparsed:
        _audit(
            flags,
            "unparsed_dimension_text",
            "warning",
            "dimensions",
            "Some DIMENSION text overrides do not expose a numeric value.",
            indices=unparsed,
        )
    if invalid_measurements:
        _audit(
            flags,
            "invalid_dimension_measurement",
            "warning",
            "dimensions",
            "Some native DIMENSION measurements are unavailable or non-finite.",
            indices=invalid_measurements,
        )
    if zero_conflicts:
        _audit(
            flags,
            "zero_measurement_nonzero_display",
            "warning",
            "dimensions",
            "A non-zero display value is attached to a zero geometric measurement.",
            indices=zero_conflicts,
        )
    if duplicate_groups:
        _audit(
            flags,
            "duplicate_dimension_signatures",
            "warning",
            "dimensions",
            "Exact duplicate dimension signatures require review before coverage scoring.",
            groups=duplicate_groups,
        )
    scale_outliers = [item["index"] for item in items if not item["scale_consistent"]]
    if scale_outliers:
        _audit(
            flags,
            "dimension_scale_outliers",
            "warning",
            "dimensions",
            "Some GT dimensions do not agree with the sheet drawing scale.",
            indices=scale_outliers,
        )
    status = "ok"
    if not items:
        status = "unknown"
    elif unparsed or invalid_measurements or zero_conflicts or duplicate_groups:
        status = "needs_audit"
    return {
        "status": status,
        "count": len(items),
        "by_family": dict(sorted(family_counts.items())),
        "numeric_display_count": len(items) - len(unparsed),
        "valid_measurement_count": len(items) - len(invalid_measurements),
        "reliable_count": sum(bool(item["reliable"]) for item in items),
        "gt_dimension_values": [
            item["display_value"]
            for item in items
            if item.get("display_value") is not None
        ],
        "physical_per_drawing_ratio": _rounded(consensus_ratio),
        "scale_consistency": _rounded(statistics.fmean(scale_qualities)) if scale_qualities else None,
        "duplicate_signature_groups": duplicate_groups,
        "items": items,
    }


def _crosscheck_parameters(
    parameters: dict[str, Any], dimensions: Mapping[str, Any], flags: list[dict[str, Any]]
) -> None:
    dimension_items = dimensions.get("items", [])
    unmatched: list[str] = []
    negative: list[str] = []
    for candidate in parameters["candidates"]:
        value = candidate["value"]
        if value is None:
            candidate["signed_dimension_matches"] = []
            candidate["magnitude_dimension_matches"] = []
            unmatched.append(candidate["parameter_id"])
            continue
        if value < 0:
            negative.append(candidate["parameter_id"])
        tolerance = max(0.05, 0.001 * abs(value))
        signed_matches: list[int] = []
        magnitude_matches: list[int] = []
        reliable_signed_matches: list[int] = []
        for dimension in dimension_items:
            display = dimension.get("display_value")
            if display is None:
                continue
            if abs(display - value) <= tolerance:
                signed_matches.append(dimension["index"])
                if dimension.get("reliable"):
                    reliable_signed_matches.append(dimension["index"])
            if abs(abs(display) - abs(value)) <= tolerance:
                magnitude_matches.append(dimension["index"])
        candidate["match_tolerance_mm"] = _rounded(tolerance)
        candidate["signed_dimension_matches"] = signed_matches
        candidate["magnitude_dimension_matches"] = magnitude_matches
        candidate["reliable_signed_dimension_matches"] = reliable_signed_matches
        if not magnitude_matches:
            unmatched.append(candidate["parameter_id"])
    parameters["matched_candidate_count"] = len(parameters["candidates"]) - len(unmatched)
    parameters["unmatched_candidate_ids"] = unmatched
    parameters["negative_candidate_ids"] = negative
    parameters["value_crosscheck_status"] = (
        "ok"
        if parameters["candidates"] and not unmatched
        else "needs_audit"
        if parameters["candidates"]
        else "unknown"
    )
    if negative:
        _audit(
            flags,
            "negative_prompt_parameters",
            "warning",
            "parameters",
            "Negative prompt values were preserved; magnitude matches do not authorize rewriting them.",
            parameter_ids=negative,
        )
    if unmatched:
        _audit(
            flags,
            "prompt_parameters_without_dimension_value_match",
            "warning",
            "parameters",
            "Some prompt millimetre values have no matching GT DIMENSION display value.",
            parameter_ids=unmatched,
        )
    if not parameters["candidates"]:
        _audit(
            flags,
            "no_prompt_parameter_candidates",
            "warning",
            "parameters",
            "No explicit millimetre-valued parameter candidates were extracted.",
        )


def _fmfs_manifest(
    parameters: Mapping[str, Any],
    dimensions: Mapping[str, Any],
) -> dict[str, Any]:
    """Build a conservative full-manufacturing-feature verifier manifest.

    Every explicit prompt millimetre value must have a signed match to a
    reliable, view-bound native GT dimension.  Extra GT dimensions are retained
    as possible image/geometry-derived targets but do not by themselves make
    the prompt inconsistent.  ``fully_derivable`` therefore remains a separate
    diagnostic instead of being silently assumed.
    """

    candidates = list(parameters.get("candidates", []))
    reliable_dimensions = [
        item for item in dimensions.get("items", []) if item.get("reliable")
    ]
    by_index = {item["index"]: item for item in reliable_dimensions}
    matched_by_dimension: defaultdict[int, list[str]] = defaultdict(list)
    for candidate in candidates:
        for index in candidate.get("reliable_signed_dimension_matches", []):
            if index in by_index:
                matched_by_dimension[index].append(candidate["parameter_id"])

    items: list[dict[str, Any]] = []
    for dimension in reliable_dimensions:
        prompt_ids = sorted(matched_by_dimension.get(dimension["index"], []))
        items.append(
            {
                "id": dimension["id"],
                "gt_dimension_index": dimension["index"],
                "family": dimension["family"],
                "value": dimension["display_value"],
                "measurement": dimension["measurement"],
                "physical_per_drawing_ratio": dimension["drawing_scale_ratio"],
                "view": dimension.get("nearest_view_role"),
                "position": dimension.get("nearest_view_position"),
                "binding_point": dimension.get("binding_point"),
                "prompt_parameter_ids": prompt_ids,
                "derivable": bool(prompt_ids),
                "consistent": bool(dimension.get("scale_consistent")),
            }
        )

    reasons: list[str] = []
    if not candidates:
        reasons.append("no_prompt_parameters")
    if parameters.get("negative_candidate_ids"):
        reasons.append("negative_prompt_parameters")
    unmatched_reliable = [
        candidate["parameter_id"]
        for candidate in candidates
        if not candidate.get("reliable_signed_dimension_matches")
    ]
    if unmatched_reliable:
        reasons.append("prompt_gt_value_mismatch")
    gt_consistent = bool(dimensions.get("count")) and (
        dimensions.get("reliable_count") == dimensions.get("count")
    )
    if not reliable_dimensions:
        reasons.append("no_reliable_gt_dimensions")
    elif not gt_consistent:
        reasons.append("gt_dimension_manifest_needs_audit")
    prompt_consistent = bool(candidates) and not parameters.get(
        "negative_candidate_ids"
    ) and not unmatched_reliable
    eligible = bool(prompt_consistent and gt_consistent and items)
    return {
        "eligible": eligible,
        "reason": reasons or ["ok"],
        "prompt_consistent": prompt_consistent,
        "gt_consistent": gt_consistent,
        "fully_derivable": bool(
            prompt_consistent and items and all(item["derivable"] for item in items)
        ),
        "unmatched_prompt_parameter_ids": unmatched_reliable,
        "item_count": len(items),
        "items": items,
        "notes": (
            "This evaluator-only manifest is not a model target. Extra reliable "
            "GT dimensions may be derivable from the ISO image or feature relations; "
            "that claim is reported separately by fully_derivable."
        ),
    }


def _empty_row(row: Mapping[str, Any], gt_path: Path | None) -> dict[str, Any]:
    part_id = str(row.get("id", "")).strip()
    return {
        "schema_version": SCHEMA_VERSION,
        "id": part_id,
        "category": row.get("category"),
        "tier": row.get("tier"),
        "split": row.get("split"),
        "gt_dxf": str(gt_path) if gt_path is not None else None,
        "gt_dxf_sha256": None,
        "gt_dxf_bytes": None,
        "source": {},
        "drawing": {},
        "entities": {
            "modelspace_entity_count": 0,
            "by_type": {},
            "view_geometry_by_type": {},
            "unsupported_by_type": {},
            "items": [],
        },
        "layers": [],
        "views": {
            "status": "unknown",
            "method": "orthogonal_empty_gap_v1",
            "candidate_count": 0,
            "candidates": [],
            "split": None,
            "role_assignment": {"status": "unknown", "basis": None},
        },
        "dimensions": {
            "status": "unknown",
            "count": 0,
            "by_family": {},
            "items": [],
        },
        "fmfs": {
            "eligible": False,
            "reason": ["gt_unavailable"],
            "prompt_consistent": False,
            "gt_consistent": False,
            "fully_derivable": False,
            "item_count": 0,
            "items": [],
        },
        "parameters": extract_prompt_parameters(_user_prompt(row)),
        "eligibility": {},
        "audit_flags": [],
    }


def _resolve_gt_path(row: Mapping[str, Any], dataset_path: Path | None) -> Path | None:
    raw = row.get("gt_dxf")
    if not raw:
        return None
    path = Path(str(raw)).expanduser()
    if not path.is_absolute() and dataset_path is not None:
        path = dataset_path.parent / path
    return path.resolve()


def build_sidecar_row(
    row: Mapping[str, Any], dataset_path: str | Path | None = None
) -> dict[str, Any]:
    """Build one sidecar row without executing any generated model code."""

    part_id = str(row.get("id", "")).strip()
    if not part_id:
        raise SidecarError("dataset row is missing a non-empty id")
    source_path = Path(dataset_path).resolve() if dataset_path is not None else None
    gt_path = _resolve_gt_path(row, source_path)
    output = _empty_row(row, gt_path)
    flags = output["audit_flags"]
    prompt = _user_prompt(row)
    output["source"] = {
        "dataset": str(source_path) if source_path is not None else None,
        "prompt_sha256": _text_sha256(prompt),
        "image_basenames": [
            Path(str(image).replace("\\", "/")).name
            for image in (
                [row.get("images")]
                if isinstance(row.get("images"), str)
                else row.get("images", [])
            )
        ],
    }
    if output["category"] is None:
        _audit(flags, "missing_category", "warning", "sample", "Category is missing.")
    if output["tier"] is None:
        _audit(flags, "missing_tier", "warning", "sample", "Tier is missing.")
    if not prompt:
        _audit(
            flags,
            "missing_unique_user_prompt",
            "warning",
            "sample",
            "Expected exactly one string-valued user message.",
        )
    if gt_path is None:
        _audit(
            flags,
            "missing_gt_dxf_path",
            "error",
            "dxf",
            "Dataset row has no GT DXF path.",
        )
        output["eligibility"] = _eligibility(output)
        return output
    if not gt_path.is_file() or gt_path.stat().st_size <= 0:
        _audit(
            flags,
            "missing_or_empty_gt_dxf",
            "error",
            "dxf",
            "GT DXF is missing or empty.",
            path=str(gt_path),
        )
        output["eligibility"] = _eligibility(output)
        return output

    output["gt_dxf_sha256"] = _sha256(gt_path)
    output["gt_dxf_bytes"] = gt_path.stat().st_size
    try:
        doc = ezdxf.readfile(str(gt_path))
    except Exception as error:
        _audit(
            flags,
            "unreadable_gt_dxf",
            "error",
            "dxf",
            "ezdxf could not read the GT file.",
            error=f"{type(error).__name__}: {error}",
        )
        output["eligibility"] = _eligibility(output)
        return output

    extracted = _extract_dxf(doc, flags)
    output["drawing"] = {
        "dxfversion": str(doc.dxfversion),
        "insertion_units_code": int(doc.header.get("$INSUNITS", 0) or 0),
    }
    output["entities"] = {
        key: extracted[key]
        for key in (
            "modelspace_entity_count",
            "by_type",
            "view_geometry_by_type",
            "unsupported_by_type",
            "items",
        )
    }
    output["layers"] = extracted["layers"]
    output["views"] = detect_view_candidates(extracted["geometry_records"], flags)
    _attach_dimensions_to_views(extracted["dimension_items"], output["views"])
    output["dimensions"] = _dimension_manifest(extracted["dimension_items"], flags)
    _crosscheck_parameters(output["parameters"], output["dimensions"], flags)
    output["fmfs"] = _fmfs_manifest(output["parameters"], output["dimensions"])
    output["eligibility"] = _eligibility(output)
    return output


def _eligibility(row: Mapping[str, Any]) -> dict[str, Any]:
    flags = row.get("audit_flags", [])
    fatal_codes = sorted(
        flag["code"] for flag in flags if flag.get("severity") == "error"
    )
    unsupported = bool(row.get("entities", {}).get("unsupported_by_type"))
    view_regions = row.get("views", {}).get("status") == "ok"
    dimensions = row.get("dimensions", {})
    parameters = row.get("parameters", {})
    fmfs = row.get("fmfs", {})
    return {
        "inventory": not fatal_codes,
        "view_geometry": not fatal_codes and not unsupported,
        "view_regions": view_regions,
        # Roles and physical feature bindings are intentionally not certified by
        # this first sidecar version.  Downstream code must not mistake hints for GT.
        "view_roles": False,
        "native_dimensions": bool(dimensions.get("count")) and not fatal_codes,
        "dimension_value_inventory": bool(dimensions.get("numeric_display_count")),
        "prompt_parameter_candidates": bool(parameters.get("candidate_count")),
        "parameter_value_crosscheck": parameters.get("value_crosscheck_status") == "ok",
        "fmfs": bool(fmfs.get("eligible")),
        "physical_parameter_binding": False,
        "automatic_v5_reward": False,
        "fatal_reason_codes": fatal_codes,
        "notes": (
            "automatic_v5_reward stays false until view-role convention and "
            "feature/parameter bindings have been audited."
        ),
    }


def _validate_loaded_row(row: Any, path: Path, line_number: int) -> dict[str, Any]:
    if not isinstance(row, dict):
        raise SidecarError(f"{path}:{line_number}: expected a JSON object")
    missing = [field for field in REQUIRED_TOP_LEVEL_FIELDS if field not in row]
    if missing:
        raise SidecarError(f"{path}:{line_number}: missing fields {missing}")
    if row["schema_version"] != SCHEMA_VERSION:
        raise SidecarError(
            f"{path}:{line_number}: unsupported schema {row['schema_version']!r}"
        )
    part_id = str(row.get("id", "")).strip()
    if not part_id:
        raise SidecarError(f"{path}:{line_number}: missing id")
    fmfs = row.get("fmfs")
    eligibility = row.get("eligibility")
    if not isinstance(fmfs, dict) or not isinstance(eligibility, dict):
        raise SidecarError(f"{path}:{line_number}: missing fmfs/eligibility contract")
    items = fmfs.get("items")
    if not isinstance(items, list):
        raise SidecarError(f"{path}:{line_number}: fmfs.items must be a list")
    expected_derivable = bool(
        fmfs.get("prompt_consistent")
        and items
        and all(isinstance(item, dict) and item.get("derivable") for item in items)
    )
    if fmfs.get("fully_derivable") is not expected_derivable:
        raise SidecarError(
            f"{path}:{line_number}: stale/inconsistent fmfs.fully_derivable"
        )
    if bool(eligibility.get("fmfs")) != bool(fmfs.get("eligible")):
        raise SidecarError(
            f"{path}:{line_number}: eligibility.fmfs disagrees with fmfs.eligible"
        )
    row["id"] = part_id
    return row


def load_sidecar_jsonl(path: str | Path) -> dict[str, dict[str, Any]]:
    """Load a sidecar by ID, rejecting schema drift and duplicate identities."""

    source = Path(path)
    rows: dict[str, dict[str, Any]] = {}
    with source.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 SidecarError(f"{source}:{line_number}: {error}") from error
            row = _validate_loaded_row(decoded, source, line_number)
            if row["id"] in rows:
                raise SidecarError(f"{source}:{line_number}: duplicate id {row['id']}")
            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,
    output_path: str | Path,
    *,
    limit: int | None = None,
    strict: bool = False,
) -> dict[str, Any]:
    """Build and atomically write sidecars for a JSONL dataset."""

    source = Path(dataset_path).resolve()
    destination = Path(output_path).resolve()
    if limit is not None and limit < 0:
        raise SidecarError("limit must be non-negative")
    outputs: list[dict[str, Any]] = []
    seen: set[str] = set()
    with source.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            if limit is not None and len(outputs) >= limit:
                break
            try:
                row = json.loads(line)
            except json.JSONDecodeError as error:
                raise SidecarError(f"{source}:{line_number}: {error}") from error
            if not isinstance(row, dict):
                raise SidecarError(f"{source}:{line_number}: expected a JSON object")
            part_id = str(row.get("id", "")).strip()
            if not part_id:
                raise SidecarError(f"{source}:{line_number}: missing id")
            if part_id in seen:
                raise SidecarError(f"{source}:{line_number}: duplicate id {part_id}")
            seen.add(part_id)
            sidecar = build_sidecar_row(row, source)
            if strict:
                fatal = sidecar["eligibility"]["fatal_reason_codes"]
                if fatal:
                    raise SidecarError(
                        f"{source}:{line_number}:{part_id}: structural failures {fatal}"
                    )
            outputs.append(sidecar)

    _atomic_jsonl(destination, outputs)
    status_counts = Counter(row["views"]["status"] for row in outputs)
    fmfs_counts = Counter(
        "eligible" if row.get("fmfs", {}).get("eligible") else "ineligible"
        for row in outputs
    )
    flag_counts = Counter(
        flag["code"] for row in outputs for flag in row.get("audit_flags", [])
    )
    summary = {
        "schema_version": SCHEMA_VERSION,
        "dataset": str(source),
        "dataset_sha256": _sha256(source),
        "output": str(destination),
        "output_sha256": _sha256(destination),
        "count": len(outputs),
        "strict": bool(strict),
        "limit": limit,
        "view_status_counts": dict(sorted(status_counts.items())),
        "fmfs_eligibility_counts": dict(sorted(fmfs_counts.items())),
        "audit_flag_counts": dict(sorted(flag_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("--out", type=Path, required=True)
    parser.add_argument("--limit", type=int)
    parser.add_argument(
        "--strict",
        action="store_true",
        help="abort on structural GT failures; needs_audit remains allowed",
    )
    args = parser.parse_args(argv)
    summary = build_sidecar_dataset(
        args.dataset, args.out, limit=args.limit, strict=args.strict
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


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