-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate_state.py
More file actions
1964 lines (1858 loc) · 80.6 KB
/
Copy pathevaluate_state.py
File metadata and controls
1964 lines (1858 loc) · 80.6 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
#!/usr/bin/env python3
"""Evaluate one GitHub Codex PR-loop snapshot without performing mutations.
The caller supplies already-fetched GitHub and Automation state as JSON. This
module validates the complete snapshot, applies the bounded lifecycle policy,
and returns one permitted next action. It has no third-party dependencies and
does not access Git, GitHub, the network, or Codex Automations itself.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
import unicodedata
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
DEFAULT_POLICY_PATH = Path(__file__).resolve().parents[1] / "references" / "loop-policy.json"
FULL_SHA = re.compile(r"^[0-9a-f]{40}$")
SHA256 = re.compile(r"^[0-9a-f]{64}$")
RUN_ID = re.compile(r"^[0-9a-f]{32}$")
REPOSITORY = re.compile(r"^[a-z0-9][a-z0-9-]{0,38}/[a-z0-9._-]{1,100}$")
REQUEST_KEY = re.compile(r"^[1-9][0-9]*:[0-9a-f]{40}$")
WINDOWS_DEVICE_STEM = re.compile(
r"^(?:con|prn|aux|nul|clock\$|conin\$|conout\$|com[1-9]|lpt[1-9])$",
re.IGNORECASE,
)
WINDOWS_GIT_ALIAS = re.compile(r"^\.?git~[1-9][0-9]*$", re.IGNORECASE)
AUTOMATION_STATUSES = {"ACTIVE", "PAUSED"}
AUTOMATION_PROMPT_PLACEHOLDERS = (
"AUTOMATION_KEY",
"BOOTSTRAP_CHECKPOINT_JSON",
)
AUTOMATION_PROMPT_TEMPLATE = "\n".join(
(
"Continue $github-codex-pr-loop from the exact checkpoint below. "
"Re-fetch all external state and follow only the installed evaluator's emitted action.",
"Loop key: {{AUTOMATION_KEY}}",
"Bootstrap checkpoint JSON: {{BOOTSTRAP_CHECKPOINT_JSON}}",
)
)
POLICY_V1 = {
"schema_version": 1,
"supported_host": "github.com",
"same_repository_pull_requests_only": True,
"minimum_python_version": "3.10",
"manifest_hash": "sha256-canonical-json-v1",
"git_execution_profile": "sanitized-gh-https-v1",
"run_id_bits": 128,
"trusted_codex_bot_database_id": 199175422,
"heartbeat_interval_minutes": 2,
"heartbeat_rrule": "FREQ=MINUTELY;INTERVAL=2",
"no_response_timeout_minutes": 60,
"max_fix_rounds": 5,
"default_mode": "autonomous",
"modes": ["autonomous", "approval-gated", "report-only"],
"gate_states": ["pass", "fail", "pending", "unknown"],
"terminal_message_template": (
"No remaining actionable Codex findings for SHA `<full-sha>`."
),
}
RESPONSE_SOURCES = {"issue-comment", "review", "review-comment"}
RESPONSE_FIELDS = {
"source",
"id",
"bot_type",
"bot_id",
"body_sha256",
"content_version_at",
"created_at",
"commit_sha",
"trigger_request_comment_id",
"zero_findings_signal",
}
GATE_STATES = {"pass", "fail", "pending", "unknown"}
REQUEST_STATES = {
"pending",
"awaiting-remediation-approval",
"awaiting-finalization-approval",
"processing",
}
REQUIRED_STATE_FIELDS = {
"actionable_codex_threads",
"actionable_thread_snapshots",
"approval_gate",
"approved_finalization_plan_hash",
"approved_remediation_plan_hash",
"approved_request_key",
"authenticated_user_id",
"automation_key",
"automations",
"branch_protection_gate",
"base_branch",
"check_gate",
"claimed_finalization_plan_hash",
"claimed_finalization_request_key",
"completed_request_keys",
"current_head_sha",
"current_base_sha",
"eligible_codex_threads",
"eligible_thread_snapshots",
"finalization_plan_hash",
"finalization_approved_request_key",
"fix_rounds",
"head_branch_exists",
"head_branch",
"host",
"intervening_review_requests",
"mergeability_gate",
"mode",
"non_codex_rooted_threads",
"now",
"owned_automation_id",
"policy_schema_version",
"post_finalization",
"processing_claim_token",
"pr_number",
"pr_base_branch",
"pr_head_branch",
"pr_is_draft",
"pr_state",
"finalization_manifest",
"execution_boundary",
"remediation_manifest",
"remediation_plan_hash",
"remote_name",
"repository",
"request_author_id",
"request_comment_id",
"request_created_at",
"request_base_sha",
"request_head_sha",
"request_state",
"responses",
"run_id",
"same_repository_pr",
"terminal_error",
}
def _timestamp(value: Any, field: str) -> datetime:
if not isinstance(value, str) or not value:
raise ValueError(f"{field} must be a non-empty ISO-8601 timestamp")
normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
try:
parsed = datetime.fromisoformat(normalized)
except ValueError as exc:
raise ValueError(f"{field} must be a valid ISO-8601 timestamp") from exc
if parsed.tzinfo is None:
raise ValueError(f"{field} must include a timezone")
return parsed.astimezone(timezone.utc)
def _sha(value: Any, field: str) -> str:
if not isinstance(value, str) or not FULL_SHA.fullmatch(value):
raise ValueError(f"{field} must be a lowercase 40-character Git SHA")
return value
def _nonnegative_int(value: Any, field: str) -> int:
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ValueError(f"{field} must be a non-negative integer")
return value
def _positive_int(value: Any, field: str) -> int:
result = _nonnegative_int(value, field)
if result == 0:
raise ValueError(f"{field} must be positive")
return result
def _boolean(value: Any, field: str) -> bool:
if not isinstance(value, bool):
raise ValueError(f"{field} must be a boolean")
return value
def _optional_request_key(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not REQUEST_KEY.fullmatch(value):
raise ValueError(f"{field} must be a canonical request key or null")
return value
def _optional_sha256(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, str) or not SHA256.fullmatch(value):
raise ValueError(f"{field} must be a lowercase SHA-256 digest or null")
return value
def _gate(value: Any, field: str) -> str:
if value not in GATE_STATES:
raise ValueError(f"{field} must be one of: {', '.join(sorted(GATE_STATES))}")
return value
def _manifest_digest(value: Any, field: str) -> str | None:
if value is None:
return None
if not isinstance(value, dict):
raise ValueError(f"{field} must be an object or null")
def validate(node: Any, path: str) -> None:
if node is None or isinstance(node, (bool, int, str)):
return
if isinstance(node, float):
raise ValueError(f"{path} must not contain floating-point values")
if isinstance(node, list):
for index, item in enumerate(node):
validate(item, f"{path}[{index}]")
return
if isinstance(node, dict):
if not all(isinstance(key, str) for key in node):
raise ValueError(f"{path} object keys must be strings")
for key, item in node.items():
validate(item, f"{path}.{key}")
return
raise ValueError(f"{path} contains an unsupported JSON value")
validate(value, field)
canonical = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _exact_fields(value: Any, fields: set[str], field: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise ValueError(f"{field} must be an object")
actual = set(value)
if actual != fields:
missing = sorted(fields - actual)
extra = sorted(actual - fields)
details = []
if missing:
details.append(f"missing {', '.join(missing)}")
if extra:
details.append(f"unexpected {', '.join(extra)}")
raise ValueError(f"{field} has invalid fields: {'; '.join(details)}")
return value
def _ref_name(value: Any, field: str) -> str:
if not isinstance(value, str) or not value:
raise ValueError(f"{field} must be a non-empty Git ref name")
forbidden = set(" ~^:?*[\\")
if (
value.startswith("-")
or value.startswith("/")
or value.endswith("/")
or value.endswith(".")
or "//" in value
or ".." in value
or "@{" in value
or any(ord(char) < 0x20 or ord(char) == 0x7F or char in forbidden for char in value)
or any(
not component
or component.startswith(".")
or component.endswith(".lock")
for component in value.split("/")
)
):
raise ValueError(f"{field} must be a normalized Git ref name")
return value
def _manifest_paths(value: Any, field: str, *, allow_empty: bool) -> list[str]:
if not isinstance(value, list) or (not allow_empty and not value):
qualifier = "a list" if allow_empty else "a non-empty list"
raise ValueError(f"{field} must be {qualifier}")
if not all(isinstance(path, str) and path for path in value):
raise ValueError(f"{field} must contain non-empty strings")
if value != sorted(set(value)):
raise ValueError(f"{field} must be sorted and unique")
for path in value:
parts = path.split("/")
windows_parts = [unicodedata.normalize("NFKC", part) for part in parts]
windows_stems = [part.split(".", 1)[0].rstrip(" .") for part in windows_parts]
normalized_first = windows_parts[0].rstrip(" .")
if (
path.startswith("/")
or "\\" in path
or "\x00" in path
or ":" in path
or any(part in {"", ".", ".."} for part in parts)
or any(any(ord(char) < 0x20 or ord(char) == 0x7F for char in part) for part in parts)
or any(part.endswith((" ", ".")) for part in parts)
or any(WINDOWS_DEVICE_STEM.fullmatch(stem) for stem in windows_stems)
or normalized_first.casefold() == ".git"
or WINDOWS_GIT_ALIAS.fullmatch(normalized_first) is not None
):
raise ValueError(f"{field} must be normalized repository-relative paths")
return value
def _manifest_commands(value: Any, field: str) -> list[dict[str, Any]]:
if not isinstance(value, list):
raise ValueError(f"{field} must be a list")
for index, command in enumerate(value):
command = _exact_fields(
command, {"argv", "definition_sha256"}, f"{field}[{index}]"
)
argv = command["argv"]
if (
not isinstance(argv, list)
or not argv
or not all(isinstance(argument, str) for argument in argv)
or not argv[0]
):
raise ValueError(f"{field}[{index}].argv must be a non-empty string list")
digest = command["definition_sha256"]
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise ValueError(f"{field}[{index}].definition_sha256 must be a lowercase SHA-256")
return value
def _path_records(value: Any, paths: list[str], field: str) -> list[dict[str, Any]]:
if not isinstance(value, list):
raise ValueError(f"{field} must be a list")
records: list[dict[str, Any]] = []
record_fields = {
"path",
"lstat_chain_sha256",
"resolved_target_sha256",
"inside_worktree",
"outside_git_metadata",
}
for index, item in enumerate(value):
record = _exact_fields(item, record_fields, f"{field}[{index}]")
if not isinstance(record["path"], str) or not record["path"]:
raise ValueError(f"{field}[{index}].path must be a non-empty string")
for name in ("lstat_chain_sha256", "resolved_target_sha256"):
digest = record[name]
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise ValueError(f"{field}[{index}].{name} must be a lowercase SHA-256")
if _boolean(record["inside_worktree"], f"{field}[{index}].inside_worktree") is not True:
raise ValueError(f"{field}[{index}] must resolve inside the worktree")
if (
_boolean(
record["outside_git_metadata"],
f"{field}[{index}].outside_git_metadata",
)
is not True
):
raise ValueError(f"{field}[{index}] must resolve outside Git metadata")
records.append(record)
if [record["path"] for record in records] != paths:
raise ValueError(f"{field} must be sorted and exactly match approved paths")
return records
def _automation_prompt_template(value: Any, field: str) -> str:
if not isinstance(value, str) or not value or "\x00" in value:
raise ValueError(f"{field} must be a non-empty NUL-free string")
found = re.findall(r"\{\{([A-Z0-9_]+)\}\}", value)
if sorted(found) != sorted(AUTOMATION_PROMPT_PLACEHOLDERS):
raise ValueError(
f"{field} must contain each supported typed placeholder exactly once"
)
stripped = re.sub(r"\{\{[A-Z0-9_]+\}\}", "", value)
if "{{" in stripped or "}}" in stripped:
raise ValueError(f"{field} contains an unsupported placeholder")
if value != AUTOMATION_PROMPT_TEMPLATE:
raise ValueError(f"{field} must equal the evaluator-owned v1 template")
return value
def _review_request_template(value: Any, field: str, run_id: str, round_number: int) -> str:
if not isinstance(value, str) or not value or "\x00" in value:
raise ValueError(f"{field} must be a non-empty NUL-free string")
placeholder = "{{FINAL_HEAD_SHA}}"
marker = (
"<!-- github-codex-pr-loop-request "
f"run={run_id} round={round_number} sha={placeholder} -->"
)
if value.count(placeholder) != 1 or marker not in value or "@codex" not in value:
raise ValueError(f"{field} must contain the exact Codex request marker and placeholder")
stripped = value.replace(placeholder, "")
if "{{" in stripped or "}}" in stripped:
raise ValueError(f"{field} contains an unsupported placeholder")
return value
def _thread_snapshots(value: Any, field: str, now: datetime) -> list[dict[str, Any]]:
if not isinstance(value, list):
raise ValueError(f"{field} must be a list")
snapshots: list[dict[str, Any]] = []
seen_ids: set[str] = set()
fields = {
"id",
"root_comment_id",
"body_sha256",
"position_sha256",
"content_version_at",
}
for index, item in enumerate(value):
snapshot = _exact_fields(item, fields, f"{field}[{index}]")
for name in ("id", "root_comment_id"):
if not isinstance(snapshot[name], str) or not snapshot[name]:
raise ValueError(f"{field}[{index}].{name} must be a non-empty string")
if snapshot["id"] in seen_ids:
raise ValueError(f"{field} IDs must be unique")
seen_ids.add(snapshot["id"])
for name in ("body_sha256", "position_sha256"):
if not isinstance(snapshot[name], str) or not SHA256.fullmatch(snapshot[name]):
raise ValueError(f"{field}[{index}].{name} must be a lowercase SHA-256")
if _timestamp(
snapshot["content_version_at"], f"{field}[{index}].content_version_at"
) > now:
raise ValueError(f"{field}[{index}].content_version_at is after snapshot time")
snapshots.append(snapshot)
if [item["id"] for item in snapshots] != sorted(item["id"] for item in snapshots):
raise ValueError(f"{field} must be sorted by id")
return snapshots
def _response_manifest_view(response: dict[str, Any]) -> dict[str, Any]:
return {field: response[field] for field in sorted(RESPONSE_FIELDS)}
def _validate_manifest_identity(
manifest: dict[str, Any],
*,
kind: str,
policy_schema_version: int,
run_id: str,
repository: str,
pr_number: int,
remote_name: str,
base_branch: str,
head_branch: str,
base_sha: str,
request_key: str,
request_sha: str,
) -> None:
expected = {
"kind": kind,
"version": 1,
"policy_schema_version": policy_schema_version,
"run_id": run_id,
"repository": repository,
"pr_number": pr_number,
"remote_name": remote_name,
"base_branch": base_branch,
"head_branch": head_branch,
"base_sha": base_sha,
"request_key": request_key,
"current_head_sha": request_sha,
}
if any(
type(manifest.get(key)) is not type(value) or manifest.get(key) != value
for key, value in expected.items()
):
raise ValueError(f"{kind}_manifest identity does not match current state")
def _validate_response_binding(
value: Any, expected: list[dict[str, Any]], field: str
) -> None:
if not isinstance(value, list):
raise ValueError(f"{field} must be a list")
actual_json = json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
expected_json = json.dumps(
expected, ensure_ascii=False, separators=(",", ":"), sort_keys=True
)
if actual_json != expected_json:
raise ValueError(f"{field} does not match qualifying response state")
def _validate_execution_boundary(
value: Any, field: str, safe_profile: str
) -> dict[str, Any]:
execution = _exact_fields(
value,
{
"filesystem_read_scope_sha256",
"filesystem_write_scope_sha256",
"isolation",
"risk_acceptance_sha256",
"git",
},
field,
)
for name in ("filesystem_read_scope_sha256", "filesystem_write_scope_sha256"):
digest = execution[name]
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise ValueError(f"{field}.{name} must be a lowercase SHA-256")
isolation = execution["isolation"]
risk_digest = execution["risk_acceptance_sha256"]
if isolation == "no-network-minimal-env-checkout-only":
if risk_digest is not None:
raise ValueError(f"{field} isolated execution cannot carry a risk-acceptance hash")
elif isolation == "explicit-risk-acceptance":
if not isinstance(risk_digest, str) or not SHA256.fullmatch(risk_digest):
raise ValueError(f"{field} explicit risk acceptance requires a lowercase SHA-256")
else:
raise ValueError(f"{field}.isolation is unsupported")
git_fields = {
"active_clean_filters",
"attributes_snapshot_sha256",
"config_snapshot_sha256",
"credential_strategy",
"external_diff_disabled",
"fsmonitor_disabled",
"git_metadata_snapshot_sha256",
"hooks_disabled",
"invocation_sha256",
"profile",
"protect_hfs_enabled",
"protect_ntfs_enabled",
"protocol_restricted",
"signing_disabled",
"textconv_disabled",
"transport_url_sha256",
}
git_state = _exact_fields(execution["git"], git_fields, f"{field}.git")
for name in (
"attributes_snapshot_sha256",
"config_snapshot_sha256",
"git_metadata_snapshot_sha256",
"invocation_sha256",
"transport_url_sha256",
):
digest = git_state[name]
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise ValueError(f"{field}.git.{name} must be a lowercase SHA-256")
for name in (
"external_diff_disabled",
"fsmonitor_disabled",
"hooks_disabled",
"protect_hfs_enabled",
"protect_ntfs_enabled",
"protocol_restricted",
"signing_disabled",
"textconv_disabled",
):
_boolean(git_state[name], f"{field}.git.{name}")
filters = git_state["active_clean_filters"]
if (
not isinstance(filters, list)
or not all(isinstance(item, str) and item for item in filters)
or filters != sorted(set(filters))
):
raise ValueError(f"{field}.git.active_clean_filters must be sorted unique strings")
credential_strategy = git_state["credential_strategy"]
if credential_strategy not in {"gh-cli-https", "explicitly-accepted"}:
raise ValueError(f"{field}.git.credential_strategy is unsupported")
profile = git_state["profile"]
if profile == safe_profile:
if credential_strategy != "gh-cli-https":
raise ValueError(f"{field} safe Git profile requires the GitHub CLI HTTPS helper")
if filters:
raise ValueError(f"{field} safe Git profile forbids active clean filters")
for name in (
"external_diff_disabled",
"fsmonitor_disabled",
"hooks_disabled",
"protect_hfs_enabled",
"protect_ntfs_enabled",
"protocol_restricted",
"signing_disabled",
"textconv_disabled",
):
if git_state[name] is not True:
raise ValueError(f"{field} safe Git profile requires {name}")
elif profile == "explicit-risk-acceptance-v1":
if isolation != "explicit-risk-acceptance":
raise ValueError(f"{field} unsafe Git profile requires explicit risk acceptance")
else:
raise ValueError(f"{field}.git.profile is unsupported")
return execution
def _validate_remediation_manifest(
manifest: dict[str, Any],
*,
policy_schema_version: int,
run_id: str,
repository: str,
pr_number: int,
remote_name: str,
base_branch: str,
head_branch: str,
base_sha: str,
request_key: str,
request_sha: str,
expected_responses: list[dict[str, Any]],
expected_actionable_threads: list[dict[str, Any]],
expected_execution: dict[str, Any],
safe_git_profile: str,
fix_rounds: int,
now: datetime,
) -> None:
fields = {
"kind",
"version",
"policy_schema_version",
"run_id",
"repository",
"pr_number",
"remote_name",
"base_branch",
"head_branch",
"base_sha",
"request_key",
"current_head_sha",
"responses",
"actionable_threads",
"paths",
"path_records",
"commands",
"execution",
"review_request_body_template",
"review_request_body_template_sha256",
"operations",
}
_exact_fields(manifest, fields, "remediation_manifest")
_validate_manifest_identity(
manifest,
kind="remediation",
policy_schema_version=policy_schema_version,
run_id=run_id,
repository=repository,
pr_number=pr_number,
remote_name=remote_name,
base_branch=base_branch,
head_branch=head_branch,
base_sha=base_sha,
request_key=request_key,
request_sha=request_sha,
)
_validate_response_binding(
manifest["responses"], expected_responses, "remediation_manifest.responses"
)
threads = _thread_snapshots(
manifest["actionable_threads"], "remediation_manifest.actionable_threads", now
)
if json.dumps(
threads, ensure_ascii=False, separators=(",", ":"), sort_keys=True
) != json.dumps(
expected_actionable_threads,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
):
raise ValueError(
"remediation_manifest.actionable_threads does not match current thread snapshots"
)
paths = _manifest_paths(manifest["paths"], "remediation_manifest.paths", allow_empty=False)
_path_records(manifest["path_records"], paths, "remediation_manifest.path_records")
commands = _manifest_commands(manifest["commands"], "remediation_manifest.commands")
request_template = _review_request_template(
manifest["review_request_body_template"],
"remediation_manifest.review_request_body_template",
run_id,
fix_rounds + 1,
)
if manifest["review_request_body_template_sha256"] != hashlib.sha256(
request_template.encode("utf-8")
).hexdigest():
raise ValueError(
"remediation_manifest.review_request_body_template_sha256 does not match the template"
)
execution = _validate_execution_boundary(
manifest["execution"], "remediation_manifest.execution", safe_git_profile
)
if json.dumps(
execution, ensure_ascii=False, separators=(",", ":"), sort_keys=True
) != json.dumps(
expected_execution, ensure_ascii=False, separators=(",", ":"), sort_keys=True
):
raise ValueError("remediation_manifest.execution does not match current execution state")
expected_operations = ["edit-files"]
if commands:
expected_operations.append("run-validation")
expected_operations.extend(
[
"commit",
"push",
"reply-to-codex-threads",
"request-codex-review",
"update-automation",
]
)
if manifest["operations"] != expected_operations:
raise ValueError("remediation_manifest.operations does not match the bounded write batch")
def _validate_finalization_manifest(
manifest: dict[str, Any],
*,
policy_schema_version: int,
run_id: str,
repository: str,
pr_number: int,
remote_name: str,
base_branch: str,
head_branch: str,
base_sha: str,
request_key: str,
request_sha: str,
expected_responses: list[dict[str, Any]],
expected_eligible_threads: list[dict[str, Any]],
non_codex_threads: int,
pr_is_draft: bool,
gates: dict[str, str],
now: datetime,
) -> None:
fields = {
"kind",
"version",
"policy_schema_version",
"run_id",
"repository",
"pr_number",
"remote_name",
"base_branch",
"head_branch",
"base_sha",
"request_key",
"current_head_sha",
"responses",
"eligible_threads",
"non_codex_rooted_threads",
"pr_is_draft",
"gates",
"operations",
}
_exact_fields(manifest, fields, "finalization_manifest")
_validate_manifest_identity(
manifest,
kind="finalization",
policy_schema_version=policy_schema_version,
run_id=run_id,
repository=repository,
pr_number=pr_number,
remote_name=remote_name,
base_branch=base_branch,
head_branch=head_branch,
base_sha=base_sha,
request_key=request_key,
request_sha=request_sha,
)
_validate_response_binding(
manifest["responses"], expected_responses, "finalization_manifest.responses"
)
threads = _thread_snapshots(
manifest["eligible_threads"], "finalization_manifest.eligible_threads", now
)
if json.dumps(
threads, ensure_ascii=False, separators=(",", ":"), sort_keys=True
) != json.dumps(
expected_eligible_threads,
ensure_ascii=False,
separators=(",", ":"),
sort_keys=True,
):
raise ValueError(
"finalization_manifest.eligible_threads does not match current thread snapshots"
)
manifest_non_codex_threads = _nonnegative_int(
manifest["non_codex_rooted_threads"],
"finalization_manifest.non_codex_rooted_threads",
)
if manifest_non_codex_threads != non_codex_threads:
raise ValueError(
"finalization_manifest.non_codex_rooted_threads does not match current state"
)
if manifest["pr_is_draft"] is not pr_is_draft:
raise ValueError("finalization_manifest.pr_is_draft does not match current state")
_exact_fields(manifest["gates"], set(gates), "finalization_manifest.gates")
if manifest["gates"] != gates:
raise ValueError("finalization_manifest.gates does not match current gate state")
expected_operations = []
if pr_is_draft:
expected_operations.append("mark-draft-ready")
if expected_eligible_threads:
expected_operations.append("resolve-codex-threads")
expected_operations.append("delete-owned-automation")
if manifest["operations"] != expected_operations:
raise ValueError("finalization_manifest.operations does not match the bounded write batch")
def validate_initial_document(
document: dict[str, Any], policy: dict[str, Any]
) -> dict[str, Any]:
"""Validate the exact initial write batch without performing a mutation."""
outer = _exact_fields(
document,
{"initial_snapshot", "initial_manifest", "initial_plan_hash"},
"initial_document",
)
snapshot_fields = {
"policy_schema_version",
"host",
"repository",
"authenticated_user_id",
"base_branch",
"base_sha",
"head_branch",
"current_head_sha",
"remote_name",
"existing_pr_number",
"existing_pr_base_branch",
"existing_pr_head_branch",
"existing_pr_head_sha",
"existing_pr_same_repository",
"heartbeat_rrule",
"create_branch_required",
"commit_required",
"push_required",
"paths",
"path_records",
"diff_sha256",
"worktree_status_sha256",
"remote_refs_sha256",
"open_prs_sha256",
"commands",
"execution_boundary",
}
snapshot = _exact_fields(outer["initial_snapshot"], snapshot_fields, "initial_snapshot")
policy_schema_version = _positive_int(
snapshot["policy_schema_version"], "initial_snapshot.policy_schema_version"
)
if policy_schema_version != policy["schema_version"]:
raise ValueError("initial_snapshot policy version differs from installed policy")
if snapshot["host"] != policy["supported_host"]:
raise ValueError("initial_snapshot.host is outside the supported policy")
repository = snapshot["repository"]
if not isinstance(repository, str) or not REPOSITORY.fullmatch(repository):
raise ValueError("initial_snapshot.repository must be canonical lowercase owner/repo")
_positive_int(
snapshot["authenticated_user_id"], "initial_snapshot.authenticated_user_id"
)
base_branch = _ref_name(snapshot["base_branch"], "initial_snapshot.base_branch")
head_branch = _ref_name(snapshot["head_branch"], "initial_snapshot.head_branch")
if base_branch == head_branch:
raise ValueError("initial_snapshot base and head branches must differ")
_sha(snapshot["base_sha"], "initial_snapshot.base_sha")
_sha(snapshot["current_head_sha"], "initial_snapshot.current_head_sha")
_ref_name(snapshot["remote_name"], "initial_snapshot.remote_name")
existing_pr_number = snapshot["existing_pr_number"]
existing_base = snapshot["existing_pr_base_branch"]
existing_head = snapshot["existing_pr_head_branch"]
existing_head_sha = snapshot["existing_pr_head_sha"]
existing_same_repository = snapshot["existing_pr_same_repository"]
if existing_pr_number is None:
if any(
value is not None
for value in (
existing_base,
existing_head,
existing_head_sha,
existing_same_repository,
)
):
raise ValueError("initial_snapshot existing PR fields must be null without a PR")
else:
_positive_int(existing_pr_number, "initial_snapshot.existing_pr_number")
if (
_ref_name(existing_base, "initial_snapshot.existing_pr_base_branch")
!= base_branch
):
raise ValueError("initial_snapshot existing PR base does not match base_branch")
if (
_ref_name(existing_head, "initial_snapshot.existing_pr_head_branch")
!= head_branch
):
raise ValueError("initial_snapshot existing PR head does not match head_branch")
if (
_sha(existing_head_sha, "initial_snapshot.existing_pr_head_sha")
!= snapshot["current_head_sha"]
):
raise ValueError("initial_snapshot existing PR head SHA does not match current_head_sha")
if _boolean(
existing_same_repository, "initial_snapshot.existing_pr_same_repository"
) is not True:
raise ValueError("initial_snapshot existing PR must use same-repository topology")
if snapshot["heartbeat_rrule"] != policy["heartbeat_rrule"]:
raise ValueError("initial_snapshot.heartbeat_rrule differs from installed policy")
create_branch_required = _boolean(
snapshot["create_branch_required"], "initial_snapshot.create_branch_required"
)
commit_required = _boolean(snapshot["commit_required"], "initial_snapshot.commit_required")
push_required = _boolean(snapshot["push_required"], "initial_snapshot.push_required")
paths = _manifest_paths(snapshot["paths"], "initial_snapshot.paths", allow_empty=True)
_path_records(snapshot["path_records"], paths, "initial_snapshot.path_records")
if commit_required and not paths:
raise ValueError("initial_snapshot commit_required needs at least one approved path")
if (create_branch_required or commit_required) and not push_required:
raise ValueError("initial_snapshot branch creation or commit requires a push")
if create_branch_required and existing_pr_number is not None:
raise ValueError("initial_snapshot cannot create a branch for an existing PR")
for name in (
"diff_sha256",
"worktree_status_sha256",
"remote_refs_sha256",
"open_prs_sha256",
):
digest = snapshot[name]
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise ValueError(f"initial_snapshot.{name} must be a lowercase SHA-256")
commands = _manifest_commands(snapshot["commands"], "initial_snapshot.commands")
_validate_execution_boundary(
snapshot["execution_boundary"],
"initial_snapshot.execution_boundary",
policy["git_execution_profile"],
)
snapshot_digest = _manifest_digest(snapshot, "initial_snapshot")
manifest_fields = {
"kind",
"version",
"run_id",
"mode",
"snapshot_sha256",
"pr_title_sha256",
"pr_body_sha256",
"review_request_body_template",
"review_request_body_template_sha256",
"automation_prompt_template",
"automation_prompt_template_sha256",
"operations",
}
manifest = _exact_fields(outer["initial_manifest"], manifest_fields, "initial_manifest")
if (
manifest["kind"] != "initial"
or isinstance(manifest["version"], bool)
or manifest["version"] != 1
):
raise ValueError("initial_manifest kind/version is unsupported")
if not isinstance(manifest["run_id"], str) or not RUN_ID.fullmatch(manifest["run_id"]):
raise ValueError("initial_manifest.run_id must be 32 lowercase hex characters")
if manifest["mode"] not in {"autonomous", "approval-gated"}:
raise ValueError("initial_manifest.mode must be autonomous or approval-gated")
if manifest["snapshot_sha256"] != snapshot_digest:
raise ValueError("initial_manifest.snapshot_sha256 does not match initial_snapshot")
for name in ("pr_title_sha256", "pr_body_sha256"):
digest = manifest[name]
if not isinstance(digest, str) or not SHA256.fullmatch(digest):
raise ValueError(f"initial_manifest.{name} must be a lowercase SHA-256")
request_template = _review_request_template(
manifest["review_request_body_template"],
"initial_manifest.review_request_body_template",
manifest["run_id"],
0,
)
request_template_digest = hashlib.sha256(request_template.encode("utf-8")).hexdigest()
if manifest["review_request_body_template_sha256"] != request_template_digest:
raise ValueError(
"initial_manifest.review_request_body_template_sha256 does not match the template"
)
prompt_template = _automation_prompt_template(
manifest["automation_prompt_template"],
"initial_manifest.automation_prompt_template",
)
prompt_template_digest = hashlib.sha256(prompt_template.encode("utf-8")).hexdigest()
if manifest["automation_prompt_template_sha256"] != prompt_template_digest:
raise ValueError(
"initial_manifest.automation_prompt_template_sha256 does not match the template"
)
expected_operations = ["fetch-base"]
if create_branch_required:
expected_operations.append("create-branch")
if commands:
expected_operations.append("run-validation")
if commit_required:
expected_operations.extend(["stage-files", "commit"])
if push_required:
expected_operations.append("push")
expected_operations.append("reuse-pr" if existing_pr_number is not None else "create-pr")
expected_operations.extend(["request-codex-review", "bootstrap-automation"])
if manifest["operations"] != expected_operations:
raise ValueError("initial_manifest.operations does not match the bounded write batch")
manifest_digest = _manifest_digest(manifest, "initial_manifest")
plan_hash = outer["initial_plan_hash"]
if not isinstance(plan_hash, str) or not SHA256.fullmatch(plan_hash):
raise ValueError("initial_plan_hash must be a lowercase SHA-256")
if plan_hash != manifest_digest:
raise ValueError("initial_plan_hash does not match the canonical manifest")
return {
"action": "initial-plan-valid",
"reason": "the exact initial snapshot and bounded write batch are valid",