forked from ChelseaKR/permit-bearings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbeta_gate.py
More file actions
2924 lines (2756 loc) · 101 KB
/
Copy pathbeta_gate.py
File metadata and controls
2924 lines (2756 loc) · 101 KB
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
"""Strict pilot-neutral aggregate gate for a future limited beta.
The committed record is intentionally a planning artifact. It binds existing
specialized ledgers and recomputes their current conservative state, but schema
version 1 cannot record a tested beta, an approval, or a partner decision.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import stat
import tempfile
import unicodedata
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import asdict, dataclass
from datetime import date
from pathlib import Path, PurePosixPath
from typing import Any
from .beta_operations import load_beta_operations_readiness
from .conformance_evaluation import load_evaluation_manifest
from .dates import resolve_today
from .journey import load_journey_config, resolve_journey
from .program_availability import load_program_availability
from .readiness import load_and_evaluate_readiness
from .rule_verification import effective_status, level_coverage, load_rule_verifications
from .screening import load_rules
from .source_state import load_source_state_snapshot
from .workflow_registry import load_workflow_registry
SCHEMA_VERSION = 1
GATE_ID = "limited-beta-aggregate-v1"
GATE_VERSION = "1.0.0"
RECORD_STATUS = "prepared"
BETA_STATUS = "not_run"
DEFAULT_RECORD_PATH = Path("data/validation/pilot-beta-gate.json")
MAX_RECORD_BYTES = 256 * 1024
MAX_ARTIFACT_BYTES = 8 * 1024 * 1024
MAX_SNAPSHOT_FILE_BYTES = 16 * 1024 * 1024
MAX_SNAPSHOT_BYTES = 40 * 1024 * 1024
WORKFLOW_REGISTRY_PATH = "data/workflows/registry.json"
CLAIM_BOUNDARY = (
"PREPARED AGGREGATE / TESTED BETA NOT RUN. This record recomputes the "
"current conservative gate state from bound repository artifacts. It is "
"not evidence of an active pilot, deployed beta, human or jurisdiction "
"review, applicant research, accessibility or language approval, partner "
"acceptance, privacy/security/records approval, completed rehearsal, "
"application completeness, compliance, eligibility, permit approval, or "
"statewide local coverage. A passing or decision-bearing gate requires a "
"separately reviewed execution schema and external receipts."
)
EXPORT_BOUNDARY_CLAIM = (
"This aggregate record, its validator, and any future filled execution "
"record are outside public/synthetic evidence export profiles v1 and v2. "
"Profile validity is portability-mechanism evidence only, not jurisdiction "
"ownership, offboarding acceptance, or beta evidence."
)
_STABLE_ID = re.compile(r"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$")
_TOKEN_ID = re.compile(r"^[A-Za-z][A-Za-z0-9]*(?:[-_.][A-Za-z0-9]+)*$")
_SEMVER = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+$")
_FINGERPRINT = re.compile(r"^sha256:[0-9a-f]{64}$")
_RAW_SHA256 = re.compile(r"^[0-9a-f]{64}$")
_ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
_TOP_LEVEL_KEYS = {
"aggregate",
"artifact_bindings",
"beta_status",
"claim_boundary",
"derived_gates",
"export_boundary",
"gate_id",
"gate_version",
"pilot_scope",
"prepared_on",
"prototype_reference",
"record_status",
"schema_version",
}
_PILOT_SCOPE_KEYS = {
"active_source_package_id",
"deployment_url",
"frozen_commit_sha",
"jurisdiction_id",
"permit_subtype_id",
"review_owner_role",
"source_owner_role",
"sponsor_role",
"status",
"workflow_id",
"workflow_version",
}
_REFERENCE_KEYS = {
"classification",
"counts_as_active_pilot",
"fact_envelope_fingerprint",
"journey_fingerprint",
"journey_id",
"journey_version",
"readiness_packet_fingerprint",
"readiness_packet_id",
"readiness_workflow_fingerprint",
"readiness_workflow_id",
"screening_case_fingerprint",
"screening_case_id",
}
_BINDING_KEYS = {"artifact_id", "path", "sha256"}
_GATE_KEYS = {"artifact_ids", "gate_id", "reason_code", "status"}
_AGGREGATE_KEYS = {
"artifact_set_fingerprint",
"blocking_gate_ids",
"changed_source_count",
"not_run_gate_count",
"prepared_gate_count",
"reference_currency_blocker_ids",
"stale_rule_count",
"status",
"supports_deployment_approval_claim",
"supports_human_review_claim",
"supports_partner_acceptance_claim",
"supports_statewide_beta_claim",
"supports_tested_beta_claim",
"unverifiable_source_count",
"unverified_rule_count",
}
_EXPORT_BOUNDARY_KEYS = {
"claim",
"future_profile_review_status",
"gate_path",
"inclusion_status",
"profile_id",
"profile_path",
}
_ARTIFACT_PATHS = {
"beta_operations": "data/validation/beta-operations-readiness.json",
"content_review": "data/validation/woodland-content-review.json",
"external_evidence_gate": "data/validation/woodland-flagship-gate.json",
"heldout_evaluation": "data/conformance/evaluations/heldout-v1/manifest.json",
"manual_evidence": "data/validation/woodland-manual-evidence.json",
"participant_sessions": "data/validation/woodland-participant-sessions.json",
"public_synthetic_export": "data/export/public-synthetic-evidence-v1.json",
"reference_journey": (
"data/journeys/generated/woodland-preapproved-detached-adu.json"
),
"reference_packet": (
"data/readiness/generated/woodland-preapproved-adu-evidence.json"
),
"rule_verification": "data/validation/rule-verification.json",
"source_change_rehearsal": (
"data/validation/woodland-source-change-rehearsal.json"
),
"source_state": "data/source-status/current.json",
}
_ARTIFACT_IDS = tuple(sorted(_ARTIFACT_PATHS))
_EXPORT_PROFILE_ID = "permit-bearings-public-synthetic-evidence-v1"
_EXPORT_PROFILE_V2_ID = "permit-bearings-public-synthetic-evidence-v2"
_EXPORT_PROFILE_V2_PATH = "data/export/public-synthetic-evidence-v2.json"
_EXPORT_PROFILE_V2_SHA256 = (
"sha256:01d4072735806eeab6cb8ba8bdc2f1c5118b62f28206405d95fa50179059f371"
)
_EXPORT_EXCLUDED_PATHS = {
DEFAULT_RECORD_PATH.as_posix(),
"src/permit_pathways/beta_gate.py",
"src/permit_pathways/beta_gate_cli.py",
"tests/test_beta_gate.py",
}
# These planning ledgers are deliberately immutable in aggregate schema v1.
# Pinning their independent raw bytes prevents a coordinated rewrite of a
# favorable nested result, disclaimer, or aggregate plus the binding digest.
# Executed evidence belongs in a separately reviewed execution schema.
_NOT_RUN_ARTIFACT_SHA256 = {
"beta_operations": (
"sha256:858dad1191fd070eab4d3c2c168d77b6c61ac45553d0e968d4070e22075bf394"
),
"content_review": (
"sha256:7110471ca09e6919dad42ef47990286f5530ba993d8840214a4f6e432b9d6abe"
),
"external_evidence_gate": (
"sha256:88f43375a80b0a0e02177e3605706c4e5251854cd00c94a0b18e42c773a33a7f"
),
"heldout_evaluation": (
"sha256:816bb414a09edbc024a2be7780761a1a2abb5f6cb2464c56e5790b58ad79e7b2"
),
"manual_evidence": (
"sha256:db1c41cf2752f1517a608e2ae6523cc5cf5b53099bd0413458aee1da0004d8d9"
),
"participant_sessions": (
"sha256:28e564adf81ec942f7a74a5cb849972f9607c4701ce8921673e644924028ab0f"
),
"public_synthetic_export": (
"sha256:2e5153f1dae2f7b660dcae156ed2d0f84480eff7a02a163fa8426a5272314e9e"
),
"source_change_rehearsal": (
"sha256:f28de3e2d86022ec61e6c73bbc98b64a658543886d98344e69063cd3d3c7d1f1"
),
}
_ARTIFACT_TOP_LEVEL_KEYS = {
"beta_operations": {
"approvals",
"architecture_decision_path",
"boundary",
"claim_boundary",
"controls",
"decision_status",
"deployment",
"document_bindings",
"export_boundary",
"prepared_on",
"record_id",
"record_version",
"records_boundary",
"runbook_path",
"schema_version",
"status",
},
"content_review": {
"artifact_lock",
"baseline_provenance",
"cross_cutting_checks",
"gate",
"prepared_on",
"record_type",
"reviewer_slots",
"rows",
"schema_version",
"scoring_key_version",
"status",
"thresholds",
},
"external_evidence_gate": {
"answer_key",
"artifact_lock",
"claim_boundary",
"decision",
"evidence_ledgers",
"external_evidence",
"gate_id",
"prepared_on",
"recruitment",
"schema_version",
"status",
"thresholds",
},
"heldout_evaluation": {
"claim_boundary",
"coverage_contract",
"development_source_exclusions",
"evaluation_id",
"external_blockers",
"freeze",
"inputs",
"output",
"raw_count_fields",
"reference_labels",
"scanner",
"schema_version",
"scoring_unit",
"status",
},
"manual_evidence": {
"artifact_lock",
"claim_boundary",
"manual_checks",
"prepared_on",
"privacy_protocol",
"record_id",
"record_version",
"schema_version",
"scope",
"spanish_review_protocol",
"spanish_semantic_reviews",
"status",
},
"participant_sessions": {
"aggregate",
"artifact_lock",
"claim_boundary",
"prepared_on",
"privacy_protocol",
"record_id",
"record_version",
"schema_version",
"scorecard_version",
"scorecards",
"status",
},
"public_synthetic_export": {
"entries",
"package",
"public_state_assertions",
"schema_version",
"scope",
},
"reference_journey": {
"applicability_facts",
"applicability_status",
"boundary",
"candidate_route_rule_ids",
"candidate_routes",
"editable_applicability_fact_ids",
"fact_envelope",
"fact_envelope_fingerprint",
"journey_fingerprint",
"journey_id",
"label",
"readiness_evidence_manifest",
"readiness_packet_fingerprint",
"readiness_packet_id",
"readiness_workflow_fingerprint",
"readiness_workflow_id",
"route_source_review_due_on",
"route_source_status",
"route_source_status_as_of",
"schema_version",
"screening_case_fingerprint",
"screening_case_id",
"screening_expected_rule_ids",
"screening_intake",
"status",
"synthetic",
"version",
},
"reference_packet": {
"applicability_status",
"boundary",
"counts",
"evaluated_on",
"facts",
"findings",
"inventory",
"manifest_type",
"overall_status",
"packet_fingerprint",
"packet_id",
"schema_version",
"source_bindings",
"source_review_due_on",
"source_status",
"source_status_as_of",
"staff_questions",
"synthetic",
"workflow_fingerprint",
"workflow_id",
},
"rule_verification": {"entries", "schema_version"},
"source_change_rehearsal": {
"aggregate",
"artifact_lock",
"claim_boundary",
"execution",
"expected_impact",
"observed_impact",
"partner_burden_decision",
"prepared_on",
"publication_receipt",
"record_id",
"record_version",
"schema_version",
"simulation_contract",
"stages",
"status",
"timing",
},
"source_state": {
"affected_golden_case_ids",
"affected_rule_ids",
"changed_source_ids",
"checked_at",
"observations",
"receipt",
"schema_version",
"snapshot_id",
"source_registry_sha256",
"unaffected_golden_case_ids",
"unaffected_rule_ids",
"unverifiable_source_ids",
},
}
_GATE_CONTRACTS: dict[str, tuple[tuple[str, ...], str]] = {
"active_scope": ((), "pilot_scope_not_selected"),
"applicant_evidence": (
("participant_sessions",),
"participant_sessions_not_run",
),
"content_authority": (("content_review",), "content_review_not_run"),
"deterministic_evaluation": (
("heldout_evaluation", "source_state"),
"heldout_evaluation_not_run",
),
"frozen_artifact": (
("external_evidence_gate", "source_state"),
"artifact_lock_not_run",
),
"human_access": (("manual_evidence",), "manual_access_checks_not_run"),
"language": (("manual_evidence",), "language_reviews_not_run"),
"maintainability": (
("source_change_rehearsal",),
"source_change_rehearsal_not_run",
),
"ownership_export": (
("public_synthetic_export",),
"partner_ownership_acceptance_not_run",
),
"packet_behavior": (
("reference_journey", "reference_packet"),
"synthetic_reference_is_not_pilot_evidence",
),
"partner_decision": (
("external_evidence_gate",),
"partner_and_decision_receipts_absent",
),
"privacy_records_security": (
("beta_operations",),
"operations_package_not_approved",
),
"problem_evidence": (
("participant_sessions",),
"problem_evidence_sessions_not_run",
),
"review_levels": (
("rule_verification", "source_state"),
"reachable_human_review_not_established",
),
}
class _DuplicateKey(ValueError):
"""Raised before a duplicate JSON key can replace evidence."""
@dataclass(frozen=True)
class ArtifactBinding:
"""One raw-byte-bound repository artifact."""
artifact_id: str
path: str
sha256: str
raw: bytes
payload: dict[str, Any]
@dataclass(frozen=True)
class BetaGateSummary:
"""Conservative result from validating and recomputing the gate."""
gate_id: str
gate_version: str
prepared_on: str
record_status: str
beta_status: str
artifact_count: int
artifact_set_fingerprint: str
not_run_gate_count: int
blocking_gate_ids: tuple[str, ...]
rule_count: int
machine_linked_rule_count: int
stale_rule_count: int
unverified_rule_count: int
changed_source_count: int
unverifiable_source_count: int
reference_currency_blocker_ids: tuple[str, ...]
record_sha256: str
def to_dict(self) -> dict[str, Any]:
"""Return stable machine-readable CLI output."""
return {
"artifact_count": self.artifact_count,
"artifact_set_fingerprint": self.artifact_set_fingerprint,
"beta_status": self.beta_status,
"blocking_gate_ids": list(self.blocking_gate_ids),
"changed_source_count": self.changed_source_count,
"gate_id": self.gate_id,
"gate_version": self.gate_version,
"machine_linked_rule_count": self.machine_linked_rule_count,
"not_run_gate_count": self.not_run_gate_count,
"prepared_on": self.prepared_on,
"record_sha256": self.record_sha256,
"record_status": self.record_status,
"reference_currency_blocker_ids": list(self.reference_currency_blocker_ids),
"rule_count": self.rule_count,
"stale_rule_count": self.stale_rule_count,
"supports_deployment_approval_claim": False,
"supports_human_review_claim": False,
"supports_partner_acceptance_claim": False,
"supports_statewide_beta_claim": False,
"supports_tested_beta_claim": False,
"unverifiable_source_count": self.unverifiable_source_count,
"unverified_rule_count": self.unverified_rule_count,
}
def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise _DuplicateKey(key)
result[key] = value
return result
def _reject_constant(value: str) -> None:
raise ValueError(f"unsupported JSON constant {value!r}")
def _decode_json(raw: bytes, field: str, *, maximum: int) -> dict[str, Any]:
if len(raw) > maximum:
raise ValueError(f"{field}: exceeds byte limit")
try:
payload = json.loads(
raw.decode("utf-8"),
object_pairs_hook=_unique_object,
parse_constant=_reject_constant,
)
except (
UnicodeDecodeError,
json.JSONDecodeError,
_DuplicateKey,
RecursionError,
ValueError,
) as error:
raise ValueError(f"{field}: expected strict UTF-8 JSON") from error
if not isinstance(payload, dict):
raise ValueError(f"{field}: expected an object")
return payload
def _object(value: Any, field: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise ValueError(f"{field}: expected an object")
return value
def _array(value: Any, field: str) -> list[Any]:
if not isinstance(value, list):
raise ValueError(f"{field}: expected an array")
return value
def _text(value: Any, field: str) -> str:
if not isinstance(value, str) or not value or value != value.strip():
raise ValueError(f"{field}: expected non-blank trimmed text")
if all(unicodedata.category(character)[0] in ("C", "Z") for character in value):
raise ValueError(f"{field}: expected non-blank trimmed text")
return value
def _exact_keys(value: dict[str, Any], expected: set[str], field: str) -> None:
unknown = sorted(set(value) - expected)
if unknown:
raise ValueError(f"{field}: unknown fields: {', '.join(unknown)}")
missing = sorted(expected - set(value))
if missing:
raise ValueError(f"{field}: missing fields: {', '.join(missing)}")
def _strict_equal(value: Any, expected: Any) -> bool:
if type(value) is not type(expected):
return False
if isinstance(expected, dict):
return set(value) == set(expected) and all(
_strict_equal(value[key], expected[key]) for key in expected
)
if isinstance(expected, list):
return len(value) == len(expected) and all(
_strict_equal(item, other)
for item, other in zip(value, expected, strict=True)
)
return bool(value == expected)
def _exact(value: Any, expected: Any, field: str) -> None:
if not _strict_equal(value, expected):
raise ValueError(f"{field}: expected {expected!r}")
def _stable_id(value: Any, field: str) -> str:
identifier = _text(value, field)
if not _STABLE_ID.fullmatch(identifier):
raise ValueError(f"{field}: expected a stable identifier")
return identifier
def _token_id(value: Any, field: str) -> str:
identifier = _text(value, field)
if not _TOKEN_ID.fullmatch(identifier):
raise ValueError(f"{field}: expected a stable token")
return identifier
def _semver(value: Any, field: str) -> str:
version = _text(value, field)
if not _SEMVER.fullmatch(version):
raise ValueError(f"{field}: expected a semantic version")
return version
def _fingerprint(value: Any, field: str) -> str:
fingerprint = _text(value, field)
if not _FINGERPRINT.fullmatch(fingerprint):
raise ValueError(f"{field}: expected sha256:<64 lowercase hex>")
return fingerprint
def _prepared_on(value: Any, *, today: date) -> str:
if not isinstance(value, str) or not _ISO_DATE.fullmatch(value):
raise ValueError("prepared_on: expected YYYY-MM-DD")
try:
parsed = date.fromisoformat(value)
except ValueError as error:
raise ValueError("prepared_on: invalid date") from error
if parsed > today:
raise ValueError("prepared_on: future dates are not allowed")
return value
def _iso_date_value(value: Any, field: str) -> date:
if not isinstance(value, str) or not _ISO_DATE.fullmatch(value):
raise ValueError(f"{field}: expected YYYY-MM-DD")
try:
parsed = date.fromisoformat(value)
except ValueError as error:
raise ValueError(f"{field}: invalid date") from error
if parsed.isoformat() != value:
raise ValueError(f"{field}: expected an exact ISO date")
return parsed
def _canonical_relative_path(value: Any, field: str) -> str:
relative = _text(value, field)
pure = PurePosixPath(relative)
if (
pure.is_absolute()
or not pure.parts
or ".." in pure.parts
or any(part in {"", ".", ".."} for part in pure.parts)
or "\\" in relative
or str(pure) != relative
):
raise ValueError(f"{field}: expected a canonical repository-relative path")
return relative
def _repository_root(path: Path) -> Path:
lexical = Path(os.path.abspath(path))
for candidate in reversed((lexical, *lexical.parents[:-1])):
try:
if candidate.is_symlink():
raise ValueError(
f"{path}: symbolic-link repository roots are not allowed"
)
except OSError as error:
raise ValueError(
f"{path}: repository root could not be inspected"
) from error
try:
root = lexical.resolve(strict=True)
except OSError as error:
raise ValueError(f"{path}: repository root could not be resolved") from error
if not root.is_dir():
raise ValueError(f"{path}: repository root must be a directory")
return root
def _is_canonical_record(path: Path, root: Path) -> bool:
specified = path if path.is_absolute() else root / path
lexical = Path(os.path.abspath(specified))
return lexical == root / DEFAULT_RECORD_PATH
def _read_repository_file(
root: Path,
relative: str,
field: str,
*,
maximum: int,
) -> bytes:
"""Read one regular file through no-follow descriptors anchored at ``root``."""
canonical = _canonical_relative_path(relative, field)
parts = PurePosixPath(canonical).parts
directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW
file_flags = os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW
descriptors: list[int] = []
try:
directory_fd = os.open(root, directory_flags)
descriptors.append(directory_fd)
for part in parts[:-1]:
directory_fd = os.open(
part,
directory_flags,
dir_fd=directory_fd,
)
descriptors.append(directory_fd)
file_fd = os.open(parts[-1], file_flags, dir_fd=directory_fd)
descriptors.append(file_fd)
metadata = os.fstat(file_fd)
if not stat.S_ISREG(metadata.st_mode):
raise ValueError(f"{field}: expected a regular file")
if metadata.st_nlink != 1:
raise ValueError(f"{field}: linked files are not allowed")
if metadata.st_size > maximum:
raise ValueError(f"{field}: exceeds byte limit")
chunks: list[bytes] = []
total = 0
while chunk := os.read(file_fd, 64 * 1024):
total += len(chunk)
if total > maximum:
raise ValueError(f"{field}: exceeds byte limit")
chunks.append(chunk)
return b"".join(chunks)
except OSError as error:
raise ValueError(
f"{field}: expected a regular file without symbolic links or aliases"
) from error
finally:
for descriptor in reversed(descriptors):
os.close(descriptor)
def _read_external_record(path: Path) -> tuple[dict[str, Any], bytes]:
"""Read an explicit test/draft record once without following any links."""
lexical = Path(os.path.abspath(path))
parts = lexical.parts[1:]
descriptors: list[int] = []
try:
directory_fd = os.open("/", os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
descriptors.append(directory_fd)
for part in parts[:-1]:
directory_fd = os.open(
part,
os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW,
dir_fd=directory_fd,
)
descriptors.append(directory_fd)
file_fd = os.open(
parts[-1],
os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW,
dir_fd=directory_fd,
)
descriptors.append(file_fd)
metadata = os.fstat(file_fd)
if not stat.S_ISREG(metadata.st_mode):
raise ValueError("aggregate gate: expected a regular file")
if metadata.st_nlink != 1:
raise ValueError("aggregate gate: linked files are not allowed")
if metadata.st_size > MAX_RECORD_BYTES:
raise ValueError("aggregate gate: exceeds byte limit")
chunks: list[bytes] = []
total = 0
while chunk := os.read(file_fd, 64 * 1024):
total += len(chunk)
if total > MAX_RECORD_BYTES:
raise ValueError("aggregate gate: exceeds byte limit")
chunks.append(chunk)
raw = b"".join(chunks)
except OSError as error:
raise ValueError(
"aggregate gate: expected a regular file without symbolic-link ancestors"
) from error
finally:
for descriptor in reversed(descriptors):
os.close(descriptor)
return _decode_json(raw, "aggregate gate", maximum=MAX_RECORD_BYTES), raw
def _capture_repository_tree( # noqa: C901
root: Path,
relative: str,
) -> tuple[dict[str, bytes], set[str]]:
"""Capture a complete repository subtree through no-follow descriptors.
Each regular file is opened exactly once. Directories and files are
inventoried by canonical relative path; any linked or special entry fails
closed before specialized loaders see a private snapshot.
"""
base = _canonical_relative_path(relative, "snapshot tree")
directory_flags = os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW
descriptors: list[int] = []
payloads: dict[str, bytes] = {}
directories: set[str] = {base}
total = 0
def visit(directory_fd: int, prefix: str) -> None: # noqa: C901
nonlocal total
try:
names = sorted(os.listdir(directory_fd))
except OSError as error:
raise ValueError(f"snapshot tree {prefix}: could not be listed") from error
for name in names:
if not name or name in {".", ".."} or "/" in name or "\\" in name:
raise ValueError(f"snapshot tree {prefix}: unsafe entry name")
child = f"{prefix}/{name}"
try:
metadata = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
except OSError as error:
raise ValueError(
f"snapshot tree {child}: could not be inspected"
) from error
if stat.S_ISDIR(metadata.st_mode):
try:
child_fd = os.open(name, directory_flags, dir_fd=directory_fd)
except OSError as error:
raise ValueError(
f"snapshot tree {child}: linked directories are not allowed"
) from error
descriptors.append(child_fd)
directories.add(child)
visit(child_fd, child)
continue
if not stat.S_ISREG(metadata.st_mode):
raise ValueError(
f"snapshot tree {child}: symbolic links and special files "
"are not allowed"
)
try:
file_fd = os.open(
name,
os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW,
dir_fd=directory_fd,
)
descriptors.append(file_fd)
opened = os.fstat(file_fd)
if not stat.S_ISREG(opened.st_mode):
raise ValueError(f"snapshot tree {child}: expected a regular file")
if opened.st_nlink != 1:
raise ValueError(
f"snapshot tree {child}: linked files are not allowed"
)
if opened.st_size > MAX_SNAPSHOT_FILE_BYTES:
raise ValueError(f"snapshot tree {child}: exceeds byte limit")
chunks: list[bytes] = []
count = 0
while chunk := os.read(file_fd, 64 * 1024):
count += len(chunk)
total += len(chunk)
if count > MAX_SNAPSHOT_FILE_BYTES or total > MAX_SNAPSHOT_BYTES:
raise ValueError(
"repository snapshot exceeds aggregate byte limit"
)
chunks.append(chunk)
payloads[child] = b"".join(chunks)
except OSError as error:
raise ValueError(
f"snapshot tree {child}: linked files are not allowed"
) from error
try:
root_fd = os.open(
root, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC | os.O_NOFOLLOW
)
descriptors.append(root_fd)
directory_fd = root_fd
for part in PurePosixPath(base).parts:
directory_fd = os.open(part, directory_flags, dir_fd=directory_fd)
descriptors.append(directory_fd)
visit(directory_fd, base)
except OSError as error:
raise ValueError(f"snapshot tree {base}: could not be opened") from error
finally:
for descriptor in reversed(descriptors):
os.close(descriptor)
return payloads, directories
def _sha256(raw: bytes) -> str:
return f"sha256:{hashlib.sha256(raw).hexdigest()}"
def artifact_set_fingerprint(rows: list[dict[str, Any]]) -> str:
"""Fingerprint the exact ordered binding registry."""
encoded = json.dumps(
rows,
ensure_ascii=True,
separators=(",", ":"),
sort_keys=True,
).encode("utf-8")
return _sha256(encoded)
def _load_bindings(
value: Any,
captured: dict[str, bytes],
) -> dict[str, ArtifactBinding]:
rows = _array(value, "artifact_bindings")
observed_ids: list[str] = []
observed_paths: list[str] = []
bindings: dict[str, ArtifactBinding] = {}
for index, item in enumerate(rows):
field = f"artifact_bindings[{index}]"
record = _object(item, field)
_exact_keys(record, _BINDING_KEYS, field)
artifact_id = _stable_id(record["artifact_id"], f"{field}.artifact_id")
observed_ids.append(artifact_id)
if artifact_id not in _ARTIFACT_PATHS:
raise ValueError(f"{field}.artifact_id: unsupported artifact role")
relative = _canonical_relative_path(record["path"], f"{field}.path")
_exact(relative, _ARTIFACT_PATHS[artifact_id], f"{field}.path")
observed_paths.append(relative)
expected_sha = _fingerprint(record["sha256"], f"{field}.sha256")
try:
raw = captured[relative]
except KeyError as error:
raise ValueError(f"{field}.path: bound artifact is missing") from error
if len(raw) > MAX_ARTIFACT_BYTES:
raise ValueError(f"{field}.path: exceeds byte limit")
actual_sha = _sha256(raw)
if actual_sha != expected_sha:
raise ValueError(f"{field}.sha256: bound artifact bytes drifted")
payload = _decode_json(raw, relative, maximum=MAX_ARTIFACT_BYTES)
_exact_keys(
payload,
_ARTIFACT_TOP_LEVEL_KEYS[artifact_id],
f"{artifact_id} artifact",
)
bindings[artifact_id] = ArtifactBinding(
artifact_id=artifact_id,
path=relative,
sha256=expected_sha,
raw=raw,
payload=payload,
)
if observed_ids != list(_ARTIFACT_IDS):
raise ValueError(
"artifact_bindings: expected the exact sorted artifact registry"
)
if len(observed_paths) != len(set(observed_paths)):
raise ValueError("artifact_bindings: duplicate paths are not allowed")
return bindings
def _validate_not_run_pins(bindings: dict[str, ArtifactBinding]) -> None:
for artifact_id, pinned in sorted(_NOT_RUN_ARTIFACT_SHA256.items()):
_exact(
bindings[artifact_id].sha256,
pinned,
f"{artifact_id} immutable not-run nested schema and bytes",
)
def _snapshot_dependency_paths(
bindings: dict[str, ArtifactBinding],
) -> tuple[str, ...]:
paths = {binding.path for binding in bindings.values()}
profile = bindings["public_synthetic_export"].payload
entries = _array(profile["entries"], "export profile.entries")
exported_paths: set[str] = set()
for index, item in enumerate(entries):
entry = _object(item, f"export profile.entries[{index}]")
exported_paths.add(
_canonical_relative_path(
entry.get("path"), f"export profile.entries[{index}].path"
)
)
forbidden = sorted(exported_paths.intersection(_EXPORT_EXCLUDED_PATHS))
if forbidden:
raise ValueError(
"export profile v1 includes beta-gate files: " + ", ".join(forbidden)
)
paths.update(exported_paths)
evaluation = bindings["heldout_evaluation"].payload
scanner = _object(evaluation["scanner"], "heldout evaluation.scanner")
for field in ("scanner_path", "checks_path", "evaluator_path"):
paths.add(
_canonical_relative_path(
scanner.get(field), f"heldout evaluation.scanner.{field}"
)
)
operations = bindings["beta_operations"].payload
for field in ("architecture_decision_path", "runbook_path"):
paths.add(
_canonical_relative_path(operations[field], f"beta operations.{field}")
)
for index, item in enumerate(
_array(operations["document_bindings"], "beta operations.document_bindings")
):
document = _object(item, f"beta operations.document_bindings[{index}]")
paths.add(
_canonical_relative_path(
document.get("path"),
f"beta operations.document_bindings[{index}].path",
)
)