File size: 44,835 Bytes
339ddd8
 
 
 
 
48f2b75
f628309
339ddd8
ba784dc
 
c35ac38
339ddd8
e1de134
339ddd8
 
ba784dc
339ddd8
c35ac38
339ddd8
 
 
 
 
 
2a9dc4c
339ddd8
 
 
2a9dc4c
 
 
 
 
 
 
339ddd8
2a9dc4c
f4952b6
 
 
 
 
 
 
2a9dc4c
f4952b6
 
ba784dc
2a9dc4c
339ddd8
 
1600cd6
 
 
339ddd8
 
 
 
 
 
f628309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
ba784dc
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
f4952b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
ba784dc
 
f4952b6
ba784dc
 
 
f4952b6
 
 
 
 
 
 
 
 
ba784dc
 
 
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a9dc4c
339ddd8
 
 
 
 
 
 
 
 
 
 
 
1600cd6
f4952b6
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
f4952b6
1600cd6
f4952b6
 
 
 
 
1600cd6
 
 
 
 
 
 
 
 
db2c7db
1600cd6
db2c7db
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db2c7db
 
 
 
 
 
 
1600cd6
 
e1de134
 
 
 
 
 
 
 
 
 
 
 
f4952b6
 
 
 
 
 
e1de134
 
 
 
 
 
 
 
 
f4952b6
 
e1de134
f4952b6
e1de134
f4952b6
e1de134
 
 
f4952b6
e1de134
 
 
 
 
 
 
 
 
f4952b6
e1de134
 
 
 
 
 
 
f4952b6
e1de134
 
 
 
 
f4952b6
e1de134
 
 
 
1600cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f628309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f2b75
c35ac38
48f2b75
 
 
 
 
 
c35ac38
48f2b75
 
c35ac38
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
48f2b75
 
 
 
 
 
 
 
 
 
 
 
 
c35ac38
 
 
 
 
 
 
 
 
48f2b75
 
 
c35ac38
 
48f2b75
 
 
339ddd8
 
 
 
f4952b6
339ddd8
 
ba784dc
339ddd8
1600cd6
 
e1de134
1600cd6
f628309
48f2b75
339ddd8
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
339ddd8
ba784dc
339ddd8
ba784dc
339ddd8
ba784dc
339ddd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba784dc
 
 
 
 
 
 
339ddd8
 
 
 
 
ba784dc
f4952b6
339ddd8
 
 
 
 
ba784dc
339ddd8
 
 
 
 
 
 
2a9dc4c
339ddd8
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
"""Run deterministic gates for the external datasets/codex-python package."""

from __future__ import annotations

import argparse
import ast
import hashlib
import json
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Callable, Dict, List, Sequence, Set, Tuple

ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))
sys.dont_write_bytecode = True

from lingologos_python._codex_bridge import ensure_codex_on_path  # noqa: E402

ensure_codex_on_path(ROOT)

from lingologos_codex.adapter_contract import check_adapter_contract  # noqa: E402
from lingologos_codex.agents import ROLES  # noqa: E402
from lingologos_codex.casecorpus import read_rows, validate_case_rows  # noqa: E402
from lingologos_codex.decision import dossier_from_dict  # noqa: E402
from lingologos_codex.envelope import ENVELOPE_KIND  # noqa: E402
from lingologos_codex.patcher import FuzzyPatchConfig, SearchReplaceBlock, apply_controlled_fuzzy_patch  # noqa: E402
from lingologos_codex.types import ABSTAIN, CONFIRMED, REJECTED, VERDICTS, GateResult  # noqa: E402

from lingologos_python.adapter import PythonLanguageAdapter, StrictPythonLanguageAdapter  # noqa: E402
from lingologos_python.ast_graph import (
    build_reverse_index,
    discover_python_files,
    extract_python_graph,
    importers_from_index,
    importers_of,
)  # noqa: E402
from lingologos_python.patterns import PATTERNS, module_level_functions, plan_pattern  # noqa: E402
from lingologos_python.reasons import REASON_CODES, SESSION_LOCKED  # noqa: E402
import lingologos_python.session as session_module  # noqa: E402
from lingologos_python.session import SESSION_LOCK_NAME, PythonWorkspaceSession  # noqa: E402
from lingologos_python.test_selector import select_python_tests  # noqa: E402

FIXTURE_PKG = ROOT / "fixtures" / "sample_pkg"
PATTERN_LAB = ROOT / "fixtures" / "pattern_lab"
PATTERN_CASES = ROOT / "patterns" / "pattern_cases.jsonl"
PATTERN_COVERAGE = ROOT / "patterns" / "coverage.json"


def _confirmed(check: str, note: str) -> GateResult:
    return GateResult(CONFIRMED, check, note=note)


# The report states what the gates judged; the digest anchors that claim to the
# tree the gates were run on. Everything published is hashed except the reports
# folder itself, so a publisher can refuse a report describing another
# revision, and a test can refuse a stale report in the tree.
DIGEST_IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git", ".venv", ".venv-train", "results"}


def digest_input_files(root: Path = ROOT) -> List[Path]:
    files: List[Path] = []
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        rel = path.relative_to(root)
        if any(part in DIGEST_IGNORED_DIRS for part in rel.parts[:-1]):
            continue
        if path.suffix in (".pyc", ".pyo"):
            continue
        files.append(path)
    return files


def bundle_digest(files: Sequence[Path], root: Path = ROOT) -> str:
    digest = hashlib.sha256()
    for path in sorted(files, key=lambda p: p.relative_to(root).as_posix()):
        digest.update(path.relative_to(root).as_posix().encode("ascii") + b"\0")
        digest.update(path.read_bytes() + b"\0")
    return digest.hexdigest()


CODEX_KERNEL_ROOT = ROOT.parent / "codex"


def kernel_digest() -> str:
    """The bytes of the kernel this bundle tests against, as one hash.

    The kernel lives in its own bundle, is never carried here, and is never
    modified here. Naming its digest pins which kernel answered the gates in
    this report, so a card can promise behaviour without anyone remembering
    which kernel revision produced it.
    """
    files = [
        path
        for path in CODEX_KERNEL_ROOT.rglob("*.py")
        if "__pycache__" not in path.relative_to(CODEX_KERNEL_ROOT).parts
    ]
    return bundle_digest(files, CODEX_KERNEL_ROOT)


def _rejected(check: str, note: str, failed: Sequence[str] = ()) -> GateResult:
    return GateResult(REJECTED, check, failed_targets=tuple(failed), note=note)


def gate_adapter_contract() -> GateResult:
    check = "check_adapter_contract on PythonLanguageAdapter"
    adapter = PythonLanguageAdapter(FIXTURE_PKG)
    files = discover_python_files(FIXTURE_PKG)
    violations = check_adapter_contract(adapter, str(FIXTURE_PKG), files)
    if violations:
        return _rejected(check, "; ".join(violations), violations)
    return _confirmed(check, f"no violations for {adapter.meta().name}")


def gate_ast_graph() -> GateResult:
    check = "Python AST symbol, method, inheritance, and import graph"
    files = discover_python_files(FIXTURE_PKG)
    symbols, edges = extract_python_graph(FIXTURE_PKG, files)
    expected_syms = {
        "src/mathops.py::Accumulator",
        "src/mathops.py::BoundedAccumulator.add",
        "src/mathops.py::double_sum",
        "src/textops.py::format_sum",
    }
    missing = sorted(expected_syms - set(symbols))
    if missing:
        return _rejected(check, f"missing symbols: {missing}", missing)
    expected_edges = {
        ("src/mathops.py::BoundedAccumulator", "src/mathops.py::Accumulator"),
        ("src/mathops.py::double_sum", "src/mathops.py::add_numbers"),
        ("src/textops.py", "src/mathops.py"),
    }
    missing_edges = sorted(str(e) for e in (expected_edges - set(edges)))
    if missing_edges:
        return _rejected(check, f"missing edges: {missing_edges}", missing_edges)
    return _confirmed(check, f"{len(symbols)} symbols, {len(edges)} edges extracted")


def gate_test_selection() -> GateResult:
    check = "import-aware Python test selection"
    selected = select_python_tests(FIXTURE_PKG, ["src/mathops.py"])
    if "tests/test_mathops.py" not in selected or "tests/test_textops.py" not in selected:
        return _rejected(check, f"unexpected selection: {selected}", selected)
    return _confirmed(check, f"selected {len(selected)} dependent test file(s)")


GRAPH_SCALING_PACKAGES = 50
GRAPH_SCALING_FILES = 1500
GRAPH_SCALING_SEED = 20261127


def _seed_scaling_workspace(root: Path) -> Set[Tuple[str, str]]:
    """Write a deterministic import web and return the file edges those imports state.

    Every generated module but the first imports one function from a module written
    before it, so the expected edges are known the moment the text is written: the
    gate can then demand that the extractor answer with exactly that set.
    """
    rng = random.Random(GRAPH_SCALING_SEED)
    earlier: List[Tuple[str, str, str]] = []
    edges: Set[Tuple[str, str]] = set()
    written = 0
    for package in range(GRAPH_SCALING_PACKAGES):
        package_dir = root / "app" / ("pkg%d" % package)
        package_dir.mkdir(parents=True)
        (package_dir / "__init__.py").write_text("", encoding="utf-8", newline="\n")
        written += 1
        for module in range((GRAPH_SCALING_FILES - GRAPH_SCALING_PACKAGES) // GRAPH_SCALING_PACKAGES):
            rel = "app/pkg%d/mod%d.py" % (package, module)
            dotted = "app.pkg%d.mod%d" % (package, module)
            name = "value_%d_%d" % (package, module)
            if not earlier:
                text = "def %s() -> int:\n    return 0\n" % name
            else:
                source_dotted, source_rel, source_name = rng.choice(earlier)
                text = (
                    "from %s import %s as handed\n\n\ndef %s() -> int:\n    return handed() + 1\n"
                    % (source_dotted, source_name, name)
                )
                edges.add((rel, source_rel))
            (root / Path(*rel.split("/"))).write_text(text, encoding="utf-8", newline="\n")
            earlier.append((dotted, rel, name))
            written += 1
    return edges


def gate_graph_scaling() -> GateResult:
    check = "the symbol graph stays exact at %d generated files" % GRAPH_SCALING_FILES
    started = time.perf_counter()
    with tempfile.TemporaryDirectory(prefix="lingologos_scaling_") as tmp_dir:
        root = Path(tmp_dir)
        expected = _seed_scaling_workspace(root)
        files = discover_python_files(root)
        if len(files) != GRAPH_SCALING_FILES:
            return _rejected(
                check,
                "generated %d python files, discovery found %d" % (GRAPH_SCALING_FILES, len(files)),
            )
        read = time.perf_counter()
        _symbols, edges = extract_python_graph(root, files)
        extract_seconds = time.perf_counter() - read
        file_edges = {edge for edge in edges if "::" not in edge[0] and "::" not in edge[1]}
        missing = sorted(str(edge) for edge in (expected - file_edges))
        extra = sorted(str(edge) for edge in (file_edges - expected))
        if missing or extra:
            return _rejected(
                check,
                "file edges drifted: missing %s, extra %s" % (missing[:3], extra[:3]),
                missing[:3] + extra[:3],
            )
        index = build_reverse_index(root, files)
        probe = random.Random(GRAPH_SCALING_SEED + 1)
        for target in probe.sample(files, 12):
            remaining = [p for p in files if p != target]
            if importers_from_index(index, target) != sorted(importers_of(root, remaining, target)):
                return _rejected(check, "the index and the walk disagree about %s" % target, [target])
    return _confirmed(
        check,
        "%d files, %d import edges exact, reverse index agrees on 12 probes, %.1fs total with %.1fs extract"
        % (GRAPH_SCALING_FILES, len(expected), time.perf_counter() - started, extract_seconds),
    )


def gate_strict_abstain_control() -> GateResult:
    check = "missing optional tools produce ABSTAIN and block verdict"
    adapter = StrictPythonLanguageAdapter(FIXTURE_PKG)
    gates = adapter.run_typecheck_and_lint(str(FIXTURE_PKG), ["src/mathops.py"])
    if not any(g.verdict == ABSTAIN for g in gates):
        return _confirmed(check, "mypy and ruff are installed and ran cleanly")
    session = PythonWorkspaceSession(FIXTURE_PKG, strict_tools=True)
    res = session.verify("src/mathops.py")
    if res.verdict != "UNKNOWN" or res.reason != "GATE_ABSTAIN":
        return _rejected(check, f"expected UNKNOWN/GATE_ABSTAIN, got {res.verdict}/{res.reason}")
    return _confirmed(check, "missing static tools abstained and ended in UNKNOWN/GATE_ABSTAIN")


def gate_session_transactions() -> GateResult:
    check = "staged edit commit on VERIFIED and disk isolation on refusal"
    with tempfile.TemporaryDirectory(prefix="lingologos_python_gate_") as tmp_dir:
        ws = Path(tmp_dir) / "pkg"
        shutil.copytree(FIXTURE_PKG, ws)
        session = PythonWorkspaceSession(ws)

        # 1. Clean edit commits atomically with assurance 3
        clean = session.edit_file(
            "src/mathops.py",
            "return left + right",
            "return int(left + right)",
            commit=True,
        )
        if clean.verdict != "VERIFIED" or clean.assurance != 3 or not clean.committed:
            return _rejected(check, f"clean edit failed: {clean.verdict}/{clean.reason}")

        # 2. Broken syntax edit is refused and leaves file unchanged
        before = (ws / "src" / "mathops.py").read_text(encoding="utf-8")
        broken = session.edit_file(
            "src/mathops.py",
            "return int(left + right)",
            "return int(left +",
            commit=True,
        )
        after = (ws / "src" / "mathops.py").read_text(encoding="utf-8")
        if broken.verdict != "UNKNOWN" or broken.committed or before != after:
            return _rejected(check, f"broken edit leaked or committed: {broken.verdict}")

        # 3. Protected path is refused
        (ws / ".env").write_text("A=1\n", encoding="utf-8")
        secret = session.edit_file(".env", "A=1", "A=2", commit=True)
        if secret.verdict != "UNKNOWN" or secret.reason != "PROTECTED_PATH" or secret.committed:
            return _rejected(check, f"protected path was not blocked: {secret.verdict}/{secret.reason}")

    return _confirmed(check, "clean edit committed VERIFIED (3); syntax error and protected path refused")


# The sweep the fuzz test runs at full length gets a short, seeded twin here:
# the same invariant, a dozen operations, a fixed seed so the gate answers the
# same way on every machine. It exists because the card promises that no change
# lands without a commit and no refusal leaves a trace, and a gate, not only a
# test file, has to keep that promise under review.
SESSION_SWEEP_SEED = 20260301
SESSION_SWEEP_PLAN: List[str] = (
    ["valid_edit_commit"] * 2
    + ["valid_create_commit"]
    + ["verify"]
    + ["traversal_edit"] * 2
    + ["protected_create"]
    + ["missing_edit"]
    + ["missing_delete"]
    + ["create_existing"]
    + ["empty_edit"]
    + ["bad_pattern"]
    + ["tampered_lock_edit"]
)
# The sweep states, per operation, how it must end. "verified_no_write" is a
# verify that judged the file without touching the tree. Operation 5 of the
# shuffle always runs under a planted live lock, so its only honest outcome is
# a refusal whatever the verb.
SESSION_SWEEP_EXPECTED: Dict[str, str] = {
    "valid_edit_commit": "committed",
    "valid_create_commit": "committed",
    "verify": "verified_no_write",
    "traversal_edit": "refused",
    "protected_create": "refused",
    "missing_edit": "refused",
    "missing_delete": "raised",
    "create_existing": "raised",
    "empty_edit": "refused",
    "bad_pattern": "raised",
    "tampered_lock_edit": "refused",
}


def _sweep_tree_state(root: Path) -> Dict[str, bytes]:
    state: Dict[str, bytes] = {}
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        rel = path.relative_to(root).as_posix()
        parts = rel.split("/")
        if any(part in ("__pycache__", ".pytest_cache") for part in parts[:-1]):
            continue
        if path.suffix in (".pyc", ".pyo"):
            continue
        state[rel] = path.read_bytes()
    return state


def gate_session_sweep() -> GateResult:
    check = "fixed-seed sweep of session verbs over a copied package"
    rng = random.Random(SESSION_SWEEP_SEED)
    kinds = list(SESSION_SWEEP_PLAN)
    rng.shuffle(kinds)
    files = ["src/mathops.py", "src/textops.py", "tests/test_mathops.py", "tests/test_textops.py"]
    ops = [(kind, rng.choice(files)) for kind in kinds]

    with tempfile.TemporaryDirectory(prefix="lingologos_python_sweep_") as tmp_dir:
        ws = Path(tmp_dir) / "pkg"
        shutil.copytree(FIXTURE_PKG, ws)
        failures: List[str] = []
        committed = 0
        refused = 0
        raised = 0
        outcomes: List[str] = []
        for index, (kind, rel) in enumerate(ops):
            session = PythonWorkspaceSession(ws)
            lock_held = False
            if index == 5:
                # Plant a live holder: our own process is alive, so the lock is real.
                (ws / SESSION_LOCK_NAME).write_text(str(os.getpid()), encoding="ascii")
                lock_held = True
            before = _sweep_tree_state(ws)
            try:
                res = None
                if kind == "valid_edit_commit":
                    path = ws / Path(*rel.split("/"))
                    text = path.read_text(encoding="utf-8", newline="")
                    anchor = [line for line in text.split("\n") if line.strip()][-1]
                    res = session.edit_file(rel, anchor, anchor + "\n# swept", commit=True)
                elif kind == "valid_create_commit":
                    res = session.create_file(
                        "src/extra_%d.py" % index,
                        "def extra_%d() -> int:\n    return %d\n" % (index, index),
                        commit=True,
                    )
                elif kind == "verify":
                    res = session.verify(rel)
                elif kind == "traversal_edit":
                    res = session.edit_file("../outside_the_tree.py", "a", "b", commit=True)
                elif kind == "protected_create":
                    res = session.create_file(".env", "SECRET=1\n", commit=True)
                elif kind == "missing_edit":
                    res = session.edit_file("src/absent_%d.py" % index, "a", "b", commit=True)
                elif kind == "missing_delete":
                    try:
                        res = session.delete_file("src/gone_%d.py" % index, commit=True)
                    except FileNotFoundError:
                        raised += 1
                elif kind == "create_existing":
                    try:
                        res = session.create_file(rel, "x = 1\n", commit=True)
                    except FileExistsError:
                        raised += 1
                elif kind == "empty_edit":
                    res = session.edit_file(rel, "", "", commit=True)
                elif kind == "bad_pattern":
                    try:
                        res = session.apply_pattern("ghost-card-%d" % index, commit=True)
                    except KeyError:
                        raised += 1
                elif kind == "tampered_lock_edit":
                    # An outsider overwrites our lock mid-run: the commit must
                    # notice that the lock no longer names this run and refuse,
                    # leaving both the tree and the stolen lock in place.
                    path = ws / Path(*rel.split("/"))
                    text = path.read_text(encoding="utf-8", newline="")
                    anchor = [line for line in text.split("\n") if line.strip()][-1]
                    real_run = session_module.run_pipeline

                    def tamper(case, _real=real_run):
                        (ws / SESSION_LOCK_NAME).write_text(
                            "%d - not-our-token" % os.getpid(), encoding="ascii"
                        )
                        return _real(case)

                    session_module.run_pipeline = tamper
                    try:
                        res = session.edit_file(rel, anchor, anchor + "\n# swept", commit=True)
                    finally:
                        session_module.run_pipeline = real_run
                        (ws / SESSION_LOCK_NAME).unlink(missing_ok=True)
                after = _sweep_tree_state(ws)
                if res is None:
                    outcome = "raised"
                elif res.committed:
                    outcome = "committed"
                elif res.verdict in ("REFUSED", "UNKNOWN"):
                    outcome = "refused"
                else:
                    outcome = "verified_no_write"
                outcomes.append(outcome)
                if res is not None:
                    expected = "refused" if index == 5 else SESSION_SWEEP_EXPECTED[kind]
                    if outcome != expected:
                        failures.append(
                            "%d %s: ended %s where the plan promised %s"
                            % (index, kind, outcome, expected)
                        )
                    if kind == "tampered_lock_edit" and res.reason != SESSION_LOCKED:
                        failures.append(
                            "%d %s: refused for %s instead of %s"
                            % (index, kind, res.reason, SESSION_LOCKED)
                        )
                if res is None:
                    if after != before:
                        failures.append("%d %s: an expected exception still wrote to disk" % (index, kind))
                    continue
                if res.verdict in ("REFUSED", "UNKNOWN") and res.reason not in REASON_CODES:
                    failures.append("%d %s: unregistered reason %s" % (index, kind, res.reason))
                if res.committed:
                    committed += 1
                    if res.verdict not in ("VERIFIED", "SINGLE_PROVER") or not res.accepted:
                        failures.append("%d %s: committed with verdict %s" % (index, kind, res.verdict))
                    changed = {r for r in set(before) | set(after) if before.get(r) != after.get(r)}
                    if changed and not changed <= set(res.touched_files):
                        failures.append("%d %s: changed files the result did not name" % (index, kind))
                else:
                    refused += 1
                    if after != before:
                        failures.append(
                            "%d %s (%s): disk moved without a commit" % (index, kind, res.reason)
                        )
                if lock_held and res.verdict != "REFUSED":
                    failures.append("%d %s: a planted lock did not refuse the run" % (index, kind))
            except Exception as exc:  # a crash of the sweep is a finding, not a pass
                failures.append("%d %s: %s: %s" % (index, kind, type(exc).__name__, exc))
            finally:
                if lock_held:
                    (ws / SESSION_LOCK_NAME).unlink(missing_ok=True)
        if failures:
            return _rejected(check, "; ".join(failures), failures)
        promised = [
            "refused" if index == 5 else SESSION_SWEEP_EXPECTED[kind]
            for index, (kind, _rel) in enumerate(ops)
        ]
        if outcomes != promised:
            return _rejected(
                check,
                "sweep outcomes %s do not match the promised %s" % (outcomes, promised),
            )
    return _confirmed(
        check,
        "%d seeded operations: %d committed, %d refused, %d raised, %d verified without a write, "
        "tree state compared after each one"
        % (
            len(ops),
            outcomes.count("committed"),
            outcomes.count("refused"),
            outcomes.count("raised"),
            outcomes.count("verified_no_write"),
        ),
    )


def gate_external_topology() -> GateResult:
    check = "external topology.json, node folders, and six subprocess turns"
    topo = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))
    ids = sorted(inst["id"] for inst in topo.get("instances", []))
    if ids != sorted(ROLES) or topo.get("terminationCondition") != "FIXED_PIPELINE":
        return _rejected(check, f"unexpected topology instances: {ids}")

    for role in ROLES:
        folder = ROOT / "nodes" / role
        for fname in ("grammar.gf", "ontology.smt2", "seed_payload.json"):
            if not (folder / fname).is_file():
                return _rejected(check, f"missing {folder / fname}")
        seed = json.loads((folder / "seed_payload.json").read_text(encoding="utf-8"))
        if seed.get("kind") != ENVELOPE_KIND or seed.get("sender") != role:
            return _rejected(check, f"invalid seed in {folder}")
        dossier_from_dict(json.loads(seed["payload"]["abstractSyntaxTree"]))

    with tempfile.TemporaryDirectory(prefix="lingologos_python_subproc_") as tmp_dir:
        ws = Path(tmp_dir) / "pkg"
        shutil.copytree(FIXTURE_PKG, ws)
        session = PythonWorkspaceSession(ws, use_subprocesses=True)
        res = session.verify("src/mathops.py")
        if res.verdict != "VERIFIED" or res.assurance != 3 or len(res.trace) != 7:
            return _rejected(
                check,
                f"subprocess topology returned {res.verdict}/{res.assurance} with {len(res.trace)} envelopes",
            )
    return _confirmed(check, "6 node folders valid, 7 subprocess envelopes reached VERIFIED (3)")


def gate_pattern_corpus_schema() -> GateResult:
    check = "patterns/pattern_cases.jsonl is a valid case-1 corpus with a pair at least for every card"
    if not PATTERN_CASES.is_file():
        return _rejected(check, "patterns/pattern_cases.jsonl is missing")
    rows = read_rows(PATTERN_CASES)
    problems = validate_case_rows(rows)
    if problems:
        return _rejected(check, "; ".join(problems), problems)
    unknown = sorted({str(row["pattern_id"]) for row in rows} - set(PATTERNS))
    if unknown:
        return _rejected(check, f"rows name patterns this bundle does not hold: {unknown}", unknown)
    short: List[str] = []
    for pattern_id in sorted(PATTERNS):
        positive = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "VERIFIED"]
        negative = [row for row in rows if row["pattern_id"] == pattern_id and row["expect"] == "REFUSED"]
        if len(positive) < 1 or len(negative) < 1:
            short.append("%s has %d positive and %d negative rows" % (pattern_id, len(positive), len(negative)))
        for row in positive:
            if len(row["edits"]) < 2:
                short.append(
                    "%s claims a companion test but its row holds %d edits" % (row["case_id"], len(row["edits"]))
                )
    if short:
        return _rejected(check, "; ".join(short), short)
    return _confirmed(check, f"{len(rows)} rows over {len(PATTERNS)} cards, each with its lock test and its refusal")


def gate_pattern_round_trip() -> GateResult:
    check = "every row of the pattern corpus re-plans on the fixture as written"
    if not PATTERN_CASES.is_file():
        return _rejected(check, "patterns/pattern_cases.jsonl is missing")
    rows = read_rows(PATTERN_CASES)
    failures: List[str] = []
    for row in rows:
        case_id = str(row["case_id"])
        pattern_id = str(row["pattern_id"])
        targets = [str(item) for item in row["targets"]]
        if not targets:
            failures.append("%s names no target" % case_id)
            continue
        plan = plan_pattern(PATTERN_LAB, pattern_id, targets[0])
        if row["expect"] == "REFUSED":
            if not plan.refused:
                failures.append("%s was refused by the corpus and re-planned as a change" % case_id)
            elif plan.reason_code != str(row.get("reason_code", "")):
                failures.append(
                    "%s refused with '%s', the corpus states '%s'"
                    % (case_id, plan.reason_code, row.get("reason_code", ""))
                )
            continue
        if plan.refused:
            failures.append("%s applied in the corpus and re-plans as a refusal: %s" % (case_id, plan.detail))
            continue
        for edit in plan.edits:
            path = PATTERN_LAB / Path(*edit.file.split("/"))
            if not path.is_file():
                failures.append("%s edits '%s', which the fixture does not hold" % (case_id, edit.file))
                continue
            original = path.read_text(encoding="utf-8", newline="")
            outcome = apply_controlled_fuzzy_patch(
                original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig()
            )
            if not outcome.applied:
                failures.append("%s: the anchor for '%s' does not apply" % (case_id, edit.file))
                continue
            try:
                compile(outcome.updated_text, edit.file, "exec")
            except SyntaxError as exc:
                failures.append("%s: '%s' stops compiling after the edit (%s)" % (case_id, edit.file, exc.msg))
    if failures:
        return _rejected(check, "; ".join(failures), failures)
    landing = sum(1 for row in rows if row["expect"] == "VERIFIED")
    refusing = sum(1 for row in rows if row["expect"] == "REFUSED")
    return _confirmed(
        check,
        "%d rows re-planned: %d pairs land and compile, %d refusals repeat with the same code"
        % (len(rows), landing, refusing),
    )


def _pytest_return_code(lab: Path) -> int:
    proc = subprocess.run(
        [sys.executable, "-B", "-m", "pytest", "-q", "-p", "no:cacheprovider"],
        cwd=str(lab),
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    return proc.returncode


def gate_pattern_pair_honesty() -> GateResult:
    check = "each card's lock test fails until the source edit of its pair lands"
    positives: List[Tuple[str, str, str]] = [
        (str(row["case_id"]), str(row["pattern_id"]), str(row["targets"][0]))
        for row in read_rows(PATTERN_CASES)
        if row["expect"] == "VERIFIED"
    ]
    missing = sorted(set(PATTERNS) - {pattern_id for _case, pattern_id, _target in positives})
    if missing:
        return _rejected(check, "no positive corpus row names a target for: " + ", ".join(missing), missing)

    failures: List[str] = []
    with tempfile.TemporaryDirectory(prefix="lingologos_python_honesty_") as tmp:
        base = Path(tmp) / "lab"
        shutil.copytree(PATTERN_LAB, base)
        if _pytest_return_code(base) != 0:
            return _rejected(check, "the pattern_lab fixture does not pass its own suite as published")
        for case_id, pattern_id, target in positives:
            lab = Path(tmp) / ("lab_" + case_id)
            shutil.copytree(PATTERN_LAB, lab)
            plan = plan_pattern(lab, pattern_id, target)
            if plan.refused:
                failures.append("%s: the positive row no longer plans: %s" % (case_id, plan.detail))
                continue
            companions = plan.companions()
            if not companions:
                failures.append("%s: the card carries no lock test in its pair" % case_id)
                continue
            broke = False
            for edit in companions:
                path = lab / Path(*edit.file.split("/"))
                original = path.read_text(encoding="utf-8", newline="")
                outcome = apply_controlled_fuzzy_patch(
                    original, SearchReplaceBlock(edit.search, edit.replace), FuzzyPatchConfig()
                )
                if not outcome.applied:
                    failures.append("%s: the lock test anchor for '%s' does not apply" % (case_id, edit.file))
                    broke = True
                    break
                path.write_text(outcome.updated_text, encoding="utf-8", newline="")
            if broke:
                continue
            if _pytest_return_code(lab) == 0:
                failures.append(
                    "%s: the suite still passes with only the test side of the pair written" % case_id
                )
        if failures:
            return _rejected(check, "; ".join(failures), failures)
    return _confirmed(
        check,
        "%d pairs: every lock test fails while its source edit is missing, so the pairs are not decoration"
        % len(positives),
    )


def gate_pattern_coverage() -> GateResult:
    check = "patterns/coverage.json states a denominator this fixture still supports"
    if not PATTERN_COVERAGE.is_file():
        return _rejected(check, "patterns/coverage.json is missing")
    payload = json.loads(PATTERN_COVERAGE.read_text(encoding="utf-8"))
    source_files = [name for name in discover_python_files(PATTERN_LAB) if not name.startswith("tests/")]
    if payload.get("source_files") != source_files:
        return _rejected(check, f"the fixture holds {source_files}, the table states {payload.get('source_files')}")
    functions = payload.get("module_level_functions_by_file") or {}
    stated = int(payload.get("module_level_functions", -1))
    by_file = {rel: len(module_level_functions((PATTERN_LAB / Path(*rel.split("/"))).read_text(encoding="utf-8", newline=""))) for rel in source_files}
    if by_file != functions or sum(by_file.values()) != stated:
        return _rejected(check, f"the functions of the fixture are {by_file}, the table states {functions} totaling {stated}")
    if int(payload.get("rows", -1)) != len(read_rows(PATTERN_CASES)):
        return _rejected(check, f"the corpus holds {len(read_rows(PATTERN_CASES))} rows, the table states {payload.get('rows')}")
    entries = payload.get("patterns") or []
    if sorted(str(entry["pattern_id"]) for entry in entries) != sorted(PATTERNS):
        return _rejected(check, "the table does not list exactly the cards this bundle holds")
    wrong = [
        str(entry["pattern_id"])
        for entry in entries
        if int(entry["min_assurance"]) != PATTERNS[str(entry["pattern_id"])].min_assurance
        or str(entry["family"]) != PATTERNS[str(entry["pattern_id"])].family
    ]
    if wrong:
        return _rejected(check, f"family or assurance differs from the card for: {wrong}", wrong)
    return _confirmed(
        check,
        "%d cards over %d source files and %d module level functions, denominator stated as the fixture"
        % (len(entries), len(source_files), stated),
    )


def _self_valued_codes(text: str) -> List[str]:
    """Reason-code constants of the form NAME = "NAME" at the top level of a module."""
    codes: List[str] = []
    for node in ast.parse(text).body:
        if not isinstance(node, ast.Assign) or len(node.targets) != 1:
            continue
        target = node.targets[0]
        if (
            isinstance(target, ast.Name)
            and target.id.isupper()
            and isinstance(node.value, ast.Constant)
            and isinstance(node.value.value, str)
            and node.value.value == target.id
        ):
            codes.append(target.id)
    return codes


def _defined_names(texts: Dict[str, str]) -> Set[str]:
    """Names the package itself defines: functions, classes, methods, constants, dict keys, CLI verbs."""
    names: Set[str] = set()
    for text in texts.values():
        for node in ast.walk(ast.parse(text)):
            if isinstance(node, ast.Assign):
                for target in node.targets:
                    if isinstance(target, ast.Name):
                        names.add(target.id)
            elif isinstance(node, ast.AnnAssign):
                if isinstance(node.target, ast.Name):
                    names.add(node.target.id)
            elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
                names.add(node.name)
            elif isinstance(node, ast.Dict):
                for key in node.keys:
                    if isinstance(key, ast.Constant) and isinstance(key.value, str):
                        names.add(key.value)
            elif (
                isinstance(node, ast.Call)
                and isinstance(node.func, ast.Attribute)
                and node.func.attr == "add_parser"
                and node.args
                and isinstance(node.args[0], ast.Constant)
                and isinstance(node.args[0].value, str)
            ):
                names.add(node.args[0].value)
            elif (
                isinstance(node, ast.Call)
                and isinstance(node.func, ast.Attribute)
                and node.func.attr == "add_argument"
            ):
                for keyword in node.keywords:
                    if keyword.arg == "choices" and isinstance(keyword.value, (ast.Tuple, ast.List)):
                        for element in keyword.value.elts:
                            if isinstance(element, ast.Constant) and isinstance(element.value, str):
                                names.add(element.value)
    return names


def _card_promises(readme: str) -> List[str]:
    """Backticked identifiers inside parentheses in the Contents section of the card.

    Those parentheses are promises: the bullet says the module carries that name.
    Listing them and checking them against the modules is what keeps the card a
    description and not a hope.
    """
    if "## Contents" not in readme:
        return []
    section = readme.split("## Contents", 1)[1].split("\n## ", 1)[0]
    promises: List[str] = []
    for group in re.finditer(r"\(([^()]*)\)", section):
        for span in re.findall(r"`([^`]*)`", group.group(1)):
            for token in re.split(r"[|\s]+", span):
                if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*(?:-[A-Za-z0-9_]+)*", token):
                    continue
                if token not in promises:
                    promises.append(token)
    return promises


def _card_commands(readme: str) -> List[Tuple[str, List[str]]]:
    """Verbs and long flags the card prints as runnable command lines.

    Continuation backslashes are joined, so a wrapped example is still one
    command. Lines that launch another tool (pytest, the gate runner itself)
    carry no verb of this CLI and stay out.
    """
    commands: List[Tuple[str, List[str]]] = []
    pending: List[str] = []
    for raw in readme.splitlines():
        line = raw.strip()
        if line.startswith("$ "):
            line = line[2:].strip()
        if pending:
            line = " ".join(pending + [line]).strip()
            pending = []
        if line.endswith("\\"):
            pending.append(line[:-1].strip())
            continue
        for prefix in ("python -B -m lingologos_python", "python -m lingologos_python"):
            if line.startswith(prefix):
                rest = line[len(prefix):].split()
                if rest:
                    verb = rest[0]
                    commands.append((verb, [t for t in rest[1:] if t.startswith("--")]))
                break
    return commands


def _parser_surface(parser: argparse.ArgumentParser) -> Tuple[Set[str], Dict[str, Set[str]]]:
    """Top-level long flags, and the long flags of every verb of the parser."""
    top = {opt for action in parser._actions for opt in action.option_strings if opt.startswith("--")}
    verbs: Dict[str, Set[str]] = {}
    for action in parser._actions:
        if isinstance(action, argparse._SubParsersAction):
            for name, sub in action.choices.items():
                verbs[name] = {
                    opt for a in sub._actions for opt in a.option_strings if opt.startswith("--")
                }
    return top, verbs


def _card_command_problems(readme: str, parser: argparse.ArgumentParser) -> List[str]:
    top, verbs = _parser_surface(parser)
    problems: List[str] = []
    for verb, flags in _card_commands(readme):
        if verb.startswith("--"):
            if verb not in top:
                problems.append(verb)
            continue
        if verb not in verbs:
            problems.append("verb %s" % verb)
            continue
        for flag in flags:
            name = flag.split("=", 1)[0]
            if name not in top and name not in verbs[verb]:
                problems.append("%s %s" % (verb, name))
    return problems


def gate_cli_card_agreement() -> GateResult:
    check = "every verb and flag the card prints exists in the real parser"
    from lingologos_python.cli import _build_parser

    readme = (ROOT / "README.md").read_text(encoding="utf-8")
    printed = _card_commands(readme)
    problems = _card_command_problems(readme, _build_parser())
    if problems:
        return _rejected(
            check,
            "the card prints commands the parser does not carry: " + ", ".join(problems),
            problems,
        )
    _, verbs = _parser_surface(_build_parser())
    return _confirmed(
        check,
        "%d printed command lines agree with the %d verbs of the parser" % (len(printed), len(verbs)),
    )


def gate_self_lint() -> GateResult:
    check = "the package reads itself: modules compile, the graph spans them, the reason registry matches the card, the promised names exist"
    pkg = ROOT / "lingologos_python"
    files = discover_python_files(pkg)
    if len(files) < 10:
        return _rejected(check, f"only {len(files)} modules discovered inside the package")
    broken: List[str] = []
    undocumented: List[str] = []
    texts: Dict[str, str] = {}
    for rel in files:
        text = (pkg / rel).read_text(encoding="utf-8", newline="")
        texts[rel] = text
        try:
            tree = ast.parse(text)
            compile(tree, rel, "exec")
        except SyntaxError:
            broken.append(rel)
            continue
        if not ast.get_docstring(tree):
            undocumented.append(rel)
    if broken:
        return _rejected(check, f"modules that no longer compile: {broken}", broken)
    if undocumented:
        return _rejected(check, f"modules without a module docstring: {undocumented}", undocumented)
    symbols, edges = extract_python_graph(pkg, files)
    if not symbols or not edges:
        return _rejected(check, "the package graph came back empty")
    defined: List[str] = []
    for rel in files:
        defined.extend(_self_valued_codes(texts[rel]))
    unregistered = sorted(set(defined) - REASON_CODES)
    if unregistered:
        return _rejected(
            check,
            f"reason codes raised somewhere but absent from the registry: {unregistered}",
            unregistered,
        )
    readme = (ROOT / "README.md").read_text(encoding="utf-8", newline="")
    unnamed = sorted(code for code in REASON_CODES if "`%s`" % code not in readme)
    if unnamed:
        return _rejected(
            check, f"reason codes the card never names: {unnamed}", unnamed
        )
    promises = _card_promises(readme)
    own_names = _defined_names(texts)
    unmet = sorted(name for name in promises if name not in own_names)
    if unmet:
        return _rejected(
            check,
            f"names the card promises in parentheses that no module defines: {unmet}",
            unmet,
        )
    return _confirmed(
        check,
        "%d modules parse, compile, and carry docstrings; own graph has %d symbols and %d edges; "
        "%d reason codes, every one named in the card; %d names promised in the Contents, all defined"
        % (len(files), len(symbols), len(edges), len(REASON_CODES), len(promises)),
    )


GATES: Tuple[Tuple[str, Callable[[], GateResult]], ...] = (
    ("adapter_contract", gate_adapter_contract),
    ("ast_symbol_graph", gate_ast_graph),
    ("test_selection", gate_test_selection),
    ("graph_scaling", gate_graph_scaling),
    ("strict_abstain_control", gate_strict_abstain_control),
    ("session_transactions", gate_session_transactions),
    ("session_sweep", gate_session_sweep),
    ("external_topology", gate_external_topology),
    ("pattern_corpus_schema", gate_pattern_corpus_schema),
    ("pattern_round_trip", gate_pattern_round_trip),
    ("pattern_pair_honesty", gate_pattern_pair_honesty),
    ("pattern_coverage", gate_pattern_coverage),
    ("cli_card_agreement", gate_cli_card_agreement),
    ("self_lint", gate_self_lint),
)


def main(argv: Sequence[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Run deterministic gates for datasets/codex-python."
    )
    parser.add_argument("--report", default=None, help="Optional path to write JSON report.")
    args = parser.parse_args(argv)

    # The digest anchors the report to a tree, so it is taken before the first
    # gate runs and asked for again when the report is written: the numbers
    # inside describe the tree that was judged at the start, and a tree that
    # moved while the gates ran earns no report at all.
    opening_digest = bundle_digest(digest_input_files(ROOT))

    results: Dict[str, GateResult] = {}
    seconds: Dict[str, float] = {}
    for name, fn in GATES:
        started = time.monotonic()
        results[name] = fn()
        seconds[name] = round(time.monotonic() - started, 3)

    counts = {v: 0 for v in VERDICTS}
    for res in results.values():
        counts[res.verdict] = counts.get(res.verdict, 0) + 1

    overall = REJECTED if counts[REJECTED] else (ABSTAIN if counts[ABSTAIN] else CONFIRMED)
    for name, _ in GATES:
        r = results[name]
        print(f"{name:<24} {r.verdict:<9} {r.note}")
    print(
        f"GATES: {overall} ({len(GATES)} gates: "
        + ", ".join(f"{counts[v]} {v}" for v in VERDICTS)
        + ")"
    )

    if args.report:
        closing_digest = bundle_digest(digest_input_files(ROOT))
        if closing_digest != opening_digest:
            print(
                "REPORT: REFUSED (the tree changed while the gates ran, before %s and after %s): "
                "rerun on a quiet tree" % (opening_digest[:12], closing_digest[:12])
            )
            return 1
        out_path = Path(args.report)
        out_path.parent.mkdir(parents=True, exist_ok=True)
        payload = {
            "schema": "lingologos-python-gates-1",
            "verdict": overall,
            "sources_sha256": opening_digest,
            "kernel_sha256": kernel_digest(),
            "counts": counts,
            "gates": [
                {
                    "name": name,
                    "verdict": results[name].verdict,
                    "seconds": seconds[name],
                    "check": results[name].command,
                    "note": results[name].note,
                    "failed_targets": list(results[name].failed_targets),
                }
                for name, _ in GATES
            ],
        }
        out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8", newline="\n")

    return 1 if overall == REJECTED else 0


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