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
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
#!/usr/bin/env python3
"""Build the public [[210,10,16]] release from sealed Stage 3 artifacts.

This release-specific builder intentionally fails closed.  It accepts only the
audited candidate, source commit, aggregate, and terminal checkpoints named
below.  Operational paths, process metadata, commands, and raw logs are not
copied into the public records.
"""

from __future__ import annotations

import argparse
import gzip
import hashlib
import io
import json
import subprocess
import sys
from pathlib import Path
from typing import Any


CANDIDATE_ID = "5f773fbfbce9775bc30b"
CANONICAL_DIGEST = (
    "4ba2bcc894b883eb930bf727148c2f57bcf4963c903a940528613b2f542a607c"
)
STATE_KEY = (
    "2975b8ebd74a3842501a042746bf7877ca11d0326841d3ee4238a6724d0da26e"
)
QCODE_COMMIT = "ade9dc706a455427384e4ba82c0981d9cc9f6671"
HF_BASE_COMMIT = "3a24375d3494479c76ecd7c377c9b5d038f2561b"

EXPECTED_SOURCE_SHA256 = {
    "stage3-summary.json": (
        "4579c4472879e78da8a77b66e240b6e2ea66a1d47ca782f889247b3186b0a5ab"
    ),
    "stage3-ranked.jsonl": (
        "b8a0f2a7dd4191dd6d578addaec67cee60786104a748dd78203a822e196e3129"
    ),
    "stage3-thresholds.jsonl": (
        "1c3a4bcf0a4598fc7c91236c01513f375746ba0d8c635d88630800be9f5bfcd6"
    ),
    "aggregate": (
        "ee2965586cff334caf22d1c0b360127c22cca34c5136f58c88cdd150a5ffeefd"
    ),
    "lower-terminal": (
        "9def4c1d0134165bbf3166382d8b07b361b816504e00e2473615fe9c45a26218"
    ),
    "upper-terminal": (
        "f1fe9686eaac799ecf4583d48fe39858381b29e7a47844af5c447e6e21ebc86e"
    ),
}

DISTQLDPC_BINARY_SHA256 = (
    "9e09c544d5151d872dc1037dcb1440509e27b8b485a7f9ea5a15d6e55b36d3fa"
)
DISTQLDPC_SOURCE_COMMIT = (
    "c01fa93eb5e1e62948e4861e2c164a6b64fe88eb"
)

EXPECTED_TYPED_CLAIM_SHA256 = (
    "1a2a076a891a790a92359d903f7874f989d12a2f684518fd227923bbe7f0c2c9"
)
EXPECTED_TYPED_REQUEST_SHA256 = (
    "ce20b44a85b000cf59b24fa4fa69196ccd596ba3d42c78ab325bad1fac99caad"
)
EXPECTED_TYPED_ARTIFACT_SHA256 = (
    "ed3f639b3b7254566b248e3314dcca9aed82a8a91f0465a61d920571b2c9c6d3"
)
RAW_LOWER_EVIDENCE_SHA256 = (
    "75ac260531dba3618c14fb459e86e2e8bfe39d205a1705da61d516528d0db581"
)
RESUMED_LOWER_EVIDENCE_SHA256 = (
    "fb0bb3fc7b3dc6312952ad7ba9d324346ebd16db35e59e3b894ae3c0f70d489e"
)
RAW_UPPER_EVIDENCE_SHA256 = (
    "8da3a1ee2523a0e7e4c4e21a627c8a780d8160cd09d9beb5130044cd8936fdbe"
)
RESUMED_UPPER_EVIDENCE_SHA256 = (
    "d637b58008f17e1380fb1a3ed6f262b4183b7e19f4c420555d89df0c33340d5b"
)
KNOWN_ANSWER_GATE_SHA256 = (
    "7adf6f4a93cb321fa0501cbb62723370cdbc3a85db7d9e2565cc086ea6a00687"
)
KNOWN_ANSWER_TRUST_SHA256 = (
    "1e67120095a358bbcb2166a6804479655dc3bdd8b36c4d12bc56f73d5e741140"
)
REGISTRY_FILE_SHA256 = (
    "265f1a3fefef884adeaa980a5dce2441dee4f6f6d71c253ba7a6491360733689"
)
REGISTRY_INTERNAL_SHA256 = (
    "536c733d68d344ed9fef9992bbeb1000900174ad0c500ddb7004126ae5c98408"
)
EXPECTED_MATRIX_RECORDS = {
    "hx": {
        "content_sha256": "3e84de485357b46239174805f8fc3378eeb0e4207a06fc3a95568e5630c58c8e",
        "file_sha256": "a8d53c3e14419e0b0c30e2960621394475e06d0cff30a6c1f0c9635c8f5bf9ea",
    },
    "hz": {
        "content_sha256": "21b89580009d0ce19cab3c537ddc53c0211a962d88e4aaa1cf3b9a6752d502ab",
        "file_sha256": "fae00c16429f8312a9a5f1c8e7f025431f986ac8dcc13a433887111f5503baa4",
    },
}
MUTABLE_BASE_FILES = frozenset(
    {
        "README.md",
        "THIRD_PARTY_NOTICES.md",
        "docs/REPRODUCE.md",
        "docs/SCHEMA.md",
        "docs/STAGE3_TYPED_EXACT_FOM_GT_12.md",
        "data/stage3_typed_exact_fom_gt_12.jsonl",
        "evidence/stage3_typed_exact_matrix_index.jsonl",
        "evidence/stage3_typed_exact_proofs.jsonl",
        "manifests/stage3_typed_exact_fom_gt_12.json",
        "scripts/build_exact_fom_gt_12_release.py",
        "scripts/verify_stage3_typed_exact_fom_gt_12.py",
        "scripts/verify_dataset.py",
    }
)
LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1\n"


def sha256_bytes(value: bytes) -> str:
    return hashlib.sha256(value).hexdigest()


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


def canonical_sha256(value: dict[str, Any], omitted: str) -> str:
    payload = {key: item for key, item in value.items() if key != omitted}
    encoded = json.dumps(
        payload,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
        allow_nan=False,
    ).encode()
    return sha256_bytes(encoded)


def canonical_value_sha256(value: Any) -> str:
    encoded = json.dumps(
        value,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
        allow_nan=False,
    ).encode()
    return sha256_bytes(encoded)


def load_json(path: Path) -> dict[str, Any]:
    value = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(f"expected one JSON object: {path}")
    return value


def verify_materialized_base(root: Path) -> None:
    sums_path = root / "manifests" / "SHA256SUMS"
    for line in sums_path.read_text(encoding="utf-8").splitlines():
        if not line:
            continue
        expected, relative = line.split("  ", 1)
        path = root / relative
        if not path.is_file():
            raise ValueError(f"missing base release file: {relative}")
        if path.read_bytes()[: len(LFS_POINTER_PREFIX)] == LFS_POINTER_PREFIX:
            raise ValueError(
                f"Git LFS object is not materialized: {relative}; run git lfs pull"
            )
        if relative not in MUTABLE_BASE_FILES:
            observed = sha256_file(path)
            if observed != expected:
                raise ValueError(f"sealed base file changed: {relative}")


def git_head(root: Path) -> str:
    return subprocess.check_output(
        ["git", "-C", str(root), "rev-parse", "HEAD"],
        text=True,
    ).strip()


def gf2_rank(matrix: Any) -> int:
    rows = [
        sum((int(bit) & 1) << col for col, bit in enumerate(row))
        for row in matrix.tolist()
    ]
    rank = 0
    while rows:
        pivot = max(rows)
        if not pivot:
            break
        bit = 1 << (pivot.bit_length() - 1)
        rank += 1
        rows = [
            value ^ pivot if value & bit else value
            for value in rows
            if value != pivot
        ]
    return rank


def content_sha256(matrix: Any) -> str:
    shape = [int(matrix.shape[0]), int(matrix.shape[1])]
    header = json.dumps(
        {"dtype": "uint8-gf2", "shape": shape},
        sort_keys=True,
        separators=(",", ":"),
    )
    return sha256_bytes(header.encode() + b"\n" + matrix.tobytes(order="C"))


def dist_array_sha256(name: str, matrix: Any) -> str:
    digest = hashlib.sha256()
    digest.update(name.encode())
    digest.update(b"\0")
    digest.update(json.dumps(list(matrix.shape), separators=(",", ":")).encode())
    digest.update(b"\0")
    digest.update(matrix.tobytes(order="C"))
    return digest.hexdigest()


def matrix_market_gzip(name: str, matrix: Any) -> bytes:
    rows, cols = map(int, matrix.shape)
    entries = [
        f"{row + 1} {col + 1} 1\n"
        for row in range(rows)
        for col in range(cols)
        if int(matrix[row, col]) & 1
    ]
    body = (
        "%%MatrixMarket matrix coordinate integer general\n"
        f"% qcode candidate {CANDIDATE_ID} {name}; entries are GF(2)\n"
        f"{rows} {cols} {len(entries)}\n"
        + "".join(entries)
    ).encode("ascii")
    output = io.BytesIO()
    with gzip.GzipFile(
        filename="",
        mode="wb",
        fileobj=output,
        compresslevel=9,
        mtime=0,
    ) as handle:
        handle.write(body)
    return output.getvalue()


def matrix_record(root: Path, name: str, matrix: Any) -> dict[str, Any]:
    relative = Path("matrices") / CANDIDATE_ID / f"{name}.mtx.gz"
    path = root / relative
    path.parent.mkdir(parents=True, exist_ok=True)
    payload = matrix_market_gzip(name, matrix)
    path.write_bytes(payload)
    return {
        "path": relative.as_posix(),
        "shape": [int(matrix.shape[0]), int(matrix.shape[1])],
        "file_sha256": sha256_bytes(payload),
        "content_sha256": content_sha256(matrix),
    }


def write_jsonl_one(path: Path, value: dict[str, Any]) -> None:
    payload = json.dumps(
        value,
        sort_keys=True,
        separators=(",", ":"),
        ensure_ascii=False,
        allow_nan=False,
    ) + "\n"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(payload, encoding="utf-8")


def source_paths(run: Path) -> dict[str, Path]:
    unit_dir = (
        run
        / "solver-state"
        / "sat-sectors"
        / "sat-units"
        / STATE_KEY
    )
    return {
        "stage3-summary.json": run / "stage3-summary.json",
        "stage3-ranked.jsonl": run / "stage3-ranked.jsonl",
        "stage3-thresholds.jsonl": run / "stage3-thresholds.jsonl",
        "aggregate": run / "solver-state" / "sat-sectors" / f"{STATE_KEY}.json",
        "lower-terminal": unit_dir / "lower-distqldpc-mto-XZ-global.json",
        "upper-terminal": unit_dir / "upper-X-global.json",
    }


def build(root: Path, source_run: Path, qcode_root: Path) -> None:
    root = root.resolve(strict=True)
    source_run = source_run.resolve(strict=True)
    qcode_root = qcode_root.resolve(strict=True)
    verify_materialized_base(root)
    if git_head(root) != HF_BASE_COMMIT:
        raise ValueError("Hugging Face release base commit changed")
    if git_head(qcode_root) != QCODE_COMMIT:
        raise ValueError("qcode source commit changed")
    if subprocess.check_output(
        [
            "git", "-C", str(qcode_root), "status", "--porcelain",
            "--untracked-files=no",
        ],
        text=True,
    ).strip():
        raise ValueError("qcode source tree has tracked modifications")
    if sha256_file(root / "reference/known_answer_gate.json") != KNOWN_ANSWER_GATE_SHA256:
        raise ValueError("known-answer gate changed")
    if sha256_file(root / "reference/known_answer_trust.json") != KNOWN_ANSWER_TRUST_SHA256:
        raise ValueError("known-answer trust record changed")
    registry_path = qcode_root / "results" / "known_code_registry.json"
    if sha256_file(registry_path) != REGISTRY_FILE_SHA256:
        raise ValueError("known-code registry file changed")
    registry = load_json(registry_path)
    if registry.get("registry_sha256") != REGISTRY_INTERNAL_SHA256:
        raise ValueError("known-code registry internal seal changed")
    paths = source_paths(source_run)
    for label, path in paths.items():
        observed = sha256_file(path)
        if observed != EXPECTED_SOURCE_SHA256[label]:
            raise ValueError(f"unexpected {label} SHA256: {observed}")

    sys.path.insert(0, str(qcode_root))
    import numpy as np
    from evaluation.bb_code import build_bb_code
    from evaluation.distance_distqldpc import (
        verify_distqldpc_exact_evidence,
        verify_distqldpc_lower_evidence,
    )
    from evaluation.distance_milp import get_code_matrices
    from evaluation.sector_certificate import (
        REQUEST_FIELD,
        claim_from_sector_sat_artifact,
    )
    from humanize.state import code_key

    aggregate = load_json(paths["aggregate"])
    lower = load_json(paths["lower-terminal"])
    upper = load_json(paths["upper-terminal"])
    summary = load_json(paths["stage3-summary.json"])
    candidate = aggregate["candidate"]

    if aggregate.get("status") != "EXACT_PROVEN":
        raise ValueError("source aggregate is not EXACT_PROVEN")
    if aggregate.get("artifact_sha256") != (
        "fa03b3a2a8f43d77131c8a5491efbb56d98800d9e215b45e9e5b3e7f86509159"
    ):
        raise ValueError("source aggregate canonical seal changed")
    if candidate.get("canonical_digest") != CANONICAL_DIGEST:
        raise ValueError("source candidate digest changed")
    if code_key(candidate) != CANDIDATE_ID:
        raise ValueError("candidate_id no longer matches humanize.state.code_key")
    if summary.get("status_counts") != {"EXACT_PROVEN": 1}:
        raise ValueError("Stage 3 summary is not the accepted one-result handoff")
    summary_expected = {
        "schema_version": 1,
        "gate": "qldpc-direction-candidate-pool",
        "target_mode": "scalar-fom-inclusive-v1",
        "backend": "sat-sectors",
        "input_rows": 4096,
        "selected_candidates": 1,
        "malformed_unresolved_rows": 0,
        "duplicate_digests_skipped": 0,
        "unselected_unresolved_candidates": 0,
        "selection_exhausted": True,
        "threshold_only": False,
        "status_counts": {"EXACT_PROVEN": 1},
        "retry_required": False,
        "retry_reasons": {
            "unresolved_candidates": 0,
            "unselected_unresolved_candidates": 0,
            "operational_errors": 0,
        },
        "certify": False,
        "stage4_candidates": 1,
        "certified_wins": 0,
        "operational_errors": 0,
    }
    if any(summary.get(key) != value for key, value in summary_expected.items()):
        raise ValueError("Stage 3 summary fields changed")
    stage3_budget = summary["worker_budget"]["stage3"]
    if {
        "candidate_workers": stage3_budget.get("candidate_workers"),
        "direction_workers": stage3_budget.get("direction_workers"),
        "configured_solver_workers": stage3_budget.get("configured_solver_workers"),
        "admitted_solver_workers": stage3_budget.get("admitted_solver_workers"),
        "max_total_workers": summary["worker_budget"].get("max_total_workers"),
    } != {
        "candidate_workers": 1,
        "direction_workers": 2,
        "configured_solver_workers": 2,
        "admitted_solver_workers": 2,
        "max_total_workers": 2,
    }:
        raise ValueError("Stage 3 worker budget changed")
    wall = summary["hard_wall_budget"]
    if (
        float(wall.get("direction_timeout_s", -1)) != 21600.0
        or float(wall.get("candidate_timeout_s", -1)) != 134400.0
        or float(wall.get("termination_grace_s", -1)) != 600.0
    ):
        raise ValueError("Stage 3 hard-wall budget changed")
    results = summary.get("results")
    if (
        not isinstance(results, list)
        or len(results) != 1
        or results[0].get("canonical_digest") != CANONICAL_DIGEST
        or results[0].get("status") != "EXACT_PROVEN"
        or results[0].get("completed_proof_units") != 2
        or results[0].get("expected_proof_units") != 27
        or "error" in results[0]
        or "hard_wall" in results[0]
    ):
        raise ValueError("Stage 3 result summary changed")

    typed_claim = claim_from_sector_sat_artifact(aggregate)
    typed_request = typed_claim[REQUEST_FIELD]
    if canonical_value_sha256(typed_claim) != EXPECTED_TYPED_CLAIM_SHA256:
        raise ValueError("typed Stage 3 claim changed")
    if canonical_value_sha256(typed_request) != EXPECTED_TYPED_REQUEST_SHA256:
        raise ValueError("typed Stage 3 request changed")
    typed_expected = {
        "coverage_mode": "global",
        "requested_coverage_mode": "first-nonzero",
        "requested_lower_backend": "distqldpc",
        "lower_bound_backend": "distqldpc",
        "lower_bound_threshold": 15,
        "required_distance": 16,
        "stage3_status": "EXACT_PROVEN",
        "target_mode": "scalar-fom-inclusive-v1",
        "use_translation_anchors": True,
        "use_construction_anchors": False,
        "anchor_cover_cubes": None,
        "distqldpc_exact_distances": [16],
        "distqldpc_conflict": False,
        "distqldpc_conflict_details": None,
        "low_witnesses": [],
        "escalation_decisions": [],
        "stage3_artifact_sha256": EXPECTED_TYPED_ARTIFACT_SHA256,
    }
    if any(typed_request.get(key) != value for key, value in typed_expected.items()):
        raise ValueError("typed Stage 3 request semantics changed")
    if {
        "canonical_digest": typed_claim.get("canonical_digest"),
        "n": typed_claim.get("n"),
        "k": typed_claim.get("k"),
        "required_distance": typed_claim.get("required_distance"),
    } != {
        "canonical_digest": CANONICAL_DIGEST,
        "n": 210,
        "k": 10,
        "required_distance": 16,
    }:
        raise ValueError("typed Stage 3 claim parameters changed")
    typed_lower = typed_request["lower_bound_decisions"]
    typed_upper = typed_request["upper_witness"]
    if (
        len(typed_lower) != 1
        or typed_lower[0]["solver_evidence"]["evidence_sha256"]
        != RESUMED_LOWER_EVIDENCE_SHA256
        or typed_lower[0]["solver_evidence"]["exact_distance"] != 16
        or typed_upper["solver_evidence"]["evidence_sha256"]
        != RESUMED_UPPER_EVIDENCE_SHA256
        or typed_upper["solver_evidence"]["objective"] != 16
    ):
        raise ValueError("typed Stage 3 evidence identities changed")
    if lower.get("evidence_sha256") != RAW_LOWER_EVIDENCE_SHA256:
        raise ValueError("raw lower terminal evidence changed")
    if upper.get("evidence_sha256") != RAW_UPPER_EVIDENCE_SHA256:
        raise ValueError("raw upper terminal evidence changed")
    aggregate_expected = {
        "coverage_mode": "global",
        "requested_coverage_mode": "first-nonzero",
        "requested_lower_backend": "distqldpc",
        "lower_bound_backend": "distqldpc",
        "lower_bound_threshold": 15,
        "expected_units": 27,
        "attempted_units": 23,
        "terminal_units": 2,
        "retryable_units": 21,
        "expected_directions": 27,
        "completed_directions": 2,
        "expected_lower_decisions": 1,
        "completed_lower_decisions": 1,
        "expected_lower_partitions": 1,
        "completed_lower_partitions": 1,
        "upper_unsat_decisions": [],
        "threshold_only": False,
        "distqldpc_exact_distances": [16],
        "distqldpc_conflict": False,
        "distqldpc_conflict_details": None,
        "low_witnesses": [],
    }
    if any(aggregate.get(key) != value for key, value in aggregate_expected.items()):
        raise ValueError("Stage 3 aggregate terminal state changed")

    code = build_bb_code(
        21,
        5,
        [(7, 3), (18, 4), (20, 0)],
        [(2, 3), (18, 1), (19, 2)],
        geometry={"schema_version": 1, "family": "twisted_torus", "twist": 3},
    )
    hx, hz, lx, lz = (
        np.ascontiguousarray(np.asarray(value, dtype=np.uint8) & 1)
        for value in get_code_matrices(code)
    )
    gx, gz = lz, lx
    matrices = {"Hx": hx, "Hz": hz, "Gx": gx, "Gz": gz}
    expected_dist_hashes = lower["instance"]["matrix_files"]
    for name, matrix in matrices.items():
        if dist_array_sha256(name, matrix) != expected_dist_hashes[name]["array_sha256"]:
            raise ValueError(f"{name} does not match the sealed solver instance")
    checkpoint_identity = lower["instance"]["checkpoint_identity"]
    verifier_args = {
        "max_weight": 15,
        "cardinality_mode": "mto",
        "expected_checkpoint_identity": checkpoint_identity,
        "expected_binary_sha256": DISTQLDPC_BINARY_SHA256,
        "expected_source_commit": DISTQLDPC_SOURCE_COMMIT,
    }
    exact_failures = verify_distqldpc_exact_evidence(
        lower, hx, hz, lx, lz, **verifier_args
    )
    lower_failures = verify_distqldpc_lower_evidence(
        lower, hx, hz, lx, lz, **verifier_args
    )
    if exact_failures or lower_failures:
        raise ValueError(
            f"raw DistQLDPC terminal replay failed: {exact_failures}; "
            f"{lower_failures}"
        )
    for name in ("Hx", "Hz"):
        matrix = matrices[name]
        generated = {
            "content_sha256": content_sha256(matrix),
            "file_sha256": sha256_bytes(matrix_market_gzip(name, matrix)),
        }
        if generated != EXPECTED_MATRIX_RECORDS[name.lower()]:
            raise ValueError(f"deterministic {name} public matrix changed")

    rank_x, rank_z = gf2_rank(hx), gf2_rank(hz)
    if (rank_x, rank_z) != (100, 100):
        raise ValueError("unexpected check ranks")
    if np.any((hx @ hz.T) & 1):
        raise ValueError("CSS checks do not commute")
    if np.any((hx @ gx.T) & 1) or np.any((hz @ gz.T) & 1):
        raise ValueError("logical representatives do not commute with checks")
    if not np.array_equal((gz @ gx.T) & 1, np.eye(10, dtype=np.uint8)):
        raise ValueError("logical representatives fail duality")

    packed = bytes.fromhex(upper["operator"]["packed_hex"])
    operator = np.unpackbits(
        np.frombuffer(packed, dtype=np.uint8), bitorder="little"
    )[:210].astype(np.uint8)
    if int(operator.sum()) != 16 or np.any((hz @ operator) & 1):
        raise ValueError("upper witness is invalid")
    syndrome = ((gx @ operator) & 1).astype(int).tolist()
    if syndrome != upper["logical_syndrome"] or not any(syndrome):
        raise ValueError("upper witness is not a nontrivial X logical")

    checks = {
        "css_commutation": True,
        "commutation_violations": 0,
        "rank_x": rank_x,
        "rank_z": rank_z,
        "k_recomputed": 210 - rank_x - rank_z,
        "max_check_weight": max(
            max(map(int, hx.sum(axis=1))),
            max(map(int, hz.sum(axis=1))),
        ),
        "max_sector_qubit_degree": max(
            max(map(int, hx.sum(axis=0))),
            max(map(int, hz.sum(axis=0))),
        ),
        "max_qubit_degree": max(map(int, hx.sum(axis=0) + hz.sum(axis=0))),
        "logical_basis_complete": True,
        "logical_duality": True,
    }
    if checks != {
        "css_commutation": True,
        "commutation_violations": 0,
        "rank_x": 100,
        "rank_z": 100,
        "k_recomputed": 10,
        "max_check_weight": 6,
        "max_sector_qubit_degree": 3,
        "max_qubit_degree": 6,
        "logical_basis_complete": True,
        "logical_duality": True,
    }:
        raise ValueError(f"unexpected matrix checks: {checks}")

    matrix_records = {
        name.lower(): matrix_record(root, name, matrix)
        for name, matrix in matrices.items()
    }

    public_source = {
        "qcode_commit": QCODE_COMMIT,
        "stage3_aggregate_byte_sha256": EXPECTED_SOURCE_SHA256["aggregate"],
        "stage3_aggregate_self_seal_sha256": aggregate["artifact_sha256"],
        "stage3_typed_request_artifact_sha256": EXPECTED_TYPED_ARTIFACT_SHA256,
        "stage3_typed_claim_sha256": EXPECTED_TYPED_CLAIM_SHA256,
        "stage3_typed_request_sha256": EXPECTED_TYPED_REQUEST_SHA256,
        "stage3_lower_terminal_byte_sha256": EXPECTED_SOURCE_SHA256["lower-terminal"],
        "stage3_lower_raw_terminal_evidence_sha256": RAW_LOWER_EVIDENCE_SHA256,
        "stage3_lower_resumed_evidence_sha256": RESUMED_LOWER_EVIDENCE_SHA256,
        "stage3_upper_terminal_byte_sha256": EXPECTED_SOURCE_SHA256["upper-terminal"],
        "stage3_upper_raw_terminal_evidence_sha256": RAW_UPPER_EVIDENCE_SHA256,
        "stage3_upper_resumed_evidence_sha256": RESUMED_UPPER_EVIDENCE_SHA256,
        "stage3_summary_byte_sha256": EXPECTED_SOURCE_SHA256["stage3-summary.json"],
        "stage3_ranked_byte_sha256": EXPECTED_SOURCE_SHA256["stage3-ranked.jsonl"],
        "stage3_threshold_byte_sha256": EXPECTED_SOURCE_SHA256["stage3-thresholds.jsonl"],
        "known_answer_gate_sha256": KNOWN_ANSWER_GATE_SHA256,
        "known_answer_trust_sha256": KNOWN_ANSWER_TRUST_SHA256,
    }
    construction = {
        "family": "css-bb",
        "representation_id": "css-bb-twisted-torus-generator-v1",
        "ell": 21,
        "m": 5,
        "geometry": {"schema_version": 1, "family": "twisted_torus", "twist": 3},
        "A_terms": [[7, 3], [18, 4], [20, 0]],
        "B_terms": [[2, 3], [18, 1], [19, 2]],
    }
    record: dict[str, Any] = {
        "schema_version": 1,
        "record_kind": "stage3_typed_exact_fom_gt_12",
        "evidence_class": "STAGE3_TYPED_EXACT_PENDING_STRICT_GATE",
        "source_stage": "stage3_direction_audit",
        "source_status": "EXACT_PROVEN",
        "release_status": "PENDING_STAGE4_STAGE5",
        "candidate_id": CANDIDATE_ID,
        "canonical_digest": CANONICAL_DIGEST,
        "code": "[[210,10,16]]",
        "construction": construction,
        "parameters": {"n": 210, "k": 10},
        "distance": {
            "status": "EXACT_PROVEN",
            "exact": 16,
            "lower_bound": 16,
            "upper_bound": 16,
            "lower_bound_backend": "DistQLDPC/MaxCDCL",
            "upper_bound_backend": "python-sat/cadical195",
        },
        "fom": {
            "exact": {
                "numerator": 256,
                "denominator": 21,
                "decimal": 256 / 21,
            },
            "excess_over_12": {
                "numerator": 4,
                "denominator": 21,
                "decimal": 4 / 21,
            },
            "strict_integer_margin": 40,
        },
        "target": {
            "strict_predicate": "k*d*d > 12*n",
            "required_distance": 16,
            "left_hand_side": 2560,
            "right_hand_side": 2520,
            "passes_strict_target": True,
            "certified_win": False,
        },
        "source_target": {
            "mode": candidate["target"]["mode"],
            "strict": candidate["target"]["strict"],
            "binding_sha256": candidate["target"]["binding_sha256"],
            "required_distance": candidate["target"]["required_distance"],
        },
        "matrices": matrix_records,
        "matrix_checks": checks,
        "novelty": {
            "status": candidate["novelty"]["status"],
            "novel": candidate["novelty"]["novel"],
            "registry_version": candidate["novelty"]["registry_version"],
            "registry_file_sha256": REGISTRY_FILE_SHA256,
            "registry_internal_sha256": REGISTRY_INTERNAL_SHA256,
            "matched_entries": candidate["novelty"]["matched_entries"],
            "source_stage3_replayed": candidate["novelty"]["replayed_from_construction"],
            "release_current_registry_replayed": False,
            "scope": "pinned known-code registry with explicit construction/matrix replay",
        },
        "known_answer_context": {
            "gate_file_sha256": KNOWN_ANSWER_GATE_SHA256,
            "trust_file_sha256": KNOWN_ANSWER_TRUST_SHA256,
            "release_replayed": False,
        },
        "authority": {
            "stage3_typed_handoff_replay": True,
            "exact_under_pinned_solver_trust_model": True,
            "pipeline_stage4_certificate": False,
            "portable_unsat_proof_certificate": False,
            "pipeline_stage5_final_gate": False,
            "pipeline_promotion": False,
            "independent_release_gate_complete": False,
            "publication_certificate": False,
            "public_dataset_record": True,
        },
        "source": public_source,
    }
    record["record_sha256"] = canonical_sha256(record, "record_sha256")

    safe_backend = {
        "distribution": lower["backend"]["distribution"],
        "interface": lower["backend"]["interface"],
        "repository": lower["backend"]["repository"],
        "source_commit": lower["backend"]["source_commit"],
        "binary_sha256": lower["backend"]["binary_sha256"],
        "binary_size": lower["backend"]["file_size"],
        "identity_sha256": lower["backend"]["identity_sha256"],
    }
    if safe_backend["binary_sha256"] != DISTQLDPC_BINARY_SHA256:
        raise ValueError("DistQLDPC binary pin changed")
    if safe_backend["source_commit"] != DISTQLDPC_SOURCE_COMMIT:
        raise ValueError("DistQLDPC source pin changed")

    evidence: dict[str, Any] = {
        "schema_version": 1,
        "record_kind": "stage3_typed_exact_fom_gt_12_evidence",
        "evidence_class": "STAGE3_TYPED_EXACT_PENDING_STRICT_GATE",
        "source_status": "EXACT_PROVEN",
        "release_status": "PENDING_STAGE4_STAGE5",
        "authority": record["authority"],
        "candidate_id": CANDIDATE_ID,
        "canonical_digest": CANONICAL_DIGEST,
        "distance_claim": {
            "status": "EXACT_PROVEN",
            "exact": 16,
            "lower_bound": 16,
            "upper_bound": 16,
        },
        "stage3_typed_handoff": {
            "gate": aggregate["gate"],
            "status": aggregate["status"],
            "backend": aggregate["lower_bound_backend"],
            "lower_bound_threshold": aggregate["lower_bound_threshold"],
            "attempted_proof_units": aggregate["attempted_units"],
            "completed_proof_units": aggregate["terminal_units"],
            "expected_proof_units": aggregate["expected_units"],
            "source_retryable_units_at_terminal": aggregate["retryable_units"],
            "summary_retry_required": summary["retry_required"],
            "terminal_reason": "distqldpc_exact_plus_upper_witness",
            "distqldpc_exact_distances": aggregate["distqldpc_exact_distances"],
            "distqldpc_conflict": aggregate["distqldpc_conflict"],
            "distqldpc_conflict_details": aggregate["distqldpc_conflict_details"],
            "low_witnesses": aggregate["low_witnesses"],
            "typed_replay_verified": True,
            **public_source,
        },
        "lower_bound_evidence": {
            "evidence_kind": lower["evidence_kind"],
            "formulation": lower["formulation"],
            "outcome": lower["outcome"],
            "exact_distance": lower["exact_distance"],
            "lower_bound": lower["lower_bound"],
            "upper_bound": lower["upper_bound"],
            "threshold_infeasible": lower["threshold_infeasible"],
            "decision_complete": lower["decision_complete"],
            "retryable": lower["retryable"],
            "returncode": lower["returncode"],
            "timed_out": lower["timed_out"],
            "hard_timeout_s": lower["hard_timeout_s"],
            "elapsed_s": lower["elapsed_s"],
            "cardinality_mode": lower["instance"]["solver_execution"]["cardinality_mode"],
            "parsed_output": lower["parsed_output"],
            "stdout_sha256": lower["stdout_sha256"],
            "stderr_sha256": lower["stderr_sha256"],
            "raw_terminal_replay_verified": True,
            "raw_terminal_evidence_sha256": lower["evidence_sha256"],
            "aggregate_resumed_evidence_sha256": RESUMED_LOWER_EVIDENCE_SHA256,
            "terminal_file_sha256": EXPECTED_SOURCE_SHA256["lower-terminal"],
            "instance_binding_sha256": lower["instance"]["binding_sha256"],
            "checkpoint_identity": checkpoint_identity,
            "logical_detector": lower["instance"]["logical_detector"],
            "solver_instance_array_sha256": {
                name: expected_dist_hashes[name]["array_sha256"]
                for name in ("Hx", "Hz", "Gx", "Gz")
            },
            "runtime_source": lower["instance"]["solver_execution"]["runtime_source"],
            "backend": safe_backend,
        },
        "upper_bound_evidence": {
            "evidence_kind": upper["evidence_kind"],
            "formulation": upper["formulation"],
            "outcome": upper["outcome"],
            "sector": upper["sector"],
            "objective": upper["objective"],
            "decision_complete": upper["decision_complete"],
            "retryable": upper["retryable"],
            "anchor_indices": upper["anchor_indices"],
            "operator": upper["operator"],
            "logical_syndrome": upper["logical_syndrome"],
            "backend": upper["backend"],
            "cnf": upper["cnf"],
            "raw_terminal_evidence_sha256": upper["evidence_sha256"],
            "aggregate_resumed_evidence_sha256": RESUMED_UPPER_EVIDENCE_SHA256,
            "terminal_file_sha256": EXPECTED_SOURCE_SHA256["upper-terminal"],
            "instance_binding_sha256": upper["instance"]["binding_sha256"],
        },
        "symmetry": {
            "translation_verified": aggregate["translation_symmetry"]["verified"],
            "orbit_representatives": aggregate["translation_symmetry"]["orbit_representatives"],
            "xz_sector_isometry_verified": aggregate["xz_sector_isometry"]["verified"],
            "xz_sector_isometry_sha256": aggregate["xz_sector_isometry"]["report_sha256"],
            "covered_sectors": aggregate["xz_sector_isometry"]["covered_sectors"],
        },
        "limitations": {
            "portable_unsat_certificate": (
                "Not available. The lower bound is a replay-bound result under the "
                "pinned DistQLDPC/MaxCDCL binary and runtime trust model."
            ),
            "independent_checks": (
                "The public verifier reconstructs Hx/Hz, checks CSS ranks and "
                "commutation, validates the complete logical basis, and replays "
                "the weight-16 upper witness. It cannot independently certify "
                "the solver-derived lower bound without a portable proof trace."
            ),
        },
    }
    evidence["evidence_sha256"] = canonical_sha256(evidence, "evidence_sha256")

    data_path = root / "data" / "stage3_typed_exact_fom_gt_12.jsonl"
    evidence_path = root / "evidence" / "stage3_typed_exact_proofs.jsonl"
    write_jsonl_one(data_path, record)
    write_jsonl_one(evidence_path, evidence)

    matrix_index = {
        "schema_version": 1,
        "record_kind": "stage3_typed_exact_matrix_index",
        "candidate_id": CANDIDATE_ID,
        "canonical_digest": CANONICAL_DIGEST,
        "n": 210,
        "k": 10,
        "matrices": matrix_records,
    }
    matrix_index["record_sha256"] = canonical_sha256(
        matrix_index, "record_sha256"
    )
    matrix_index_path = (
        root / "evidence" / "stage3_typed_exact_matrix_index.jsonl"
    )
    write_jsonl_one(matrix_index_path, matrix_index)

    release_files = [
        "README.md",
        "THIRD_PARTY_NOTICES.md",
        "docs/REPRODUCE.md",
        "docs/SCHEMA.md",
        "data/stage3_typed_exact_fom_gt_12.jsonl",
        "evidence/stage3_typed_exact_proofs.jsonl",
        "evidence/stage3_typed_exact_matrix_index.jsonl",
        *[matrix_records[name]["path"] for name in ("hx", "hz", "gx", "gz")],
        "docs/STAGE3_TYPED_EXACT_FOM_GT_12.md",
        "scripts/verify_dataset.py",
        "scripts/verify_stage3_typed_exact_fom_gt_12.py",
        "scripts/build_exact_fom_gt_12_release.py",
    ]
    manifest: dict[str, Any] = {
        "schema_version": 1,
        "gate": "qcode-public-stage3-typed-exact-fom-gt-12-v1",
        "status": "STAGE3_TYPED_EXACT_PENDING_STRICT_GATE",
        "source_status": "EXACT_PROVEN",
        "release_status": "PENDING_STAGE4_STAGE5",
        "certified_win": False,
        "publication_certificate": False,
        "created_date_utc": "2026-08-19",
        "dataset_base_commit": HF_BASE_COMMIT,
        "candidate": {
            "candidate_id": CANDIDATE_ID,
            "canonical_digest": CANONICAL_DIGEST,
            "code": "[[210,10,16]]",
            "exact_fom_numerator": 256,
            "exact_fom_denominator": 21,
        },
        "authority": record["authority"],
        "source": public_source,
        "files": [],
    }
    for relative in release_files:
        path = root / relative
        item: dict[str, Any] = {
            "path": relative,
            "bytes": path.stat().st_size,
            "sha256": sha256_file(path),
        }
        if relative.endswith(".jsonl"):
            item["rows"] = len(
                [line for line in path.read_text(encoding="utf-8").splitlines() if line]
            )
        manifest["files"].append(item)
    manifest["manifest_sha256"] = canonical_sha256(manifest, "manifest_sha256")
    manifest_path = root / "manifests" / "stage3_typed_exact_fom_gt_12.json"
    manifest_path.write_text(
        json.dumps(manifest, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )

    sums_path = root / "manifests" / "SHA256SUMS"
    existing_order = []
    for line in sums_path.read_text(encoding="utf-8").splitlines():
        if not line:
            continue
        _old, relative = line.split("  ", 1)
        existing_order.append(relative)
    additions = [
        *release_files,
        "manifests/stage3_typed_exact_fom_gt_12.json",
    ]
    order = existing_order + [item for item in additions if item not in existing_order]
    sums_path.write_text(
        "".join(f"{sha256_file(root / relative)}  {relative}\n" for relative in order),
        encoding="utf-8",
    )
    print(
        json.dumps(
            {
                "candidate_id": CANDIDATE_ID,
                "code": "[[210,10,16]]",
                "fom": 256 / 21,
                "record_sha256": record["record_sha256"],
                "evidence_sha256": evidence["evidence_sha256"],
                "manifest_sha256": manifest["manifest_sha256"],
            },
            sort_keys=True,
        )
    )


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("root", type=Path)
    parser.add_argument("source_run", type=Path)
    parser.add_argument("qcode_root", type=Path)
    args = parser.parse_args()
    build(args.root, args.source_run, args.qcode_root)


if __name__ == "__main__":
    main()