agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,2727 @@
1
+ #!/usr/bin/env python3
2
+ """The model-call gate (design §3.2): the only path from a call directory to an accepted result.
3
+
4
+ A call directory `calls/<call_id>/` holds what the driver sent and declared, what it read, and
5
+ what the host recorded:
6
+
7
+ call.json the driver's record of the call (DistillCall/v1, written by dispatch): call_id,
8
+ stage, item, attempt, host and host_version, seat and child_seat, the profile
9
+ it requires, the context manifest, schema_sha256 (null: schema-less), view_window,
10
+ realization, exit_status, wall_ms, `stopped` when the supervisor stopped it, and
11
+ `contract`: "required" when steps 4 and 5 apply (contract.json must then be
12
+ there and readable), "none" when they do not (CALL_SCHEMA)
13
+ packet.md the bytes sent; schema.json the schema required; result.json the bytes read
14
+ receipt.json the ReviewReceipt/v1 the runner wrote through the launcher (receipts.py)
15
+ usage.json the call's usage (usage.py)
16
+ contract.json the stage's references (step 4) and set accounting (step 5), when call.json
17
+ declares contract "required"
18
+ capture/host.json the runner's projection of the host's own records — Claude: the
19
+ sent requests (role, params.model, request text, StructuredOutput tool
20
+ definition), the assistant messages (role, message.model, stop_reason), the
21
+ StructuredOutput calls; both hosts: profile, flag-set hash, cwd, session or
22
+ thread id, the working directory's listing before the call, and the
23
+ effective-context evidence (instruction files, appended system prompts,
24
+ skills, agents, hooks)
25
+ capture/frames.jsonl Codex: client frames, server frames, otel rows and, when the trace
26
+ carried them, codex_core::responses_retry warnings, reduced as
27
+ codex-accounting/proto/acct.py reduces them, with an info record naming the
28
+ channels captured; capture/events.jsonl Codex `--json`
29
+
30
+ Every check runs and none short-circuits, so `codes` is the complete failure set: a control
31
+ asserts its own code beside whatever else the same capture fails. Each value the receipt
32
+ carries is recomputed from the call directory, never trusted. The steps are design §3.2's:
33
+ completion and binding, seat attestation (by role, plan S-7), schema, cross-record integrity,
34
+ set accounting. A failing output is retried once with the validation message (`correction`)
35
+ and then recorded as failed with every attempt kept (`settle`); nothing is extracted from
36
+ prose, repaired, or read as empty.
37
+
38
+ Codes (the plan's, and the design's MODEL_UNATTESTED and frames_blind): COMPLETION_INCOMPLETE,
39
+ BINDING_MISMATCH, MODEL_UNATTESTED, frames_blind, SCHEMA_INVALID, RECORD_INTEGRITY,
40
+ SET_MISMATCH, CONTEXT_UNDECLARED, CONTEXT_HASH_MISMATCH, RECEIPT_STALE, RECEIPT_MISSING,
41
+ RECEIPT_KEY_MISSING, PROFILE_INHERITED, CWD_OUTSIDE_MANIFEST, RETRY_EXHAUSTED, and the review's
42
+ USAGE_ATTRIBUTION_UNKNOWN (a Codex call whose attempts cannot all be accounted for).
43
+
44
+ gate.py --self-test
45
+ """
46
+ import ast
47
+ import hashlib
48
+ import importlib.util
49
+ import itertools
50
+ import json
51
+ import pathlib
52
+ import sys
53
+
54
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
55
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
56
+ from runlib import bound as bounds
57
+ from runlib import breaker as breakers
58
+ from runlib import packet as packets
59
+ from runlib import receipts, records, usage as usages, validate
60
+ from runlib.records import Refused
61
+
62
+ SEATS = pathlib.Path(__file__).resolve().parents[1] / "seats.json"
63
+ STEPS = ("completion_binding", "seat_attestation", "schema", "cross_record_integrity", "set_accounting")
64
+ CODES = ("COMPLETION_INCOMPLETE", "BINDING_MISMATCH", "MODEL_UNATTESTED", "frames_blind", "SCHEMA_INVALID",
65
+ "RECORD_INTEGRITY", "SET_MISMATCH", "CONTEXT_UNDECLARED", "CONTEXT_HASH_MISMATCH", "RECEIPT_STALE",
66
+ "RECEIPT_MISSING", "RECEIPT_KEY_MISSING", "PROFILE_INHERITED", "CWD_OUTSIDE_MANIFEST", "RETRY_EXHAUSTED",
67
+ "USAGE_ATTRIBUTION_UNKNOWN")
68
+ CLAUDE_STOPS = ("end_turn", "stop_sequence", "tool_use")
69
+ # A stage's own judgement of an attempt the gate accepted (`dispatch.Supervisor.item(stage_check=)`), written beside the
70
+ # attempt by the supervisor: `{"failures": [line, ...]}`, empty when the stage's check passed it.
71
+ STAGE_CHECK = "stage_check.json"
72
+
73
+
74
+ def _closed(required=(), **properties):
75
+ return {"type": "object", "additionalProperties": False, "required": list(required), "properties": properties}
76
+
77
+
78
+ _text, _int, _str_or_null = {"type": "string"}, {"type": "integer"}, {"type": ["string", "null"]}
79
+ _strings = {"type": "array", "items": {"type": "string"}}
80
+ _number_or_null = {"type": ["number", "null"]}
81
+ STOP_RECORD = _closed(("code", "call_id", "kept"), code=_text, call_id=_text, observed=_int, at=_number_or_null,
82
+ detail=_text, declaration_seq=_int, stamp=_text, clock=_text, kept={"type": "boolean"},
83
+ requests=_int, largest_input=_int, requests_at_most={"type": ["integer", "null"]},
84
+ input_at_most={"type": ["integer", "null"]}, first_at_most={"type": ["integer", "null"]},
85
+ breaches=_strings)
86
+ CALL_SCHEMA = _closed(
87
+ ("schema", "call_id", "stage", "item", "attempt", "host", "host_version", "seat", "child_seat", "profile",
88
+ "manifest", "schema_sha256", "view_window", "realization", "exit_status", "wall_ms", "stopped", "contract"),
89
+ schema={"const": "DistillCall/v1"}, call_id={"type": "string", "minLength": 1}, stage={"type": "string", "minLength": 1},
90
+ item=_text, attempt={"type": "integer", "minimum": 1}, host={"enum": ["claude", "codex"]}, host_version=_text,
91
+ seat={"type": "string", "minLength": 1}, child_seat=_str_or_null, profile=_text, schema_sha256=_str_or_null,
92
+ view_window={"type": "boolean"}, realization={"enum": ["live", "replay", "golden"]},
93
+ exit_status={"type": ["integer", "null"]}, wall_ms={"type": ["integer", "null"]},
94
+ contract={"enum": ["required", "none"]}, provider_signals=_strings, input_observed=_int,
95
+ host_schema_sha256=_str_or_null,
96
+ bound=_closed(("limit", "driver_bytes", "stop_standing"), limit=_int,
97
+ driver_bytes={"type": ["integer", "null"]}, stop_standing={"type": "boolean"},
98
+ context_capacity={"type": ["integer", "null"]},
99
+ output_reservation={"type": ["integer", "null"]},
100
+ # what the call claimed at most, on the bytes it sent (dispatch `call_claim`; W review of WP-08e r1,
101
+ # F4): optional, null for a call no claim could be computed for and absent from a record written before
102
+ claim={**_closed(("requests_at_most", "input_at_most"), requests_at_most=_int, input_at_most=_int,
103
+ first=_int, step=_int, basis=_text), "type": ["object", "null"]}),
104
+ use={"enum": ["judge", "producing", "authoring"]}, max_output_tokens={"type": ["integer", "null"]},
105
+ runner_refused=_str_or_null,
106
+ # the sha256 of the payload the item was asked with, before any retry's correction: what makes an earlier accepted
107
+ # attempt the answer to this call (dispatch `Supervisor.reusable`); optional, a record written before carries none
108
+ payload_sha256=_str_or_null,
109
+ # the run's server-delivered policy verdict, which the dispatcher hands every hermetic Claude call
110
+ # (D-20261102-252c92); optional, like `bound`: a golden host's call and one recorded before carry none
111
+ server_policy={**_closed(("status", "verdict", "reason"), status=_str_or_null,
112
+ verdict={"enum": ["clean", "not confirmed", "unknown"]}, reason=_str_or_null),
113
+ "type": ["object", "null"]},
114
+ caps=_closed(("tokens", "compactions"), tokens=_int, compactions=_int),
115
+ reservation=_closed(("amount", "calibration", "tranche", "declaration_seq"), amount=_int,
116
+ calibration={"enum": ["measured", "provisional"]}, tranche={"enum": ["broad", "calibration"]},
117
+ declaration_seq=_int),
118
+ stopped={**_closed(("why",), outcome=_text, why=_text,
119
+ cap={**_closed(("why", "at"), why=_text, at=_number_or_null), "type": ["object", "null"]}, decided_at=_number_or_null,
120
+ freeze_at=_number_or_null, kill_at=_number_or_null, survivors={"type": "array", "items": _int},
121
+ problems=_strings, uncertain=_strings,
122
+ boundary={"enum": ["clean", "STOP_BOUNDARY_UNVERIFIED", "STOP_BOUNDARY_VIOLATED"]},
123
+ tree={"type": "array", "items": _closed(("pid", "start"), pid=_int, start=_text)}),
124
+ "type": ["object", "null"]},
125
+ # the stop THIS call offered the run, written by dispatch.py the moment its excess was observed and
126
+ # before any other settlement work (F-19): its stamp and reason when it could not be stamped, and
127
+ # whether the run kept it or an earlier, stronger stop stands. Optional, like `bound`: a record
128
+ # written before this existed carries none (F-20).
129
+ # `clock` appears when the run's own clock could not be read and the timestamp came from a
130
+ # fallback instead (HC#0) - a stop is never blocked by its own timestamp
131
+ # A record written before one stop per obligation carries one `stop`; `stops` holds each obligation's
132
+ # (W review of WP-08e r2; lead decision): a claim excess (CLAIM_EXCEEDED) names each breach, the call's main
133
+ # requests and the largest of them beside what it claimed, in place of `observed`
134
+ stop={**STOP_RECORD, "type": ["object", "null"]},
135
+ stops={"type": "object", "additionalProperties": False,
136
+ "patternProperties": {"^(INPUT_BOUND_EXCEEDED|CLAIM_EXCEEDED)$": STOP_RECORD}},
137
+ manifest=_closed(("workdir_path", "workdir_files", "instructions", "appended_prompts", "skills", "agents", "hooks"),
138
+ workdir_path=_text, skills=_strings, agents=_strings, hooks=_strings, mcp_servers=_strings,
139
+ workdir_files={"type": "array", "items": _closed(("path",), path=_text, sha256=_str_or_null)},
140
+ # `observer_sha256` is the same bytes in the form the host's observer reports
141
+ # (gate.observer_sha256, BC#2); optional for the same reason `bytes` is - a record
142
+ # written before it existed carries neither and is judged on what it has
143
+ instructions={"type": "array", "items": _closed(("path", "sha256"), path=_text,
144
+ sha256=_str_or_null, bytes=_int,
145
+ observer_sha256=_str_or_null)},
146
+ # `bytes` is the length the payload count counted, and it is OPTIONAL in the shape
147
+ # for the same reason the `bound` block is: a call record captured before the seam
148
+ # carries none, and requiring it would re-judge evidence already frozen. That every
149
+ # record dispatch writes TODAY carries it is held where it is produced, by
150
+ # dispatch.py's `an-appended-prompt-is-recorded-as-its-hash-and-the-length-counted`.
151
+ appended_prompts={"type": "array", "items": _closed(("sha256",), name=_text,
152
+ sha256=_text, bytes=_int)}),
153
+ )
154
+ CALL_SCHEMA["$comment"] = "DistillCall/v1, written by dispatch.py: what the driver sent and declared, and what it observed"
155
+ CALL_VALIDATOR = validate.compile_schema(CALL_SCHEMA)
156
+ # The containers of capture/host.json the checks traverse; what each value must equal is theirs.
157
+ HOST_SHAPE = {"requests": list, "assistant": list, "workdir_files": list, "structured_calls": list, "context": dict}
158
+ CONTEXT_SHAPE = {"instructions": list, "appended_prompts": list, "skills": list, "agents": list, "hooks": list}
159
+
160
+
161
+ def host_shape(host):
162
+ """The shape violations of capture/host.json: a container of the wrong kind, or a record in a
163
+ list of records that is not an object."""
164
+ errors = []
165
+ for key, kind in HOST_SHAPE.items():
166
+ if key in host and not isinstance(host[key], kind):
167
+ errors.append(f"{key}: not a {kind.__name__}")
168
+ elif key in ("requests", "assistant", "workdir_files") and key in host and \
169
+ not all(isinstance(item, dict) for item in host[key]):
170
+ errors.append(f"{key}: a record that is not an object")
171
+ context = host.get("context")
172
+ if isinstance(context, dict):
173
+ for key, kind in CONTEXT_SHAPE.items():
174
+ if key in context and not isinstance(context[key], kind):
175
+ errors.append(f"context.{key}: not a {kind.__name__}")
176
+ elif key in ("instructions", "appended_prompts") and key in context and \
177
+ not all(isinstance(item, dict) for item in context[key]):
178
+ errors.append(f"context.{key}: a record that is not an object")
179
+ return errors
180
+
181
+
182
+ CONTEXT_SETS = ("skills", "agents", "hooks", "mcp_servers")
183
+ _seats = {}
184
+
185
+
186
+ def canonical(obj):
187
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
188
+
189
+
190
+ def canonical_sha256(obj):
191
+ return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest()
192
+
193
+
194
+ def seats(path=SEATS):
195
+ path = pathlib.Path(path)
196
+ if path not in _seats:
197
+ _seats[path] = json.loads(path.read_text(encoding="utf-8"))
198
+ return _seats[path]
199
+
200
+
201
+ def seat_capacity(seat, host_version, path=SEATS):
202
+ """`(context_capacity, basis)` seats.json declares for `seat` at `host_version`, or `(None, reason)`.
203
+
204
+ The seat's context window is host-reported evidence, not a constant: every live Claude result of
205
+ WP-03v records `modelUsage[...].contextWindow` and that is what this carries. A seat with no entry has
206
+ no capacity, and check (d) is about the context - so a view-window call on it is refused rather than
207
+ judged against a number nobody measured (BA#1)."""
208
+ entry = (seats(path).get("seat_capacity") or {}).get(seat)
209
+ if not isinstance(entry, dict):
210
+ return None, f"seats.json declares no context capacity for {seat}"
211
+ if entry.get("host_version") != host_version:
212
+ return None, (f"seats.json declares the context capacity of {seat} at host version "
213
+ f"{entry.get('host_version')!r}, not {host_version!r}")
214
+ if not isinstance(entry.get("context_capacity"), int) or entry["context_capacity"] <= 0:
215
+ return None, f"seats.json declares a context capacity for {seat} that is not a positive integer"
216
+ if not isinstance(entry.get("basis"), str) or not entry["basis"].strip():
217
+ return None, f"seats.json declares a context capacity for {seat} with no basis"
218
+ return entry["context_capacity"], entry["basis"]
219
+
220
+
221
+ def pinned_flags_sha256(host, version, profile, path=SEATS):
222
+ """The sha256 of the flag set seats.json pins for `profile` on `host` at `version`, or None."""
223
+ entry = seats(path)["hosts"].get(host) or {}
224
+ flags = (entry.get("profiles") or {}).get(profile)
225
+ return canonical_sha256(flags) if entry.get("version") == version and flags is not None else None
226
+
227
+
228
+ def auxiliary_models(host, version, live=False, path=SEATS):
229
+ """The auxiliary roles seats.json declares for `host` at `version`. A live call is judged only
230
+ against measured declarations (preflight, WP-23); a replayed or golden call may lean on a
231
+ provisional one (S-7)."""
232
+ entry = seats(path)["hosts"].get(host) or {}
233
+ if entry.get("version") != version:
234
+ return set()
235
+ return {aux["model"] for aux in entry.get("auxiliary", []) if aux.get("measured") is True or not live}
236
+
237
+
238
+ # The file a host whose provider takes a dialect of schema.json is handed instead (packets.provider_schema_bytes, D7)
239
+ HOST_SCHEMA = "host-schema.json"
240
+
241
+
242
+ def host_schema_problems(c):
243
+ """What the call's record gets wrong about the schema its host was handed: `host_schema_sha256` names the bytes;
244
+ for a host that reads schema.json itself they are schema.json's, and no host-schema.json is kept; for one whose
245
+ provider takes a dialect they are host-schema.json's, which must be exactly the projection of this call's
246
+ schema.json, so a weakened or hand-written schema cannot have been sent in its place. A record written before the
247
+ field existed carries none, and its host was handed schema.json."""
248
+ out = []
249
+ held = c.dir / HOST_SCHEMA
250
+ present = held.is_file()
251
+ if "host_schema_sha256" not in c.call:
252
+ if present:
253
+ out.append(f"RECORD_INTEGRITY {HOST_SCHEMA}: present for a call whose record names no handed schema")
254
+ return out
255
+ named = c.call.get("host_schema_sha256")
256
+ if not c.required:
257
+ if named is not None or present:
258
+ out.append(f"RECORD_INTEGRITY {HOST_SCHEMA}: a handed schema for a call declared schema-less")
259
+ return out
260
+ try:
261
+ expected = packets.provider_schema_bytes(c.schema_bytes, c.kind) if c.schema_bytes is not None else None
262
+ except (validate.SchemaPolicyError, ValueError) as exc:
263
+ return [f"RECORD_INTEGRITY {HOST_SCHEMA}: schema.json has no projection for {c.kind} ({str(exc)[:120]})"]
264
+ if expected is None:
265
+ if present or named != c.call.get("schema_sha256"):
266
+ out.append(f"RECORD_INTEGRITY {HOST_SCHEMA}: {c.kind} reads schema.json itself, and the record names "
267
+ "other bytes as handed")
268
+ return out
269
+ sent = held.read_bytes() if present else None
270
+ if sent != expected:
271
+ out.append(f"RECORD_INTEGRITY {HOST_SCHEMA}: not the projection of schema.json for {c.kind} "
272
+ "(packets.provider_schema_bytes)")
273
+ if sent is None or hashlib.sha256(sent).hexdigest() != named:
274
+ out.append(f"RECORD_INTEGRITY {HOST_SCHEMA}: not the bytes call.json says the host was handed")
275
+ return out
276
+
277
+
278
+ def seats_problems(doc):
279
+ """What makes seats.json's pins disagree with the version each was established at, by name (`PIN_PATH_VERSION`,
280
+ `PIN_STALE`); empty when none does. A host's pinned binary is the versioned file (plan P2), so its path names the
281
+ pinned version as one of its parts. Everything measured or observed for a host is valid at the version it was
282
+ established at and says which: a measured host allowance its `measured_version`, a profile's built-in `context` its
283
+ `observed_version` unless it is declared `carried` with a basis, a measured auxiliary role its
284
+ `measured_version`, and a seat capacity its `host_version`. So a version move that leaves any of them at the old
285
+ version is named here, and the re-pin takes each with it: re-measured, marked unmeasured, or declared carried.
286
+
287
+ And every seat a stage is seated with has a capacity (`CAPACITY_UNDECLARED`): a seat with none was the one
288
+ exception check (d) could not hold, and a re-pin that drops a capacity leaves that seat unbounded by name."""
289
+ out = []
290
+ hosts = (doc or {}).get("hosts") or {}
291
+ for host, entry in sorted(hosts.items()):
292
+ version, path = entry.get("version"), str(entry.get("path") or "")
293
+ if not isinstance(version, str) or not version or version not in pathlib.PurePosixPath(path).parts:
294
+ out.append(f"PIN_PATH_VERSION {host}: the pinned path {path!r} does not name version {version!r} as one of "
295
+ "its parts, so it is no versioned file of that version")
296
+ for profile, slot in sorted((entry.get("host_allowance") or {}).items()):
297
+ if isinstance(slot, dict) and slot.get("measured") is True and slot.get("measured_version") != version:
298
+ out.append(f"PIN_STALE {host}.host_allowance.{profile}: measured at {slot.get('measured_version')!r}, "
299
+ f"and the pin is {version!r}; re-measure it, or mark it unmeasured")
300
+ for profile, held in sorted((entry.get("context") or {}).items()):
301
+ if not isinstance(held, dict) or held.get("observed_version") == version:
302
+ continue
303
+ if held.get("carried") is not True or not str(held.get("basis") or "").strip():
304
+ out.append(f"PIN_STALE {host}.context.{profile}: observed at {held.get('observed_version')!r}, and the "
305
+ f"pin is {version!r}; observe it again, or declare it carried with the basis for carrying it")
306
+ for aux in entry.get("auxiliary") or []:
307
+ if isinstance(aux, dict) and aux.get("measured") is True and aux.get("measured_version") != version:
308
+ out.append(f"PIN_STALE {host}.auxiliary.{aux.get('model')}: measured at "
309
+ f"{aux.get('measured_version')!r}, and the pin is {version!r}")
310
+ for seat, held in sorted(((doc or {}).get("seat_capacity") or {}).items()):
311
+ if seat.startswith("$") or not isinstance(held, dict):
312
+ continue
313
+ pinned = (hosts.get(seat.partition(":")[0]) or {}).get("version")
314
+ if held.get("host_version") != pinned:
315
+ out.append(f"PIN_STALE seat_capacity.{seat}: reported at host {held.get('host_version')!r}, and the pin is "
316
+ f"{pinned!r}; report it again at the pinned version, or remove it")
317
+ declared = (doc or {}).get("seat_capacity") or {}
318
+ seated = {}
319
+ for stage, rows in sorted(((doc or {}).get("stage_seats") or {}).items()):
320
+ if not stage.startswith("$") and isinstance(rows, list):
321
+ for seat in rows:
322
+ seated.setdefault(seat, stage)
323
+ for seat, stage in sorted(seated.items()):
324
+ if not isinstance(declared.get(seat), dict):
325
+ out.append(f"CAPACITY_UNDECLARED seat_capacity.{seat}: {stage} is seated with it and seats.json declares no "
326
+ "context capacity for it; every seat is held to one")
327
+ return out
328
+
329
+
330
+ def builtin_context(entry, profile, host_version):
331
+ """What the host loads by itself under `profile` at `host_version`, as seats.json declares it for a call's
332
+ manifest: the declaration's own fields, its version and basis left out; nothing when the pin is another version."""
333
+ if entry.get("version") != host_version:
334
+ return {}
335
+ held = (entry.get("context") or {}).get(profile) or {}
336
+ return {k: v for k, v in held.items() if k not in CONTEXT_PROVENANCE}
337
+
338
+
339
+ CONTEXT_PROVENANCE = ("observed_version", "carried", "basis")
340
+
341
+
342
+ def capture_sha256(call_dir):
343
+ """One digest over every file under capture/: its relative path and its bytes' sha256."""
344
+ root = pathlib.Path(call_dir) / "capture"
345
+ listing = sorted([str(p.relative_to(root)), hashlib.sha256(p.read_bytes()).hexdigest()]
346
+ for p in root.rglob("*") if p.is_file()) if root.is_dir() else []
347
+ return canonical_sha256(listing)
348
+
349
+
350
+ def seat_model(seat):
351
+ parsed = seat.partition(":")[2].rpartition("/") if isinstance(seat, str) else ("", "", "")
352
+ return parsed[0] or None
353
+
354
+
355
+ class Call:
356
+ """Everything one call directory holds, read once; a file that is absent or unreadable is None."""
357
+
358
+ def __init__(self, call_dir):
359
+ self.dir = pathlib.Path(call_dir)
360
+ self.unreadable = []
361
+ call = self._json("call.json")
362
+ self.call = call if isinstance(call, dict) else {}
363
+ if call is not None and not isinstance(call, dict):
364
+ self.unreadable.append("call.json")
365
+ self.packet = self._bytes("packet.md")
366
+ self.schema_bytes = self._bytes("schema.json")
367
+ self.schema = self._json("schema.json")
368
+ self.result_bytes = self._bytes("result.json")
369
+ self.result = self._json("result.json")
370
+ self.usage = self._json("usage.json")
371
+ self.contract_bytes = self._bytes("contract.json")
372
+ contract = self._json("contract.json")
373
+ self.contract = contract if isinstance(contract, dict) else None
374
+ self.host = self._json("capture/host.json")
375
+ self.frames = self._jsonl("capture/frames.jsonl")
376
+ self.events = self._jsonl("capture/events.jsonl")
377
+ self.kind = self.call.get("host")
378
+ self.required = self.call.get("schema_sha256") is not None
379
+
380
+ def _bytes(self, name):
381
+ try:
382
+ return (self.dir / name).read_bytes()
383
+ except OSError:
384
+ return None
385
+
386
+ def _json(self, name):
387
+ data = self._bytes(name)
388
+ try:
389
+ return json.loads(data) if data is not None else None
390
+ except ValueError:
391
+ return None
392
+
393
+ def _jsonl(self, name):
394
+ data = self._bytes(name)
395
+ try:
396
+ rows = [json.loads(line) for line in records.jsonl_lines(data.decode("utf-8")) if line.strip()] if data else []
397
+ except ValueError:
398
+ self.unreadable.append(name)
399
+ return []
400
+ if not all(isinstance(row, dict) for row in rows):
401
+ self.unreadable.append(name)
402
+ return [row for row in rows if isinstance(row, dict)]
403
+ return rows
404
+
405
+ def output(self):
406
+ """The structured result steps 3-5 judge: Claude's structured_output, or the Codex
407
+ result parsed as one JSON document; None when there is none to judge."""
408
+ if self.kind == "claude":
409
+ return self.result.get("structured_output") if isinstance(self.result, dict) else None
410
+ try:
411
+ return json.loads(self.result_bytes) if self.result_bytes else None
412
+ except ValueError:
413
+ return None
414
+
415
+ def answer(self):
416
+ """What a stage reads from an accepted call: the structured output where a schema was
417
+ required; for a schema-less call the host's final text — Claude's result text, the
418
+ Codex final message as the bytes read."""
419
+ if self.required:
420
+ return self.output()
421
+ if self.kind == "claude":
422
+ return self.result.get("result") if isinstance(self.result, dict) else None
423
+ return self.result_bytes.decode("utf-8") if self.result_bytes is not None else None
424
+
425
+
426
+ # wrappers/codex_frame_filter.py is the capture's one owner: responses, completions, join and
427
+ # attempts over a capture's frames are its functions, read here (author-side imports shipped, never
428
+ # the reverse); what the gate adds is policy against the declared seats.
429
+ FRAME_OWNER = pathlib.Path(__file__).resolve().parents[2] / "wrappers" / "codex_frame_filter.py"
430
+ FRAME_READERS = ("responses", "completions", "join", "attempts") # the owner's only functions the gate calls
431
+ _frame_owner = None
432
+
433
+
434
+ def frame_owner():
435
+ global _frame_owner
436
+ if _frame_owner is None:
437
+ spec = importlib.util.spec_from_file_location("codex_frame_filter", FRAME_OWNER)
438
+ module = importlib.util.module_from_spec(spec)
439
+ spec.loader.exec_module(module)
440
+ _frame_owner = module
441
+ return _frame_owner
442
+
443
+
444
+ # wrappers/claude_hermetic_evidence.py is the Claude observer: the FORM an instruction file is
445
+ # compared on is its `norm_sha256` (the host renders the file before use - trailing newline trimmed,
446
+ # HTML comments removed, whitespace collapsed), so a declared instruction's hash is computed by
447
+ # calling that function rather than by copying the rule (BC#2). Author-side imports shipped, never
448
+ # the reverse.
449
+ OBSERVER_OWNER = pathlib.Path(__file__).resolve().parents[2] / "wrappers" / "claude_hermetic_evidence.py"
450
+ # the observer's only functions read here and by dispatch.py (server_policy_record, over the probe's answer)
451
+ OBSERVER_READERS = ("norm_sha256", "receipt_hermeticity", "server_policy_record")
452
+ _observer_owner = None
453
+
454
+
455
+ def observer_owner():
456
+ global _observer_owner
457
+ if _observer_owner is None:
458
+ spec = importlib.util.spec_from_file_location("claude_hermetic_evidence", OBSERVER_OWNER)
459
+ module = importlib.util.module_from_spec(spec)
460
+ spec.loader.exec_module(module)
461
+ _observer_owner = module
462
+ return _observer_owner
463
+
464
+
465
+ def observer_sha256(host, body):
466
+ """The sha256 of `body` in the representation `host`'s own observer records, or None.
467
+
468
+ Only Claude renders instruction files before use, and only its observer normalizes them; a Codex
469
+ capture records what it loaded verbatim, so there is nothing to translate."""
470
+ return observer_owner().norm_sha256(body) if host == "claude" else None
471
+
472
+
473
+ def declared_instruction_hash(row):
474
+ """The hash of a declared instruction to compare with the observed one.
475
+
476
+ The record keeps both: `sha256` of the exact bytes, which is what the payload count counted, and
477
+ `observer_sha256`, the same bytes in the form the host's observer reports. The comparison takes the
478
+ observer's form, because that is what the capture carries; a record written before this existed
479
+ carries only `sha256` and is compared on it, as it was then."""
480
+ return row.get("observer_sha256") or row.get("sha256")
481
+
482
+
483
+ def codex_responses(c):
484
+ """The owner's responses, each with the seat it is judged against: the child seat for any
485
+ request a sub-agent sent — its turn, warm-up or compaction alike —, else the main seat."""
486
+ def child(send):
487
+ return bool(send and (send.get("parent_thread_id") or (send.get("agent_name") or "/root") != "/root"))
488
+ return [dict(r, seat="child_seat" if child(r["send"]) else "seat") for r in frame_owner().responses(c.frames)]
489
+
490
+
491
+ def codex_completions(c):
492
+ return frame_owner().completions(c.frames)
493
+
494
+
495
+ def join_completions(c, responses):
496
+ """(completions no frame response answers, ambiguous ones, completed responses no completion
497
+ joined), the owner's join; it marks each joined response in `responses`."""
498
+ return frame_owner().join(c.frames, responses)
499
+
500
+
501
+ def codex_attempts(c):
502
+ """The owner's attempt coverage per thread; attempt_coverage fails a call on any unknown."""
503
+ return frame_owner().attempts(c.frames)
504
+
505
+
506
+ def observed_seats(c):
507
+ """{role: [models]} as the host reported them: what the receipt's seat_observed must say."""
508
+ seen = {}
509
+ if c.kind == "claude":
510
+ for a in (c.host or {}).get("assistant") or []:
511
+ if isinstance(a, dict) and not a.get("synthetic") and a.get("model"):
512
+ seen.setdefault(a.get("role") or "unknown", set()).add(a["model"])
513
+ elif c.kind == "codex":
514
+ for r in codex_responses(c):
515
+ if r["model"]:
516
+ seen.setdefault(r["role"] or "unknown", set()).add(r["model"])
517
+ return {role: sorted(models) for role, models in sorted(seen.items())}
518
+
519
+
520
+ def effort_provenance(c):
521
+ """`host-reported` only when every Codex frame reports the effort its own seat requested —
522
+ the main seat for the root thread's main, warm-up and compaction responses, the child seat
523
+ for a child thread's (plan S-6); Claude is always `unverified`."""
524
+ if c.kind != "codex":
525
+ return "unverified"
526
+ pairs = [(r["effort"], (c.call.get(r["seat"]) or "").rpartition("/")[2] or None) for r in codex_responses(c)]
527
+ return "host-reported" if pairs and all(got is not None and got == want for got, want in pairs) else "unverified"
528
+
529
+
530
+ def walk(obj, path):
531
+ """The values at `path` (keys and "*" for every element) inside `obj`."""
532
+ values = [obj]
533
+ for key in path:
534
+ nxt = []
535
+ for value in values:
536
+ if key == "*" and isinstance(value, (list, dict)):
537
+ nxt.extend(value.values() if isinstance(value, dict) else value)
538
+ elif isinstance(value, dict) and key in value:
539
+ nxt.append(value[key])
540
+ values = nxt
541
+ return values
542
+
543
+
544
+ CHECKS = []
545
+
546
+
547
+ def check(step):
548
+ def register(fn):
549
+ CHECKS.append((step, fn.__name__, fn))
550
+ return fn
551
+ return register
552
+
553
+
554
+ # --- step 1: completion and binding ---------------------------------------------------------
555
+
556
+ @check("completion_binding")
557
+ def window_bound(c, errors):
558
+ """The bound, judged from the call directory (the seam record of 2026-10-22).
559
+
560
+ The dispatcher admits, settles and stops against `runlib/bound.py`; this is the second reader, so an
561
+ accepted call directory is evidence that the bound held rather than only that nothing raised. Both
562
+ facts are in the record the driver wrote: what the call observed, and whether a stop stood when it was
563
+ admitted. The second is impossible by construction - the dispatcher refuses such a call - which is
564
+ exactly why a gate should say so if it ever appears."""
565
+ call = c.call or {}
566
+ declared = call.get("bound") or {}
567
+ observed = call.get("input_observed")
568
+ if call.get("view_window") and isinstance(observed, int):
569
+ for line in bounds.check_observed(observed, True):
570
+ errors.append(f"{line} (call.json input_observed)")
571
+ if declared.get("stop_standing"):
572
+ errors.append(f"DISPATCHED_WHILE_STOPPED {call.get('call_id')}: the run's bound stop stood when this call was "
573
+ "admitted, and a stopped run dispatches nothing")
574
+ # W review of WP-08e r2, F1 (lead decision): a call that stopped the run is a failure, whatever its answer - its
575
+ # measured spend is kept, and its answer is never accepted or reused. Both readings: the stop the call recorded, and
576
+ # its usage against the claim it was admitted under, so a call whose stop record was lost is refused all the same.
577
+ offered = [call["stop"]] if isinstance(call.get("stop"), dict) else []
578
+ offered += [s for s in (call.get("stops") or {}).values() if isinstance(s, dict)] \
579
+ if isinstance(call.get("stops"), dict) else []
580
+ for stop in offered:
581
+ errors.append(f"{stop.get('code')} {call.get('call_id')}: this call stopped the run, so its answer is not "
582
+ f"accepted ({stop.get('detail')})")
583
+ requests = (c.usage or {}).get("requests") if isinstance(c.usage, dict) else None
584
+ claim = declared.get("claim") if isinstance(declared.get("claim"), dict) else None
585
+ breaches = bounds.claim_breaches(requests, claim) if claim else []
586
+ if breaches and not any(s.get("code") == bounds.CLAIM_CODE for s in offered):
587
+ errors.append(f"{bounds.CLAIM_CODE} {call.get('call_id')}: {'; '.join(breaches)} - past the claim it was "
588
+ "admitted under, so its answer is not accepted (usage.json against call.json bound.claim)")
589
+ # each rule judges only with the fields it needs, and a claim lacking one for rows that exist - a record written
590
+ # before `step` was named, with a retry row - is refused rather than judged by a weaker rule (the lead's
591
+ # verification of WP-08e commit 4, finding 1)
592
+ for line in bounds.claim_shape(requests, claim) if claim else []:
593
+ errors.append(f"{bounds.CLAIM_SHAPE} {call.get('call_id')}: {line}; a claim is never judged by a weaker rule "
594
+ "(usage.json against call.json bound.claim)")
595
+ # BA#1: drift, caught per call. The capacity the boundary admitted against is in the record; the host
596
+ # reports its own in every Claude result, and the two must agree or the declaration is stale.
597
+ usage = c.result.get("modelUsage") if isinstance(c.result, dict) else None
598
+ if isinstance(declared.get("context_capacity"), int) and isinstance(usage, dict):
599
+ reported = {model: u.get("contextWindow") for model, u in usage.items()
600
+ if isinstance(u, dict) and isinstance(u.get("contextWindow"), int)}
601
+ for model, window in sorted(reported.items()):
602
+ if window != declared["context_capacity"]:
603
+ errors.append(f"CAPACITY_DRIFT {model}: the host reports a context window of {window} and the call "
604
+ f"was admitted against {declared['context_capacity']}; the declaration is stale")
605
+ if declared and declared.get("limit") != bounds.INPUT_BOUND:
606
+ errors.append(f"RECORD_INTEGRITY call.json bound.limit: {declared.get('limit')} is not the bound the rule owns "
607
+ f"({bounds.INPUT_BOUND})")
608
+
609
+
610
+ @check("completion_binding")
611
+ def call_record(c, errors):
612
+ if not c.call.get("call_id") or c.kind not in ("claude", "codex"):
613
+ errors.append("RECORD_INTEGRITY call.json: absent, unreadable, or without call_id and host")
614
+ elif c.call:
615
+ errors.extend(f"RECORD_INTEGRITY call.json {line}" for line in validate.validate_instance(CALL_VALIDATOR, c.call))
616
+ if isinstance(c.host, dict):
617
+ errors.extend(f"RECORD_INTEGRITY capture/host.json {line}" for line in host_shape(c.host))
618
+ declared = c.call.get("contract")
619
+ if declared == "required" and c.contract is None:
620
+ errors.append("RECORD_INTEGRITY contract.json: call.json requires the stage's contract (steps 4 and 5), "
621
+ + ("and it is unreadable" if c.contract_bytes is not None else "and there is none"))
622
+ if declared == "required" and not c.required:
623
+ errors.append("RECORD_INTEGRITY contract.json: a reference or set contract judges a structured output, and the call is schema-less")
624
+ if declared == "none" and c.contract_bytes is not None:
625
+ errors.append("RECORD_INTEGRITY contract.json: present for a call that declares no contract")
626
+ if c.required and (c.schema_bytes is None or hashlib.sha256(c.schema_bytes).hexdigest() != c.call["schema_sha256"]):
627
+ errors.append("RECORD_INTEGRITY schema.json: not the schema call.json says the driver required")
628
+ if not c.required and c.schema_bytes is not None:
629
+ errors.append("RECORD_INTEGRITY schema.json: present for a call declared schema-less")
630
+ errors.extend(host_schema_problems(c))
631
+ if c.packet is None or c.result_bytes is None:
632
+ errors.append("RECORD_INTEGRITY packet.md and result.json: the bytes sent and read must both be kept")
633
+ if not isinstance(c.host, dict) or c.host.get("call_id") != c.call.get("call_id") or c.host.get("host") != c.kind:
634
+ errors.append(f"RECORD_INTEGRITY capture/host.json: absent, or not this call's {c.kind} capture")
635
+ if c.unreadable:
636
+ errors.append(f"RECORD_INTEGRITY {', '.join(c.unreadable)}: not well-formed JSON objects (one object, or one per line)")
637
+ if not isinstance(c.usage, dict) or usages.check(c.usage) or c.usage.get("call_id") != c.call.get("call_id"):
638
+ errors.append(f"RECORD_INTEGRITY usage.json: absent, invalid or another call's "
639
+ f"({usages.check(c.usage)[:2] if isinstance(c.usage, dict) else 'unreadable'})")
640
+
641
+
642
+ @check("completion_binding")
643
+ def exit_status(c, errors):
644
+ if c.call.get("exit_status") != 0:
645
+ errors.append(f"COMPLETION_INCOMPLETE exit: the runner exited {c.call.get('exit_status')!r}")
646
+ if c.call.get("stopped"):
647
+ errors.append(f"COMPLETION_INCOMPLETE {c.call['stopped'].get('outcome')}: the supervisor stopped the call "
648
+ f"({c.call['stopped'].get('why')})")
649
+
650
+
651
+ @check("completion_binding")
652
+ def claude_completion(c, errors):
653
+ if c.kind != "claude":
654
+ return
655
+ r = c.result if isinstance(c.result, dict) else {}
656
+ if r.get("type") != "result":
657
+ errors.append("COMPLETION_INCOMPLETE result: the host wrote no result object")
658
+ return
659
+ if r.get("is_error") is not False:
660
+ errors.append(f"COMPLETION_INCOMPLETE is_error={r.get('is_error')!r} (subtype {r.get('subtype')!r} is not read)")
661
+ overrun = breakers.cap_overrun(r, c.call.get("max_output_tokens"))
662
+ if overrun is not None:
663
+ errors.append(f"COMPLETION_INCOMPLETE max_output_tokens: the response passed the call's declared cap of {overrun} "
664
+ f"output tokens, and the host ended the call")
665
+ if r.get("terminal_reason") != "completed":
666
+ errors.append(f"COMPLETION_INCOMPLETE terminal_reason={r.get('terminal_reason')!r}, not 'completed'")
667
+ stops = r.get("safety_stops")
668
+ if type(stops) is not int or stops != 0: # bool and float are not the count
669
+ errors.append(f"COMPLETION_INCOMPLETE safety_stops={stops!r}" if "safety_stops" in r
670
+ else "COMPLETION_INCOMPLETE safety_stops: the result does not report it")
671
+ if c.required and not isinstance(r.get("structured_output"), dict):
672
+ errors.append("COMPLETION_INCOMPLETE structured_output: none, although a schema was given")
673
+ if not c.required and not isinstance(r.get("result"), str):
674
+ errors.append("COMPLETION_INCOMPLETE result text: a schema-less call's answer is the result text, and there is none")
675
+ for a in (c.host or {}).get("assistant") or []:
676
+ if a.get("stop_reason") not in CLAUDE_STOPS:
677
+ errors.append(f"COMPLETION_INCOMPLETE stop_reason {a.get('stop_reason')!r} on request {a.get('request_id')}")
678
+
679
+
680
+ @check("completion_binding")
681
+ def codex_completion(c, errors):
682
+ if c.kind != "codex":
683
+ return
684
+ types = [e.get("type") for e in c.events]
685
+ if "turn.completed" not in types:
686
+ errors.append("COMPLETION_INCOMPLETE turn: codex emitted no turn.completed")
687
+ for kind in ("turn.failed", "error"):
688
+ if kind in types:
689
+ errors.append(f"COMPLETION_INCOMPLETE {kind}: the host reported a failure")
690
+ for r in codex_responses(c):
691
+ if r["terminal"] is None:
692
+ errors.append(f"COMPLETION_INCOMPLETE aborted stream: {r['id']} has response.created and no response.completed")
693
+ elif r["terminal"] != "completed" or r["incomplete"]:
694
+ errors.append(f"COMPLETION_INCOMPLETE {r['id']} ended response.{r['terminal']} ({r['incomplete']})")
695
+ for rec in c.frames:
696
+ if rec.get("dir") == "recv" and ("refusal" in (rec.get("type") or "") or rec.get("type") == "error"):
697
+ errors.append(f"COMPLETION_INCOMPLETE {rec['type']} frame: {rec.get('detail')}")
698
+
699
+
700
+ @check("completion_binding")
701
+ def claude_bindings(c, errors):
702
+ if c.kind != "claude" or not isinstance(c.host, dict):
703
+ return
704
+ mains = [q for q in c.host.get("requests") or [] if q.get("role") == "main"]
705
+ if not mains:
706
+ errors.append("BINDING_MISMATCH request: the transcript records no main request")
707
+ return
708
+ sent = c.packet.decode("utf-8", "replace") if c.packet is not None else None
709
+ for q in mains:
710
+ if sent is None or q.get("packet_text") != sent:
711
+ errors.append(f"BINDING_MISMATCH request text: request {q.get('id')}'s recorded text is not the packet the driver sent")
712
+ if c.required:
713
+ for q in mains:
714
+ if q.get("structured_output_schema") is None or canonical(q["structured_output_schema"]) != canonical(c.schema):
715
+ errors.append(f"BINDING_MISMATCH schema: request {q.get('id')}'s StructuredOutput tool definition is not the schema")
716
+ out = c.output()
717
+ calls = c.host.get("structured_calls") or []
718
+ if isinstance(out, dict) and (not calls or canonical(calls[-1]) != canonical(out)):
719
+ errors.append("BINDING_MISMATCH result: structured_output is not the last StructuredOutput call the host recorded")
720
+
721
+
722
+ def receipt_evidence(call_dir):
723
+ """The receipt's evidence for the call directory, derived as receipt_binding recomputes it;
724
+ the dispatcher hands it to the launcher's --emit-receipt once the call's records are final."""
725
+ c = Call(call_dir)
726
+ call, host = c.call, c.host if isinstance(c.host, dict) else {}
727
+ return {"call_id": call.get("call_id"), "schema_sha256": call.get("schema_sha256") or "none",
728
+ "payload_sha256": packets.payload_sha256(c.packet), "seat_observed": canonical(observed_seats(c)),
729
+ "profile": host.get("profile"), "profile_flags_sha256": host.get("profile_flags_sha256") or "none",
730
+ "cwd": host.get("cwd") or "", "manifest_sha256": canonical_sha256(call.get("manifest")),
731
+ "context_observed_sha256": canonical_sha256(host.get("context")),
732
+ "usage_state": usages.call_state(c.usage), "usage_totals": usages.totals_text(c.usage),
733
+ "capture_sha256": capture_sha256(c.dir), "session_id": host.get("session_id") or "",
734
+ "hermeticity": observer_owner().receipt_hermeticity(host)}
735
+
736
+
737
+ @check("completion_binding")
738
+ def receipt_binding(c, errors):
739
+ receipt, problems = receipts.read(c.dir)
740
+ errors.extend(problems)
741
+ if not isinstance(receipt, dict):
742
+ return # nothing parsed: there is nothing further to judge
743
+ call_id, call = c.call.get("call_id"), c.call
744
+ errors.extend(receipts.problems(receipt, call.get("stage"), call_id))
745
+ evidence = receipt.get("evidence") if isinstance(receipt.get("evidence"), dict) else {}
746
+ provider, _, rest = (call.get("seat") or "").partition(":")
747
+ model, _, effort = rest.rpartition("/")
748
+ host = c.host if isinstance(c.host, dict) else {}
749
+ usage = c.usage if isinstance(c.usage, dict) and not usages.check(c.usage) else None
750
+ want = {
751
+ "packet_sha256": hashlib.sha256(c.packet).hexdigest() if c.packet is not None else None,
752
+ "result_sha256": hashlib.sha256(c.result_bytes).hexdigest() if c.result_bytes is not None else None,
753
+ "provider": provider, "model": model, "effort": effort, "exit_status": call.get("exit_status"),
754
+ "evidence.schema_sha256": call.get("schema_sha256") or "none",
755
+ "evidence.payload_sha256": packets.payload_sha256(c.packet) if c.packet is not None else None,
756
+ "evidence.seat_observed": canonical(observed_seats(c)),
757
+ "evidence.manifest_sha256": canonical_sha256(call.get("manifest")),
758
+ "evidence.context_observed_sha256": canonical_sha256(host.get("context")),
759
+ "evidence.usage_state": usages.call_state(usage) if usage else None,
760
+ "evidence.usage_totals": usages.totals_text(usage) if usage else None,
761
+ "evidence.capture_sha256": capture_sha256(c.dir),
762
+ "evidence.session_id": host.get("session_id"),
763
+ "evidence.hermeticity": observer_owner().receipt_hermeticity(host),
764
+ }
765
+ for key, value in want.items():
766
+ held = evidence.get(key.split(".", 1)[1]) if key.startswith("evidence.") else receipt.get(key)
767
+ present = key.split(".", 1)[1] in evidence if key.startswith("evidence.") else key in receipt
768
+ if present and held != value:
769
+ errors.append(f"RECORD_INTEGRITY receipt {key}: {held!r} is not {value!r}, recomputed from the call directory")
770
+ flags = pinned_flags_sha256(c.kind, call.get("host_version"), call.get("profile"))
771
+ if "profile" in evidence and evidence["profile"] != call.get("profile"):
772
+ errors.append(f"PROFILE_INHERITED receipt: profile {evidence['profile']!r}, the call requires {call.get('profile')!r}")
773
+ if "profile_flags_sha256" in evidence and evidence["profile_flags_sha256"] != flags:
774
+ errors.append("PROFILE_INHERITED receipt: the flag-set hash is not the one seats.json pins for the profile")
775
+ if "cwd" in evidence and evidence["cwd"] != (call.get("manifest") or {}).get("workdir_path"):
776
+ errors.append(f"CWD_OUTSIDE_MANIFEST receipt: cwd {evidence['cwd']!r} is not the declared working directory")
777
+ # the server policy the capture states is the run's verdict the dispatcher recorded for this call
778
+ if isinstance(call.get("server_policy"), dict):
779
+ stated = (host.get("hermeticity") or {}).get("server_policy") if isinstance(host.get("hermeticity"), dict) else None
780
+ if stated != call["server_policy"]:
781
+ errors.append(f"RECORD_INTEGRITY capture hermeticity: server policy {stated!r} is not the run's record "
782
+ f"{call['server_policy']!r} in call.json")
783
+
784
+
785
+ @check("completion_binding")
786
+ def profile(c, errors):
787
+ host, call = c.host if isinstance(c.host, dict) else {}, c.call
788
+ if host.get("profile") != call.get("profile"):
789
+ errors.append(f"PROFILE_INHERITED capture: the runner ran profile {host.get('profile')!r}, "
790
+ f"the call requires {call.get('profile')!r}")
791
+ flags = pinned_flags_sha256(c.kind, call.get("host_version"), call.get("profile"))
792
+ if flags is None:
793
+ errors.append(f"PROFILE_INHERITED seats.json pins no {call.get('profile')!r} flag set for "
794
+ f"{c.kind} {call.get('host_version')}")
795
+ elif host.get("profile_flags_sha256") != flags:
796
+ errors.append("PROFILE_INHERITED capture: the flag set the host ran with is not the pinned one")
797
+
798
+
799
+ @check("completion_binding")
800
+ def working_directory(c, errors):
801
+ want = (c.call.get("manifest") or {}).get("workdir_path")
802
+ got = (c.host or {}).get("cwd") if isinstance(c.host, dict) else None
803
+ if not want or got != want:
804
+ errors.append(f"CWD_OUTSIDE_MANIFEST capture: the host recorded cwd {got!r}, the manifest declares {want!r}")
805
+ # design §3.1: an empty directory the driver created, or exactly the files of the manifest
806
+ listed = {(f.get("path"), f.get("sha256")) for f in ((c.host or {}).get("workdir_files") or [])} if isinstance(c.host, dict) else set()
807
+ declared = {(f.get("path"), f.get("sha256")) for f in (c.call.get("manifest") or {}).get("workdir_files") or []}
808
+ if not isinstance(c.host, dict) or "workdir_files" not in c.host:
809
+ errors.append("CWD_OUTSIDE_MANIFEST capture: no listing of the working directory before the call")
810
+ elif listed != declared:
811
+ errors.append(f"CWD_OUTSIDE_MANIFEST working directory: holds {sorted(p for p, _ in listed - declared)}, "
812
+ f"lacks {sorted(p for p, _ in declared - listed)} against the manifest")
813
+
814
+
815
+ @check("completion_binding")
816
+ def effective_context(c, errors):
817
+ declared = c.call.get("manifest") or {}
818
+ observed = (c.host or {}).get("context") if isinstance(c.host, dict) else None
819
+ if not isinstance(observed, dict):
820
+ errors.append("CONTEXT_UNDECLARED capture: no effective-context evidence for this call")
821
+ return
822
+ want = {i["path"]: declared_instruction_hash(i) for i in declared.get("instructions") or []}
823
+ got = {i["path"]: i for i in observed.get("instructions") or []}
824
+ for path in sorted(set(got) - set(want)):
825
+ errors.append(f"CONTEXT_UNDECLARED instruction {path} ({got[path].get('kind')}) loaded, not declared")
826
+ for path in sorted(set(want) - set(got)):
827
+ errors.append(f"CONTEXT_HASH_MISMATCH instruction {path}: declared, not loaded")
828
+ for path in sorted(set(want) & set(got)):
829
+ if got[path].get("sha256") != want[path]:
830
+ errors.append(f"CONTEXT_HASH_MISMATCH instruction {path}: loaded bytes differ from the declared sha256")
831
+ want_prompts = [p.get("sha256") for p in declared.get("appended_prompts") or []]
832
+ got_prompts = [p.get("sha256") for p in observed.get("appended_prompts") or []]
833
+ for n, digest in enumerate(got_prompts):
834
+ if n >= len(want_prompts):
835
+ errors.append(f"CONTEXT_UNDECLARED appended system prompt {n + 1} (sha256 {str(digest)[:12]}) not declared")
836
+ elif digest != want_prompts[n]:
837
+ errors.append(f"CONTEXT_HASH_MISMATCH appended system prompt {n + 1}: sha256 {str(digest)[:12]}, "
838
+ f"declared {str(want_prompts[n])[:12]}")
839
+ for n in range(len(got_prompts), len(want_prompts)):
840
+ errors.append(f"CONTEXT_HASH_MISMATCH appended system prompt {n + 1}: declared, not in the sent request")
841
+ for kind in CONTEXT_SETS:
842
+ extra = sorted(set(observed.get(kind) or []) - set(declared.get(kind) or []))
843
+ absent = sorted(set(declared.get(kind) or []) - set(observed.get(kind) or []))
844
+ if extra:
845
+ errors.append(f"CONTEXT_UNDECLARED {kind} {extra} reached the call, not declared")
846
+ if absent:
847
+ errors.append(f"CONTEXT_HASH_MISMATCH {kind} {absent}: declared, not observed")
848
+
849
+
850
+ # --- step 2: seat attestation, by role -------------------------------------------------------
851
+
852
+ @check("seat_attestation")
853
+ def claude_seats(c, errors):
854
+ if c.kind != "claude" or not isinstance(c.host, dict):
855
+ return
856
+ role_seat = {"main": seat_model(c.call.get("seat")), "subagent": seat_model(c.call.get("child_seat"))}
857
+ for q in c.host.get("requests") or []:
858
+ want = role_seat.get(q.get("role"))
859
+ if want is None:
860
+ errors.append(f"MODEL_UNATTESTED request {q.get('id')}: role {q.get('role')!r} has no declared seat")
861
+ elif q.get("model") != want:
862
+ errors.append(f"MODEL_UNATTESTED request {q.get('id')} ({q.get('role')}) named {q.get('model')!r}, the seat is {want!r}")
863
+ answered = [a for a in c.host.get("assistant") or [] if not a.get("synthetic")]
864
+ for a in answered:
865
+ want = role_seat.get(a.get("role"))
866
+ if a.get("model") != want:
867
+ errors.append(f"MODEL_UNATTESTED response to {a.get('request_id')} ({a.get('role')}) came from "
868
+ f"{a.get('model')!r}, the seat is {want!r}")
869
+ if not any(a.get("role") == "main" and a.get("model") for a in answered):
870
+ errors.append("MODEL_UNATTESTED no main response carries an observed model")
871
+ usage = c.result.get("modelUsage") if isinstance(c.result, dict) else None
872
+ if not isinstance(usage, dict):
873
+ errors.append("MODEL_UNATTESTED aggregate: no result.modelUsage to attest the hidden requests by")
874
+ return
875
+ live = c.call.get("realization") == "live"
876
+ seated = {m for m in role_seat.values() if m}
877
+ declared = seated | auxiliary_models("claude", c.call.get("host_version"), live=live)
878
+ stray = sorted(set(usage) - declared)
879
+ if stray:
880
+ provisional = sorted(set(stray) & auxiliary_models("claude", c.call.get("host_version")))
881
+ errors.append(f"MODEL_UNATTESTED aggregate: result.modelUsage names {stray}, neither a declared seat "
882
+ f"nor a declared auxiliary role"
883
+ + (f" ({provisional} declared, not measured, so not for a live call)" if provisional else ""))
884
+
885
+
886
+ @check("seat_attestation")
887
+ def codex_seats(c, errors):
888
+ if c.kind != "codex":
889
+ return
890
+ responses = codex_responses(c)
891
+ if not responses:
892
+ errors.append("MODEL_UNATTESTED frames silent: no server frame carries a response, so no model is observed")
893
+ for r in responses:
894
+ want = seat_model(c.call.get(r["seat"]))
895
+ if r["ambiguous"]:
896
+ errors.append(f"MODEL_UNATTESTED {r['id']}: more than one client frame could have asked for it")
897
+ elif r["send"] is None:
898
+ errors.append(f"MODEL_UNATTESTED {r['id']}: no client frame names its role")
899
+ elif want is None:
900
+ errors.append(f"MODEL_UNATTESTED {r['id']} ({r['role']}): no seat is declared for the role")
901
+ elif not r["model"]:
902
+ errors.append(f"MODEL_UNATTESTED {r['id']} ({r['role']}): the frame carries no model")
903
+ elif r["model"] != want:
904
+ errors.append(f"MODEL_UNATTESTED {r['id']} ({r['role']}) came from {r['model']!r}, the seat is {want!r}")
905
+ if not any(rec.get("dir") == "otel" for rec in c.frames):
906
+ errors.append("MODEL_UNATTESTED completions: the capture carries no otel channel, so there is no completion ledger")
907
+ unjoined, ambiguous, leftover = join_completions(c, responses)
908
+ for comp in unjoined:
909
+ errors.append(f"frames_blind {comp.get('conversation.id')} completion at {comp.get('ts')} joins no frame "
910
+ f"response; its usage comes from otel and its request kind is unknown")
911
+ errors.append(f"MODEL_UNATTESTED completion at {comp.get('ts')} ({comp.get('input_token_count')} input "
912
+ f"tokens) has no observed model")
913
+ for comp in ambiguous:
914
+ errors.append(f"MODEL_UNATTESTED completion at {comp.get('ts')} ({comp.get('input_token_count')} input tokens): "
915
+ f"its in-order frame response disagrees in usage while another agrees, an ambiguous join")
916
+ if any(rec.get("dir") == "otel" for rec in c.frames):
917
+ for r in leftover:
918
+ errors.append(f"MODEL_UNATTESTED {r['id']}: a completed frame response no completion in the ledger joins")
919
+ attempts = codex_attempts(c)
920
+ counted = sum(t["completed"] + t["interrupted"] + t["unstarted_completions"] for t in attempts.values())
921
+ rows = len(c.usage["requests"]) if isinstance(c.usage, dict) and isinstance(c.usage.get("requests"), list) else 0
922
+ if counted > rows:
923
+ errors.append(f"RECORD_INTEGRITY usage.json: the capture shows {counted} attempts (interrupted ones included), "
924
+ f"usage records {rows}")
925
+
926
+
927
+ @check("seat_attestation")
928
+ def attempt_coverage(c, errors):
929
+ """Every attempt of a Codex call is accounted for, or the call's usage cannot be attributed
930
+ (lead decision of the WP-02 round-5 review: unknown coverage is a named failure, never a
931
+ complete reconciliation)."""
932
+ if c.kind != "codex":
933
+ return
934
+ for thread, th in sorted(codex_attempts(c).items()):
935
+ if th["coverage"] != "complete":
936
+ errors.append(f"USAGE_ATTRIBUTION_UNKNOWN {thread}: attempt coverage is unknown ({th['unknown_because']})")
937
+
938
+
939
+ # --- steps 3-5 -------------------------------------------------------------------------------
940
+
941
+ @check("schema")
942
+ def schema(c, errors):
943
+ if not c.required:
944
+ return
945
+ try:
946
+ validator = validate.compile_schema(c.schema)
947
+ except Exception as exc:
948
+ errors.append(f"SCHEMA_INVALID schema.json: refused by the schema policy ({exc.__class__.__name__})")
949
+ return
950
+ out = c.output()
951
+ if c.kind == "codex" and out is None:
952
+ errors.append("SCHEMA_INVALID result: not one JSON document (nothing is extracted from prose)")
953
+ return
954
+ if out is None:
955
+ return # Claude without structured_output: COMPLETION_INCOMPLETE already names it
956
+ for line in validate.validate_instance(validator, out):
957
+ errors.append(f"SCHEMA_INVALID {line}")
958
+
959
+
960
+ @check("cross_record_integrity")
961
+ def references(c, errors):
962
+ out, contract = c.output(), c.contract or {}
963
+ resolvable = contract.get("resolvable") or {}
964
+ for ref in contract.get("references") or []:
965
+ known = set(resolvable.get(ref.get("kind")) or [])
966
+ for value in walk(out, ref.get("path") or []):
967
+ if value not in known:
968
+ errors.append(f"RECORD_INTEGRITY {ref.get('kind')} id {value!r} at {'/'.join(ref.get('path'))} resolves to nothing")
969
+
970
+
971
+ @check("set_accounting")
972
+ def accounting(c, errors):
973
+ spec = (c.contract or {}).get("accounting")
974
+ if not spec:
975
+ return
976
+ outcomes = walk(c.output(), spec.get("path") or [])
977
+ outcomes = outcomes[0] if len(outcomes) == 1 and isinstance(outcomes[0], list) else []
978
+ for line in records.observe_set(records.expect_set(spec.get("expected") or []), [o for o in outcomes if isinstance(o, dict)]):
979
+ errors.append(f"{line} (design §3.2 item 5)")
980
+
981
+
982
+ # --- verdicts --------------------------------------------------------------------------------
983
+
984
+ def accept(call_dir, skip=()):
985
+ """The verdict on one call directory: every check run, `codes` the complete failure set.
986
+ `skip` names checks to leave out; only the mutation audit of the self-test passes it."""
987
+ try:
988
+ c = Call(call_dir)
989
+ except Exception as exc: # never a traceback: an unreadable directory is a verdict too
990
+ failure = f"RECORD_INTEGRITY call directory: unreadable ({exc.__class__.__name__}: {exc})"
991
+ return {"ok": False, "codes": ["RECORD_INTEGRITY"], "failures": [failure], "by_check": {"load": [failure]},
992
+ "call_id": None, "seat_sent": None, "seat_observed": None, "effort_provenance": None, "attempts": None,
993
+ "usage": None, "context_evidence": None}
994
+ by_check = {}
995
+ for _step, name, fn in CHECKS:
996
+ if name in skip:
997
+ continue
998
+ errors = []
999
+ try:
1000
+ fn(c, errors)
1001
+ except Exception as exc: # a malformed capture is a refusal by name, never a traceback
1002
+ errors.append(f"RECORD_INTEGRITY {name}: the call directory could not be read ({exc.__class__.__name__}: {exc})")
1003
+ if errors:
1004
+ by_check[name] = errors
1005
+ projected = {}
1006
+ for key, project in (("seat_observed", observed_seats), ("effort_provenance", effort_provenance),
1007
+ ("attempts", lambda c: codex_attempts(c) if c.kind == "codex" else {})):
1008
+ try:
1009
+ projected[key] = project(c)
1010
+ except Exception as exc: # the projection of a malformed capture is refused by name too
1011
+ by_check.setdefault("verdict", []).append(f"RECORD_INTEGRITY verdict {key}: the call directory could not be "
1012
+ f"read ({exc.__class__.__name__}: {exc})")
1013
+ projected[key] = None
1014
+ failures = [line for lines in by_check.values() for line in lines]
1015
+ usage = c.usage if isinstance(c.usage, dict) and not usages.check(c.usage) else None
1016
+ return {"ok": not failures, "codes": sorted({line.split()[0] for line in failures}), "failures": failures,
1017
+ "by_check": by_check, "call_id": c.call.get("call_id"), "seat_sent": c.call.get("seat"), **projected,
1018
+ "usage": usages.totals(usage) if usage else None,
1019
+ "context_evidence": (c.host or {}).get("context") if isinstance(c.host, dict) else None}
1020
+
1021
+
1022
+ def stage_check_of(call_dir):
1023
+ """The failure lines a stage's own check recorded for this attempt, or None when no stage judged it."""
1024
+ path = pathlib.Path(call_dir) / STAGE_CHECK
1025
+ return list(records.read_json(path)["failures"]) if path.is_file() else None
1026
+
1027
+
1028
+ def accepted(call_dir, judged=False):
1029
+ """The output a stage may read: only through here, and only when the call is accepted —
1030
+ the structured output of a schema-bound call, the final text of a schema-less one.
1031
+
1032
+ Accepted means the gate's verdict AND, where a stage judged the attempt, that judgement: an attempt whose recorded
1033
+ stage check failed is refused on every read (STAGE_CHECK_FAILED), so the gate and the stage's judge have one answer
1034
+ between them. A stage that judges its attempts reads with `judged=True`, which also refuses an attempt no judgement
1035
+ was recorded for (STAGE_CHECK_MISSING)."""
1036
+ verdict = accept(call_dir)
1037
+ if not verdict["ok"]:
1038
+ raise Refused(f"{' '.join(verdict['codes'])} {call_dir}: " + "; ".join(verdict["failures"]))
1039
+ judgement = stage_check_of(call_dir)
1040
+ if judgement:
1041
+ raise Refused(f"STAGE_CHECK_FAILED {call_dir}: " + "; ".join(judgement))
1042
+ if judged and judgement is None:
1043
+ raise Refused(f"STAGE_CHECK_MISSING {call_dir}: its stage judges every attempt, and no judgement of this one "
1044
+ "was recorded")
1045
+ return Call(call_dir).answer()
1046
+
1047
+
1048
+ def correction(verdict):
1049
+ """The validation message the one corrective retry carries (design §3.2)."""
1050
+ return ("Your previous answer was rejected by validation:\n" + "\n".join(f"- {line}" for line in verdict["failures"])
1051
+ + "\nAnswer again; follow the schema exactly and return nothing else.\n")
1052
+
1053
+
1054
+ def settle(call_dirs):
1055
+ """The outcome of one item's attempts: accepted, waiting for its one corrective retry, or
1056
+ failed with RETRY_EXHAUSTED; every attempt's verdict is kept."""
1057
+ attempts = [accept(d) for d in call_dirs]
1058
+ failures = []
1059
+ if not attempts:
1060
+ failures.append("RECORD_INTEGRITY settle: no attempt to settle")
1061
+ elif len(attempts) > 2:
1062
+ failures.append(f"RETRY_EXHAUSTED {len(attempts)} attempts: a failing output is retried once")
1063
+ elif not attempts[-1]["ok"] and len(attempts) == 2:
1064
+ failures.append(f"RETRY_EXHAUSTED both attempts failed ({' '.join(attempts[0]['codes'])}; "
1065
+ f"{' '.join(attempts[1]['codes'])})")
1066
+ ok = not failures and attempts[-1]["ok"]
1067
+ return {"ok": ok, "accepted": str(call_dirs[-1]) if ok else None, "retry": not failures and not ok,
1068
+ "codes": sorted({line.split()[0] for line in failures}), "failures": failures, "attempts": attempts}
1069
+
1070
+
1071
+ def predicate_branches(source):
1072
+ """{(check, template)}: every failure a check of `source` can emit, read from its AST — each
1073
+ `errors.append` or `errors.extend` message as a template, its placeholders `{}` except a loop
1074
+ variable over a module tuple of strings, a literal tuple, or a literal dict's keys, which is
1075
+ expanded per value; a conditional or concatenated message gives each alternative; a list of
1076
+ messages extended from elsewhere is `<the expression>`. The self-test holds this set equal to
1077
+ its own copy of design §3.2 (contract fidelity)."""
1078
+ tree = ast.parse(source)
1079
+ tuples = {t.id: [e.value for e in n.value.elts] for n in tree.body if isinstance(n, ast.Assign)
1080
+ and isinstance(n.value, ast.Tuple) and all(isinstance(e, ast.Constant) and isinstance(e.value, str) for e in n.value.elts)
1081
+ for t in n.targets if isinstance(t, ast.Name)}
1082
+ found = set()
1083
+ for fn in tree.body:
1084
+ if not (isinstance(fn, ast.FunctionDef) and any(isinstance(d, ast.Call) and getattr(d.func, "id", None) == "check"
1085
+ for d in fn.decorator_list)):
1086
+ continue
1087
+ parent = {kid: node for node in ast.walk(fn) for kid in ast.iter_child_nodes(node)}
1088
+ dicts = {t.id: [k.value for k in n.value.keys] for n in ast.walk(fn) if isinstance(n, ast.Assign) and isinstance(n.value, ast.Dict)
1089
+ and all(isinstance(k, ast.Constant) and isinstance(k.value, str) for k in n.value.keys)
1090
+ for t in n.targets if isinstance(t, ast.Name)}
1091
+
1092
+ def loops(node):
1093
+ bound = {}
1094
+ while node in parent:
1095
+ node = parent[node]
1096
+ if not isinstance(node, (ast.For, ast.comprehension)):
1097
+ continue
1098
+ target, it = node.target, node.iter
1099
+ if isinstance(target, ast.Tuple) and target.elts and isinstance(target.elts[0], ast.Name) and isinstance(it, ast.Call) \
1100
+ and isinstance(it.func, ast.Attribute) and it.func.attr == "items" and getattr(it.func.value, "id", None) in dicts:
1101
+ bound[target.elts[0].id] = dicts[it.func.value.id]
1102
+ elif isinstance(target, ast.Name) and isinstance(it, ast.Name) and it.id in tuples:
1103
+ bound[target.id] = tuples[it.id]
1104
+ elif isinstance(target, ast.Name) and isinstance(it, (ast.Tuple, ast.List)) and \
1105
+ all(isinstance(e, ast.Constant) and isinstance(e.value, str) for e in it.elts):
1106
+ bound[target.id] = [e.value for e in it.elts]
1107
+ return bound
1108
+
1109
+ def render(node, bound):
1110
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
1111
+ return [node.value]
1112
+ if isinstance(node, ast.JoinedStr):
1113
+ parts = [[v.value] if isinstance(v, ast.Constant) else bound[v.value.id]
1114
+ if isinstance(v.value, ast.Name) and v.value.id in bound and v.conversion == -1 else ["{}"] for v in node.values]
1115
+ return ["".join(p) for p in itertools.product(*parts)]
1116
+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
1117
+ return [a + b for a in render(node.left, bound) for b in render(node.right, bound)]
1118
+ if isinstance(node, ast.IfExp):
1119
+ return render(node.body, bound) + render(node.orelse, bound)
1120
+ return ["{}"]
1121
+ for node in ast.walk(fn):
1122
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr in ("append", "extend")
1123
+ and getattr(node.func.value, "id", None) == "errors" and node.args):
1124
+ continue
1125
+ message = node.args[0]
1126
+ if node.func.attr == "extend" and isinstance(message, (ast.GeneratorExp, ast.ListComp)):
1127
+ message = message.elt
1128
+ elif node.func.attr == "extend":
1129
+ found.add((fn.name, f"<{ast.unparse(message.func if isinstance(message, ast.Call) else message)}>"))
1130
+ continue
1131
+ found.update((fn.name, text) for text in render(message, loops(node)))
1132
+ return found
1133
+
1134
+
1135
+ # --- self-test -------------------------------------------------------------------------------
1136
+
1137
+ def self_test():
1138
+ try:
1139
+ replay_root = records.fixture_root("replay")
1140
+ except Refused as exc: # a tree without fixtures/ ends the suite by name, never by a traceback
1141
+ print(f"gate --self-test: {exc}")
1142
+ return 1
1143
+ import copy
1144
+ import tempfile
1145
+ failures, ran, outcomes = [], [], []
1146
+ scratch = pathlib.Path(tempfile.mkdtemp(prefix="gate-self-test-"))
1147
+ # removed at exit as well, so a suite that stops on an exception leaves nothing in its TMPDIR
1148
+ import atexit
1149
+ import shutil
1150
+ atexit.register(shutil.rmtree, scratch, True)
1151
+
1152
+ def fixture(probe, case, name):
1153
+ return (replay_root / probe / case / name).read_bytes()
1154
+
1155
+ def jload(files, name):
1156
+ return json.loads(files[name])
1157
+
1158
+ def jput(files, name, obj):
1159
+ files[name] = (json.dumps(obj, indent=1, sort_keys=True, ensure_ascii=False) + "\n").encode()
1160
+
1161
+ def jedit(files, name, edit):
1162
+ obj = jload(files, name)
1163
+ edit(obj)
1164
+ jput(files, name, obj)
1165
+
1166
+ def materialize(files):
1167
+ target = pathlib.Path(tempfile.mkdtemp(dir=scratch))
1168
+ for name, data in files.items():
1169
+ (target / name).parent.mkdir(parents=True, exist_ok=True)
1170
+ (target / name).write_bytes(data)
1171
+ return target
1172
+
1173
+ def seal(files):
1174
+ """The golden receipt: every value the gate recomputes, recomputed the same way."""
1175
+ files = dict(files)
1176
+ files.pop("receipt.json", None)
1177
+ c = Call(materialize(files))
1178
+ call = c.call
1179
+ provider, _, rest = call["seat"].partition(":")
1180
+ model, _, effort = rest.rpartition("/")
1181
+ evidence = receipt_evidence(c.dir)
1182
+ jput(files, "receipt.json", {
1183
+ "schema": "ReviewReceipt/v1", "method_id": receipts.method_id(call["stage"], call["call_id"]),
1184
+ "dispatch_id": hashlib.sha256(call["call_id"].encode()).hexdigest()[:32],
1185
+ "packet_sha256": hashlib.sha256(c.packet).hexdigest(), "result_sha256": hashlib.sha256(c.result_bytes).hexdigest(),
1186
+ "provider": provider, "model": model, "effort": effort, "exit_status": call["exit_status"], "evidence": evidence})
1187
+ return files
1188
+
1189
+ def manifest(workdir, **extra):
1190
+ return {"workdir_path": workdir, "workdir_files": [], "instructions": [], "appended_prompts": [], "skills": [],
1191
+ "agents": [], "hooks": [], **extra}
1192
+
1193
+ def claude_case(case):
1194
+ """A replayed claude-runner capture in a golden envelope (call.json, receipt)."""
1195
+ d = replay_root / "claude-runner" / case
1196
+ facts = json.loads((d / "facts.json").read_bytes())
1197
+ files = {"packet.md": fixture("claude-runner", case, "packet.md"),
1198
+ "result.json": fixture("claude-runner", case, "result.json"),
1199
+ "capture/host.json": fixture("claude-runner", case, "host.json"),
1200
+ "usage.json": fixture("claude-runner", case, "usage.json")}
1201
+ schema_sha = None
1202
+ if facts["schema"]:
1203
+ files["schema.json"] = fixture("claude-runner", case, "schema.json")
1204
+ schema_sha = hashlib.sha256(files["schema.json"]).hexdigest()
1205
+ host = jload(files, "capture/host.json")
1206
+ jput(files, "call.json", {"schema": "DistillCall/v1", "call_id": host["call_id"], "stage": "S6", "item": case,
1207
+ "attempt": 1, "host": "claude", "host_version": seats()["hosts"]["claude"]["version"],
1208
+ "seat": facts["seat"],
1209
+ "child_seat": None, "profile": "hermetic", "manifest": manifest(facts["workdir_path"]),
1210
+ "schema_sha256": schema_sha, "view_window": False, "realization": "replay",
1211
+ "exit_status": facts["exit_status"], "wall_ms": None, "stopped": None, "contract": "none"})
1212
+ return seal(files)
1213
+
1214
+ # a replayed Codex capture is judged under the version seats.json pins now, as a replayed Claude one is
1215
+ codex_version = seats()["hosts"]["codex"]["version"]
1216
+
1217
+ def codex_case(probe, case, seat=None):
1218
+ """A replayed Codex capture: codex-accounting frames inside a golden envelope, or a
1219
+ codex-runner capture with its own packet, result, schema and context."""
1220
+ d = replay_root / probe / case
1221
+ facts = json.loads((d / "facts.json").read_bytes())
1222
+ frames = (d / "frames.jsonl").read_bytes()
1223
+ root = json.loads(frames.splitlines()[0])["thread"]
1224
+ call_id = f"r0-S6-{case}-a1"
1225
+ files = {"capture/frames.jsonl": frames, "capture/events.jsonl": (d / "events.jsonl").read_bytes()}
1226
+ if probe == "codex-runner":
1227
+ seat, workdir = facts["seat"], facts["workdir_path"]
1228
+ files.update({"packet.md": (d / "packet.md").read_bytes(), "result.json": (d / "result.json").read_bytes(),
1229
+ "capture/host.json": (d / "host.json").read_bytes(), "schema.json": (d / "schema.json").read_bytes()})
1230
+ call_id = jload(files, "capture/host.json")["call_id"]
1231
+ schema_sha = hashlib.sha256(files["schema.json"]).hexdigest()
1232
+ skills = ["imagegen", "openai-docs", "skill-creator", "skill-installer"]
1233
+ else:
1234
+ seat, workdir = seat or f"codex:{facts['model']}/low", facts["cwd"]
1235
+ files["packet.md"] = packets.build(call_id, "S6", seat, "Reply with the single word OK.\n")
1236
+ files["result.json"] = b"OK"
1237
+ jput(files, "capture/host.json", {"host": "codex", "call_id": call_id, "profile": "hermetic",
1238
+ "profile_flags_sha256": pinned_flags_sha256("codex", codex_version, "hermetic"),
1239
+ "cwd": workdir, "session_id": root, "workdir_files": [],
1240
+ "context": {"instructions": [], "appended_prompts": [], "skills": [],
1241
+ "agents": [], "hooks": []}})
1242
+ schema_sha, skills = None, []
1243
+ rows = replay_usage(files)
1244
+ jput(files, "usage.json", {"call_id": call_id, "stage": "S6", "seat_requested": seat,
1245
+ "seat_observed": {}, "requests": rows, "wall_ms": None, "attempts": len(rows),
1246
+ "reconciled": bool(rows)})
1247
+ jput(files, "call.json", {"schema": "DistillCall/v1", "call_id": call_id, "stage": "S6", "item": case,
1248
+ "attempt": 1, "host": "codex", "host_version": codex_version, "seat": seat,
1249
+ "child_seat": None, "profile": "hermetic", "manifest": manifest(workdir, skills=skills),
1250
+ "schema_sha256": schema_sha, "view_window": False, "realization": "replay",
1251
+ "exit_status": facts["exit_status"], "wall_ms": None, "stopped": None, "contract": "none"})
1252
+ return seal(files)
1253
+
1254
+ def tokens(input_tokens, cached, written, output):
1255
+ input_tokens, cached, written = int(input_tokens or 0), int(cached or 0), int(written or 0)
1256
+ return {"input": max(input_tokens - cached - written, 0), "output": int(output or 0), "cache_read": cached,
1257
+ "cache_creation": written}
1258
+
1259
+ def replay_usage(files):
1260
+ """The usage a replayed Codex capture records (design §13.3): the completion ledger's
1261
+ usage-bearing rows — measured, with the joined frame response's role, or `unknown` where no
1262
+ frame joins (frames_blind) —, every interrupted attempt as unresolved, and, where a capture
1263
+ has no otel ledger at all, its frame completions."""
1264
+ c = Call(materialize({k: v for k, v in files.items() if k.startswith("capture/")}))
1265
+ responses = codex_responses(c)
1266
+ if not any(r.get("dir") == "otel" for r in c.frames):
1267
+ return [{"id": r["id"], "role": r["role"] or "unknown", "state": "measured", "estimate": None,
1268
+ **tokens(r["usage"].get("input_tokens"), r["usage"].get("cached_tokens"), r["usage"].get("cache_write_tokens"),
1269
+ r["usage"].get("output_tokens"))}
1270
+ for r in responses if r["terminal"] == "completed" and isinstance(r["usage"], dict)]
1271
+ unjoined, ambiguous, _leftover = join_completions(c, responses)
1272
+ rows = [{"id": r["id"], "role": r["role"] or "unknown", "state": "measured", "estimate": None,
1273
+ **tokens(r["usage"].get("input_tokens"), r["usage"].get("cached_tokens"), r["usage"].get("cache_write_tokens"),
1274
+ r["usage"].get("output_tokens"))} for r in responses if r["joined"]]
1275
+ rows += [{"id": f"otel-{comp.get('ts')}", "role": "unknown", "state": "measured", "estimate": None,
1276
+ **tokens(comp.get("input_token_count"), comp.get("cached_token_count"), comp.get("cache_write_token_count"),
1277
+ comp.get("output_token_count"))} for comp in unjoined + ambiguous]
1278
+ for thread, th in codex_attempts(c).items():
1279
+ rows += [{"id": f"interrupted-{thread[-6:]}-{n}", "role": "unknown", "state": "unresolved", "estimate": None,
1280
+ "input": None, "output": None, "cache_read": None, "cache_creation": None} for n in range(th["interrupted"])]
1281
+ return rows
1282
+
1283
+ def variant(base, *edits, reseal=True):
1284
+ files = dict(base)
1285
+ for edit in edits:
1286
+ edit(files)
1287
+ return seal(files) if reseal else files
1288
+
1289
+ def control(name, files, *needles, realization="golden"):
1290
+ """A named control over one call directory: the verdict must name every needle (code
1291
+ and detail); with none it must be an acceptance."""
1292
+ ran.append(name)
1293
+ verdict = accept(materialize(files))
1294
+ if not needles and not verdict["ok"]:
1295
+ failures.append(f"{name}: expected acceptance, got {verdict['failures']}")
1296
+ for needle in needles:
1297
+ if not any(needle in line for line in verdict["failures"]):
1298
+ failures.append(f"{name}: expected {needle!r} in {verdict['failures']}")
1299
+ outcomes.append((name, files, needles, realization, verdict))
1300
+ return verdict
1301
+
1302
+ claude = claude_case("acc-clean-001")
1303
+ codex = codex_case("codex-accounting", "f-normal-ws")
1304
+ # a capture row ends at "\n" only; hosts write U+2028 and U+2029 raw inside a JSON string
1305
+ ran.append("jsonl-line-separators-inside-a-string-read-whole")
1306
+ with tempfile.TemporaryDirectory() as td:
1307
+ held = {"dir": "recv", "type": "response.output_text.delta", "delta": "before\u2028between\u2029after"}
1308
+ (pathlib.Path(td) / "capture").mkdir()
1309
+ (pathlib.Path(td) / "capture" / "frames.jsonl").write_text(json.dumps(held, ensure_ascii=False) + "\n", encoding="utf-8")
1310
+ read = Call(td)
1311
+ if read.frames != [held] or "capture/frames.jsonl" in read.unreadable:
1312
+ failures.append(f"jsonl-line-separators-inside-a-string-read-whole (Call._jsonl): frames {read.frames!r}, "
1313
+ f"unreadable {read.unreadable}")
1314
+ # a bare CR is JSON whitespace, which text-mode reading would turn into a line break; CRLF still ends a row
1315
+ later = {"dir": "recv", "type": "response.completed"}
1316
+ (pathlib.Path(td) / "capture" / "frames.jsonl").write_bytes(
1317
+ ("{\r" + json.dumps(held)[1:] + "\r\n" + json.dumps(later) + "\n").encode("utf-8"))
1318
+ read = Call(td)
1319
+ if read.frames != [held, later] or "capture/frames.jsonl" in read.unreadable:
1320
+ failures.append(f"jsonl-bare-cr-whitespace-and-crlf-read-whole (Call._jsonl): frames {read.frames!r}, "
1321
+ f"unreadable {read.unreadable}")
1322
+ # the capture's owner is read through its pure readers only (its context command starts codex)
1323
+ used = {n.attr for n in ast.walk(ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8")))
1324
+ if isinstance(n, ast.Attribute) and isinstance(n.value, ast.Call) and getattr(n.value.func, "id", None) == "frame_owner"}
1325
+ if not used or used - set(FRAME_READERS):
1326
+ failures.append(f"the gate reads {sorted(used)} of {FRAME_OWNER.name}, its readers are {list(FRAME_READERS)}")
1327
+
1328
+ # positive controls, first: a real hermetic Claude capture and a real Codex frame stream, each accepted
1329
+ control("claude-replay-clean", claude, realization="replay")
1330
+ clean_codex = control("codex-replay-clean", codex, realization="replay")
1331
+ if clean_codex["effort_provenance"] != "host-reported":
1332
+ failures.append(f"codex frames report the requested effort, provenance {clean_codex['effort_provenance']}")
1333
+ if accept(materialize(claude))["effort_provenance"] != "unverified":
1334
+ failures.append("Claude effort was not left unverified (plan S-6)")
1335
+
1336
+ def schemaless(files):
1337
+ files.pop("schema.json")
1338
+ jedit(files, "call.json", lambda o: o.update(schema_sha256=None))
1339
+ jedit(files, "result.json", lambda o: o.pop("structured_output"))
1340
+ jedit(files, "capture/host.json", lambda o: (o.update(structured_calls=[]),
1341
+ [q.update(structured_output_schema=None) for q in o["requests"]]))
1342
+ control("claude-schema-less-actor-call-without-structured-output", variant(claude, schemaless))
1343
+
1344
+ # --- completion -------------------------------------------------------------------------
1345
+ control("claude-real-truncation-max-tokens", claude_case("ctl-truncation-001"),
1346
+ "COMPLETION_INCOMPLETE stop_reason 'max_tokens'", "COMPLETION_INCOMPLETE is_error=True", realization="replay")
1347
+ # the host's cap overrun (WP-03v dw5, the recorded cap16 result): named at the cap the call declared, never elsewhere
1348
+ overrun = fixture("claude-runner", "cap16-overrun", "result.json")
1349
+
1350
+ def overran(cap):
1351
+ def edit(files):
1352
+ files["result.json"] = overrun
1353
+ jedit(files, "call.json", lambda o: o.update(max_output_tokens=cap))
1354
+ return edit
1355
+ control("claude-cap-overrun-is-named-at-the-declared-cap", variant(claude, overran(16)),
1356
+ "COMPLETION_INCOMPLETE max_output_tokens: the response passed the call's declared cap of 16 output tokens",
1357
+ "COMPLETION_INCOMPLETE is_error=True", "COMPLETION_INCOMPLETE terminal_reason='api_error'")
1358
+ elsewhere = control("claude-cap-overrun-sentence-at-another-cap-is-not-named", variant(claude, overran(4096)),
1359
+ "COMPLETION_INCOMPLETE is_error=True")
1360
+ if any("max_output_tokens:" in line for line in elsewhere["failures"]):
1361
+ failures.append(f"claude-cap-overrun-sentence-at-another-cap-is-not-named: {elsewhere['failures']}")
1362
+ control("claude-real-killed-midstream", claude_case("ctl-killed-001"), "COMPLETION_INCOMPLETE exit: the runner exited 143",
1363
+ "COMPLETION_INCOMPLETE result: the host wrote no result object",
1364
+ "MODEL_UNATTESTED no main response carries an observed model", realization="replay")
1365
+ control("claude-real-impossible-schema-no-structured-output", claude_case("ctl-schema-impossible-001"),
1366
+ "COMPLETION_INCOMPLETE structured_output: none", realization="replay")
1367
+ control("claude-is-error-while-subtype-reads-success",
1368
+ variant(claude, lambda f: jedit(f, "result.json", lambda o: o.update(is_error=True))),
1369
+ "COMPLETION_INCOMPLETE is_error=True (subtype 'success' is not read)")
1370
+ control("claude-terminal-reason-present-not-completed",
1371
+ variant(claude, lambda f: jedit(f, "result.json", lambda o: o.update(terminal_reason="max_turns"))),
1372
+ "COMPLETION_INCOMPLETE terminal_reason='max_turns'")
1373
+ control("claude-safety-stop-counted",
1374
+ variant(claude, lambda f: jedit(f, "result.json", lambda o: o.update(safety_stops=1))),
1375
+ "COMPLETION_INCOMPLETE safety_stops=1")
1376
+ shape = json.loads(fixture("claude-accounting", "ep-q-refusal-continuation", "shape.json"))
1377
+
1378
+ def refusal(files):
1379
+ jedit(files, "result.json", lambda o: o.update({k: shape["result"][k] for k in ("is_error", "terminal_reason", "stop_reason", "safety_stops")}))
1380
+ jedit(files, "capture/host.json", lambda o: [a.update(stop_reason=shape["assistant"][-1]["stop_reason"]) for a in o["assistant"]])
1381
+ control("claude-refusal-shape-replayed", variant(claude, refusal), "COMPLETION_INCOMPLETE stop_reason 'refusal'",
1382
+ "COMPLETION_INCOMPLETE safety_stops=2", realization="replay")
1383
+ control("nonzero-exit-with-a-complete-capture", variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(exit_status=1))),
1384
+ "COMPLETION_INCOMPLETE exit: the runner exited 1")
1385
+ control("budget-stopped-call", variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1386
+ stopped={"outcome": "budget_stopped", "why": "token cap"}))), "COMPLETION_INCOMPLETE budget_stopped: the supervisor stopped the call (token cap)")
1387
+ control("drain-unfinished-call-named-by-its-outcome", variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1388
+ stopped={"outcome": "drain_unfinished", "why": "DRAIN_UNFINISHED held"}))),
1389
+ "COMPLETION_INCOMPLETE drain_unfinished: the supervisor stopped the call (DRAIN_UNFINISHED held)")
1390
+ control("codex-real-aborted-stream", codex_case("codex-runner", "ctl-killed-002"),
1391
+ "COMPLETION_INCOMPLETE aborted stream", "COMPLETION_INCOMPLETE turn: codex emitted no turn.completed", realization="replay")
1392
+
1393
+ def frame(files, rec, at=None):
1394
+ lines = files["capture/frames.jsonl"].decode().splitlines()
1395
+ lines.insert(len(lines) if at is None else at, json.dumps(rec))
1396
+ files["capture/frames.jsonl"] = ("\n".join(lines) + "\n").encode()
1397
+
1398
+ def frames_edit(files, edit):
1399
+ recs = [json.loads(line) for line in files["capture/frames.jsonl"].decode().splitlines() if line.strip()]
1400
+ recs = edit(recs)
1401
+ files["capture/frames.jsonl"] = "".join(json.dumps(r) + "\n" for r in recs).encode()
1402
+
1403
+ def last_completed(recs):
1404
+ return [r for r in recs if r.get("type") == "response.completed"][-1]
1405
+
1406
+ control("codex-planted-response-incomplete", variant(codex, lambda f: frames_edit(f, lambda rs: [
1407
+ dict(r, type="response.incomplete", response=dict(r["response"], incomplete_details={"reason": "max_output_tokens"}))
1408
+ if r is last_completed(rs) else r for r in rs])), "COMPLETION_INCOMPLETE resp_fake_485723508_1 ended response.incomplete")
1409
+ control("codex-planted-refusal-frame", variant(codex, lambda f: frame(f, {"dir": "recv", "type": "response.refusal.done"})),
1410
+ "COMPLETION_INCOMPLETE response.refusal.done frame")
1411
+ control("codex-turn-failed", variant(codex, lambda f: f.update({"capture/events.jsonl": f["capture/events.jsonl"]
1412
+ + b'{"type": "turn.failed", "error": {}}\n'})),
1413
+ "COMPLETION_INCOMPLETE turn.failed")
1414
+ control("codex-no-turn-completed", variant(codex, lambda f: f.update({"capture/events.jsonl": b'{"type": "turn.started"}\n'})),
1415
+ "COMPLETION_INCOMPLETE turn: codex emitted no turn.completed")
1416
+ limit = codex_case("codex-accounting", "f-ws-usage-limit")
1417
+ control("codex-usage-limit-error-frame", limit, "COMPLETION_INCOMPLETE error frame", "COMPLETION_INCOMPLETE turn.failed",
1418
+ realization="replay")
1419
+
1420
+ # --- Claude host-level bindings, each broken alone ---------------------------------------
1421
+ control("binding-request-text-is-not-the-packet",
1422
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["requests"][0].update(packet_text="CALL-ID: acc-clean-001\nsomething else\n"))),
1423
+ "BINDING_MISMATCH request text")
1424
+ control("binding-tool-definition-is-not-the-schema",
1425
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["requests"][0]["structured_output_schema"].update(required=[]))),
1426
+ "BINDING_MISMATCH schema")
1427
+ control("binding-structured-output-is-not-the-last-call",
1428
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(structured_calls=[{"answer": "other"}]))),
1429
+ "BINDING_MISMATCH result")
1430
+ control("binding-no-main-request-recorded",
1431
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(requests=[]))),
1432
+ "BINDING_MISMATCH request: the transcript records no main request")
1433
+
1434
+ # --- receipts ------------------------------------------------------------------------------
1435
+ control("no-receipt", variant(claude, lambda f: f.pop("receipt.json"), reseal=False), "RECEIPT_MISSING")
1436
+ other = claude_case("ctl-memory-001")
1437
+ control("stale-receipt-of-another-call", variant(claude, lambda f: f.update({"receipt.json": other["receipt.json"]}), reseal=False),
1438
+ "RECEIPT_STALE method_id", "RECEIPT_STALE evidence.call_id")
1439
+
1440
+ def relabelled(files):
1441
+ receipt = json.loads(other["receipt.json"])
1442
+ receipt["method_id"], receipt["evidence"]["call_id"] = "distill/S6/acc-clean-001", "acc-clean-001"
1443
+ jput(files, "receipt.json", receipt)
1444
+ control("receipt-relabelled-to-this-call", variant(claude, relabelled, reseal=False),
1445
+ "RECORD_INTEGRITY receipt packet_sha256", "RECORD_INTEGRITY receipt evidence.session_id")
1446
+ control("receipt-key-missing", variant(claude, lambda f: jedit(f, "receipt.json", lambda o: o["evidence"].pop("payload_sha256")), reseal=False),
1447
+ "RECEIPT_KEY_MISSING evidence.payload_sha256")
1448
+ control("mismatched-result-hash", variant(claude, lambda f: f.update({"result.json": f["result.json"].replace(b'"num_turns":2', b'"num_turns":3')}),
1449
+ reseal=False), "RECORD_INTEGRITY receipt result_sha256")
1450
+ control("packet-changed-after-the-receipt", variant(claude, lambda f: f.update({"packet.md": f["packet.md"] + b" "}), reseal=False),
1451
+ "RECORD_INTEGRITY receipt packet_sha256", "BINDING_MISMATCH request text")
1452
+ for key, value in (("schema_sha256", "0" * 64), ("payload_sha256", "0" * 64), ("seat_observed", '{"main":["claude-opus-5-5"]}'),
1453
+ ("manifest_sha256", "0" * 64), ("context_observed_sha256", "0" * 64), ("usage_state", "provisional"),
1454
+ ("usage_totals", '{"measured":1}'), ("capture_sha256", "0" * 64), ("session_id", "another-session"),
1455
+ ("hermeticity", '{"assessed":true,"fully_hermetic":true}')):
1456
+ control(f"receipt-{key}-is-not-recomputed", variant(claude, lambda f, k=key, v=value: jedit(f, "receipt.json", lambda o: o["evidence"].update({k: v})),
1457
+ reseal=False), f"RECORD_INTEGRITY receipt evidence.{key}")
1458
+ # the capture states the run's server-policy verdict as call.json records it (D-20261102-252c92)
1459
+ run_policy = {"status": "none configured for this organization", "verdict": "clean", "reason": None}
1460
+ stated_policy = {"assessed": True, "managed_sources": [], "managed_unverified": [], "server_policy": run_policy,
1461
+ "fully_hermetic": True, "setting_sources_note": "n"}
1462
+ control("capture-server-policy-is-the-runs", variant(
1463
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(server_policy=run_policy)),
1464
+ lambda f: jedit(f, "capture/host.json", lambda o: o.update(hermeticity=stated_policy))))
1465
+ control("capture-server-policy-is-not-the-runs", variant(
1466
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(server_policy=run_policy)),
1467
+ lambda f: jedit(f, "capture/host.json", lambda o: o.update(hermeticity={**stated_policy, "server_policy": {
1468
+ "status": None, "verdict": "unknown", "reason": "no server-policy check was run for this call"}}))),
1469
+ "RECORD_INTEGRITY capture hermeticity: server policy {'reason': 'no server-policy check was run for this call'")
1470
+ # A capture whose server policy contradicts itself (a clean verdict without the clean status) is not
1471
+ # fully hermetic in the receipt the gate recomputes: the observer's own validator reads the verdict.
1472
+ ran.append("receipt-a-contradictory-server-policy-is-not-fully-hermetic")
1473
+ contradictory = variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(hermeticity={
1474
+ **stated_policy, "server_policy": {"status": None, "verdict": "clean", "reason": "failed"}})))
1475
+ recomputed = json.loads(json.loads(contradictory["receipt.json"])["evidence"]["hermeticity"])
1476
+ if recomputed.get("fully_hermetic") is not False:
1477
+ failures.append(f"receipt-a-contradictory-server-policy-is-not-fully-hermetic: the recomputed receipt "
1478
+ f"states {recomputed!r}")
1479
+ control("receipt-seat-sent-is-not-the-call-seat", variant(claude, lambda f: jedit(f, "receipt.json", lambda o: o.update(model="claude-opus-5-5")),
1480
+ reseal=False), "RECORD_INTEGRITY receipt model")
1481
+ control("receipt-exit-status-is-not-observed", variant(claude, lambda f: jedit(f, "receipt.json", lambda o: o.update(exit_status=1)),
1482
+ reseal=False), "RECORD_INTEGRITY receipt exit_status")
1483
+ control("capture-changed-after-the-receipt", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(note="x")),
1484
+ reseal=False), "RECORD_INTEGRITY receipt evidence.capture_sha256")
1485
+
1486
+ # --- profile, working directory -------------------------------------------------------------
1487
+ control("codex-real-inherited-profile", codex_case("codex-runner", "ctl-inherit-002"),
1488
+ "PROFILE_INHERITED capture: the runner ran profile 'inherit'", "PROFILE_INHERITED receipt: profile 'inherit'", realization="replay")
1489
+ control("claude-flag-set-is-not-the-pinned-one",
1490
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(profile_flags_sha256="0" * 64))),
1491
+ "PROFILE_INHERITED capture: the flag set", "PROFILE_INHERITED receipt: the flag-set hash")
1492
+ control("host-version-without-a-pinned-flag-set",
1493
+ variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(host_version="2.1.303"))),
1494
+ "PROFILE_INHERITED seats.json pins no 'hermetic' flag set for claude 2.1.303")
1495
+ control("host-cwd-outside-the-manifest",
1496
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(cwd="/Users/Shared/elsewhere"))),
1497
+ "CWD_OUTSIDE_MANIFEST capture: the host recorded cwd '/Users/Shared/elsewhere'")
1498
+ listed = {"path": "notes.txt", "sha256": "e" * 64}
1499
+ control("working-directory-holds-an-undeclared-file",
1500
+ variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(workdir_files=[listed]))),
1501
+ "CWD_OUTSIDE_MANIFEST working directory: holds ['notes.txt']")
1502
+ control("working-directory-holds-exactly-the-manifest", variant(
1503
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(workdir_files=[listed])),
1504
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(workdir_files=[listed]))))
1505
+ control("working-directory-not-listed", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.pop("workdir_files"))),
1506
+ "CWD_OUTSIDE_MANIFEST capture: no listing")
1507
+ control("receipt-cwd-outside-the-manifest",
1508
+ variant(claude, lambda f: jedit(f, "receipt.json", lambda o: o["evidence"].update(cwd="/tmp/x")), reseal=False),
1509
+ "CWD_OUTSIDE_MANIFEST receipt: cwd '/tmp/x'")
1510
+
1511
+ # --- effective context: the five contaminated working directories, each answering validly ---
1512
+ for case, needle in (("ctl-work-claude-md-001", "/ctl-work-claude-md-001/work/CLAUDE.md (Project)"),
1513
+ ("ctl-anc-claude-md-001", "/anc-root-undeclared/CLAUDE.md (Project)"),
1514
+ ("ctl-cfg-claude-md-001", "/ctl-cfg-claude-md-001/cfg/CLAUDE.md (User)"),
1515
+ ("ctl-skill-001", "CONTEXT_UNDECLARED skills ["),
1516
+ ("ctl-memory-001", "/memory/MEMORY.md (AutoMem)")):
1517
+ verdict = control(f"claude-real-contaminated-{case[4:-4]}", claude_case(case), "CONTEXT_UNDECLARED", needle,
1518
+ realization="replay")
1519
+ if case == "ctl-work-claude-md-001" and "CWD_OUTSIDE_MANIFEST working directory: holds ['CLAUDE.md']" not in " ".join(verdict["failures"]):
1520
+ failures.append(f"{case}: the undeclared working-directory file was not named by the listing check")
1521
+ if verdict["codes"] and "SCHEMA_INVALID" in verdict["codes"]:
1522
+ failures.append(f"{case}: the contaminated answer was not schema-valid, so it is not the canary-free control")
1523
+ control("codex-real-contaminated-agents-md", codex_case("codex-runner", "ctl-agents-workdir-001"),
1524
+ "CONTEXT_UNDECLARED instruction", "/AGENTS.md (AGENTS.md)", realization="replay")
1525
+ # the window bound, judged here as well as at the boundary (the seam record of 2026-10-22). The clean
1526
+ # case first: the same call directory with the bound block and an observation inside it is accepted.
1527
+ control("a-view-window-call-within-the-bound-is-accepted", variant(
1528
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1529
+ view_window=True, input_observed=bounds.INPUT_BOUND,
1530
+ bound={"limit": bounds.INPUT_BOUND, "driver_bytes": 4096, "stop_standing": False}))))
1531
+ control("a-view-window-call-past-the-bound-fails-the-gate", variant(
1532
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1533
+ view_window=True, input_observed=bounds.INPUT_BOUND + 1,
1534
+ bound={"limit": bounds.INPUT_BOUND, "driver_bytes": 4096, "stop_standing": False}))),
1535
+ "INPUT_BOUND_EXCEEDED")
1536
+ control("the-same-observation-on-a-non-window-call-is-accepted", variant(
1537
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1538
+ view_window=False, input_observed=bounds.INPUT_BOUND + 1,
1539
+ bound={"limit": bounds.INPUT_BOUND, "driver_bytes": None, "stop_standing": False}))))
1540
+ control("a-call-admitted-while-the-run-was-stopped-fails-the-gate", variant(
1541
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1542
+ bound={"limit": bounds.INPUT_BOUND, "driver_bytes": 4096, "stop_standing": True}))),
1543
+ "DISPATCHED_WHILE_STOPPED")
1544
+ # BA#1: the declaration against the host's own report, per call. The window is planted on BOTH sides,
1545
+ # because what is under test is the comparison - this replayed capture is older than the field, and a
1546
+ # control that depended on its number would be testing the fixture. Clean case first.
1547
+ def reports(window):
1548
+ return lambda f: jedit(f, "result.json", lambda o: o.update(
1549
+ modelUsage={model: {**u, "contextWindow": window}
1550
+ for model, u in (o.get("modelUsage") or {}).items()}))
1551
+
1552
+ def admitted_against(capacity):
1553
+ return lambda f: jedit(f, "call.json", lambda o: o.update(
1554
+ bound={"limit": bounds.INPUT_BOUND, "driver_bytes": 4096, "context_capacity": capacity,
1555
+ "stop_standing": False}))
1556
+
1557
+ control("a-call-admitted-against-the-capacity-the-host-reports-is-accepted",
1558
+ variant(claude, reports(1_000_000), admitted_against(1_000_000)))
1559
+ control("a-call-admitted-against-a-capacity-the-host-contradicts-fails-the-gate",
1560
+ variant(claude, reports(1_000_000), admitted_against(200_000)), "CAPACITY_DRIFT")
1561
+ control("a-host-that-reports-no-context-window-is-no-drift",
1562
+ variant(claude, admitted_against(1_000_000)))
1563
+ control("a-call-recording-a-bound-that-is-not-the-rule-s-fails-the-gate", variant(
1564
+ claude, lambda f: jedit(f, "call.json", lambda o: o.update(
1565
+ bound={"limit": 999_999, "driver_bytes": 4096, "stop_standing": False}))),
1566
+ "RECORD_INTEGRITY call.json bound.limit")
1567
+ appended = {"sha256": "a" * 64, "bytes": 48}
1568
+ control("appended-prompt-undeclared", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(appended_prompts=[appended]))),
1569
+ "CONTEXT_UNDECLARED appended system prompt 1")
1570
+ control("appended-prompt-declared-and-matching", variant(
1571
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(appended_prompts=[appended])),
1572
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(appended_prompts=[{"name": "stage.md", **appended}]))))
1573
+ # BA#2: the declared prompt carries the length that was counted as well as its hash, and the gate
1574
+ # accepts that shape - one representation for the payload count and for the record
1575
+ control("appended-prompt-declared-with-its-counted-length", variant(
1576
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(
1577
+ appended_prompts=[{"sha256": appended["sha256"]}])),
1578
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(
1579
+ appended_prompts=[{"name": "stage.md", "sha256": appended["sha256"], "bytes": 48}]))))
1580
+ control("appended-prompt-declared-hash-differs", variant(
1581
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(appended_prompts=[appended])),
1582
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(appended_prompts=[{"name": "stage.md", "sha256": "b" * 64}]))),
1583
+ "CONTEXT_HASH_MISMATCH appended system prompt 1")
1584
+ control("appended-prompt-declared-not-sent", variant(
1585
+ claude, lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(appended_prompts=[{"name": "stage.md", **appended}]))),
1586
+ "CONTEXT_HASH_MISMATCH appended system prompt 1: declared, not in the sent request")
1587
+ declared_file = {"path": "/Users/Shared/x/work/CLAUDE.md", "sha256": "c" * 64}
1588
+ control("instruction-declared-and-loaded", variant(
1589
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(instructions=[dict(declared_file, kind="Project")])),
1590
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(instructions=[declared_file]))))
1591
+ control("instruction-declared-other-bytes", variant(
1592
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(instructions=[dict(declared_file, sha256="d" * 64)])),
1593
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(instructions=[declared_file]))),
1594
+ "CONTEXT_HASH_MISMATCH instruction /Users/Shared/x/work/CLAUDE.md: loaded bytes differ")
1595
+ # BC#2: the two sides in their REAL forms. The declaration carries the raw sha256 of the bytes the
1596
+ # payload count counted and the observer form beside it; the capture carries what the Claude observer
1597
+ # records, which is that file rendered - so a synthetic pair of equal hashes would have proved nothing
1598
+ # about the comparison this leg actually makes.
1599
+ ordinary = b"# Rules\n\n<!-- a comment the host strips -->\nFollow these rules.\nAnd these.\n"
1600
+ produced = {"path": "/Users/Shared/x/work/CLAUDE.md", "sha256": packets.sha256_bytes(ordinary),
1601
+ "bytes": len(ordinary), "observer_sha256": observer_sha256("claude", ordinary)}
1602
+ control("instruction-declared-raw-and-observed-through-the-real-normalisation", variant(
1603
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(
1604
+ instructions=[{"path": produced["path"], "kind": "Project",
1605
+ "sha256": observer_owner().norm_sha256(ordinary.decode())}])),
1606
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(instructions=[produced]))))
1607
+ ran.append("instruction-declared-raw-hash-alone-is-not-the-observed-form")
1608
+ if produced["sha256"] == produced["observer_sha256"]:
1609
+ # without this the control above would pass whether or not the comparison translates
1610
+ failures.append("instruction-declared-raw-hash-alone-is-not-the-observed-form: the raw and the "
1611
+ "rendered hash of the fixture are equal, so it tests no translation")
1612
+ edited = ordinary.replace(b"And these.", b"And those.")
1613
+ control("instruction-whose-content-changed-fails-on-the-observed-form", variant(
1614
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(
1615
+ instructions=[{"path": produced["path"], "kind": "Project",
1616
+ "sha256": observer_owner().norm_sha256(edited.decode())}])),
1617
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(instructions=[produced]))),
1618
+ "CONTEXT_HASH_MISMATCH instruction /Users/Shared/x/work/CLAUDE.md: loaded bytes differ")
1619
+ control("instruction-declared-not-loaded", variant(
1620
+ claude, lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(instructions=[declared_file]))),
1621
+ "CONTEXT_HASH_MISMATCH instruction /Users/Shared/x/work/CLAUDE.md: declared, not loaded")
1622
+ control("hook-attachment-reached-the-call", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(hooks=["hook_success"]))),
1623
+ "CONTEXT_UNDECLARED hooks ['hook_success']")
1624
+ agent = ["reviewer"]
1625
+ control("agent-reached-the-call", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(agents=agent))),
1626
+ "CONTEXT_UNDECLARED agents ['reviewer'] reached the call, not declared")
1627
+ control("agent-declared-and-observed", variant(
1628
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(agents=agent)),
1629
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(agents=agent))))
1630
+ mcp = ["plant-mcp"]
1631
+ control("mcp-server-reached-the-call", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(mcp_servers=mcp))),
1632
+ "CONTEXT_UNDECLARED mcp_servers ['plant-mcp'] reached the call, not declared")
1633
+ control("mcp-server-declared-and-observed", variant(
1634
+ claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(mcp_servers=mcp)),
1635
+ lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(mcp_servers=mcp))))
1636
+ control("declared-skill-not-observed", variant(claude, lambda f: jedit(f, "call.json", lambda o: o["manifest"].update(skills=["imagegen"]))),
1637
+ "CONTEXT_HASH_MISMATCH skills ['imagegen']")
1638
+ control("no-context-evidence", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.pop("context"))),
1639
+ "CONTEXT_UNDECLARED capture: no effective-context evidence")
1640
+
1641
+ # --- seat attestation by role (plan S-7) ------------------------------------------------------
1642
+ control("claude-real-fallback-model-answered", claude_case("ctl-fallback-001"),
1643
+ "MODEL_UNATTESTED response to a6454b14-", "came from 'claude-haiku-5-5', the seat is 'claude-nonexistent-probe-0'",
1644
+ realization="replay")
1645
+ control("claude-undeclared-model-usage-key", variant(claude, lambda f: jedit(f, "result.json", lambda o: o["modelUsage"].update({"claude-sonnet-4-5": {}}))),
1646
+ "MODEL_UNATTESTED aggregate: result.modelUsage names ['claude-sonnet-4-5']")
1647
+ aux = "claude-haiku-4-5"
1648
+
1649
+ def all_auxiliary(files):
1650
+ jedit(files, "capture/host.json", lambda o: ([q.update(model=aux) for q in o["requests"]], [a.update(model=aux) for a in o["assistant"]]))
1651
+ jedit(files, "result.json", lambda o: o.update(modelUsage={aux: o["modelUsage"]["claude-haiku-5-5"]}))
1652
+ control("claude-all-auxiliary-main-response", variant(claude, all_auxiliary),
1653
+ f"MODEL_UNATTESTED request d1aa236f-2f1d-4308-bba1-8ccd49635ce4 (main) named '{aux}'",
1654
+ f"MODEL_UNATTESTED response to d1aa236f-2f1d-4308-bba1-8ccd49635ce4 (main) came from '{aux}'")
1655
+ control("claude-main-on-seat-auxiliary-in-aggregate", variant(claude, lambda f: jedit(f, "result.json", lambda o: o["modelUsage"].update({aux: {}}))))
1656
+ sub = {"id": "sub-1", "role": "subagent", "model": "claude-haiku-5-5", "packet_text": None, "structured_output_schema": None}
1657
+
1658
+ def with_subagent(model):
1659
+ def edit(files):
1660
+ jedit(files, "capture/host.json", lambda o: (o["requests"].append(dict(sub, model=model)),
1661
+ o["assistant"].append({"request_id": "sub-1", "role": "subagent", "model": model,
1662
+ "stop_reason": "end_turn", "synthetic": False})))
1663
+ return edit
1664
+ control("claude-child-on-the-main-seat-where-another-is-declared", variant(
1665
+ claude, with_subagent("claude-haiku-5-5"), lambda f: jedit(f, "call.json", lambda o: o.update(child_seat="claude:claude-sonnet-5-5/medium"))),
1666
+ "MODEL_UNATTESTED request sub-1 (subagent) named 'claude-haiku-5-5', the seat is 'claude-sonnet-5-5'")
1667
+ control("claude-child-on-its-declared-seat", variant(
1668
+ claude, with_subagent("claude-sonnet-5-5"), lambda f: jedit(f, "call.json", lambda o: o.update(child_seat="claude:claude-sonnet-5-5/medium")),
1669
+ lambda f: jedit(f, "result.json", lambda o: o["modelUsage"].update({"claude-sonnet-5-5": {}}))))
1670
+ control("claude-child-without-a-declared-seat", variant(claude, with_subagent("claude-haiku-5-5")),
1671
+ "MODEL_UNATTESTED request sub-1: role 'subagent' has no declared seat")
1672
+ control("claude-no-closing-aggregate", variant(claude, lambda f: jedit(f, "result.json", lambda o: o.pop("modelUsage"))),
1673
+ "MODEL_UNATTESTED aggregate: no result.modelUsage")
1674
+ control("codex-real-frames-silent", codex_case("codex-runner", "ctl-channel-broken-001"),
1675
+ "MODEL_UNATTESTED frames silent", realization="replay")
1676
+ control("codex-transport-fallback-blinds-the-frames", codex_case("codex-accounting", "f-ws-refuse-always-fallback"),
1677
+ "frames_blind", "MODEL_UNATTESTED completion at", realization="replay")
1678
+ control("codex-otel-completion-without-a-joined-frame", variant(codex, lambda f: frames_edit(f, lambda rs: [
1679
+ r for r in rs if (r.get("response") or {}).get("id") != "resp_fake_485723508_1"])),
1680
+ "frames_blind 01a15879-8cf7-7922-b112-264744011239 completion at 2026-10-20T08:42:03.509846Z")
1681
+ control("codex-response-on-another-model", variant(codex, lambda f: frames_edit(f, lambda rs: [
1682
+ dict(r, response=dict(r["response"], model="gpt-6-luna")) if (r.get("response") or {}).get("id") == "resp_fake_485723508_1" else r for r in rs])),
1683
+ "MODEL_UNATTESTED resp_fake_485723508_1 (main) came from 'gpt-6-luna'")
1684
+ control("codex-no-otel-channel", variant(codex, lambda f: frames_edit(f, lambda rs: [r for r in rs if r.get("dir") != "otel"])),
1685
+ "MODEL_UNATTESTED completions: the capture carries no otel channel")
1686
+ control("codex-response-without-a-client-frame", variant(codex, lambda f: frames_edit(f, lambda rs: [
1687
+ r for r in rs if not (r.get("dir") == "send" and r.get("request_kind") == "turn")])),
1688
+ "MODEL_UNATTESTED resp_fake_485723508_1: no client frame names its role")
1689
+ root = "01a15879-8cf7-7922-b112-264744011239"
1690
+ kid = "01a15879-0000-7000-8000-00000000c41d"
1691
+
1692
+ def with_child(model_in_frame, otel=True, effort="low", seat_effort="low", kind="turn"):
1693
+ def edit(files):
1694
+ created = {"dir": "recv", "type": "response.created", "ts": "2026-10-20T08:42:03.6Z",
1695
+ "response": {"id": "resp_kid_0", "model": model_in_frame, "status": "in_progress", "generate": None,
1696
+ "previous_response_id": None, "prompt_cache_key": root, "reasoning_effort": effort,
1697
+ "incomplete_details": None, "error": None, "usage": None}}
1698
+ frame(files, {"dir": "otel", "ts": "2026-10-20T08:42:03.59Z", "event.name": "codex.websocket_request",
1699
+ "conversation.id": kid, "model": "fake-kid"})
1700
+ usage = {"input_tokens": 700, "cached_tokens": 0, "cache_write_tokens": 0, "output_tokens": 9, "reasoning_tokens": 0, "total_tokens": 709}
1701
+ for rec in ({"dir": "send", "type": "response.create", "ts": "2026-10-20T08:42:03.59Z", "thread_id": kid,
1702
+ "agent_name": "/root/kid", "request_kind": kind, "parent_thread_id": root, "previous_response_id": None,
1703
+ "prompt_cache_key": root, "model": "fake-kid", "reasoning_effort": None},
1704
+ created, {**created, "type": "response.completed", "response": {**created["response"], "status": "completed", "usage": usage}}):
1705
+ frame(files, rec)
1706
+ if otel:
1707
+ frame(files, {"dir": "otel", "ts": "2026-10-20T08:42:03.61Z", "event.name": "codex.sse_event", "event.kind": "response.completed",
1708
+ "input_token_count": "700", "output_token_count": "9", "cached_token_count": "0", "conversation.id": kid, "model": "fake-kid"})
1709
+ jedit(files, "call.json", lambda o: o.update(child_seat=f"codex:fake-kid/{seat_effort}"))
1710
+ role = {"prewarm": "warmup", "compaction": "compaction"}.get(kind, "child")
1711
+ jedit(files, "usage.json", lambda o: o["requests"].append({"id": "resp_kid_0", "role": role, "state": "measured", "input": 700,
1712
+ "output": 9, "cache_read": 0, "cache_creation": 0, "estimate": None}))
1713
+ return edit
1714
+ control("codex-child-on-its-declared-seat", variant(codex, with_child("fake-kid")))
1715
+ unattested_child = control("codex-child-response-without-a-model-in-its-frame", variant(codex, with_child(None)),
1716
+ "MODEL_UNATTESTED resp_kid_0 (child): the frame carries no model")
1717
+ if not unattested_child["usage"] or unattested_child["usage"]["measured"] != 2002 + 709:
1718
+ failures.append(f"an unattested child's usage was not still recorded: {unattested_child['usage']}")
1719
+ control("codex-child-on-the-main-seat", variant(codex, with_child("fake-model")),
1720
+ "MODEL_UNATTESTED resp_kid_0 (child) came from 'fake-model', the seat is 'fake-kid'")
1721
+ # a sub-agent's warm-up and compaction are the child seat's, whatever their request kind
1722
+ for kind, role in (("prewarm", "warmup"), ("compaction", "compaction")):
1723
+ control(f"codex-child-{role}-on-the-child-seat", variant(codex, with_child("fake-kid", kind=kind)))
1724
+ control(f"codex-child-{role}-on-the-main-model", variant(codex, with_child("fake-model", kind=kind)),
1725
+ f"MODEL_UNATTESTED resp_kid_0 ({role}) came from 'fake-model', the seat is 'fake-kid'")
1726
+ for name, effort, seat_effort, want in (("its-own-effort", "medium", "medium", "host-reported"),
1727
+ ("the-main-effort", "low", "medium", "unverified")):
1728
+ ran.append(f"effort-child-{role}-echoes-{name}")
1729
+ got = accept(materialize(variant(codex, with_child("fake-kid", effort=effort, seat_effort=seat_effort, kind=kind))))
1730
+ if got["effort_provenance"] != want or not got["ok"]:
1731
+ failures.append(f"effort-child-{role}-echoes-{name}: provenance {got['effort_provenance']}, expected {want}; "
1732
+ f"{got['failures']}")
1733
+ control("codex-child-without-a-declared-seat", variant(codex, with_child("fake-kid"),
1734
+ lambda f: jedit(f, "call.json", lambda o: o.update(child_seat=None))),
1735
+ "MODEL_UNATTESTED resp_kid_0 (child): no seat is declared for the role")
1736
+ effort = accept(materialize(variant(codex, lambda f: frames_edit(f, lambda rs: [
1737
+ dict(r, response=dict(r["response"], reasoning_effort="high")) if r.get("response") else r for r in rs]))))
1738
+ if effort["effort_provenance"] != "unverified" or not effort["ok"]:
1739
+ failures.append(f"frames reporting another effort: provenance {effort['effort_provenance']}, verdict {effort['failures']}")
1740
+
1741
+ # --- schema; the F22 boundary ----------------------------------------------------------------
1742
+ control("claude-structured-output-violates-the-schema", variant(claude, lambda f: (
1743
+ jedit(f, "result.json", lambda o: o.update(structured_output={"answer": 5})),
1744
+ jedit(f, "capture/host.json", lambda o: o.update(structured_calls=[{"answer": 5}])))),
1745
+ "SCHEMA_INVALID answer: 5 is not of type 'string'")
1746
+ verdict_schema = {"type": "object", "additionalProperties": False, "required": ["verdict", "why"],
1747
+ "properties": {"verdict": {"enum": ["PRESENT", "ABSENT", "UNCLEAR"]}, "why": {"type": "string"}}}
1748
+ prose = b'Here is my verdict: {"verdict": "ABSENT", "why": "no section names it"}'
1749
+
1750
+ def schema_call(result):
1751
+ def edit(files):
1752
+ files["schema.json"] = packets.schema_bytes(verdict_schema)
1753
+ files["result.json"] = result
1754
+ jedit(files, "call.json", lambda o: o.update(schema_sha256=hashlib.sha256(files["schema.json"]).hexdigest()))
1755
+ return edit
1756
+ control("codex-schema-valid-json-result", variant(codex, schema_call(b'{"verdict": "ABSENT", "why": "no section names it"}')))
1757
+ # D7: what the host was handed beside schema.json. A Codex host is handed its provider's projection of it
1758
+ # (packets.provider_schema_bytes), recorded by its own hash; a Claude host reads schema.json itself.
1759
+ def handed(files):
1760
+ sent = packets.provider_schema_bytes(files["schema.json"], "codex")
1761
+ files[HOST_SCHEMA] = sent
1762
+ jedit(files, "call.json", lambda o: o.update(host_schema_sha256=hashlib.sha256(sent).hexdigest()))
1763
+ answered = schema_call(b'{"verdict": "ABSENT", "why": "no section names it"}')
1764
+ control("codex-handed-the-projection-of-its-schema", variant(codex, answered, handed))
1765
+ control("codex-handed-a-schema-that-is-not-the-projection",
1766
+ variant(codex, answered, handed, lambda f: f.update({HOST_SCHEMA: f[HOST_SCHEMA].replace(b'"why"', b'"whz"', 1)})),
1767
+ f"RECORD_INTEGRITY {HOST_SCHEMA}: not the projection of schema.json for codex")
1768
+ control("codex-handed-bytes-the-record-does-not-name",
1769
+ variant(codex, answered, handed, lambda f: jedit(f, "call.json", lambda o: o.update(host_schema_sha256="0" * 64))),
1770
+ f"RECORD_INTEGRITY {HOST_SCHEMA}: not the bytes call.json says the host was handed")
1771
+ control("codex-recorded-a-handed-schema-it-did-not-keep", variant(codex, answered, handed, lambda f: f.pop(HOST_SCHEMA)),
1772
+ f"RECORD_INTEGRITY {HOST_SCHEMA}: not the projection of schema.json for codex")
1773
+ control("a-handed-schema-the-record-does-not-name",
1774
+ variant(codex, answered, lambda f: f.update({HOST_SCHEMA: packets.provider_schema_bytes(f["schema.json"], "codex")})),
1775
+ f"RECORD_INTEGRITY {HOST_SCHEMA}: present for a call whose record names no handed schema")
1776
+ control("claude-handed-schema-json-itself",
1777
+ variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(host_schema_sha256=o["schema_sha256"]))))
1778
+ control("claude-recorded-as-handed-other-bytes",
1779
+ variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(host_schema_sha256="0" * 64))),
1780
+ f"RECORD_INTEGRITY {HOST_SCHEMA}: claude reads schema.json itself")
1781
+ control("codex-prose-wrapped-json-is-never-parsed", variant(codex, schema_call(prose)),
1782
+ "SCHEMA_INVALID result: not one JSON document")
1783
+ # The brace-extraction path is taken from benchmarks/absence.py's own source — its parse_verdict
1784
+ # and the labels it reads — without importing the module, whose imports reach a host dispatcher
1785
+ # (benchmarks/dispatch.py) that the driver's closure may not load (dispatch.py --self-test).
1786
+ tree = ast.parse((REPO_ROOT / "benchmarks" / "absence.py").read_text(encoding="utf-8"))
1787
+ kept = [n for n in tree.body if (isinstance(n, ast.FunctionDef) and n.name == "parse_verdict")
1788
+ or (isinstance(n, ast.Assign) and {x.id for t in n.targets for x in ast.walk(t) if isinstance(x, ast.Name)}
1789
+ & {"PRESENT", "ABSENT", "UNCLEAR"})]
1790
+ absence = {"json": json}
1791
+ exec(compile(ast.Module(body=kept, type_ignores=[]), "benchmarks/absence.py", "exec"), absence)
1792
+ if not {"parse_verdict", "PRESENT", "ABSENT", "UNCLEAR"} <= set(absence) or absence["parse_verdict"](prose.decode()) != "ABSENT":
1793
+ failures.append("the F22 boundary is not shown: benchmarks/absence.py did not accept the prose-wrapped verdict the gate refuses")
1794
+ control("schema-the-policy-refuses", variant(codex, schema_call(b'{"verdict": "ABSENT", "why": "x"}'),
1795
+ lambda f: f.update({"schema.json": b'{"type": "object"}\n'}),
1796
+ lambda f: jedit(f, "call.json", lambda o: o.update(schema_sha256=hashlib.sha256(b'{"type": "object"}\n').hexdigest()))),
1797
+ "SCHEMA_INVALID schema.json: refused by the schema policy")
1798
+
1799
+ # --- steps 4 and 5 -----------------------------------------------------------------------------
1800
+ judged = {"outcomes": [{"id": "c1", "outcome": "retained", "evidence_ids": ["e1"]},
1801
+ {"id": "c2", "outcome": "rejected", "reason": "duplicate", "evidence_ids": ["e2"]}]}
1802
+ contract = {"references": [{"path": ["outcomes", "*", "evidence_ids", "*"], "kind": "evidence"}],
1803
+ "resolvable": {"evidence": ["e1", "e2"]}, "accounting": {"path": ["outcomes"], "expected": ["c1", "c2"]}}
1804
+ out_schema = {"type": "object", "additionalProperties": False, "required": ["outcomes"], "properties": {"outcomes": {
1805
+ "type": "array", "items": {"type": "object", "additionalProperties": False, "required": ["id", "outcome", "evidence_ids"],
1806
+ "properties": {"id": {"type": "string"}, "outcome": {"type": "string"}, "reason": {"type": "string"},
1807
+ "evidence_ids": {"type": "array", "items": {"type": "string"}}}}}}}
1808
+
1809
+ def staged(output, contract_doc):
1810
+ def edit(files):
1811
+ files["schema.json"] = packets.schema_bytes(out_schema)
1812
+ files["result.json"] = json.dumps(output).encode()
1813
+ jput(files, "contract.json", contract_doc)
1814
+ jedit(files, "call.json", lambda o: o.update(schema_sha256=hashlib.sha256(files["schema.json"]).hexdigest(),
1815
+ contract="required"))
1816
+ return edit
1817
+ control("references-resolve-and-every-input-accounted", variant(codex, staged(judged, contract)))
1818
+ dangling = copy.deepcopy(judged)
1819
+ dangling["outcomes"][1]["evidence_ids"] = ["e9"]
1820
+ control("reference-resolves-to-nothing", variant(codex, staged(dangling, contract)), "RECORD_INTEGRITY evidence id 'e9'")
1821
+ missing = {"outcomes": judged["outcomes"][:1]}
1822
+ control("an-input-id-unaccounted", variant(codex, staged(missing, contract)), "SET_MISMATCH missing=['c2']")
1823
+ extra = copy.deepcopy(judged)
1824
+ extra["outcomes"].append({"id": "c3", "outcome": "retained", "evidence_ids": []})
1825
+ control("an-extra-output-id", variant(codex, staged(extra, contract)), "SET_MISMATCH missing=[] extra=['c3']")
1826
+ control("malformed-capture-is-refused-by-name", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(requests=[7]))),
1827
+ "RECORD_INTEGRITY claude_bindings: the call directory could not be read")
1828
+ control("usage-record-of-another-call", variant(claude, lambda f: jedit(f, "usage.json", lambda o: o.update(call_id="x"))),
1829
+ "RECORD_INTEGRITY usage.json")
1830
+ control("capture-of-another-call", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(call_id="acc-clean-002"))),
1831
+ "RECORD_INTEGRITY capture/host.json")
1832
+ control("schema-file-is-not-the-declared-one", variant(claude, lambda f: f.update({"schema.json": f["schema.json"] + b" "})),
1833
+ "RECORD_INTEGRITY schema.json: not the schema call.json says")
1834
+ control("schema-file-for-a-schema-less-call", variant(codex, lambda f: f.update({"schema.json": packets.schema_bytes(verdict_schema)})),
1835
+ "RECORD_INTEGRITY schema.json: present for a call declared schema-less")
1836
+ control("result-bytes-not-kept", variant(codex, lambda f: f.pop("result.json"), reseal=False),
1837
+ "RECORD_INTEGRITY packet.md and result.json")
1838
+ control("frames-not-json-lines", variant(codex, lambda f: f.update({"capture/frames.jsonl": f["capture/frames.jsonl"] + b"{torn\n"})),
1839
+ "RECORD_INTEGRITY capture/frames.jsonl: not well-formed JSON objects")
1840
+ control("call-record-unreadable", variant(claude, lambda f: f.update({"call.json": b"{"}), reseal=False),
1841
+ "RECORD_INTEGRITY call.json")
1842
+
1843
+ # --- review round of fe3f55c: each control below fails on the defect it names ----------------
1844
+ # done-when 1: a child response with no frame while the root and its warm-up have frames. The
1845
+ # usage is the production path's: the capture's frames rendered back into the trace lines the
1846
+ # host writes, fed through the live monitor, and reconciled by dispatch.reconcile_codex.
1847
+ from runlib import dispatch as dispatches, monitor as monitors
1848
+ import zlib
1849
+
1850
+ def live_usage(files):
1851
+ recs = [json.loads(line) for line in files["capture/frames.jsonl"].decode().splitlines() if line.strip()]
1852
+ mon, deflaters = monitors.Monitor("codex", {"tokens": 10 ** 12, "compactions": 10 ** 6}), {}
1853
+ for rec in recs:
1854
+ ts = rec.get("ts")
1855
+ if rec.get("dir") == "info" and rec.get("type") == "root_thread":
1856
+ trace = [f'2026-10-20T00:00:00.000000Z INFO codex.exec{{thread.id="{rec["thread"]}"}}: started']
1857
+ elif rec.get("dir") == "send":
1858
+ meta = {k: rec.get(k) for k in ("thread_id", "agent_name", "request_kind", "parent_thread_id")}
1859
+ create = {"type": "response.create", "model": rec.get("model"), "previous_response_id": rec.get("previous_response_id"),
1860
+ "prompt_cache_key": rec.get("prompt_cache_key"), "reasoning": {"effort": rec.get("reasoning_effort")},
1861
+ "client_metadata": {"x-codex-turn-metadata": json.dumps(meta)}}
1862
+ deflate = deflaters.setdefault(rec.get("thread_id"), zlib.compressobj(wbits=-15))
1863
+ data = (deflate.compress(json.dumps(create).encode()) + deflate.flush(zlib.Z_SYNC_FLUSH))[:-4]
1864
+ trace = [f"{ts} TRACE tungstenite::protocol::frame: writing frame", "opcode: TEXT", "reserved: true false false",
1865
+ "payload: 0x" + data.hex()]
1866
+ elif rec.get("dir") == "recv" and isinstance(rec.get("response"), dict):
1867
+ resp = {k: v for k, v in rec["response"].items() if k not in ("usage", "reasoning_effort")}
1868
+ u = rec["response"].get("usage")
1869
+ resp.update(reasoning={"effort": rec["response"].get("reasoning_effort")}, usage=None if u is None else {
1870
+ "input_tokens": u.get("input_tokens"), "output_tokens": u.get("output_tokens"), "total_tokens": u.get("total_tokens"),
1871
+ "input_tokens_details": {"cached_tokens": u.get("cached_tokens"), "cache_write_tokens": u.get("cache_write_tokens")},
1872
+ "output_tokens_details": {"reasoning_tokens": u.get("reasoning_tokens")}})
1873
+ trace = [f"{ts} TRACE tungstenite::protocol: Received message " + json.dumps({"type": rec.get("type"), "response": resp})]
1874
+ elif rec.get("dir") == "otel":
1875
+ trace = [f"{ts} INFO session_loop: codex_otel.log_only: "
1876
+ + " ".join(f"{k}={v}" for k, v in rec.items() if k not in ("dir", "ts"))]
1877
+ elif rec.get("dir") == "warn":
1878
+ trace = [f"{ts} WARN codex_core::responses_retry: retrying sampling request"]
1879
+ else:
1880
+ continue
1881
+ for line in trace:
1882
+ mon.line(line, 1.0)
1883
+ mon.finish(1.0)
1884
+ reconciled = dispatches.reconcile_codex(materialize(files), mon.ledger, lambda: 0.0)
1885
+ return [{k: r[k] for k in ("id", "role", "state", "estimate", *usages.TOKEN_KEYS)} for r in mon.ledger.requests], reconciled
1886
+
1887
+ def through_the_supervisor(files):
1888
+ rows, reconciled = live_usage(files)
1889
+ jedit(files, "usage.json", lambda o: o.update(requests=rows, attempts=len(rows), reconciled=reconciled))
1890
+
1891
+ def measured_rows(files):
1892
+ return sorted((r["role"], usages.request_total(r)) for r in jload(files, "usage.json")["requests"] if r["state"] == "measured")
1893
+ child_capture = variant(codex, with_child("fake-kid"), through_the_supervisor)
1894
+ control("codex-root-warmup-and-child-framed", child_capture)
1895
+ if measured_rows(child_capture) != [("child", 709), ("main", 1002), ("warmup", 1000)]:
1896
+ failures.append(f"codex-root-warmup-and-child-framed: the supervisor's usage is {measured_rows(child_capture)}")
1897
+ blind_files = variant(child_capture, lambda f: frames_edit(f, lambda rs: [
1898
+ r for r in rs if not (r.get("dir") == "recv" and (r.get("response") or {}).get("id") == "resp_kid_0")]), through_the_supervisor)
1899
+ blind_child = control("codex-child-response-without-its-frames", blind_files,
1900
+ f"frames_blind {kid} completion at 2026-10-20T08:42:03.61Z joins no frame response; its usage comes from otel "
1901
+ f"and its request kind is unknown",
1902
+ "MODEL_UNATTESTED completion at 2026-10-20T08:42:03.61Z (700 input tokens) has no observed model")
1903
+ # the stored request rows: the child's 709 tokens once, on a row of unknown kind; its sent
1904
+ # request is unmeasured, and the root and warm-up are attested
1905
+ if measured_rows(blind_files) != [("main", 1002), ("unknown", 709), ("warmup", 1000)] or \
1906
+ [(r["role"], r["state"]) for r in jload(blind_files, "usage.json")["requests"] if r["role"] == "child"] != [("child", "unresolved")] \
1907
+ or (blind_child["usage"] or {}).get("measured") != 2002 + 709 or any(
1908
+ "resp_fake" in line for line in blind_child["failures"] if line.startswith("MODEL_UNATTESTED")):
1909
+ failures.append(f"codex-child-response-without-its-frames: stored rows {jload(blind_files, 'usage.json')['requests']}, "
1910
+ f"usage {blind_child['usage']}, failures {blind_child['failures']}")
1911
+
1912
+ # the receipt: dispatch_id is required; a structural defect hides no other defect
1913
+ control("receipt-without-dispatch-id", variant(claude, lambda f: jedit(f, "receipt.json", lambda o: o.pop("dispatch_id")),
1914
+ reseal=False), "RECEIPT_KEY_MISSING dispatch_id")
1915
+ combined = control("receipt-with-three-independent-defects", variant(claude, lambda f: jedit(f, "receipt.json", lambda o: (
1916
+ o.update(note="x", method_id="distill/S6/acc-clean-002"), o["evidence"].pop("cwd"))), reseal=False),
1917
+ "RECORD_INTEGRITY receipt: unknown receipt key", "RECEIPT_STALE method_id", "RECEIPT_KEY_MISSING evidence.cwd")
1918
+ if not {"RECORD_INTEGRITY", "RECEIPT_STALE", "RECEIPT_KEY_MISSING"} <= set(combined["codes"]):
1919
+ failures.append(f"receipt-with-three-independent-defects: codes {combined['codes']}")
1920
+
1921
+ # design §3.2 step 2: attempt reconciliation and coverage, over probe 9's retained recordings
1922
+ def thread_of(files):
1923
+ return json.loads(files["capture/frames.jsonl"].splitlines()[0])["thread"]
1924
+
1925
+ def attempts_control(name, files, want, *needles, realization="replay"):
1926
+ v = control(name, files, *needles, realization=realization)
1927
+ got = {t: (a["completed"], a["interrupted"], a["coverage"]) for t, a in (v["attempts"] or {}).items()}
1928
+ if got != want:
1929
+ failures.append(f"{name}: attempts {got}, expected {want}")
1930
+ return v
1931
+
1932
+ def retry_channel(*stamps, usage=True):
1933
+ """The retry channel captured, a warning at each instant, in time order among the
1934
+ records, and the usage the capture then records (replay_usage)."""
1935
+ def edit(files):
1936
+ frame(files, {"dir": "info", "type": "channels", "channels": ["frames", "otel", "responses_retry"]}, at=1)
1937
+ for ts in stamps:
1938
+ recs = [json.loads(line) for line in files["capture/frames.jsonl"].decode().splitlines() if line.strip()]
1939
+ frame(files, {"dir": "warn", "type": "responses_retry", "ts": ts},
1940
+ at=next((n for n, r in enumerate(recs) if r.get("ts") and r["ts"] > ts), None))
1941
+ if usage:
1942
+ jedit(files, "usage.json", lambda o: o.update(requests=replay_usage(files), attempts=len(replay_usage(files))))
1943
+ return edit
1944
+ sse = codex_case("codex-accounting", "f-http-sse-drop")
1945
+ dropped = attempts_control("codex-http-stream-dropped-is-an-interrupted-attempt", sse, {thread_of(sse): (1, 1, "unknown")},
1946
+ "frames_blind")
1947
+ if (dropped["usage"] or {}).get("unresolved") != 1 or (dropped["usage"] or {}).get("measured") != 1002:
1948
+ failures.append(f"the dropped stream is not recorded as an attempt beside the measured one: {dropped['usage']}")
1949
+ if (dropped["attempts"] or {}).get(thread_of(sse), {}).get("interrupted_at") != ["2026-10-20T08:42:19.593307Z"]:
1950
+ failures.append(f"codex-http-stream-dropped-is-an-interrupted-attempt: the first stream is not the interrupted one: "
1951
+ f"{dropped['attempts']}")
1952
+ retried = codex_case("codex-accounting", "f-http-500-once")
1953
+ attempts_control("codex-http-retry-before-streaming-leaves-coverage-unknown", retried, {thread_of(retried): (1, 0, "unknown")},
1954
+ "frames_blind")
1955
+ # the three readings impl-wp04 measured model-free on the capture's owner, held here as the
1956
+ # gate's: a clean websocket call is complete and accepted; an HTTP call with a retry warning
1957
+ # (WP-04 ruling F#1: HTTP attempt coverage is always unknown) and a websocket call beside a
1958
+ # codex.api_request row (ruling K#1: those rows are attempt evidence) are unknown, and unknown
1959
+ # coverage fails the call by USAGE_ATTRIBUTION_UNKNOWN
1960
+ https_unknown = "attempt coverage is unknown (HTTPS streams: the HTTP transport keeps no record of its posts"
1961
+ measured = (
1962
+ ("codex-measured-websocket-clean-is-complete", codex, {root: (2, 0, "complete")}, ()),
1963
+ ("codex-measured-http-with-a-retry-warning-is-unknown", variant(retried, retry_channel("2026-10-20T08:42:18.200000Z")),
1964
+ {thread_of(retried): (1, 1, "unknown")}, (f"USAGE_ATTRIBUTION_UNKNOWN {thread_of(retried)}: {https_unknown}",)),
1965
+ ("codex-measured-websocket-beside-an-api-request-is-unknown",
1966
+ variant(codex, lambda f: frame(f, {"dir": "otel", "event.name": "codex.api_request", "conversation.id": root,
1967
+ "endpoint": "/responses", "ts": "2026-10-20T08:42:03.500000Z"})),
1968
+ {root: (2, 0, "unknown")}, (f"USAGE_ATTRIBUTION_UNKNOWN {root}: {https_unknown}",)))
1969
+ for name, files, want, needles in measured:
1970
+ v = attempts_control(name, files, want, *needles, realization="golden" if needles else "replay")
1971
+ consequence = "USAGE_ATTRIBUTION_UNKNOWN" in v["codes"]
1972
+ if v["ok"] is bool(needles) or consequence is not bool(needles):
1973
+ failures.append(f"{name}: accepted {v['ok']}, codes {v['codes']}: unknown coverage must fail by "
1974
+ f"USAGE_ATTRIBUTION_UNKNOWN and complete coverage must not")
1975
+ # a retry warning names no thread: in a call of one thread it is one failed post of unknown
1976
+ # usage there (f-http-500-once's first post; beside f-http-sse-drop's dropped stream, a post of
1977
+ # its own), counted, but no count of warnings shows an HTTP call's every post (ruling F#1)
1978
+ attempts_control("codex-https-coverage-unknown-even-when-the-warnings-reconcile",
1979
+ variant(sse, retry_channel("2026-10-20T08:42:19.900000Z")),
1980
+ {thread_of(sse): (1, 2, "unknown")}, "frames_blind", f"USAGE_ATTRIBUTION_UNKNOWN {thread_of(sse)}: {https_unknown}",
1981
+ realization="golden")
1982
+ posted = attempts_control("codex-https-retry-warning-accounts-for-the-unstreamed-post",
1983
+ variant(retried, retry_channel("2026-10-20T08:42:18.200000Z")),
1984
+ {thread_of(retried): (1, 1, "unknown")}, "frames_blind",
1985
+ f"USAGE_ATTRIBUTION_UNKNOWN {thread_of(retried)}: {https_unknown}", realization="golden")
1986
+ if (posted["usage"] or {}).get("unresolved") != 1 or (posted["usage"] or {}).get("measured") != 1002 or \
1987
+ (posted["attempts"] or {}).get(thread_of(retried), {}).get("failed_posts") != 1:
1988
+ failures.append(f"both posts of f-http-500-once are not accounted for: {posted['usage']} {posted['attempts']}")
1989
+ control("codex-usage-missing-the-post-that-failed-before-streaming",
1990
+ variant(retried, retry_channel("2026-10-20T08:42:18.200000Z", usage=False)),
1991
+ "RECORD_INTEGRITY usage.json: the capture shows 2 attempts (interrupted ones included), usage records 1")
1992
+ one_thread = attempts_control("codex-single-thread-warning-accepted-with-an-unresolved-post",
1993
+ variant(codex, retry_channel("2026-10-20T08:42:03.500000Z")), {root: (2, 1, "complete")},
1994
+ realization="golden")
1995
+ if (one_thread["usage"] or {}).get("unresolved") != 1 or (one_thread["usage"] or {}).get("measured") != 2002:
1996
+ failures.append(f"codex-single-thread-warning-accepted-with-an-unresolved-post: {one_thread['usage']}")
1997
+ wsdrop = codex_case("codex-accounting", "f-ws-drop-after-created")
1998
+ attempts_control("codex-websocket-retry-reconciles-its-starts", wsdrop, {thread_of(wsdrop): (2, 1, "complete")},
1999
+ "COMPLETION_INCOMPLETE aborted stream")
2000
+ interruption_at = [json.loads(line)["ts"] for line in wsdrop["capture/frames.jsonl"].decode().splitlines()
2001
+ if '"event.kind": "response.completed"' in line and "input_token_count" not in line][0]
2002
+ after = attempts_control("codex-warning-after-a-recorded-interruption-is-a-post-of-its-own",
2003
+ variant(wsdrop, retry_channel(interruption_at[:-1] + "9Z")), {thread_of(wsdrop): (2, 2, "complete")},
2004
+ "COMPLETION_INCOMPLETE aborted stream", realization="golden")
2005
+ if (after["attempts"] or {}).get(thread_of(wsdrop), {}).get("failed_posts") != 1:
2006
+ failures.append(f"codex-warning-after-a-recorded-interruption-is-a-post-of-its-own: {after['attempts']}")
2007
+ # in a call of more than one thread a warning is attributed to none: coverage is unknown on
2008
+ # every thread and the call fails USAGE_ATTRIBUTION_UNKNOWN — two dropped streams, or a
2009
+ # child's post failing before it streamed beside a root completing
2010
+ second = "01a15879-cc33-7070-893a-0000000000b2"
2011
+
2012
+ def two_dropping_threads(files):
2013
+ recs = [json.loads(line) for line in files["capture/frames.jsonl"].decode().splitlines() if line.strip()]
2014
+ otel = [r for r in recs if r.get("dir") == "otel"]
2015
+ rest = [r for r in recs if r.get("dir") != "otel"]
2016
+ both = sorted(otel + [dict(r, **{"conversation.id": second}) for r in otel], key=lambda r: r["ts"])
2017
+ files["capture/frames.jsonl"] = "".join(json.dumps(r) + "\n" for r in rest + both).encode()
2018
+ attempts_control("codex-warning-over-two-threads-is-attributed-to-neither",
2019
+ variant(sse, two_dropping_threads, retry_channel("2026-10-20T08:42:19.900000Z")),
2020
+ {thread_of(sse): (1, 1, "unknown"), second: (1, 1, "unknown")},
2021
+ f"USAGE_ATTRIBUTION_UNKNOWN {second}: attempt coverage is unknown (1 retry warnings name no thread", realization="golden")
2022
+ attempts_control("codex-concurrent-pre-stream-failure-is-attributed-to-neither",
2023
+ variant(codex, with_child("fake-kid"), retry_channel("2026-10-20T08:42:03.595000Z")),
2024
+ {root: (2, 0, "unknown"), kid: (1, 0, "unknown")},
2025
+ f"USAGE_ATTRIBUTION_UNKNOWN {root}: attempt coverage is unknown (1 retry warnings name no thread",
2026
+ f"USAGE_ATTRIBUTION_UNKNOWN {kid}: attempt coverage is unknown", realization="golden")
2027
+ # a thread only a sent frame names counts: a second thread's send that no otel row or response
2028
+ # follows, beside a warning, leaves every thread unknown — the single-thread warning above is
2029
+ # the positive counterpart; a send naming no thread at all establishes none either
2030
+ def with_send(**fields):
2031
+ def edit(files):
2032
+ frame(files, {"dir": "send", "type": "response.create", "ts": "2026-10-20T08:42:03.59Z", "thread_id": None,
2033
+ "agent_name": None, "request_kind": "turn", "parent_thread_id": None, "previous_response_id": None,
2034
+ "prompt_cache_key": None, "model": "gpt-6-astra", "reasoning_effort": "low", **fields})
2035
+ return edit
2036
+ unanswered = variant(codex, with_send(thread_id=second, agent_name="/root/kid", parent_thread_id=root, prompt_cache_key=second),
2037
+ retry_channel("2026-10-20T08:42:03.500000Z"), through_the_supervisor)
2038
+ sent_only = attempts_control("codex-warning-beside-a-second-thread-only-a-send-names-is-attributed-to-neither", unanswered,
2039
+ {root: (2, 0, "unknown"), second: (0, 0, "unknown")},
2040
+ f"USAGE_ATTRIBUTION_UNKNOWN {second}: attempt coverage is unknown (1 retry warnings name no thread",
2041
+ realization="golden")
2042
+ if "USAGE_ATTRIBUTION_UNKNOWN" not in sent_only["codes"] or jload(unanswered, "usage.json")["reconciled"] is not False:
2043
+ failures.append(f"codex-warning-beside-a-second-thread-only-a-send-names-is-attributed-to-neither: {sent_only['codes']} "
2044
+ f"reconciled {jload(unanswered, 'usage.json')['reconciled']}")
2045
+ attempts_control("codex-warning-beside-a-send-naming-no-thread-is-attributed-to-neither",
2046
+ variant(codex, with_send(), retry_channel("2026-10-20T08:42:03.500000Z")), {root: (2, 0, "unknown")},
2047
+ f"USAGE_ATTRIBUTION_UNKNOWN {root}: attempt coverage is unknown (1 retry warnings name no thread, and the "
2048
+ f"call has more than one)", realization="golden")
2049
+ attempts_control("codex-warning-beside-a-second-thread-only-a-response-names-is-attributed-to-neither",
2050
+ variant(codex, lambda f: frame(f, {"dir": "recv", "type": "response.created", "ts": "2026-10-20T08:42:03.6Z",
2051
+ "response": {"id": "resp_second_0", "model": "gpt-6-astra", "status": "in_progress",
2052
+ "previous_response_id": None, "prompt_cache_key": second}}),
2053
+ retry_channel("2026-10-20T08:42:03.500000Z")),
2054
+ {root: (2, 0, "unknown"), second: (0, 0, "unknown")},
2055
+ f"USAGE_ATTRIBUTION_UNKNOWN {second}: attempt coverage is unknown (1 retry warnings name no thread", realization="golden")
2056
+ # completions whose starts are missing, every frame and usage join intact: incomplete usage
2057
+ # through the supervisor's reconciliation, and the call fails by that name alone
2058
+ startless = variant(codex, lambda f: frames_edit(f, lambda rs: [r for r in rs if r.get("event.name") != "codex.websocket_request"]),
2059
+ through_the_supervisor)
2060
+ no_starts = attempts_control("codex-completions-without-their-starts-fail-attribution", startless, {root: (0, 0, "unknown")},
2061
+ f"USAGE_ATTRIBUTION_UNKNOWN {root}: attempt coverage is unknown (a completion without its start)",
2062
+ realization="golden")
2063
+ if no_starts["codes"] != ["USAGE_ATTRIBUTION_UNKNOWN"] or jload(startless, "usage.json")["reconciled"] is not False:
2064
+ failures.append(f"codex-completions-without-their-starts-fail-attribution: {no_starts['codes']} "
2065
+ f"reconciled {jload(startless, 'usage.json')['reconciled']}")
2066
+ fallback = codex_case("codex-accounting", "f-ws-refuse-always-fallback")
2067
+ blind = attempts_control("codex-fallback-usage-measured-from-otel", fallback, {thread_of(fallback): (1, 0, "unknown")},
2068
+ "frames_blind")
2069
+ if (blind["usage"] or {}).get("measured") != 1002:
2070
+ failures.append(f"the fallback's otel completion is not in its usage: {blind['usage']}")
2071
+ attempts_control("codex-websocket-capture-coverage-complete", codex, {root: (2, 0, "complete")})
2072
+ http_rows = [json.loads(line) for line in codex_case("codex-accounting", "f-http-normal")["capture/frames.jsonl"].splitlines()
2073
+ if line.strip() and json.loads(line).get("dir") == "otel"]
2074
+ mixed_thread = "01a15879-0000-7000-8000-0000000004f7"
2075
+
2076
+ def mixed(files):
2077
+ for rec in http_rows:
2078
+ frame(files, dict(rec, **{"conversation.id": mixed_thread}))
2079
+ jedit(files, "usage.json", lambda o: o.update(requests=replay_usage(files)))
2080
+ attempts_control("codex-mixed-coverage-websocket-and-https", variant(codex, mixed),
2081
+ {root: (2, 0, "complete"), mixed_thread: (1, 0, "unknown")}, f"frames_blind {mixed_thread}",
2082
+ realization="golden")
2083
+ control("codex-usage-missing-an-interrupted-attempt", variant(sse, lambda f: jedit(f, "usage.json", lambda o: o.update(
2084
+ requests=[r for r in o["requests"] if r["state"] == "measured"]))),
2085
+ "RECORD_INTEGRITY usage.json: the capture shows 2 attempts (interrupted ones included), usage records 1")
2086
+
2087
+ # joins by thread, order and full usage; an ambiguous one is no join
2088
+ completions = [n for n, line in enumerate(codex["capture/frames.jsonl"].decode().splitlines())
2089
+ if '"input_token_count"' in line]
2090
+
2091
+ def lines_edit(edit):
2092
+ def apply(files):
2093
+ lines = files["capture/frames.jsonl"].decode().splitlines()
2094
+ files["capture/frames.jsonl"] = ("\n".join(edit(lines)) + "\n").encode()
2095
+ return apply
2096
+ control("codex-completions-reordered", variant(codex, lines_edit(lambda ls: [
2097
+ ls[completions[1]] if n == completions[0] else ls[completions[0]] if n == completions[1] else line for n, line in enumerate(ls)])),
2098
+ "MODEL_UNATTESTED completion at 2026-10-20T08:42:03.509846Z (1000 input tokens): its in-order frame response disagrees",
2099
+ "MODEL_UNATTESTED resp_fake_485723508_1: a completed frame response no completion in the ledger joins")
2100
+ control("codex-completion-duplicated", variant(codex, lines_edit(lambda ls: ls + [ls[completions[1]]])),
2101
+ "an ambiguous join")
2102
+ control("codex-warmup-completion-missing", variant(codex, lines_edit(lambda ls: [line for n, line in enumerate(ls) if n != completions[0]])),
2103
+ "MODEL_UNATTESTED resp_fake_485723468_0: a completed frame response no completion in the ledger joins")
2104
+ control("codex-completion-cache-count-disagrees", variant(codex, lines_edit(lambda ls: [
2105
+ json.dumps(dict(json.loads(line), cached_token_count="5")) if n == completions[1] else line for n, line in enumerate(ls)])),
2106
+ "frames_blind 01a15879-8cf7-7922-b112-264744011239 completion at 2026-10-20T08:42:03.509846Z")
2107
+ sends = [n for n, line in enumerate(codex["capture/frames.jsonl"].decode().splitlines()) if '"dir": "send"' in line]
2108
+ control("codex-client-frame-duplicated", variant(codex, lines_edit(lambda ls: ls[:sends[1] + 1] + [ls[sends[1]]] + ls[sends[1] + 1:])),
2109
+ "MODEL_UNATTESTED resp_fake_485723508_1: more than one client frame could have asked for it")
2110
+
2111
+ # steps 4 and 5 apply when, and only when, the call record says so
2112
+ contracted = variant(codex, staged(judged, contract))
2113
+ control("required-contract-missing", variant(contracted, lambda f: f.pop("contract.json")),
2114
+ "RECORD_INTEGRITY contract.json: call.json requires the stage's contract (steps 4 and 5), and there is none")
2115
+ control("required-contract-unreadable", variant(contracted, lambda f: f.update({"contract.json": b"{"})),
2116
+ "RECORD_INTEGRITY contract.json: call.json requires the stage's contract (steps 4 and 5), and it is unreadable")
2117
+ control("contract-present-for-a-call-declaring-none", variant(contracted, lambda f: jedit(f, "call.json", lambda o: o.update(contract="none"))),
2118
+ "RECORD_INTEGRITY contract.json: present for a call that declares no contract")
2119
+ control("call-record-without-a-contract-declaration", variant(claude, lambda f: jedit(f, "call.json", lambda o: o.pop("contract"))),
2120
+ "RECORD_INTEGRITY call.json <root>: 'contract' is a required property")
2121
+ control("contract-required-for-a-schema-less-call", variant(codex, lambda f: (
2122
+ jput(f, "contract.json", contract), jedit(f, "call.json", lambda o: o.update(contract="required")))),
2123
+ "RECORD_INTEGRITY contract.json: a reference or set contract judges a structured output")
2124
+ for name, outcome, needle in (("merged-without-members", {"id": "m1", "outcome": "merged"}, "invalid=['m1']"),
2125
+ ("rejected-without-a-reason", {"id": "c2", "outcome": "rejected"}, "invalid=['c2']"),
2126
+ ("an-id-twice", {"id": "c1", "outcome": "retained", "evidence_ids": []}, "repeated=['c1']")):
2127
+ doc = copy.deepcopy(judged)
2128
+ doc["outcomes"] = [o for o in doc["outcomes"] if not (name == "rejected-without-a-reason" and o["id"] == "c2")] + [
2129
+ dict(outcome, evidence_ids=outcome.get("evidence_ids", []))]
2130
+ control(f"set-accounting-{name}", variant(codex, staged(doc, contract)), needle)
2131
+
2132
+ # malformed inputs get a named verdict, never a traceback
2133
+ control("call-record-not-an-object", variant(claude, lambda f: f.update({"call.json": b"[1]\n"}), reseal=False),
2134
+ "RECORD_INTEGRITY call.json: absent, unreadable", "RECORD_INTEGRITY call.json: not well-formed JSON objects")
2135
+ # caps holds the two caps the supervisor evaluates (design §13.2); an output-token cap is the
2136
+ # runner's flag (plan WP-03), and a field no code reads is refused rather than carried
2137
+ control("call-record-caps-with-a-field-nothing-reads", variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(
2138
+ caps={"tokens": 50_000, "compactions": 2, "output_tokens": 4096}))),
2139
+ "RECORD_INTEGRITY call.json caps: Additional properties are not allowed ('output_tokens' was unexpected)")
2140
+ control("call-record-field-of-the-wrong-type", variant(claude, lambda f: jedit(f, "call.json", lambda o: o.update(attempt="one"))),
2141
+ "RECORD_INTEGRITY call.json attempt: 'one' is not of type 'integer'")
2142
+ control("assistant-record-not-an-object", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["assistant"].append(7)),
2143
+ reseal=False),
2144
+ "RECORD_INTEGRITY capture/host.json assistant: a record that is not an object")
2145
+ control("frame-line-not-an-object", variant(codex, lambda f: f.update({"capture/frames.jsonl": f["capture/frames.jsonl"] + b"7\n"})),
2146
+ "RECORD_INTEGRITY capture/frames.jsonl: not well-formed JSON objects")
2147
+ control("call-record-seat-not-text", variant(codex, lambda f: jedit(f, "call.json", lambda o: o.update(seat=7)), reseal=False),
2148
+ "RECORD_INTEGRITY call.json seat: 7 is not of type 'string'", "RECORD_INTEGRITY verdict effort_provenance")
2149
+ control("host-container-of-the-wrong-kind", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o.update(requests="x"))),
2150
+ "RECORD_INTEGRITY capture/host.json requests: not a list")
2151
+ control("context-record-not-an-object", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(instructions=[7]))),
2152
+ "RECORD_INTEGRITY capture/host.json context.instructions: a record that is not an object")
2153
+ control("context-of-the-wrong-kind", variant(claude, lambda f: jedit(f, "capture/host.json", lambda o: o["context"].update(skills="x"))),
2154
+ "RECORD_INTEGRITY capture/host.json context.skills: not a list")
2155
+
2156
+ # every main request carries the packet; safety_stops is a present zero
2157
+ def later_main(text):
2158
+ def edit(files):
2159
+ jedit(files, "capture/host.json", lambda o: (o["requests"].append(dict(o["requests"][0], id="req-2", packet_text=text)),
2160
+ o["assistant"].append(dict(o["assistant"][0], request_id="req-2"))))
2161
+ return edit
2162
+ control("binding-a-later-request-carries-the-packet", variant(claude, later_main(claude["packet.md"].decode())))
2163
+ control("binding-a-later-request-text-is-not-the-packet", variant(claude, later_main("CALL-ID: acc-clean-001\nanother text\n")),
2164
+ "BINDING_MISMATCH request text: request req-2's recorded text")
2165
+ for name, edit, needle in (("missing", lambda o: o.pop("safety_stops"), "COMPLETION_INCOMPLETE safety_stops: the result does not report it"),
2166
+ ("null", lambda o: o.update(safety_stops=None), "COMPLETION_INCOMPLETE safety_stops=None"),
2167
+ ("text", lambda o: o.update(safety_stops="0"), "COMPLETION_INCOMPLETE safety_stops='0'"),
2168
+ ("false", lambda o: o.update(safety_stops=False), "COMPLETION_INCOMPLETE safety_stops=False")):
2169
+ control(f"claude-safety-stops-{name}", variant(claude, lambda f, e=edit: jedit(f, "result.json", e)), needle)
2170
+
2171
+ # effort provenance per resolved seat
2172
+ for name, effort, seat_effort, want in (("child-echoes-its-own-seat", "medium", "medium", "host-reported"),
2173
+ ("child-echoes-the-main-seat", "low", "medium", "unverified"),
2174
+ ("child-echoes-another-than-the-main", "medium", "low", "unverified")):
2175
+ ran.append(f"effort-{name}")
2176
+ got = accept(materialize(variant(codex, with_child("fake-kid", effort=effort, seat_effort=seat_effort))))
2177
+ if got["effort_provenance"] != want or not got["ok"]:
2178
+ failures.append(f"effort-{name}: provenance {got['effort_provenance']}, expected {want}; {got['failures']}")
2179
+
2180
+ # accepted() hands a schema-less call's final text to the stage, on both hosts
2181
+ ran.append("accepted-keeps-schema-less-output")
2182
+ claude_text = jload(claude, "result.json")["result"]
2183
+ try:
2184
+ handed, refused = (accepted(materialize(variant(claude, schemaless))), accepted(materialize(codex))), ""
2185
+ except Refused as exc: # a refusal of the clean fixtures is reported by its codes, not raised past the suite
2186
+ handed, refused = None, f"; refused: {exc}"
2187
+ if handed != (claude_text, "OK"):
2188
+ failures.append("accepted() did not return a schema-less call's final text" + refused)
2189
+ control("claude-schema-less-call-without-result-text", variant(claude, schemaless, lambda f: jedit(f, "result.json", lambda o: o.pop("result"))),
2190
+ "COMPLETION_INCOMPLETE result text")
2191
+
2192
+ # an auxiliary role lets a live call pass only once it is measured (S-7)
2193
+ control("live-call-on-a-provisional-auxiliary-role", variant(claude, lambda f: (
2194
+ jedit(f, "result.json", lambda o: o["modelUsage"].update({aux: {}})), jedit(f, "call.json", lambda o: o.update(realization="live")))),
2195
+ f"MODEL_UNATTESTED aggregate: result.modelUsage names ['{aux}'], neither a declared seat nor a declared auxiliary "
2196
+ f"role (['{aux}'] declared, not measured, so not for a live call)")
2197
+ ran.append("live-call-on-a-measured-auxiliary-role")
2198
+ measured_seats = scratch / "seats-measured.json"
2199
+ held = json.loads(SEATS.read_text(encoding="utf-8"))
2200
+ held["hosts"]["claude"]["auxiliary"][0]["measured"] = True
2201
+ measured_seats.write_text(json.dumps(held), encoding="utf-8")
2202
+ pinned_claude = seats()["hosts"]["claude"]["version"]
2203
+ if (auxiliary_models("claude", pinned_claude, live=True, path=measured_seats) != {aux}
2204
+ or auxiliary_models("claude", pinned_claude, live=True)):
2205
+ failures.append("a measured auxiliary declaration is not what admits a live call")
2206
+
2207
+ # --- the corrective retry ---------------------------------------------------------------------
2208
+ bad = variant(codex, schema_call(prose))
2209
+ good = variant(codex, schema_call(b'{"verdict": "ABSENT", "why": "no section names it"}'))
2210
+ ran.append("retry-invalid-then-valid")
2211
+ first, second = materialize(bad), materialize(good)
2212
+ settled = settle([first, second])
2213
+ if not (settled["ok"] and settled["accepted"] == str(second) and len(settled["attempts"]) == 2
2214
+ and not settled["attempts"][0]["ok"] and first.is_dir()):
2215
+ failures.append(f"retry-invalid-then-valid: {settled['failures']}, attempts kept {len(settled['attempts'])}")
2216
+ ran.append("retry-invalid-twice")
2217
+ twice = settle([materialize(bad), materialize(bad)])
2218
+ if twice["ok"] or twice["codes"] != ["RETRY_EXHAUSTED"] or len(twice["attempts"]) != 2:
2219
+ failures.append(f"retry-invalid-twice: {twice['codes']} {twice['failures']}")
2220
+ ran.append("retry-pending-after-one-failure")
2221
+ pending = settle([materialize(bad)])
2222
+ if not pending["retry"] or pending["ok"] or "SCHEMA_INVALID" not in correction(pending["attempts"][0]):
2223
+ failures.append(f"retry-pending-after-one-failure: retry {pending['retry']}, correction lacks the validation message")
2224
+ ran.append("retry-only-once")
2225
+ thrice = settle([materialize(bad), materialize(bad), materialize(good)])
2226
+ if thrice["ok"] or "RETRY_EXHAUSTED 3 attempts" not in " ".join(thrice["failures"]):
2227
+ failures.append(f"retry-only-once: {thrice['failures']}")
2228
+ ran.append("settle-without-an-attempt")
2229
+ if settle([])["failures"] != ["RECORD_INTEGRITY settle: no attempt to settle"]:
2230
+ failures.append(f"settle-without-an-attempt: {settle([])['failures']}")
2231
+ ran.append("accepted-reads-only-an-accepted-call")
2232
+ try:
2233
+ accepted(materialize(bad))
2234
+ failures.append("accepted() returned the output of a rejected call")
2235
+ except Refused as exc:
2236
+ if "SCHEMA_INVALID" not in str(exc):
2237
+ failures.append(f"accepted() refused unnamed: {exc}")
2238
+ try:
2239
+ handed, refused = accepted(materialize(claude)), ""
2240
+ except Refused as exc:
2241
+ handed, refused = None, f"; refused: {exc}"
2242
+ if handed != {"answer": '{"answer":"OK"}'}:
2243
+ failures.append("accepted() did not return the accepted call's structured output" + refused)
2244
+ # a stage's judgement recorded beside an attempt the gate accepted: one answer between the gate and the judge (WP-08)
2245
+ for label, judgement, judged, code in (
2246
+ ("a recorded stage-check failure is refused on a read that does not ask for the judgement",
2247
+ ["SET_MISMATCH planted judgement"], False, "STAGE_CHECK_FAILED"),
2248
+ ("a recorded stage-check failure is refused on a judged read", ["SET_MISMATCH planted judgement"], True,
2249
+ "STAGE_CHECK_FAILED"),
2250
+ ("a judged read of an attempt no judgement was recorded for is refused", None, True, "STAGE_CHECK_MISSING"),
2251
+ ("a judged read of an attempt its stage passed returns the output", [], True, None)):
2252
+ ran.append(f"accepted: {label}")
2253
+ judged_dir = materialize(claude)
2254
+ if judgement is not None:
2255
+ (judged_dir / STAGE_CHECK).write_text(json.dumps({"failures": judgement}), encoding="utf-8")
2256
+ try:
2257
+ handed, refused = accepted(judged_dir, judged=judged), ""
2258
+ except Refused as exc:
2259
+ handed, refused = None, str(exc)
2260
+ if code is None and handed != {"answer": '{"answer":"OK"}'}:
2261
+ failures.append(f"accepted: {label}: {refused}")
2262
+ if code is not None and not refused.startswith(code):
2263
+ failures.append(f"accepted: {label}: {refused or 'the output was returned'}")
2264
+
2265
+ # --- contract fidelity (done-when 8) and the port of the probe's mutation audit -----------------
2266
+ # design §3.2's predicate branches and its control list, and the plan's additions, copied here
2267
+ # by hand from the sections and never derived from STEPS, CHECKS or the receipt's key tuples:
2268
+ # each branch names the control that realizes it and the code its verdict must carry (None: the
2269
+ # clean counterpart, accepted), or the work package whose live call realizes it. A branch the
2270
+ # gate does not implement leaves its control without that code, and fails here.
2271
+ branches = {
2272
+ # step 1, completion
2273
+ "exit status zero": ("nonzero-exit-with-a-complete-capture", "COMPLETION_INCOMPLETE"),
2274
+ "no refusal (Claude)": ("claude-refusal-shape-replayed", "COMPLETION_INCOMPLETE"),
2275
+ "no refusal (Codex frames)": ("codex-planted-refusal-frame", "COMPLETION_INCOMPLETE"),
2276
+ "no truncation (Claude max_tokens)": ("claude-real-truncation-max-tokens", "COMPLETION_INCOMPLETE"),
2277
+ # lead ruling on WP-03v dw5 (cap16): the host ends a call past its declared cap with an api_error, named here
2278
+ "Claude cap overrun named at the declared cap": ("claude-cap-overrun-is-named-at-the-declared-cap", "COMPLETION_INCOMPLETE"),
2279
+ "Claude completion read from is_error, not subtype": ("claude-is-error-while-subtype-reads-success", "COMPLETION_INCOMPLETE"),
2280
+ "Claude terminal_reason completed": ("claude-terminal-reason-present-not-completed", "COMPLETION_INCOMPLETE"),
2281
+ "Claude every assistant stop_reason in end_turn/stop_sequence/tool_use": ("claude-real-truncation-max-tokens", "COMPLETION_INCOMPLETE"),
2282
+ "Claude safety_stops zero": ("claude-safety-stop-counted", "COMPLETION_INCOMPLETE"),
2283
+ "Claude safety_stops present": ("claude-safety-stops-missing", "COMPLETION_INCOMPLETE"),
2284
+ "Claude structured_output present where a schema was given": ("claude-real-impossible-schema-no-structured-output", "COMPLETION_INCOMPLETE"),
2285
+ "schema-less call without structured_output accepted": ("claude-schema-less-actor-call-without-structured-output", None),
2286
+ "Codex aborted stream is failure": ("codex-real-aborted-stream", "COMPLETION_INCOMPLETE"),
2287
+ "Codex response.incomplete is failure": ("codex-planted-response-incomplete", "COMPLETION_INCOMPLETE"),
2288
+ "budget-stopped call is not complete": ("budget-stopped-call", "COMPLETION_INCOMPLETE"),
2289
+ # step 1, the receipt and each of its values
2290
+ "receipt present": ("no-receipt", "RECEIPT_MISSING"),
2291
+ "receipt carries this call_id": ("stale-receipt-of-another-call", "RECEIPT_STALE"),
2292
+ "receipt dispatch_id (plan)": ("receipt-without-dispatch-id", "RECEIPT_KEY_MISSING"),
2293
+ "receipt packet hash of the bytes sent": ("packet-changed-after-the-receipt", "RECORD_INTEGRITY"),
2294
+ "receipt result hash of the bytes read": ("mismatched-result-hash", "RECORD_INTEGRITY"),
2295
+ "receipt schema hash": ("receipt-schema_sha256-is-not-recomputed", "RECORD_INTEGRITY"),
2296
+ "receipt payload hash (plan)": ("receipt-payload_sha256-is-not-recomputed", "RECORD_INTEGRITY"),
2297
+ "receipt seat sent": ("receipt-seat-sent-is-not-the-call-seat", "RECORD_INTEGRITY"),
2298
+ "receipt seat observed": ("receipt-seat_observed-is-not-recomputed", "RECORD_INTEGRITY"),
2299
+ "receipt profile and flag-set hash": ("claude-flag-set-is-not-the-pinned-one", "PROFILE_INHERITED"),
2300
+ "receipt working directory": ("receipt-cwd-outside-the-manifest", "CWD_OUTSIDE_MANIFEST"),
2301
+ "receipt context-manifest hash": ("receipt-manifest_sha256-is-not-recomputed", "RECORD_INTEGRITY"),
2302
+ "receipt observed-context hash": ("receipt-context_observed_sha256-is-not-recomputed", "RECORD_INTEGRITY"),
2303
+ "receipt usage state": ("receipt-usage_state-is-not-recomputed", "RECORD_INTEGRITY"),
2304
+ "receipt usage totals": ("receipt-usage_totals-is-not-recomputed", "RECORD_INTEGRITY"),
2305
+ "receipt capture hash": ("receipt-capture_sha256-is-not-recomputed", "RECORD_INTEGRITY"),
2306
+ "receipt session or thread id": ("receipt-session_id-is-not-recomputed", "RECORD_INTEGRITY"),
2307
+ "receipt exit status": ("receipt-exit-status-is-not-observed", "RECORD_INTEGRITY"),
2308
+ "receipt evidence key missing": ("receipt-key-missing", "RECEIPT_KEY_MISSING"),
2309
+ "complete failure set across receipt defects": ("receipt-with-three-independent-defects", "RECEIPT_STALE"),
2310
+ # step 1, Claude host-level bindings
2311
+ "recorded request text equals the packet": ("binding-request-text-is-not-the-packet", "BINDING_MISMATCH"),
2312
+ "every main request carries the packet": ("binding-a-later-request-text-is-not-the-packet", "BINDING_MISMATCH"),
2313
+ "StructuredOutput tool definition equals the schema": ("binding-tool-definition-is-not-the-schema", "BINDING_MISMATCH"),
2314
+ "structured_output equals the last recorded tool call": ("binding-structured-output-is-not-the-last-call", "BINDING_MISMATCH"),
2315
+ # step 1, the rejections it names
2316
+ "inherited profile rejected": ("codex-real-inherited-profile", "PROFILE_INHERITED"),
2317
+ "working directory outside the manifest rejected": ("host-cwd-outside-the-manifest", "CWD_OUTSIDE_MANIFEST"),
2318
+ "undeclared working-directory instruction": ("claude-real-contaminated-work-claude-md", "CONTEXT_UNDECLARED"),
2319
+ "undeclared ancestor instruction": ("claude-real-contaminated-anc-claude-md", "CONTEXT_UNDECLARED"),
2320
+ "undeclared configuration-home instruction": ("claude-real-contaminated-cfg-claude-md", "CONTEXT_UNDECLARED"),
2321
+ "undeclared skill": ("claude-real-contaminated-skill", "CONTEXT_UNDECLARED"),
2322
+ "undeclared memory source": ("claude-real-contaminated-memory", "CONTEXT_UNDECLARED"),
2323
+ "undeclared hook": ("hook-attachment-reached-the-call", "CONTEXT_UNDECLARED"),
2324
+ "undeclared agent": ("agent-reached-the-call", "CONTEXT_UNDECLARED"),
2325
+ "declared agent observed accepted": ("agent-declared-and-observed", None),
2326
+ # design §8.1 (isolation, check 2): the host's report names its MCP servers, judged by name like skills and agents
2327
+ "undeclared MCP server": ("mcp-server-reached-the-call", "CONTEXT_UNDECLARED"),
2328
+ "declared MCP server observed accepted": ("mcp-server-declared-and-observed", None),
2329
+ "undeclared appended system prompt (O4)": ("appended-prompt-undeclared", "CONTEXT_UNDECLARED"),
2330
+ "declared appended prompt whose hash differs (O4)": ("appended-prompt-declared-hash-differs", "CONTEXT_HASH_MISMATCH"),
2331
+ # step 2, seat attestation
2332
+ "Claude message.model per response": ("claude-real-fallback-model-answered", "MODEL_UNATTESTED"),
2333
+ "Claude params.model per request": ("claude-all-auxiliary-main-response", "MODEL_UNATTESTED"),
2334
+ "Claude modelUsage keys declared": ("claude-undeclared-model-usage-key", "MODEL_UNATTESTED"),
2335
+ "Claude auxiliary role in the aggregate accepted": ("claude-main-on-seat-auxiliary-in-aggregate", None),
2336
+ "Claude child on its declared seat": ("claude-child-on-the-main-seat-where-another-is-declared", "MODEL_UNATTESTED"),
2337
+ "Codex every response carries an observed model": ("codex-child-response-without-a-model-in-its-frame", "MODEL_UNATTESTED"),
2338
+ "Codex response on its seat": ("codex-response-on-another-model", "MODEL_UNATTESTED"),
2339
+ "Codex completion ledger exists (otel)": ("codex-no-otel-channel", "MODEL_UNATTESTED"),
2340
+ "Codex frames silent": ("codex-real-frames-silent", "MODEL_UNATTESTED"),
2341
+ "completion with no joined frame (frames_blind)": ("codex-transport-fallback-blinds-the-frames", "frames_blind"),
2342
+ "child response with no frame beside framed root and warm-up": ("codex-child-response-without-its-frames", "frames_blind"),
2343
+ "join by order: reordered completions": ("codex-completions-reordered", "MODEL_UNATTESTED"),
2344
+ "join exactly once: duplicated completion": ("codex-completion-duplicated", "MODEL_UNATTESTED"),
2345
+ "join by full usage": ("codex-completion-cache-count-disagrees", "frames_blind"),
2346
+ "ambiguous client frame": ("codex-client-frame-duplicated", "MODEL_UNATTESTED"),
2347
+ "usage-less row without its usage-bearing row is an interrupted attempt": ("codex-http-stream-dropped-is-an-interrupted-attempt", "frames_blind"),
2348
+ "interrupted attempts are recorded in usage": ("codex-usage-missing-an-interrupted-attempt", "RECORD_INTEGRITY"),
2349
+ "websocket starts reconcile": ("codex-websocket-retry-reconciles-its-starts", "COMPLETION_INCOMPLETE"),
2350
+ "HTTPS coverage unknown without the retry warnings": ("codex-http-retry-before-streaming-leaves-coverage-unknown", "frames_blind"),
2351
+ # plan addendum WP-04 (2026-10-21T1752) closes "complete when the warnings reconcile" (ruling F#1)
2352
+ "HTTPS coverage unknown even when the warnings reconcile": ("codex-https-coverage-unknown-even-when-the-warnings-reconcile",
2353
+ "USAGE_ATTRIBUTION_UNKNOWN"),
2354
+ "unknown attempt coverage fails the call (review round 5)": (
2355
+ "codex-completions-without-their-starts-fail-attribution", "USAGE_ATTRIBUTION_UNKNOWN"),
2356
+ "HTTPS failed post before streaming is an attempt (two posts, one stream)": (
2357
+ "codex-usage-missing-the-post-that-failed-before-streaming", "RECORD_INTEGRITY"),
2358
+ "mixed coverage": ("codex-mixed-coverage-websocket-and-https", "frames_blind"),
2359
+ "fallback usage measured from otel": ("codex-fallback-usage-measured-from-otel", "frames_blind"),
2360
+ "live call needs a measured auxiliary declaration (S-7)": ("live-call-on-a-provisional-auxiliary-role", "MODEL_UNATTESTED"),
2361
+ # steps 3-5
2362
+ "schema": ("claude-structured-output-violates-the-schema", "SCHEMA_INVALID"),
2363
+ "prose is never parsed (F22)": ("codex-prose-wrapped-json-is-never-parsed", "SCHEMA_INVALID"),
2364
+ "every reference resolves": ("reference-resolves-to-nothing", "RECORD_INTEGRITY"),
2365
+ "a required contract is there": ("required-contract-missing", "RECORD_INTEGRITY"),
2366
+ "every input id accounted": ("an-input-id-unaccounted", "SET_MISMATCH"),
2367
+ "no extra output id": ("an-extra-output-id", "SET_MISMATCH"),
2368
+ "ids unique": ("set-accounting-an-id-twice", "SET_MISMATCH"),
2369
+ "merged with explicit membership": ("set-accounting-merged-without-members", "SET_MISMATCH"),
2370
+ "rejected with a reason": ("set-accounting-rejected-without-a-reason", "SET_MISMATCH"),
2371
+ "malformed record is a named verdict": ("assistant-record-not-an-object", "RECORD_INTEGRITY"),
2372
+ }
2373
+ live_only = {"truncated output (Claude, CLAUDE_CODE_MAX_OUTPUT_TOKENS)": "WP-03 done-when 5",
2374
+ "aborted stream (Codex, real)": "WP-04", "nonzero exit (live)": "WP-03/WP-04",
2375
+ "inherited profile (--profile inherit)": "WP-03 done-when 5, WP-04",
2376
+ "contaminated working directory under the loading flag set": "WP-03 done-when 3",
2377
+ "Codex frames silent (live)": "WP-04"}
2378
+ verdicts = {name: v for name, _f, _n, _r, v in outcomes}
2379
+ for branch, (name, code) in branches.items():
2380
+ verdict = verdicts.get(name)
2381
+ if verdict is None:
2382
+ failures.append(f"design §3.2 branch {branch!r}: its control {name} did not run")
2383
+ elif code is None and not verdict["ok"]:
2384
+ failures.append(f"design §3.2 branch {branch!r}: the clean counterpart {name} is not accepted")
2385
+ elif code is not None and code not in verdict["codes"]:
2386
+ failures.append(f"design §3.2 branch {branch!r}: {name} does not carry {code} ({verdict['codes']})")
2387
+ if not live_only or len(branches) < 84:
2388
+ failures.append(f"the branch inventory shrank to {len(branches)}; it is copied from design §3.2, not generated")
2389
+
2390
+ # The implemented predicate branches, by identity (predicate_branches: the check and its
2391
+ # message template), copied here by hand and each named with the design §3.2 branches above
2392
+ # it realizes or with the plan addition or gap it closes (`additions`). The guard holds this
2393
+ # copy EQUAL to the branches read from the source, so a branch added without its entry, or an
2394
+ # entry whose branch is gone — one value of a loop over CONTEXT_SETS included —, fails by
2395
+ # identity; and every §3.2 branch that rejects names an implementing identity, unless the
2396
+ # attempt projection (`projections`, verdict["attempts"]) realizes it.
2397
+ additions = {
2398
+ "call record": "plan WP-02: call.json is DistillCall/v1, readable, and this call's",
2399
+ "capture": "design §3.2 step 1: the host's records are this call's capture",
2400
+ "contract scope": "plan WP-02 (A#7): steps 4 and 5 judge a structured output, and only where call.json declares them",
2401
+ "bytes kept": "design §3.2 step 1: the hashes are of the bytes the driver sent and read, so both are kept",
2402
+ "schema file": "design §3.2 step 1: the schema hash is of the schema required, so the file is that schema",
2403
+ "handed schema": "D7 (2026-11-12): what the host was handed is schema.json, or its provider dialect's projection "
2404
+ "of it made by packets.provider_schema_bytes, recorded by its own hash",
2405
+ "usage record": "design §13.3: every call records its usage, and it is this call's",
2406
+ "main request recorded": "design §3.2 step 1: the Claude bindings are of the main request, so one is recorded",
2407
+ "result object": "design §3.2 step 1: completion is read from the result, so the host wrote one",
2408
+ "result text": "plan WP-02: a schema-less call's answer is the result text accepted() hands the stage",
2409
+ "aggregate present": "design §3.2 step 2: the hidden requests are attested by result.modelUsage, so it is there",
2410
+ "main response observed": "design §3.2 step 2: the main response carries an observed model",
2411
+ "role without a seat": "plan S-7: a role is judged against its declared seat, so it has one",
2412
+ "host failure events": "design §3.2 step 1: a turn.failed or error event is the host reporting failure",
2413
+ "turn completed": "design §3.2 step 1: a Codex call completes its turn",
2414
+ "response without a client frame": "design §3.2 step 2: a response's role is its client frame's",
2415
+ "frame response never completed by the ledger": "design §3.2 step 2: each completion joins exactly one frame response",
2416
+ "declared context not observed": "design §3.2 step 1: the observed context equals the declared manifest, both ways",
2417
+ "no context evidence": "design §3.2 step 1: the effective context is evidenced",
2418
+ "flag set ran": "design §3.2 step 1: the profile and flag-set hash, on the host's own record",
2419
+ "no pinned flag set": "plan WP-02: seats.json pins the flag set per host version",
2420
+ "schema policy": "plan WP-01: a schema the validator's policy refuses judges nothing",
2421
+ "working directory listed": "design §3.1: the working directory is listed before the call",
2422
+ "working directory holds the manifest": "design §3.1: an empty directory or exactly the manifest's files",
2423
+ "receipt hermeticity": "the contract-fix records of 2026-11-02 (F-31): the receipt states the call's hermeticity, "
2424
+ "recomputed from the call directory",
2425
+ "capture server policy is the run's": "the contract-fix records of 2026-11-02 (D-20261102-252c92): the "
2426
+ "capture states the run's server-policy verdict, as call.json records it",
2427
+ "the window bound": "the input-bound amendment record 2026-10-21T0026--cc0498f and the seam record of "
2428
+ "2026-10-22: the bound `runlib/bound.py` owns is judged a second time here, from "
2429
+ "the call directory, so an accepted call is evidence that it held",
2430
+ }
2431
+ projections = {"usage-less row without its usage-bearing row is an interrupted attempt", "websocket starts reconcile",
2432
+ "HTTPS coverage unknown without the retry warnings", "HTTPS coverage unknown even when the warnings reconcile",
2433
+ "mixed coverage", "fallback usage measured from otel"}
2434
+ receipt_value = "RECORD_INTEGRITY receipt {}: {{}} is not {{}}, recomputed from the call directory"
2435
+ implemented = {
2436
+ ("accounting", "{} (design §3.2 item 5)"): ("every input id accounted", "no extra output id", "ids unique",
2437
+ "merged with explicit membership", "rejected with a reason"),
2438
+ # the window bound, judged a second time here (the amendment record of 2026-10-21 and the seam
2439
+ # record of 2026-10-22): the rule is `runlib/bound.py`'s and this is its second reader
2440
+ ("window_bound", "{} (call.json input_observed)"): ("the window bound",),
2441
+ ("window_bound", "DISPATCHED_WHILE_STOPPED {}: the run's bound stop stood when this call was admitted, and a "
2442
+ "stopped run dispatches nothing"): ("the window bound",),
2443
+ ("window_bound", "RECORD_INTEGRITY call.json bound.limit: {} is not the bound the rule owns ({})"): (
2444
+ "the window bound",),
2445
+ ("window_bound", "CAPACITY_DRIFT {}: the host reports a context window of {} and the call was admitted "
2446
+ "against {}; the declaration is stale"): ("the window bound",),
2447
+ # a call that stopped the run is a failure whatever its answer, read from its stop and from its usage against
2448
+ # its claim (W review of WP-08e r2, F1; lead decision)
2449
+ ("window_bound", "{} {}: this call stopped the run, so its answer is not accepted ({})"): ("the window bound",),
2450
+ ("window_bound", "{} {}: {} - past the claim it was admitted under, so its answer is not accepted (usage.json "
2451
+ "against call.json bound.claim)"): ("the window bound",),
2452
+ ("window_bound", "{} {}: {}; a claim is never judged by a weaker rule (usage.json against call.json "
2453
+ "bound.claim)"): ("the window bound",),
2454
+ ("call_record", "RECORD_INTEGRITY call.json {}"): ("call record",),
2455
+ ("call_record", "<host_schema_problems>"): ("handed schema",),
2456
+ ("call_record", "RECORD_INTEGRITY call.json: absent, unreadable, or without call_id and host"): ("call record",),
2457
+ ("call_record", "RECORD_INTEGRITY capture/host.json {}"): ("malformed record is a named verdict",),
2458
+ ("call_record", "RECORD_INTEGRITY capture/host.json: absent, or not this call's {} capture"): ("capture",),
2459
+ ("call_record", "RECORD_INTEGRITY contract.json: a reference or set contract judges a structured output, and the call is "
2460
+ "schema-less"): ("contract scope",),
2461
+ ("call_record", "RECORD_INTEGRITY contract.json: call.json requires the stage's contract (steps 4 and 5), and it is "
2462
+ "unreadable"): ("a required contract is there",),
2463
+ ("call_record", "RECORD_INTEGRITY contract.json: call.json requires the stage's contract (steps 4 and 5), and there is "
2464
+ "none"): ("a required contract is there",),
2465
+ ("call_record", "RECORD_INTEGRITY contract.json: present for a call that declares no contract"): ("contract scope",),
2466
+ ("call_record", "RECORD_INTEGRITY packet.md and result.json: the bytes sent and read must both be kept"): ("bytes kept",),
2467
+ ("call_record", "RECORD_INTEGRITY schema.json: not the schema call.json says the driver required"): ("schema file",),
2468
+ ("call_record", "RECORD_INTEGRITY schema.json: present for a call declared schema-less"): ("schema file",),
2469
+ ("call_record", "RECORD_INTEGRITY usage.json: absent, invalid or another call's ({})"): ("usage record",),
2470
+ ("call_record", "RECORD_INTEGRITY {}: not well-formed JSON objects (one object, or one per line)"): (
2471
+ "malformed record is a named verdict",),
2472
+ ("claude_bindings", "BINDING_MISMATCH request text: request {}'s recorded text is not the packet the driver sent"): (
2473
+ "recorded request text equals the packet", "every main request carries the packet"),
2474
+ ("claude_bindings", "BINDING_MISMATCH request: the transcript records no main request"): ("main request recorded",),
2475
+ ("claude_bindings", "BINDING_MISMATCH result: structured_output is not the last StructuredOutput call the host recorded"): (
2476
+ "structured_output equals the last recorded tool call",),
2477
+ ("claude_bindings", "BINDING_MISMATCH schema: request {}'s StructuredOutput tool definition is not the schema"): (
2478
+ "StructuredOutput tool definition equals the schema",),
2479
+ ("claude_completion", "COMPLETION_INCOMPLETE is_error={} (subtype {} is not read)"): (
2480
+ "Claude completion read from is_error, not subtype", "no refusal (Claude)"),
2481
+ ("claude_completion", "COMPLETION_INCOMPLETE result text: a schema-less call's answer is the result text, and there is "
2482
+ "none"): ("result text",),
2483
+ ("claude_completion", "COMPLETION_INCOMPLETE result: the host wrote no result object"): ("result object",),
2484
+ ("claude_completion", "COMPLETION_INCOMPLETE safety_stops: the result does not report it"): ("Claude safety_stops present",),
2485
+ ("claude_completion", "COMPLETION_INCOMPLETE safety_stops={}"): ("Claude safety_stops zero",),
2486
+ ("claude_completion", "COMPLETION_INCOMPLETE max_output_tokens: the response passed the call's declared cap of {} "
2487
+ "output tokens, and the host ended the call"): ("Claude cap overrun named at the declared cap",),
2488
+ ("claude_completion", "COMPLETION_INCOMPLETE stop_reason {} on request {}"): (
2489
+ "Claude every assistant stop_reason in end_turn/stop_sequence/tool_use", "no truncation (Claude max_tokens)"),
2490
+ ("claude_completion", "COMPLETION_INCOMPLETE structured_output: none, although a schema was given"): (
2491
+ "Claude structured_output present where a schema was given",),
2492
+ ("claude_completion", "COMPLETION_INCOMPLETE terminal_reason={}, not 'completed'"): ("Claude terminal_reason completed",),
2493
+ ("claude_seats", "MODEL_UNATTESTED aggregate: no result.modelUsage to attest the hidden requests by"): ("aggregate present",),
2494
+ ("claude_seats", "MODEL_UNATTESTED aggregate: result.modelUsage names {}, neither a declared seat nor a declared auxiliary "
2495
+ "role"): ("Claude modelUsage keys declared",),
2496
+ ("claude_seats", "MODEL_UNATTESTED aggregate: result.modelUsage names {}, neither a declared seat nor a declared auxiliary "
2497
+ "role ({} declared, not measured, so not for a live call)"): (
2498
+ "live call needs a measured auxiliary declaration (S-7)",),
2499
+ ("claude_seats", "MODEL_UNATTESTED no main response carries an observed model"): ("main response observed",),
2500
+ ("claude_seats", "MODEL_UNATTESTED request {} ({}) named {}, the seat is {}"): (
2501
+ "Claude params.model per request", "Claude child on its declared seat"),
2502
+ ("claude_seats", "MODEL_UNATTESTED request {}: role {} has no declared seat"): ("role without a seat",),
2503
+ ("claude_seats", "MODEL_UNATTESTED response to {} ({}) came from {}, the seat is {}"): ("Claude message.model per response",),
2504
+ ("codex_completion", "COMPLETION_INCOMPLETE aborted stream: {} has response.created and no response.completed"): (
2505
+ "Codex aborted stream is failure",),
2506
+ ("codex_completion", "COMPLETION_INCOMPLETE error: the host reported a failure"): ("host failure events",),
2507
+ ("codex_completion", "COMPLETION_INCOMPLETE turn.failed: the host reported a failure"): ("host failure events",),
2508
+ ("codex_completion", "COMPLETION_INCOMPLETE turn: codex emitted no turn.completed"): ("turn completed",),
2509
+ ("codex_completion", "COMPLETION_INCOMPLETE {} ended response.{} ({})"): ("Codex response.incomplete is failure",),
2510
+ ("codex_completion", "COMPLETION_INCOMPLETE {} frame: {}"): ("no refusal (Codex frames)",),
2511
+ ("attempt_coverage", "USAGE_ATTRIBUTION_UNKNOWN {}: attempt coverage is unknown ({})"): (
2512
+ "unknown attempt coverage fails the call (review round 5)",),
2513
+ ("codex_seats", "MODEL_UNATTESTED completion at {} ({} input tokens) has no observed model"): (
2514
+ "completion with no joined frame (frames_blind)",),
2515
+ ("codex_seats", "MODEL_UNATTESTED completion at {} ({} input tokens): its in-order frame response disagrees in usage while "
2516
+ "another agrees, an ambiguous join"): ("join by order: reordered completions",
2517
+ "join exactly once: duplicated completion"),
2518
+ ("codex_seats", "MODEL_UNATTESTED completions: the capture carries no otel channel, so there is no completion ledger"): (
2519
+ "Codex completion ledger exists (otel)",),
2520
+ ("codex_seats", "MODEL_UNATTESTED frames silent: no server frame carries a response, so no model is observed"): (
2521
+ "Codex frames silent",),
2522
+ ("codex_seats", "MODEL_UNATTESTED {} ({}) came from {}, the seat is {}"): ("Codex response on its seat",),
2523
+ ("codex_seats", "MODEL_UNATTESTED {} ({}): no seat is declared for the role"): ("role without a seat",),
2524
+ ("codex_seats", "MODEL_UNATTESTED {} ({}): the frame carries no model"): ("Codex every response carries an observed model",),
2525
+ ("codex_seats", "MODEL_UNATTESTED {}: a completed frame response no completion in the ledger joins"): (
2526
+ "frame response never completed by the ledger",),
2527
+ ("codex_seats", "MODEL_UNATTESTED {}: more than one client frame could have asked for it"): ("ambiguous client frame",),
2528
+ ("codex_seats", "MODEL_UNATTESTED {}: no client frame names its role"): ("response without a client frame",),
2529
+ ("codex_seats", "RECORD_INTEGRITY usage.json: the capture shows {} attempts (interrupted ones included), usage records {}"): (
2530
+ "interrupted attempts are recorded in usage", "HTTPS failed post before streaming is an attempt (two posts, one stream)"),
2531
+ ("codex_seats", "frames_blind {} completion at {} joins no frame response; its usage comes from otel and its request kind is "
2532
+ "unknown"): ("completion with no joined frame (frames_blind)",
2533
+ "child response with no frame beside framed root and warm-up", "join by full usage"),
2534
+ **{("effective_context", f"CONTEXT_HASH_MISMATCH {kind} {{}}: declared, not observed"): ("declared context not observed",)
2535
+ for kind in ("skills", "agents", "hooks", "mcp_servers")},
2536
+ ("effective_context", "CONTEXT_HASH_MISMATCH appended system prompt {}: declared, not in the sent request"): (
2537
+ "declared context not observed",),
2538
+ ("effective_context", "CONTEXT_HASH_MISMATCH appended system prompt {}: sha256 {}, declared {}"): (
2539
+ "declared appended prompt whose hash differs (O4)",),
2540
+ ("effective_context", "CONTEXT_HASH_MISMATCH instruction {}: declared, not loaded"): ("declared context not observed",),
2541
+ ("effective_context", "CONTEXT_HASH_MISMATCH instruction {}: loaded bytes differ from the declared sha256"): (
2542
+ "declared context not observed",),
2543
+ ("effective_context", "CONTEXT_UNDECLARED agents {} reached the call, not declared"): ("undeclared agent",),
2544
+ ("effective_context", "CONTEXT_UNDECLARED appended system prompt {} (sha256 {}) not declared"): (
2545
+ "undeclared appended system prompt (O4)",),
2546
+ ("effective_context", "CONTEXT_UNDECLARED capture: no effective-context evidence for this call"): ("no context evidence",),
2547
+ ("effective_context", "CONTEXT_UNDECLARED hooks {} reached the call, not declared"): ("undeclared hook",),
2548
+ ("effective_context", "CONTEXT_UNDECLARED instruction {} ({}) loaded, not declared"): (
2549
+ "undeclared working-directory instruction", "undeclared ancestor instruction", "undeclared configuration-home instruction",
2550
+ "undeclared memory source"),
2551
+ ("effective_context", "CONTEXT_UNDECLARED skills {} reached the call, not declared"): ("undeclared skill",),
2552
+ ("effective_context", "CONTEXT_UNDECLARED mcp_servers {} reached the call, not declared"): ("undeclared MCP server",),
2553
+ ("exit_status", "COMPLETION_INCOMPLETE {}: the supervisor stopped the call ({})"): (
2554
+ "budget-stopped call is not complete",),
2555
+ ("exit_status", "COMPLETION_INCOMPLETE exit: the runner exited {}"): ("exit status zero",),
2556
+ ("profile", "PROFILE_INHERITED capture: the flag set the host ran with is not the pinned one"): ("flag set ran",),
2557
+ ("profile", "PROFILE_INHERITED capture: the runner ran profile {}, the call requires {}"): ("inherited profile rejected",),
2558
+ ("profile", "PROFILE_INHERITED seats.json pins no {} flag set for {} {}"): ("no pinned flag set",),
2559
+ ("receipt_binding", "<problems>"): ("receipt present", "receipt evidence key missing", "receipt dispatch_id (plan)"),
2560
+ ("receipt_binding", "<receipts.problems>"): ("receipt carries this call_id", "complete failure set across receipt defects"),
2561
+ ("receipt_binding", "CWD_OUTSIDE_MANIFEST receipt: cwd {} is not the declared working directory"): (
2562
+ "receipt working directory",),
2563
+ ("receipt_binding", "PROFILE_INHERITED receipt: profile {}, the call requires {}"): ("receipt profile and flag-set hash",),
2564
+ ("receipt_binding", "PROFILE_INHERITED receipt: the flag-set hash is not the one seats.json pins for the profile"): (
2565
+ "receipt profile and flag-set hash",),
2566
+ **{("receipt_binding", receipt_value.format(key)): (branch,) for key, branch in (
2567
+ ("packet_sha256", "receipt packet hash of the bytes sent"), ("result_sha256", "receipt result hash of the bytes read"),
2568
+ ("provider", "receipt seat sent"), ("model", "receipt seat sent"), ("effort", "receipt seat sent"),
2569
+ ("exit_status", "receipt exit status"), ("evidence.schema_sha256", "receipt schema hash"),
2570
+ ("evidence.payload_sha256", "receipt payload hash (plan)"), ("evidence.seat_observed", "receipt seat observed"),
2571
+ ("evidence.manifest_sha256", "receipt context-manifest hash"),
2572
+ ("evidence.context_observed_sha256", "receipt observed-context hash"), ("evidence.usage_state", "receipt usage state"),
2573
+ ("evidence.usage_totals", "receipt usage totals"), ("evidence.capture_sha256", "receipt capture hash"),
2574
+ ("evidence.session_id", "receipt session or thread id"), ("evidence.hermeticity", "receipt hermeticity"))},
2575
+ ("receipt_binding", "RECORD_INTEGRITY capture hermeticity: server policy {} is not the run's record {} in "
2576
+ "call.json"): ("capture server policy is the run's",),
2577
+ ("references", "RECORD_INTEGRITY {} id {} at {} resolves to nothing"): ("every reference resolves",),
2578
+ ("schema", "SCHEMA_INVALID result: not one JSON document (nothing is extracted from prose)"): ("prose is never parsed (F22)",),
2579
+ ("schema", "SCHEMA_INVALID schema.json: refused by the schema policy ({})"): ("schema policy",),
2580
+ ("schema", "SCHEMA_INVALID {}"): ("schema",),
2581
+ ("working_directory", "CWD_OUTSIDE_MANIFEST capture: no listing of the working directory before the call"): (
2582
+ "working directory listed",),
2583
+ ("working_directory", "CWD_OUTSIDE_MANIFEST capture: the host recorded cwd {}, the manifest declares {}"): (
2584
+ "working directory outside the manifest rejected",),
2585
+ ("working_directory", "CWD_OUTSIDE_MANIFEST working directory: holds {}, lacks {} against the manifest"): (
2586
+ "working directory holds the manifest",),
2587
+ }
2588
+
2589
+ def fidelity(text):
2590
+ """(branches the source implements that the copy lacks, branches the copy names that the source lacks)."""
2591
+ found = predicate_branches(text)
2592
+ return sorted(found - set(implemented)), sorted(set(implemented) - found)
2593
+ source = pathlib.Path(__file__).read_text(encoding="utf-8")
2594
+ extra_branches, missing_branches = fidelity(source)
2595
+ for identity in extra_branches:
2596
+ failures.append(f"CONTRACT_MISMATCH {identity}: implemented, absent from the copied §3.2 inventory")
2597
+ for identity in missing_branches:
2598
+ failures.append(f"CONTRACT_MISMATCH {identity}: in the copied §3.2 inventory, not implemented")
2599
+ labels = {label for named in implemented.values() for label in named}
2600
+ for label in sorted(labels - set(branches) - set(additions)):
2601
+ failures.append(f"CONTRACT_MISMATCH {label!r}: an implemented branch names neither a §3.2 branch nor an addition")
2602
+ for branch, (_name, code) in branches.items():
2603
+ if code is not None and branch not in projections and branch not in labels:
2604
+ failures.append(f"CONTRACT_MISMATCH design §3.2 branch {branch!r}: no implemented branch realizes it")
2605
+ for label in sorted(set(additions) - labels):
2606
+ failures.append(f"CONTRACT_MISMATCH addition {label!r}: no implemented branch is it")
2607
+ # the guard against planted drift, at the grain of one branch: an added message, a removed
2608
+ # statement, and one value taken out of the loop over CONTEXT_SETS
2609
+ ran.append("fidelity-an-added-branch-is-named")
2610
+ anchor = ' errors.append(f"COMPLETION_INCOMPLETE exit: the runner exited {c.call.get(\'exit_status\')!r}")\n'
2611
+ planted = source.replace(anchor, anchor + ' errors.append("COMPLETION_INCOMPLETE planted branch")\n', 1)
2612
+ if planted == source or fidelity(planted) != ([("exit_status", "COMPLETION_INCOMPLETE planted branch")], []):
2613
+ failures.append(f"fidelity-an-added-branch-is-named: {fidelity(planted)}")
2614
+ ran.append("fidelity-an-added-computed-branch-is-named")
2615
+ computed = source.replace(anchor, anchor + ' errors.append(str(c.call.get("note")))\n', 1)
2616
+ if computed == source or fidelity(computed) != ([("exit_status", "{}")], []):
2617
+ failures.append(f"fidelity-an-added-computed-branch-is-named: {fidelity(computed)}")
2618
+ ran.append("fidelity-a-removed-branch-is-named")
2619
+ removed = source.replace(' errors.append(f"COMPLETION_INCOMPLETE {c.call', ' str(f"COMPLETION_INCOMPLETE {c.call', 1)
2620
+ if removed == source or fidelity(removed) != ([], [("exit_status", "COMPLETION_INCOMPLETE {}: the supervisor stopped "
2621
+ "the call ({})")]):
2622
+ failures.append(f"fidelity-a-removed-branch-is-named: {fidelity(removed)}")
2623
+ ran.append("fidelity-a-context-set-taken-out-is-named")
2624
+ narrowed = source.replace('CONTEXT_SETS = ("skills", "agents", "hooks", "mcp_servers")', 'CONTEXT_SETS = ("skills", "hooks", "mcp_servers")', 1)
2625
+ if narrowed == source or fidelity(narrowed) != ([], [("effective_context", "CONTEXT_HASH_MISMATCH agents {}: declared, not observed"),
2626
+ ("effective_context", "CONTEXT_UNDECLARED agents {} reached the call, not declared")]):
2627
+ failures.append(f"fidelity-a-context-set-taken-out-is-named: {fidelity(narrowed)}")
2628
+ plan_codes = {"COMPLETION_INCOMPLETE", "BINDING_MISMATCH", "MODEL_UNATTESTED", "frames_blind", "SCHEMA_INVALID",
2629
+ "RECORD_INTEGRITY", "SET_MISMATCH", "CONTEXT_UNDECLARED", "CONTEXT_HASH_MISMATCH", "RECEIPT_STALE",
2630
+ "RECEIPT_MISSING", "RECEIPT_KEY_MISSING", "PROFILE_INHERITED", "CWD_OUTSIDE_MANIFEST", "RETRY_EXHAUSTED",
2631
+ "USAGE_ATTRIBUTION_UNKNOWN"} # the last: lead decision, WP-02 review round 5
2632
+ if set(CODES) != plan_codes:
2633
+ failures.append(f"CONTRACT_MISMATCH gate codes {sorted(CODES)} (plan WP-02)")
2634
+ exercised = {code for _n, _f, needles, _r, v in outcomes for code in v["codes"] if any(code in n for n in needles)}
2635
+ exercised.add("RETRY_EXHAUSTED") if not twice["ok"] else None
2636
+ if plan_codes - exercised:
2637
+ failures.append(f"codes no control exercises: {sorted(plan_codes - exercised)}")
2638
+ # seats.json's pins against the version each value was established at: the real file first, then one planted
2639
+ # break per rule, each on rows of its own, so the controls keep testing after the next re-pin
2640
+ held_seats = json.loads(SEATS.read_text(encoding="utf-8"))
2641
+ ran.append("seats-pins-agree-with-their-versions")
2642
+ if seats_problems(held_seats) or not held_seats.get("hosts"):
2643
+ failures.append(f"seats-pins-agree-with-their-versions: {seats_problems(held_seats) or 'no hosts'}")
2644
+
2645
+ def other_context(carried, basis):
2646
+ return lambda d: d["hosts"]["codex"].setdefault("context", {}).update(
2647
+ planted={"skills": [], "observed_version": "0.0.1", "carried": carried, "basis": basis})
2648
+ for name, bend, want in (
2649
+ ("a-version-moved-without-its-path", lambda d: d["hosts"]["codex"].update(version="9.9.9"),
2650
+ "PIN_PATH_VERSION codex"),
2651
+ ("a-measured-allowance-left-at-the-old-version",
2652
+ lambda d: d["hosts"]["claude"]["host_allowance"].update(
2653
+ planted={"allowance_tokens": 1, "measured": True, "measured_version": "0.0.1", "basis": "b"}),
2654
+ "PIN_STALE claude.host_allowance.planted"),
2655
+ ("a-measured-allowance-naming-no-version",
2656
+ lambda d: d["hosts"]["claude"]["host_allowance"].update(
2657
+ planted={"allowance_tokens": 1, "measured": True, "basis": "b"}),
2658
+ "PIN_STALE claude.host_allowance.planted"),
2659
+ ("a-context-observed-at-another-version-not-carried", other_context(False, "b"),
2660
+ "PIN_STALE codex.context.planted"),
2661
+ ("a-carried-context-without-its-basis", other_context(True, " "), "PIN_STALE codex.context.planted"),
2662
+ ("a-measured-auxiliary-at-another-version",
2663
+ lambda d: d["hosts"]["claude"].setdefault("auxiliary", []).append(
2664
+ {"model": "planted", "measured": True, "measured_version": "0.0.1"}),
2665
+ "PIN_STALE claude.auxiliary.planted"),
2666
+ ("a-seat-capacity-at-another-version",
2667
+ lambda d: d.setdefault("seat_capacity", {}).update(
2668
+ {"claude:planted/high": {"context_capacity": 1, "host_version": "0.0.1", "basis": "b"}}),
2669
+ "PIN_STALE seat_capacity.claude:planted/high"),
2670
+ # a seat of its own, so the control keeps testing whichever seats the real file holds
2671
+ ("a-seated-seat-with-no-capacity",
2672
+ lambda d: d.setdefault("stage_seats", {}).update(Splanted=["codex:planted/xhigh"]),
2673
+ "CAPACITY_UNDECLARED seat_capacity.codex:planted/xhigh")):
2674
+ ran.append(name)
2675
+ bent = copy.deepcopy(held_seats)
2676
+ bend(bent)
2677
+ got = seats_problems(bent)
2678
+ if not any(line.startswith(want) for line in got):
2679
+ failures.append(f"{name}: expected a line starting {want!r}, got {got}")
2680
+ # a call's manifest declares the built-in context without the declaration's provenance, and none at another version
2681
+ ran.append("builtin-context-is-the-declaration-without-its-provenance")
2682
+ codex_entry = held_seats["hosts"]["codex"]
2683
+ declared = (codex_entry.get("context") or {}).get("hermetic") or {}
2684
+ got = builtin_context(codex_entry, "hermetic", codex_entry["version"])
2685
+ if (not declared.get("skills") or got != {k: v for k, v in declared.items() if k not in CONTEXT_PROVENANCE}
2686
+ or set(got) & set(CONTEXT_PROVENANCE) or builtin_context(codex_entry, "hermetic", "0.0.1") != {}):
2687
+ failures.append(f"builtin-context-is-the-declaration-without-its-provenance: {got}")
2688
+
2689
+ # The port of claude-runner/proto/mutation_audit.py, at the grain of a check rather than of a
2690
+ # code (the plan's codes are coarser than the probe's): drop one check from the gate, re-judge
2691
+ # the same artifacts, and require some control to notice — an asserted line of a control that
2692
+ # only this check emits disappears. A check no control notices losing is a rule nothing
2693
+ # tests; a control's own needles are asserted on lines, so a code that fires for an unrelated
2694
+ # reason cannot stand in for the one the mutation planted.
2695
+ rejecting = [o for o in outcomes if o[2] and not o[4]["ok"]]
2696
+ for _step, check_name, _fn in CHECKS:
2697
+ sole = [(name, files, needle) for name, files, needles, _r, v in rejecting for needle in needles
2698
+ if any(needle in line for line in v["by_check"].get(check_name, []))
2699
+ and not any(needle in line for other, lines in v["by_check"].items() if other != check_name for line in lines)]
2700
+ if not sole:
2701
+ failures.append(f"mutation audit: no control's asserted line comes from check {check_name} alone")
2702
+ continue
2703
+ name, files, needle = sole[0]
2704
+ without = accept(materialize(files), skip={check_name})
2705
+ if any(needle in line for line in without["failures"]):
2706
+ failures.append(f"mutation audit: control {name} still finds {needle!r} with check {check_name} removed")
2707
+ if len(rejecting) < 40:
2708
+ failures.append(f"only {len(rejecting)} rejecting controls over recorded captures; WP-02 done-when 1 asks for at least 40")
2709
+ audited = len(rejecting)
2710
+
2711
+ shutil.rmtree(scratch, ignore_errors=True)
2712
+ for failure in failures:
2713
+ print(f"gate --self-test [FAIL] {failure}")
2714
+ if failures:
2715
+ return 1
2716
+ replayed = sum(1 for o in outcomes if o[3] == "replay")
2717
+ print(f"gate --self-test: OK ({len(ran)} controls, {replayed} realized by replay, {audited} rejections; "
2718
+ f"every check load-bearing for a control, every code exercised: " + ", ".join(ran) + ")")
2719
+ return 0
2720
+
2721
+
2722
+ REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
2723
+
2724
+ if __name__ == "__main__":
2725
+ if "--self-test" not in sys.argv[1:]:
2726
+ sys.exit("usage: gate.py --self-test")
2727
+ sys.exit(self_test())