agent-bios 0.19.4 → 0.20.1

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 (162) hide show
  1. package/DEPENDENCIES.md +20 -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 +8 -7
  6. package/claude/guides/gpt-prompting.md +319 -144
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/agents/frontier.toml +1 -1
  10. package/codex/agents/reviewer.toml +1 -1
  11. package/codex/agents/workhorse.toml +1 -1
  12. package/codex/guides/claude-prompting.md +475 -234
  13. package/codex/guides/cli-multi-model-workflow.md +8 -7
  14. package/codex/guides/gpt-prompting.md +319 -144
  15. package/codex/guides/session-distill-workflow.md +93 -43
  16. package/codex/guides/tooling-gotchas.md +3 -1
  17. package/compose/assemble.py +4 -1
  18. package/compose/canary.sh +8 -6
  19. package/compose/host_platform.py +158 -15
  20. package/compose/instructions-state.py +183 -41
  21. package/compose/instructions_install.py +222 -27
  22. package/compose/instructions_session.py +250 -75
  23. package/compose/instructions_setup_cli.py +2 -36
  24. package/compose/instructions_store.py +160 -3
  25. package/compose/instructions_transaction.py +29 -5
  26. package/docs/advanced-launch.md +5 -1
  27. package/docs/releases/0.20.0.md +102 -0
  28. package/docs/releases/0.20.1.md +76 -0
  29. package/install.sh +42 -14
  30. package/launch/agent-launch.py +152 -18
  31. package/launch/agent-launch.toml +28 -16
  32. package/launch/agent-launch.zsh +104 -13
  33. package/launch/claude_subcommands.py +179 -0
  34. package/launch/shell_integration.py +7 -1
  35. package/learn/collect-learning.py +60 -9
  36. package/learn/migrate-learnings.py +70 -4
  37. package/learn/redact.py +2 -1
  38. package/package.json +36 -3
  39. package/provenance.json +1 -1
  40. package/session-cost.py +80 -9
  41. package/session-distill/coverage.json +6 -0
  42. package/session-distill/distill.py +2575 -0
  43. package/session-distill/grammar/__init__.py +0 -0
  44. package/session-distill/grammar/owner_lines.py +874 -0
  45. package/session-distill/originators.json +9 -0
  46. package/session-distill/packets/cross_review.md +31 -0
  47. package/session-distill/packets/form.md +86 -0
  48. package/session-distill/packets/judge.md +81 -0
  49. package/session-distill/packets/placement_contract.md +90 -0
  50. package/session-distill/packets/propose.md +124 -0
  51. package/session-distill/packets/read.md +57 -0
  52. package/session-distill/packets/reconsider.md +53 -0
  53. package/session-distill/packets/s7b.md +65 -0
  54. package/session-distill/packets/s9b.md +39 -0
  55. package/session-distill/packets/stitch.md +35 -0
  56. package/session-distill/packets/sweep.md +33 -0
  57. package/session-distill/runlib/__init__.py +0 -0
  58. package/session-distill/runlib/bound.py +1102 -0
  59. package/session-distill/runlib/breaker.py +467 -0
  60. package/session-distill/runlib/census.py +2347 -0
  61. package/session-distill/runlib/claims.py +420 -0
  62. package/session-distill/runlib/controls.py +902 -0
  63. package/session-distill/runlib/coverage.py +881 -0
  64. package/session-distill/runlib/declare.py +888 -0
  65. package/session-distill/runlib/delivery_evidence.py +1145 -0
  66. package/session-distill/runlib/derive.py +812 -0
  67. package/session-distill/runlib/destinations.py +3072 -0
  68. package/session-distill/runlib/dispatch.py +7940 -0
  69. package/session-distill/runlib/drift.py +1077 -0
  70. package/session-distill/runlib/entry.py +401 -0
  71. package/session-distill/runlib/evidence.py +890 -0
  72. package/session-distill/runlib/exposure.py +1162 -0
  73. package/session-distill/runlib/gate.py +2727 -0
  74. package/session-distill/runlib/gitread.py +79 -0
  75. package/session-distill/runlib/inventory.py +19624 -0
  76. package/session-distill/runlib/journal.py +1919 -0
  77. package/session-distill/runlib/ledger.py +3210 -0
  78. package/session-distill/runlib/ledger_compat.py +101 -0
  79. package/session-distill/runlib/ledger_migration.py +190 -0
  80. package/session-distill/runlib/lifecycle_intake.py +693 -0
  81. package/session-distill/runlib/lineage.py +454 -0
  82. package/session-distill/runlib/measures.py +249 -0
  83. package/session-distill/runlib/monitor.py +1180 -0
  84. package/session-distill/runlib/operations.py +522 -0
  85. package/session-distill/runlib/packet.py +838 -0
  86. package/session-distill/runlib/placement.py +1769 -0
  87. package/session-distill/runlib/projection.py +4090 -0
  88. package/session-distill/runlib/ranking.py +740 -0
  89. package/session-distill/runlib/receipts.py +200 -0
  90. package/session-distill/runlib/records.py +1965 -0
  91. package/session-distill/runlib/search.py +249 -0
  92. package/session-distill/runlib/sequencing.py +829 -0
  93. package/session-distill/runlib/sources.py +641 -0
  94. package/session-distill/runlib/stage_adjudicate.py +845 -0
  95. package/session-distill/runlib/stage_apply.py +1378 -0
  96. package/session-distill/runlib/stage_approvals.py +758 -0
  97. package/session-distill/runlib/stage_close.py +1220 -0
  98. package/session-distill/runlib/stage_confirm.py +929 -0
  99. package/session-distill/runlib/stage_delivery.py +3080 -0
  100. package/session-distill/runlib/stage_form.py +2576 -0
  101. package/session-distill/runlib/stage_judge.py +4248 -0
  102. package/session-distill/runlib/stage_propose.py +3307 -0
  103. package/session-distill/runlib/stage_read.py +5179 -0
  104. package/session-distill/runlib/stage_render.py +2739 -0
  105. package/session-distill/runlib/stage_retrieve.py +924 -0
  106. package/session-distill/runlib/stage_review_korean.py +1002 -0
  107. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  108. package/session-distill/runlib/stagelock.py +412 -0
  109. package/session-distill/runlib/stop.py +1061 -0
  110. package/session-distill/runlib/targets.py +809 -0
  111. package/session-distill/runlib/usage.py +280 -0
  112. package/session-distill/runlib/validate.py +319 -0
  113. package/session-distill/runlib/views.py +4327 -0
  114. package/session-distill/schemas/adjudication.schema.json +35 -0
  115. package/session-distill/schemas/approval.schema.json +35 -0
  116. package/session-distill/schemas/census.schema.json +128 -0
  117. package/session-distill/schemas/checks.schema.json +207 -0
  118. package/session-distill/schemas/claim.schema.json +16 -0
  119. package/session-distill/schemas/confirmation.schema.json +24 -0
  120. package/session-distill/schemas/coverage.schema.json +66 -0
  121. package/session-distill/schemas/cross_review.schema.json +24 -0
  122. package/session-distill/schemas/event.schema.json +20 -0
  123. package/session-distill/schemas/evidence.schema.json +20 -0
  124. package/session-distill/schemas/expected_observation.schema.json +18 -0
  125. package/session-distill/schemas/form.schema.json +103 -0
  126. package/session-distill/schemas/intake.schema.json +71 -0
  127. package/session-distill/schemas/inventory.schema.json +872 -0
  128. package/session-distill/schemas/judge.schema.json +77 -0
  129. package/session-distill/schemas/ledger.schema.json +313 -0
  130. package/session-distill/schemas/observation.schema.json +16 -0
  131. package/session-distill/schemas/propose.schema.json +555 -0
  132. package/session-distill/schemas/read.schema.json +76 -0
  133. package/session-distill/schemas/reconsider.schema.json +122 -0
  134. package/session-distill/schemas/run.schema.json +150 -0
  135. package/session-distill/schemas/s7b.schema.json +200 -0
  136. package/session-distill/schemas/s9b.schema.json +28 -0
  137. package/session-distill/schemas/stitch.schema.json +25 -0
  138. package/session-distill/schemas/sweep.schema.json +25 -0
  139. package/session-distill/seats.json +149 -0
  140. package/session-distill/tables/allowed_pairs.json +257 -0
  141. package/session-distill/tables/controls.json +30 -0
  142. package/session-distill/tables/delivery_evidence.json +36 -0
  143. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  144. package/session-distill/tables/destinations.json +684 -0
  145. package/session-distill/tables/drift_layers.json +68 -0
  146. package/session-distill/tables/exposure_rules.json +192 -0
  147. package/session-distill/tables/placement_rules.json +148 -0
  148. package/session-distill/tables/propose_fixtures.json +154 -0
  149. package/session-distill/tables/ranking.json +194 -0
  150. package/session-distill/tables/redundancy.json +10 -0
  151. package/session-distill/tables/structural_rules.json +44 -0
  152. package/session-distill/tables/transition_fixtures.json +398 -0
  153. package/session-distill/tables/transitions.json +69 -0
  154. package/session-distill/tables/unit_outcome.json +67 -0
  155. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  156. package/wrappers/claude-run.sh +481 -33
  157. package/wrappers/claude_hermetic_evidence.py +1423 -0
  158. package/wrappers/codex-helm.sh +46 -15
  159. package/wrappers/codex-run.sh +183 -20
  160. package/wrappers/codex_frame_filter.py +1199 -0
  161. package/wrappers/codex_protocol.py +737 -0
  162. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,1102 @@
1
+ #!/usr/bin/env python3
2
+ """The window bound, owned once (design §5.4 as amended, record
3
+ `design/session-distill/2026-10-21T0026--cc0498f--input-bound-amendment.md`).
4
+
5
+ A view-window call keeps one rule, and before this module the rule existed twice: `views.py` cut
6
+ windows against its own copy and `dispatch.py` admitted calls against another, with two constants
7
+ spelled `INPUT_LIMIT` and `INPUT_BOUND`, check (a) in both, check (d) in only one, the excess record
8
+ written by neither, and the recovery rule in the side that cannot dispatch. Two implementations of
9
+ one rule is the defect; keeping them in step is not the fix.
10
+
11
+ So the rule lives here and both sides import it: `views.py` to decide how large a window may be,
12
+ `dispatch.py` to admit a call, settle it, stop the run and lift the stop. This module is **pure** -
13
+ standard library only, no `runlib` import, no file read, no clock - so it cannot grow a second
14
+ opinion about where the run's state lives. Its callers supply the state and raise its refusals.
15
+
16
+ The rule, in the amendment's own terms:
17
+
18
+ * **(a)** what the driver sends in one call, plus the host's declared allowance, stays within
19
+ `INPUT_BOUND` tokens, each token covering at least one byte;
20
+ * **(d)** that payload, the allowance and the reserved output together stay within the seat's
21
+ context capacity;
22
+ * **settlement** - the input a view-window call really read (prompt input + cache creation + cache
23
+ read) is compared with `INPUT_BOUND` after the call; above it, the host changed;
24
+ * an excess **stops the run**, recorded once with the declaration it ran under;
25
+ * the stop **lifts only** on a re-measured `host_allowance`, declared later than that record.
26
+
27
+ A call's **claim** (W review of WP-08e r1 F4, r2; lead decisions) is the second obligation this module
28
+ owns: the call's first request within its reserved estimate, at most the declared retries, each within
29
+ its step (`claim_breaches`). A breach stops the run as `CLAIM_EXCEEDED`, lifted only by a later amendment
30
+ of `retry`. Each obligation's stop is its own record and stands until its own key is amended later than
31
+ it (`kept`, `standing`); the run is open when none stands.
32
+
33
+ A call that carries no view window is bound by none of this: its own section's contract holds, and
34
+ an R-authoring call is a non-window call by definition (design §8.6).
35
+ """
36
+
37
+ import hashlib
38
+ import json
39
+ import pathlib
40
+ import re
41
+ import sys
42
+
43
+ INPUT_BOUND = 120_000 # tokens; the driver's bytes plus the host allowance stay within this
44
+ PACKET_OVERHEAD = 12_288 # bytes of template, schema and instructions a packet adds to a window
45
+
46
+ # There is no constant for the seat's context capacity, and none for the output reservation. Both were
47
+ # invented numbers, and one of them was false: the capacity is host-reported evidence `seats.json`
48
+ # declares per seat (BA#1), and the reservation is THIS CALL's declared output cap - what the call
49
+ # reserved for its answer, not what the host would allow it (the lead's ruling of 2026-10-22). `limits`
50
+ # therefore requires both, so neither reader can fall back on a number nobody chose.
51
+
52
+ STOP_CODE = "INPUT_BOUND_EXCEEDED"
53
+ AMENDED_KEY = "host_allowance" # the only declaration key whose amendment lifts this stop
54
+
55
+ # The "at most" claim a call is admitted under (W review of WP-08e r1, F4; lead decision): one call's requests, the
56
+ # host's retries of a refused structured output included, number at most the claimed count and each takes at most the
57
+ # claimed input. A request past it is a named stop of the run, recorded and lifted as the bound's excess is - and only
58
+ # by a later amendment of the declaration's `retry` (a re-declared margin or retry count).
59
+ CLAIM_CODE = "CLAIM_EXCEEDED"
60
+ CLAIM_AMENDED_KEY = "retry"
61
+ LIFTED_BY = {STOP_CODE: AMENDED_KEY, CLAIM_CODE: CLAIM_AMENDED_KEY}
62
+
63
+
64
+ # ---- the limits one call keeps ---------------------------------------------------------------
65
+
66
+ def limits(allowance, *, capacity, reservation, seat=None, overhead=PACKET_OVERHEAD):
67
+ """The bound a view-window call keeps: a declared `allowance`, the seat's declared `capacity`, and
68
+ the call's own declared output `reservation`.
69
+
70
+ `capacity` and `reservation` are keyword-only and have no defaults on purpose - see above."""
71
+ return {"seat": seat, "allowance": allowance, "capacity": capacity, "reservation": reservation,
72
+ "overhead": overhead}
73
+
74
+
75
+ def driver_budget(limits):
76
+ """Bytes the driver may supply in one view-window call: the tighter of (a) and (d)."""
77
+ return min(INPUT_BOUND - limits["allowance"],
78
+ limits["capacity"] - limits["reservation"] - limits["allowance"])
79
+
80
+
81
+ def check_bound(driver_bytes, limits):
82
+ """Violations of the two pre-dispatch checks for a view-window call; empty when both hold."""
83
+ errors = []
84
+ if driver_bytes > INPUT_BOUND - limits["allowance"]:
85
+ errors.append(f"WINDOW_BOUND_EXCEEDED (a): {driver_bytes} driver bytes exceed {INPUT_BOUND} - the declared "
86
+ f"allowance {limits['allowance']} = {INPUT_BOUND - limits['allowance']}")
87
+ if driver_bytes + limits["allowance"] + limits["reservation"] > limits["capacity"]:
88
+ errors.append(f"WINDOW_CAPACITY_EXCEEDED (d): {driver_bytes} driver bytes + allowance {limits['allowance']} + "
89
+ f"output reservation {limits['reservation']} exceed the seat's context capacity "
90
+ f"{limits['capacity']}")
91
+ return errors
92
+
93
+
94
+ # ---- what the driver sends ------------------------------------------------------------------
95
+
96
+ BY_CONTENT = "appended_prompts" # the one declared kind with no path form - see `part_body`
97
+
98
+ # What a declared part can be refused for. The dispatcher raises these under the call id, computing the
99
+ # code from the problem rather than writing it, so its refusal inventory reads this tuple instead of a
100
+ # literal; the self-test below plants a part of each shape and requires every member to fire.
101
+ PART_CODES = ("DRIVER_PART_UNCOUNTED", "DRIVER_PART_LENGTH_CONFLICT", "APPENDED_PROMPT_PATH_FORM")
102
+
103
+
104
+ def part_body(part, kind=None):
105
+ """`(body, problem)` - the EXACT bytes of one declared driver part, read or encoded ONCE.
106
+
107
+ Everything else about the part derives from these bytes and from nothing else: the length admission
108
+ counts, the sha256 and the length the call record carries, and what the adapter delivers. Deriving
109
+ them from separate reads is how a record came to hash a whole prompt while admitting the length of
110
+ something else (BB#1), so there is one read here and no second one anywhere.
111
+
112
+ A part is text, or bytes, or a record carrying `text`, an already-read `body`, or a `path` this
113
+ process can read. A part that is none of those is **not counted as zero** - it is reported, because
114
+ an uncountable part makes the driver's share unknown, and understating that share is the one failure
115
+ the bound exists to prevent.
116
+
117
+ `kind` is the manifest key the part was declared under, because one of them admits no path: an
118
+ appended system prompt is declared by its content (BB#3) - the path form produced a record the call
119
+ schema rejects and nothing ever read it back - while an instruction file IS a path on the host and
120
+ keeps it."""
121
+ if isinstance(part, bytes):
122
+ return part, None
123
+ if isinstance(part, str):
124
+ return part.encode("utf-8"), None
125
+ if not isinstance(part, dict):
126
+ return None, f"DRIVER_PART_UNCOUNTED {type(part).__name__}: a declared part that is not text, bytes or a record"
127
+ if kind == BY_CONTENT and "path" in part:
128
+ # BEFORE any content is chosen (BC#3). A prompt carrying both content and a path used to pass
129
+ # here on its content and be recorded with the path beside it, which CALL_SCHEMA then rejects -
130
+ # after the call was launched. The field's presence is the refusal, not which branch wins.
131
+ return None, (f"APPENDED_PROMPT_PATH_FORM {part.get('path')!r}: an appended system prompt is declared by its "
132
+ f"content, and this declaration carries a path; the path form is the instruction file's, and "
133
+ f"this kind has none")
134
+ if isinstance(part.get("body"), bytes): # a snapshot: these bytes were read once already
135
+ return part["body"], None
136
+ if isinstance(part.get("text"), str):
137
+ return part["text"].encode("utf-8"), None
138
+ if isinstance(part.get("path"), str):
139
+ try:
140
+ return pathlib.Path(part["path"]).read_bytes(), None
141
+ except OSError as exc:
142
+ return None, (f"DRIVER_PART_UNCOUNTED {part['path']}: {exc.strerror or exc}; a declared part this process "
143
+ f"cannot read leaves the driver's share unknown")
144
+ return None, (f"DRIVER_PART_UNCOUNTED {sorted(part)}: a declared part carries neither content nor a readable "
145
+ f"path, so the driver's share cannot be counted")
146
+
147
+
148
+ def asserted_length_problem(part, body):
149
+ """The problem when a caller's asserted length disagrees with the bytes ALREADY READ, else None.
150
+
151
+ It takes the body rather than the part, so the check cannot be the reason a file is read a second
152
+ time (BC#1): one read, and the assertion is judged against exactly those bytes. The only thing an
153
+ assertion can do here is disagree - believing it instead let a part hash 130 KB of prompt and be
154
+ admitted as one byte (BB#1)."""
155
+ asserted = part.get("bytes") if isinstance(part, dict) else None
156
+ if asserted is None or (isinstance(asserted, int) and not isinstance(asserted, bool)
157
+ and asserted == len(body)):
158
+ return None
159
+ return (f"DRIVER_PART_LENGTH_CONFLICT {part.get('name') or part.get('path') or sorted(part)}: the part "
160
+ f"asserts {asserted!r} bytes and its content is {len(body)}; the length admission counts, the "
161
+ f"length the record carries and the bytes the host receives are one snapshot, so a number that "
162
+ f"disagrees with them is refused rather than believed")
163
+
164
+
165
+ def part_bytes(part, kind=None):
166
+ """`(bytes, problem)` for one declared driver part: the length of its own bytes."""
167
+ body, problem = part_body(part, kind)
168
+ if problem:
169
+ return 0, problem
170
+ problem = asserted_length_problem(part, body)
171
+ return (0, problem) if problem else (len(body), None)
172
+
173
+
174
+ def part_snapshot(part, kind=None):
175
+ """`(snapshot, problem)` - one declared part read ONCE: its bytes, their sha256 and their length.
176
+
177
+ One `part_body` call and nothing else reads: the length, the hash and the bytes the adapter is
178
+ handed all come off this body, and an asserted length is judged against it rather than against a
179
+ second read of the same path (BC#1). A snapshot is itself a part (its `body`), so the counter takes
180
+ it without reading anything again and the record keeps `evidence_of` it."""
181
+ body, problem = part_body(part, kind)
182
+ if problem:
183
+ return None, problem
184
+ problem = asserted_length_problem(part, body)
185
+ if problem:
186
+ return None, problem
187
+ snapshot = {"body": body, "sha256": hashlib.sha256(body).hexdigest(), "bytes": len(body)}
188
+ for key in ("name", "path"):
189
+ if isinstance(part, dict) and isinstance(part.get(key), str):
190
+ snapshot[key] = part[key]
191
+ return snapshot, None
192
+
193
+
194
+ def evidence_of(snapshot):
195
+ """What a snapshot is RECORDED as: everything about it but the bytes themselves."""
196
+ return {key: value for key, value in snapshot.items() if key != "body"}
197
+
198
+
199
+ DECLARED_PARTS = ("instructions", BY_CONTENT)
200
+
201
+
202
+ def driver_parts(packet, schema_bytes=None, manifest=None):
203
+ """`(part, kind)` for every part of one call that the DRIVER supplies, in the order counted.
204
+
205
+ The packet (its template, the principles block and the window payload are one object by the time
206
+ it is built), the schema, and what the call's own manifest declares it carries: instruction files
207
+ and appended system prompts. The packet and the schema are bytes of no declared kind, so their
208
+ `kind` is None.
209
+
210
+ What the **host** loads by itself under the profile is not here. That is the measured allowance,
211
+ and counting it again on the driver's side would charge the same tokens twice - which is why this
212
+ takes the call's own manifest and never the merged one that carries `seats.json`'s builtin
213
+ context. Files merely readable in the working directory are not sent, so they are not counted
214
+ either: a read shows up in the observed input, and settlement is what catches it."""
215
+ parts = [(packet, None)]
216
+ if schema_bytes is not None:
217
+ parts.append((schema_bytes, None))
218
+ declared = manifest or {}
219
+ for key in DECLARED_PARTS:
220
+ for item in declared.get(key) or []:
221
+ parts.append((item, key))
222
+ return parts
223
+
224
+
225
+ def part_evidence(part, kind=None):
226
+ """`(record, problem)` - what a declared driver part is RECORDED as, from the bytes just read.
227
+
228
+ One representation for both readers: the payload count needs the content, and the call record needs
229
+ evidence of it that a schema can close over. So a caller declares a part by its content - `text`, or
230
+ an instruction file's `path` to read - and what the record keeps is its name, its sha256 and its
231
+ length. A part that only asserts a number is not evidence of anything, and a record of text nobody
232
+ counted is not either (BA#2)."""
233
+ snapshot, problem = part_snapshot(part, kind)
234
+ return (None, problem) if problem else (evidence_of(snapshot), None)
235
+
236
+
237
+ def declared_snapshots(manifest):
238
+ """`(snapshots, problems)` - the call's declared parts, each read once, by manifest key.
239
+
240
+ This is the single read. `declared_evidence` records these snapshots, `driver_bytes` counts them,
241
+ and the dispatcher delivers their bytes, so the three readers cannot disagree (BB#1)."""
242
+ snapshots, problems = {}, []
243
+ for key in DECLARED_PARTS:
244
+ if not (manifest or {}).get(key):
245
+ continue
246
+ rows = []
247
+ for part in manifest[key]:
248
+ snapshot, problem = part_snapshot(part, key)
249
+ if problem:
250
+ problems.append(problem)
251
+ else:
252
+ rows.append(snapshot)
253
+ snapshots[key] = rows
254
+ return snapshots, problems
255
+
256
+
257
+ def declared_evidence(manifest):
258
+ """`(manifest, problems)` - the call's manifest with every declared driver part recorded as evidence.
259
+
260
+ The dispatcher writes this into the call record, so what the gate reads is the sha256 and length of
261
+ the bytes the payload count actually counted."""
262
+ snapshots, problems = declared_snapshots(manifest)
263
+ out = dict(manifest or {})
264
+ for key, rows in snapshots.items():
265
+ out[key] = [evidence_of(row) for row in rows]
266
+ return out, problems
267
+
268
+
269
+ def driver_bytes(packet, schema_bytes=None, manifest=None):
270
+ """`(bytes, problems)` - the UTF-8 size of everything the driver sends for one call.
271
+
272
+ Counting the window alone understates the driver's part by exactly the overhead the bound exists
273
+ to include, which is why this is the only counter and both sides call it."""
274
+ total, problems = 0, []
275
+ for part, kind in driver_parts(packet, schema_bytes, manifest):
276
+ size, problem = part_bytes(part, kind)
277
+ total += size
278
+ if problem:
279
+ problems.append(problem)
280
+ return total, problems
281
+
282
+
283
+ def admitted_parts(packet, schema_bytes=None, manifest=None):
284
+ """`(driver_bytes, evidence, snapshots, problems)` for one call, from ONE read of each part.
285
+
286
+ The dispatcher's entry point, and the reason the three answers agree by construction: the parts are
287
+ read here, the count is taken over those snapshots, the evidence is those snapshots without their
288
+ bytes, and the snapshots themselves are what the adapter is handed to deliver (BB#1, BB#2)."""
289
+ snapshots, problems = declared_snapshots(manifest)
290
+ evidence = dict(manifest or {})
291
+ for key, rows in snapshots.items():
292
+ evidence[key] = [evidence_of(row) for row in rows]
293
+ total, counting = driver_bytes(packet, schema_bytes, {**(manifest or {}), **snapshots})
294
+ return total, evidence, snapshots, problems + [p for p in counting if p not in problems]
295
+
296
+
297
+ # ---- what the call really read ---------------------------------------------------------------
298
+
299
+ # the three components of observed input, in the two spellings the artifacts use: a capture's
300
+ # what `observed_rows` reports for a row it could not read at all
301
+ ROW_UNREADABLE = "row-unreadable"
302
+
303
+ # Anthropic-shaped usage, and a usage record's own request rows
304
+ INPUT_PARTS = (("input_tokens", "input"),
305
+ ("cache_creation_input_tokens", "cache_creation"),
306
+ ("cache_read_input_tokens", "cache_read"))
307
+
308
+
309
+ def countable(value):
310
+ """A host-reported token count: a whole number, not negative, and not a bool.
311
+
312
+ `isinstance(x, int)` admits `True` and `-20000`, and both were counted (HC#4): a negative cache
313
+ field cancelled an otherwise conclusive excess, and a bool was read as one token. Neither is a
314
+ count, so both are reported as missing instead."""
315
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
316
+
317
+
318
+ def render_count(value):
319
+ """A count rendered for a diagnostic, never raising.
320
+
321
+ Python refuses to format an integer past its digit limit, so a stop could fail on its own
322
+ message with the excess already observed (HC#0). A number this reader cannot render is still a
323
+ number the rule has decided about."""
324
+ try:
325
+ return f"{value}"
326
+ except Exception: # noqa: BLE001 - a diagnostic never decides anything
327
+ return "a count too large to render"
328
+
329
+
330
+ def observed_of(usage):
331
+ """`(observed, missing)` for one usage mapping, in either spelling.
332
+
333
+ The valid components are a LOWER BOUND on what that request put in front of the model, and they
334
+ are returned as one: a request whose input alone is past the bound is past the bound whatever its
335
+ cache fields failed to say (HC#1). A component that is missing or is not a count is reported
336
+ instead, independently, and never read as a zero."""
337
+ total, missing = 0, []
338
+ for spellings in INPUT_PARTS:
339
+ found = [usage.get(name) for name in spellings if countable(usage.get(name))]
340
+ if not found:
341
+ missing.append(spellings[0])
342
+ continue
343
+ total += found[0]
344
+ return total, missing
345
+
346
+
347
+ def row_observation(row, state="measured"):
348
+ """`(observed, missing)` for ONE request row, or `(None, missing)` when it is not in `state`.
349
+
350
+ The one per-row policy both readers share, so the live rows and the written record cannot
351
+ disagree about the same row (HC#1). It raises on nothing it is given."""
352
+ try:
353
+ if row.get("state", state) != state:
354
+ return None, []
355
+ total, missing = observed_of(row)
356
+ except Exception: # noqa: BLE001 - this reading decides a stop: it cannot raise
357
+ return None, [ROW_UNREADABLE]
358
+ return total, missing
359
+
360
+
361
+ def observed_rows(rows, state="measured"):
362
+ """`(observed, missing)` - the largest observation over the `state` rows, by a reading that
363
+ cannot raise.
364
+
365
+ The maximum, not the sum: the bound is what one request put in front of the model. A row that
366
+ cannot be read at all, or a container that cannot be walked, is reported in `missing` and never
367
+ hides another row's excess. `observed_input` is this same reading over a written usage record."""
368
+ totals, missing = [], []
369
+ try:
370
+ candidates = list(rows or [])
371
+ except Exception: # noqa: BLE001 - not even a sequence (HC#0)
372
+ return 0, [ROW_UNREADABLE]
373
+ for row in candidates:
374
+ total, gaps = row_observation(row, state)
375
+ if total is not None:
376
+ totals.append(total)
377
+ missing += [gap for gap in gaps if gap not in missing]
378
+ return (max(totals) if totals else 0), missing
379
+
380
+
381
+ def observed_input(requests, state="measured"):
382
+ """The same reading over a usage record's own request rows - one policy, two callers."""
383
+ return observed_rows(requests, state)
384
+
385
+
386
+ def check_observed(observed, view_window):
387
+ """After a call: a view-window call whose observed input is above the bound is a host change."""
388
+ if view_window and observed > INPUT_BOUND:
389
+ return [f"{STOP_CODE}: observed input {render_count(observed)} tokens exceeds {INPUT_BOUND} on a view-window "
390
+ "call; the host added more than the declared allowance - re-measure it and amend the declaration"]
391
+ return []
392
+
393
+
394
+ # ---- the one excess record, and the one way back ---------------------------------------------
395
+
396
+ def excess(call_id, observed, at):
397
+ """The run's stop entry for a bound excess - the single record of it, before it is committed.
398
+
399
+ One record, written where the stop is written, read where the stop is read; a second file beside it
400
+ would be a second thing to keep true. The sequence it is compared against is NOT in it yet: see
401
+ `committed`."""
402
+ return {"code": STOP_CODE, "call_id": call_id, "observed": observed, "at": at,
403
+ "detail": f"{STOP_CODE} {call_id}: a view-window call read {render_count(observed)} input tokens, past "
404
+ f"the {INPUT_BOUND} bound; the host changed, so the run stops"}
405
+
406
+
407
+ CLAIM_SHAPE = "CLAIM_SHAPE"
408
+
409
+
410
+ def _mains(rows):
411
+ return [r for r in list(rows or []) if isinstance(r, dict) and r.get("role") == "main"]
412
+
413
+
414
+ def claim_shape(rows, claim):
415
+ """The fields a rule needs for the rows that exist and the claim does not name, each named, or [] (lead's
416
+ verification of WP-08e commit 4, finding 1; lead decision). The request count is judged by `requests_at_most`, the
417
+ first request by `first`, a retry by `first` and `step`. A claim recorded before `step` was named holds a one-request
418
+ call; one with a retry row is not judged by a weaker rule but refused (`CLAIM_SHAPE`). Raises on nothing."""
419
+ if not claim:
420
+ return []
421
+ try:
422
+ mains, out = _mains(rows), []
423
+ if mains and not isinstance(claim.get("requests_at_most"), int):
424
+ out.append("the claim names no requests_at_most, which the request count is judged by")
425
+ if mains and not isinstance(claim.get("first"), int):
426
+ out.append("the claim names no first, which request 1 is judged by")
427
+ if len(mains) > 1 and not isinstance(claim.get("step"), int):
428
+ out.append(f"the claim names no step, which request 2 (a retry) is judged by, and the call made {len(mains)}")
429
+ return out
430
+ except Exception as exc: # noqa: BLE001 - a claim this cannot read is refused, by name
431
+ return [f"the claim could not be read: {exc!r}"]
432
+
433
+
434
+ def claim_breaches(rows, claim):
435
+ """The ways a call's request `rows` went past the claim it was admitted under, each named, or [] (W review of WP-08e
436
+ r1 F4, r2 F7; lead decisions). The claim (`{requests_at_most, first, step, input_at_most}`) holds the first request
437
+ and the claimed retries: at most `requests_at_most` main requests; the first within `first`, its reserved estimate;
438
+ the k-th retry within `first + k x step`. Each rule applies whenever the fields IT needs are present - the
439
+ first-request rule needs only `first` (lead decision, verification of commit 4); a rule whose field is absent judges
440
+ nothing here and `claim_shape` names the field, so no row is judged by a weaker rule. Every main row counts toward
441
+ the requests; a row's input is read only once it is measured. It decides a stop, so it raises on nothing: a claim
442
+ it cannot read is named as a breach (fail closed)."""
443
+ if not claim:
444
+ return []
445
+ try:
446
+ mains, out = _mains(rows), []
447
+ if isinstance(claim.get("requests_at_most"), int) and len(mains) > claim["requests_at_most"]:
448
+ out.append(f"{len(mains)} main requests, at most {claim['requests_at_most']}")
449
+ first, step = claim.get("first"), claim.get("step")
450
+ for k, row in enumerate(mains):
451
+ observed, _missing = row_observation(row)
452
+ if observed is None:
453
+ continue
454
+ if k == 0 and isinstance(first, int):
455
+ ceiling = first
456
+ elif k > 0 and isinstance(first, int) and isinstance(step, int):
457
+ ceiling = first + k * step
458
+ else:
459
+ continue # the rule's field is absent: `claim_shape` names it
460
+ if observed > ceiling:
461
+ out.append(f"request {k + 1} took {render_count(observed)} input tokens, at most {render_count(ceiling)}")
462
+ return out
463
+ except Exception as exc: # noqa: BLE001 - a claim this cannot read stops the run, by name
464
+ return [f"the claim could not be read: {exc!r}"]
465
+
466
+
467
+ def claim_problems(rows, claim):
468
+ """Every reason the rows are not within the claim: its breaches, then each field it lacks (`CLAIM_SHAPE: ...`). A
469
+ reader that decides a stop or a completion fails closed on either."""
470
+ return claim_breaches(rows, claim) + [f"{CLAIM_SHAPE}: {line}" for line in claim_shape(rows, claim)]
471
+
472
+
473
+ def claim_excess(call_id, rows, claim, at):
474
+ """The run's stop entry for a claim excess, before it is committed (`committed`): each breach and each missing field
475
+ by name (`claim_problems`), the main requests and the largest of them beside what was claimed. The measured values
476
+ stay in the call's own records."""
477
+ breaches = claim_problems(rows, claim)
478
+ mains = _mains(rows)
479
+ largest = observed_rows(mains)[0]
480
+ return {"code": CLAIM_CODE, "call_id": call_id, "requests": len(mains), "largest_input": largest,
481
+ "requests_at_most": claim.get("requests_at_most"), "input_at_most": claim.get("input_at_most"),
482
+ "first_at_most": claim.get("first"), "breaches": breaches, "at": at,
483
+ "detail": f"{CLAIM_CODE} {call_id}: {'; '.join(breaches)} - past the claim it was admitted under; the run "
484
+ "stops"}
485
+
486
+
487
+ def committed(entry, declaration_seq):
488
+ """The excess record as it is COMMITTED, stamped with the sequence recovery is measured from.
489
+
490
+ That sequence is the latest the declaration had reached when the stop was written - not the one the
491
+ call was reserved under. A call can be reserved at seq 2, an amendment of `host_allowance` can land at
492
+ seq 3 while the call is still running, and the call can then overrun: stamping the call's own sequence
493
+ would let that amendment - which was recorded BEFORE anybody knew the host had changed - lift the stop
494
+ it could not have anticipated. Recovery means a measurement taken after the overrun, so the sequence
495
+ must be read where the stop is committed, under the same lock."""
496
+ return {**entry, "declaration_seq": declaration_seq}
497
+
498
+
499
+ def lifted(stopped, amendments):
500
+ """Whether one stop no longer stands.
501
+
502
+ True only for a stop of `LIFTED_BY` that a **later** amendment of its own key follows: for a bound
503
+ stop the allowance re-measured, `host_allowance`; for a claim stop the retry re-declared, `retry`
504
+ (its margin or its count) - each through `declare --amend`, at a sequence after the record's. Any
505
+ other stop code is not this rule's to lift, and neither an unrelated amendment, nor the other
506
+ stop's key, nor one recorded earlier lifts it."""
507
+ key = LIFTED_BY.get((stopped or {}).get("code"))
508
+ if key is None:
509
+ return False
510
+ seq = stopped.get("declaration_seq")
511
+ if not isinstance(seq, int):
512
+ return False
513
+ for amendment in amendments or []:
514
+ if not isinstance(amendment.get("seq"), int) or amendment["seq"] <= seq:
515
+ continue
516
+ if any(str(path).split(".")[0] == key for path in amendment.get("diff") or {}):
517
+ return True
518
+ return False
519
+
520
+
521
+ def terminal(stopped):
522
+ """Whether a stop can never be lifted: nothing this rule knows will reopen the run.
523
+
524
+ Two shapes are terminal. A stop code this rule does not own is not its to lift, and a stop of
525
+ `LIFTED_BY` with no `declaration_seq` has nothing for an amendment to be later than - which is what
526
+ makes the unstamped stop of a lock timeout the end of the run."""
527
+ if not stopped:
528
+ return False
529
+ return stopped.get("code") not in LIFTED_BY or not isinstance(stopped.get("declaration_seq"), int)
530
+
531
+
532
+ def stands(stopped, amendments):
533
+ """Whether a stop still stands: recorded, and not lifted by a later amendment of its own key."""
534
+ return bool(stopped) and not lifted(stopped, amendments)
535
+
536
+
537
+ def as_stops(held):
538
+ """The run's stops as `{code: stop}`, one per obligation (W review of WP-08e r2; lead decision): a ledger written
539
+ before held one `stopped` entry or None, and reads as the mapping of that one."""
540
+ if not held:
541
+ return {}
542
+ if isinstance(held.get("code"), str):
543
+ return {held["code"]: held}
544
+ return dict(held)
545
+
546
+
547
+ def strongest(kept, offered):
548
+ """Which of two STANDING stop records of one obligation a run keeps: **a stop never weakens** (BD#0).
549
+
550
+ More than one call can settle an excess of one obligation - one timing out on the declaration lock
551
+ and recording an unstamped stop, another, already running, settling later with a stamped one. Writing
552
+ the newer entry over the older made the run recoverable by amendment while the reason the first stop
553
+ was unstamped had not gone away. So the entry kept is the stronger of the two:
554
+
555
+ * nothing kept yet - the offered stop;
556
+ * a terminal stop already kept - that one, unchanged;
557
+ * the offered stop terminal - the offered one;
558
+ * otherwise both are stamped, and the higher `declaration_seq` is kept, so recovery must pass the
559
+ LATEST excess rather than an earlier one; an equal sequence keeps what is already recorded.
560
+
561
+ Stops of different obligations never meet here: each is its own record (`kept`)."""
562
+ if not kept:
563
+ return offered
564
+ if not offered or terminal(kept):
565
+ return kept
566
+ if terminal(offered):
567
+ return offered
568
+ return offered if offered["declaration_seq"] > kept["declaration_seq"] else kept
569
+
570
+
571
+ def kept(stops, offered):
572
+ """`(stops, kept)`: the run's stops with `offered` recorded, and the record its obligation now keeps (W review of
573
+ WP-08e r2, F5 and F6; lead decision). A stop is a record per obligation and stands until its own key is amended
574
+ later than it; records of other obligations are not touched, so a lifted stop never combines with a later one and
575
+ each stop lifts by its own amendment, in any order.
576
+
577
+ Within one obligation the offered record meets the earlier one in `strongest`, and that is the standing rule too:
578
+ an earlier stamped record a later amendment lifted is older than any stamped offer - the lifting amendment precedes
579
+ the offer's stamp - so the new breach is kept and stands; an unstamped offer is terminal and kept either way; an
580
+ earlier terminal record never lifts, so it still stands and is kept."""
581
+ stops = as_stops(stops)
582
+ stops[offered["code"]] = strongest(stops.get(offered["code"]), offered)
583
+ return stops, stops[offered["code"]]
584
+
585
+
586
+ def standing(stops, amendments):
587
+ """The stops that stand, in the order they were recorded; the run is open iff there is none."""
588
+ return [s for s in as_stops(stops).values() if stands(s, amendments)]
589
+
590
+
591
+ def projection(stops, amendments):
592
+ """The one `stopped` entry a reader of the earlier ledger shape reads (lead's verification of WP-08e commit 4,
593
+ finding 2): None when no stop stands; the one standing stop itself; several standing - one unstamped record naming
594
+ them all, which that reader holds terminal, since it cannot know that each lifts by its own key. So a reader of the
595
+ earlier shape never reads open a run this one reads stopped; it can read stopped one this reads open, after both
596
+ keys are amended. `amendments` None - unread - holds every record standing."""
597
+ held = [s for s in as_stops(stops).values() if amendments is None or stands(s, amendments)]
598
+ if not held:
599
+ return None
600
+ if len(held) == 1:
601
+ return held[0]
602
+ return {**{k: v for k, v in held[0].items() if k != "declaration_seq"},
603
+ "stamp": "several-stops: " + ", ".join(f"{s.get('code')} at {s.get('call_id')}" for s in held)}
604
+
605
+
606
+ def stop_line(stopped):
607
+ """One standing stop as the dispatcher's contract spells it, `RUN_STOPPED <code> at <call_id>`, with its way back."""
608
+ if stopped.get("code") == STOP_CODE and not terminal(stopped):
609
+ return (f"RUN_STOPPED {STOP_CODE} at {stopped.get('call_id')}: observed {stopped.get('observed')} tokens; "
610
+ "every dispatch stays refused until host_allowance is re-measured and declared through "
611
+ "`declare --amend`")
612
+ if stopped.get("code") == CLAIM_CODE and not terminal(stopped):
613
+ return (f"RUN_STOPPED {CLAIM_CODE} at {stopped.get('call_id')}: {'; '.join(stopped.get('breaches') or [])}; "
614
+ f"every dispatch stays refused until the retry is re-declared (retry.count or retry.margin) through "
615
+ f"`declare --amend`")
616
+ return f"RUN_STOPPED {stopped.get('code')} at {stopped.get('call_id')}: nothing more is dispatched in this run"
617
+
618
+
619
+ def blocked(stops, amendments):
620
+ """None when dispatch may go on - no stop stands; else every standing stop, named, in the order recorded."""
621
+ lines = [stop_line(s) for s in standing(stops, amendments)]
622
+ return "; ".join(lines) if lines else None
623
+
624
+
625
+ # ---- self-test ------------------------------------------------------------------------------
626
+
627
+ def source_text():
628
+ """This module's own source, for the controls that hold it to its shape."""
629
+ return pathlib.Path(__file__).read_text(encoding="utf-8")
630
+
631
+
632
+ def self_test():
633
+ """The rule, over the shapes its two callers really hand it.
634
+
635
+ The controls the view side used to run against its own copy live here now, by the same names, so
636
+ moving the rule did not drop them: the (a) and (d) pair, the tighter-budget case, the complete
637
+ payload count, the observed-input settlement and its non-window exemption, and the stop's
638
+ lifting. What those names cannot cover - the real dispatch boundary - is controlled in
639
+ `dispatch.py`'s own self-test against retained captures."""
640
+ failures = []
641
+
642
+ def named(label, got, want=None):
643
+ if want is None:
644
+ if got:
645
+ failures.append(f"{label}: {got}")
646
+ elif not any(want in line for line in got):
647
+ failures.append(f"{label}: {want!r} is in none of {got}")
648
+
649
+ def expect(label, got, want):
650
+ if got != want:
651
+ failures.append(f"{label}: got {got!r}, expected {want!r}")
652
+
653
+ # the self-test's own numbers, and it says so: a capacity and a reservation are declared per seat and
654
+ # per call in production, and nothing here stands in for either
655
+ held = limits(4000, seat="claude:claude-sonnet-5-5/xhigh", capacity=200_000, reservation=32_000)
656
+
657
+ # (a) and (d), the pair that was split across two modules
658
+ named("bound (a) and (d): a window inside both checks passes", check_bound(1000, held))
659
+ named("control, bound (a): driver bytes above 120k minus the declared allowance are named",
660
+ check_bound(INPUT_BOUND - held["allowance"] + 1, held), "WINDOW_BOUND_EXCEEDED")
661
+ named("control, bound (d): driver bytes that pass (a) but leave no room for the output reservation are named",
662
+ check_bound(50_000, {**held, "capacity": 60_000}), "WINDOW_CAPACITY_EXCEEDED")
663
+ expect("bound (a) at its exact value is inside the bound",
664
+ check_bound(INPUT_BOUND - held["allowance"], held), [])
665
+ tighter = limits(4000, capacity=100_000, reservation=32_000)
666
+ expect("a run whose (d) check is the tighter bound has the smaller driver budget",
667
+ (driver_budget(tighter) < driver_budget(held), driver_budget(held)),
668
+ (True, INPUT_BOUND - held["allowance"]))
669
+
670
+ # the complete driver payload: the parts a call really sends, and nothing the host adds
671
+ window = "a window of blocks\n" * 40
672
+ packet = ("CALL-ID: r1/S3/t1/0a\nSTAGE: S3\n\nthe principles block\n=== PAYLOAD ===\n" + window).encode("utf-8")
673
+ schema = b'{"type":"object"}'
674
+ own_bytes = len(pathlib.Path(__file__).read_bytes())
675
+ instruction = {"path": str(pathlib.Path(__file__)), "kind": "project"}
676
+ prompt = {"text": "an appended system prompt"}
677
+ plain, plain_problems = driver_bytes(packet, schema)
678
+ expect("done-when 3(a): the gate counts the packet and the schema",
679
+ (plain, plain_problems), (len(packet) + len(schema), []))
680
+ expect("done-when 3(a): ... which is more than the window on its own, so the overhead the bound exists to "
681
+ "include is inside it", plain > len(window.encode("utf-8")), True)
682
+ carried, carried_problems = driver_bytes(packet, schema,
683
+ {"instructions": [instruction], "appended_prompts": [prompt]})
684
+ expect("done-when 3(a): the COMPLETE driver payload counts the declared instructions and appended prompts",
685
+ (carried - plain, carried_problems),
686
+ (own_bytes + len(prompt["text"].encode("utf-8")), []))
687
+ expect("done-when 3(a): ... and the planted parts are not zero, so the equality above is not a 0-byte one",
688
+ own_bytes + len(prompt["text"].encode("utf-8")) > 0, True)
689
+ # the host's own context is NOT the driver's part: the allowance already covers it
690
+ expect("the builtin context a host loads by itself is not counted on the driver's side",
691
+ driver_bytes(packet, schema, {"skills": [{"bytes": 9999}], "agents": [{"bytes": 9999}],
692
+ "hooks": [{"bytes": 9999}], "workdir_files": [{"bytes": 9999}]})[0],
693
+ plain)
694
+ named("control, done-when 3(a): a declared part this process cannot count is reported, never read as zero",
695
+ driver_bytes(packet, schema, {"instructions": [{"kind": "project"}]})[1], "DRIVER_PART_UNCOUNTED")
696
+ named("control, done-when 3(a): a declared part whose path cannot be read is reported",
697
+ driver_bytes(packet, schema, {"instructions": [{"path": "/nonexistent/instruction.md"}]})[1],
698
+ "DRIVER_PART_UNCOUNTED")
699
+
700
+ # BB#1: one read per part. The count, the record and the bytes the host receives come from one
701
+ # snapshot, so an asserted length is only ever something that can disagree with them.
702
+ conflicting = {"name": "stage.md", "text": "P" * 130_000, "bytes": 1}
703
+ named("control, BB#1: a part asserting a length its content contradicts is refused by name",
704
+ driver_bytes(packet, schema, {"appended_prompts": [conflicting]})[1], "DRIVER_PART_LENGTH_CONFLICT")
705
+ named("control, BB#1: ... and it is refused on the recording side too, so neither reader believes it",
706
+ declared_evidence({"appended_prompts": [conflicting]})[1], "DRIVER_PART_LENGTH_CONFLICT")
707
+ expect("control, BB#1: ... and the hash of the full content is not recorded beside the asserted length",
708
+ declared_evidence({"appended_prompts": [conflicting]})[0]["appended_prompts"], [])
709
+ expect("BB#1: an asserted length equal to the content is the content's length",
710
+ part_bytes({"text": "abc", "bytes": 3}), (3, None))
711
+ named("control, BB#1: a length asserted as something other than a whole number is refused",
712
+ [part_bytes({"text": "abc", "bytes": "3"})[1] or ""], "DRIVER_PART_LENGTH_CONFLICT")
713
+ # The files the BB#1 and BC#1 controls write and rewrite live in a scratch directory of their own, never
714
+ # beside this module: the source tree is what the umbrella's other legs read while this one runs.
715
+ import shutil
716
+ import tempfile
717
+ scratch = pathlib.Path(tempfile.mkdtemp(prefix="bound-selftest-"))
718
+ moving, counted_path = scratch / "part.md", scratch / "counted.md"
719
+ source_dir = pathlib.Path(__file__).resolve().parent
720
+ expect("its scratch files live outside the source tree the other umbrella legs read",
721
+ [str(p) for p in (moving, counted_path) if p.resolve().is_relative_to(source_dir)], [])
722
+ try:
723
+ moving.write_bytes(b"the bytes that were counted")
724
+ snapshot, snapshot_problem = part_snapshot({"name": "moving.md", "path": str(moving)})
725
+ moving.write_bytes(b"other bytes entirely, written after the snapshot")
726
+ expect("BB#1: a file edited after its snapshot changes neither the count nor the record",
727
+ (snapshot_problem, part_bytes(snapshot)[0], evidence_of(snapshot)["bytes"],
728
+ evidence_of(snapshot)["sha256"]),
729
+ (None, len(b"the bytes that were counted"), len(b"the bytes that were counted"),
730
+ hashlib.sha256(b"the bytes that were counted").hexdigest()))
731
+ expect("BB#1: ... and the snapshot still carries those exact bytes, which is what is delivered",
732
+ snapshot["body"], b"the bytes that were counted")
733
+ finally:
734
+ moving.unlink(missing_ok=True)
735
+ total, evidence_once, snapshots_once, once_problems = admitted_parts(
736
+ packet, schema, {"instructions": [instruction], "appended_prompts": [prompt]})
737
+ expect("BB#1: the dispatcher's one entry point gives the count, the evidence and the snapshots of one read",
738
+ (once_problems, total, [evidence_of(s) for s in snapshots_once["appended_prompts"]],
739
+ evidence_once["appended_prompts"], snapshots_once["appended_prompts"][0]["body"]),
740
+ ([], carried, evidence_once["appended_prompts"],
741
+ [{"sha256": hashlib.sha256(prompt["text"].encode("utf-8")).hexdigest(),
742
+ "bytes": len(prompt["text"].encode("utf-8"))}], prompt["text"].encode("utf-8")))
743
+ named("control, BB#1: a conflicting length refuses the whole entry point, not one of its three answers",
744
+ admitted_parts(packet, schema, {"appended_prompts": [conflicting]})[3], "DRIVER_PART_LENGTH_CONFLICT")
745
+
746
+ # BC#1: exactly one read per path-backed part. The count, the hash and the delivered bytes come off
747
+ # one body, and the asserted length is judged against THAT body - not against a second read, which is
748
+ # what `part_bytes` used to do inside `part_snapshot`.
749
+ real_read_bytes = pathlib.Path.read_bytes
750
+ try:
751
+ counted_path.write_bytes(b"ten bytes!")
752
+ reads = []
753
+
754
+ def counting_read(self):
755
+ reads.append(str(self))
756
+ return real_read_bytes(self)
757
+
758
+ pathlib.Path.read_bytes = counting_read
759
+ snapshot, snapshot_problem = part_snapshot({"name": "i.md", "path": str(counted_path), "bytes": 10})
760
+ pathlib.Path.read_bytes = real_read_bytes
761
+ expect("BC#1: a path-backed part is read exactly once, asserted length and all",
762
+ (snapshot_problem, reads.count(str(counted_path)),
763
+ (snapshot or {}).get("bytes"), (snapshot or {}).get("body")),
764
+ (None, 1, 10, b"ten bytes!"))
765
+ # ... and a source whose answer CHANGES between reads shows the same thing from the other side:
766
+ # a second read would be judged against the first body's assertion and refuse
767
+ bodies = [b"ten bytes!", b"1"]
768
+
769
+ def changing_read(self):
770
+ return bodies.pop(0) if str(self) == str(counted_path) else real_read_bytes(self)
771
+
772
+ pathlib.Path.read_bytes = changing_read
773
+ changed, changed_problem = part_snapshot({"name": "i.md", "path": str(counted_path), "bytes": 10})
774
+ pathlib.Path.read_bytes = real_read_bytes
775
+ expect("BC#1: a changing read source is read once, so the snapshot is self-consistent",
776
+ (changed_problem, (changed or {}).get("bytes"), (changed or {}).get("sha256"),
777
+ (changed or {}).get("body"), len(bodies)),
778
+ (None, 10, hashlib.sha256(b"ten bytes!").hexdigest(), b"ten bytes!", 1))
779
+ finally:
780
+ pathlib.Path.read_bytes = real_read_bytes
781
+ shutil.rmtree(scratch, ignore_errors=True)
782
+
783
+ # BB#3: an appended system prompt is declared by content; the path form is the instruction file's
784
+ named("control, BB#3: an appended prompt declared by path is refused at declaration",
785
+ declared_evidence({"appended_prompts": [{"name": "stage.md", "path": str(pathlib.Path(__file__))}]})[1],
786
+ "APPENDED_PROMPT_PATH_FORM")
787
+ named("control, BB#3: ... on the counting side as well",
788
+ driver_bytes(packet, schema, {"appended_prompts": [{"path": str(pathlib.Path(__file__))}]})[1],
789
+ "APPENDED_PROMPT_PATH_FORM")
790
+ expect("BB#3: ... while an instruction file's path is read as before",
791
+ declared_evidence({"instructions": [instruction]})[1], [])
792
+ # BC#3: and a declaration carrying BOTH content and a path is refused for the path, before either
793
+ # content branch is taken - that mixture used to pass on its content and be recorded with a `path`
794
+ # the call schema rejects, which is a deterministic failure discovered after the launch
795
+ for label, mixed in (("text and a path", {"name": "stage.md", "text": "hello", "path": "metadata.md"}),
796
+ ("body and a path", {"name": "stage.md", "body": b"hello", "path": "metadata.md"}),
797
+ ("a path of None", {"name": "stage.md", "text": "hello", "path": None})):
798
+ named(f"control, BC#3: an appended prompt declared with {label} is refused",
799
+ declared_snapshots({"appended_prompts": [mixed]})[1], "APPENDED_PROMPT_PATH_FORM")
800
+ named(f"control, BC#3: ... and counted nowhere ({label})",
801
+ driver_bytes(b"", None, {"appended_prompts": [mixed]})[1], "APPENDED_PROMPT_PATH_FORM")
802
+ expect("BC#3: ... and no record is produced for it, so nothing reaches the call schema",
803
+ declared_evidence({"appended_prompts": [{"name": "stage.md", "text": "hello",
804
+ "path": "metadata.md"}]})[0]["appended_prompts"], [])
805
+
806
+ # every code the dispatcher's part refusal can carry, each fired by a part of that shape: the inventory
807
+ # on the other side reads PART_CODES, so a code that no shape produces, or a shape whose code is not
808
+ # named here, is caught on this side
809
+ planted = {"DRIVER_PART_UNCOUNTED": {"instructions": [{"kind": "project"}]},
810
+ "DRIVER_PART_LENGTH_CONFLICT": {"appended_prompts": [conflicting]},
811
+ "APPENDED_PROMPT_PATH_FORM": {"appended_prompts": [{"path": str(pathlib.Path(__file__))}]}}
812
+ expect("PART_CODES names exactly the refusals a declared part is planted for", sorted(planted), sorted(PART_CODES))
813
+ for code, planted_manifest in planted.items():
814
+ problems = declared_snapshots(planted_manifest)[1]
815
+ named(f"control, PART_CODES: {code} is the leading word of the problem its shape produces",
816
+ [p.split()[0] for p in problems], code)
817
+
818
+ # BA#2: one representation - counted from the content, recorded as its hash and length
819
+ evidence, evidence_problems = declared_evidence(
820
+ {"instructions": [{"path": str(pathlib.Path(__file__)), "kind": "project"}],
821
+ "appended_prompts": [{"name": "stage.md", "text": "an appended system prompt"}]})
822
+ expect("BA#2: an appended prompt is counted from its text and recorded as its hash and length",
823
+ (evidence_problems, evidence["appended_prompts"]),
824
+ ([], [{"sha256": hashlib.sha256("an appended system prompt".encode("utf-8")).hexdigest(),
825
+ "bytes": len("an appended system prompt"), "name": "stage.md"}]))
826
+ expect("BA#2: an instruction file is counted from its bytes and recorded with its path",
827
+ (evidence["instructions"][0]["bytes"], evidence["instructions"][0]["path"]),
828
+ (own_bytes, str(pathlib.Path(__file__))))
829
+ expect("BA#2: the recorded length is the length the payload count counted",
830
+ driver_bytes(b"", None, {"appended_prompts": [{"text": "an appended system prompt"}]})[0],
831
+ evidence["appended_prompts"][0]["bytes"])
832
+ named("control, BA#2: a part that asserts a number instead of content is not evidence",
833
+ declared_evidence({"appended_prompts": [{"name": "x", "bytes": 10}]})[1], "DRIVER_PART_UNCOUNTED")
834
+ named("control, BA#2: a part whose path cannot be read is reported here too",
835
+ declared_evidence({"instructions": [{"path": "/nonexistent/i.md"}]})[1], "DRIVER_PART_UNCOUNTED")
836
+ expect("a manifest with no declared parts is returned unchanged",
837
+ declared_evidence({"skills": [{"bytes": 1}]}), ({"skills": [{"bytes": 1}]}, []))
838
+
839
+ # settlement, in both artifact spellings, with the missing-field refusal
840
+ capture = {"input_tokens": 100_000, "cache_creation_input_tokens": 10_000, "cache_read_input_tokens": 5_000}
841
+ rows = [{"state": "measured", "input": 100_000, "cache_creation": 10_000, "cache_read": 5_000}]
842
+ expect("done-when 3(b): observed input is input + cache creation + cache read", observed_of(capture), (115_000, []))
843
+ expect("the two artifact spellings of observed input give one number",
844
+ observed_of(capture)[0], observed_input(rows)[0])
845
+ expect("observed input is the largest request, not their sum",
846
+ observed_input(rows + [{"state": "measured", "input": 7, "cache_creation": 0, "cache_read": 0}])[0],
847
+ 115_000)
848
+ expect("an unmeasured request is not observed input",
849
+ observed_input([{"state": "unmeasured", "input": 999_999, "cache_creation": 0, "cache_read": 0}])[0], 0)
850
+ named("control, done-when 3(b): a usage mapping missing a cache field is reported, never read as a smaller number",
851
+ observed_of({"input_tokens": 1})[1], "cache_creation_input_tokens")
852
+ # HB#0: the live reading the stop decision rests on, which runs before anything has been written and
853
+ # must therefore survive every row shape the monitor can be left in
854
+ over_row = {"state": "measured", "input": 135_796, "cache_creation": 0, "cache_read": 0}
855
+ expect("HB#0: a complete row establishes its excess beside a row that cannot be read at all",
856
+ observed_rows([None, over_row]), (135_796, [ROW_UNREADABLE]))
857
+ expect("HB#0: ... and beside a row missing a component, which is listed rather than read as a zero",
858
+ observed_rows([{"state": "measured", "input": 1}, over_row]),
859
+ (135_796, ["cache_creation_input_tokens", "cache_read_input_tokens"]))
860
+ # HC#1: the valid components of a row are a LOWER BOUND, and a lower bound past the bound is an
861
+ # excess - the components that are missing are reported beside it, never instead of it
862
+ expect("HC#1: a partial row's valid components are what that request is known to have put in",
863
+ observed_rows([{"state": "measured", "input": 1, "cache_read": 2}]),
864
+ (3, ["cache_creation_input_tokens"]))
865
+ expect("HC#1: a row whose input alone is past the bound is an excess with a cache field missing",
866
+ (observed_rows([{"state": "measured", "input": 135_796, "cache_read": 0}])[0] > INPUT_BOUND,
867
+ observed_rows([{"state": "measured", "input": 135_796, "cache_read": 0}])[1]),
868
+ (True, ["cache_creation_input_tokens"]))
869
+ expect("HC#4: a negative component is not a count, so it cannot cancel an excess",
870
+ observed_rows([{"state": "measured", "input": 135_796, "cache_creation": 0, "cache_read": -20_000}]),
871
+ (135_796, ["cache_read_input_tokens"]))
872
+ expect("HC#4: a bool component is not a count either",
873
+ observed_rows([{"state": "measured", "input": 135_796, "cache_creation": True, "cache_read": 0}]),
874
+ (135_796, ["cache_creation_input_tokens"]))
875
+ def guarded(fn, *args):
876
+ """What `fn` answered, or what it raised - a reading that must not raise is judged by a control
877
+ that can SAY it raised, rather than dying with it (BD#4)."""
878
+ try:
879
+ return fn(*args)
880
+ except Exception as exc: # noqa: BLE001 - the raise IS the finding
881
+ return f"raised: {exc!r}"
882
+
883
+ expect("HC#0: a container that cannot even be walked is reported, not raised",
884
+ guarded(observed_rows, 7), (0, [ROW_UNREADABLE]))
885
+ # HC#1: and the two readers cannot disagree, because they are one reading
886
+ shapes = ([], [None], 7, [{"state": "measured", "input": 135_796, "cache_read": 0}],
887
+ [{"state": "measured", "input": 1, "cache_creation": 0, "cache_read": 2}],
888
+ [{"state": "measured", "input": -1, "cache_creation": 0, "cache_read": 0}],
889
+ [{"state": "measured", "input": True, "cache_creation": 0, "cache_read": 0}],
890
+ [{"state": "sent", "input": 999_999, "cache_creation": 0, "cache_read": 0}],
891
+ [{"state": "measured", "input": 2, "cache_creation": 0, "cache_read": 0},
892
+ {"state": "measured", "input": 135_796, "cache_creation": 0, "cache_read": 0}])
893
+ expect("HC#1: the live rows and the written record are read by one policy",
894
+ [guarded(observed_rows, shape) for shape in shapes],
895
+ [guarded(observed_input, shape) for shape in shapes])
896
+ expect("control, HC#1: and that table is not empty, nor all one answer",
897
+ (len(shapes) >= 9, len({str(guarded(observed_rows, shape)) for shape in shapes}) > 1), (True, True))
898
+ expect("HB#0: an unmeasured row is not a live observation either",
899
+ observed_rows([{"state": "sent", "input": 999_999, "cache_creation": 0, "cache_read": 0}])[0], 0)
900
+ expect("HB#0: the reading raises on no shape it can be given",
901
+ [observed_rows(rows_in)[0] for rows_in in
902
+ (None, [], [None], ["not a row"], [{"state": "measured", "input": "x"}], [over_row])],
903
+ [0, 0, 0, 0, 0, 135_796])
904
+ named("observed input: a view-window call within 120k is accepted", check_observed(INPUT_BOUND, True))
905
+ named("control, observed input: a view-window call above 120k is a host change",
906
+ check_observed(INPUT_BOUND + 1, True), STOP_CODE)
907
+ named("observed input: the same observation on a call that carries no view window is accepted, so the R "
908
+ "authoring of §8.6 keeps its own section's contract", check_observed(136_000, False))
909
+
910
+ # the one record, and the one way back
911
+ stop = committed(excess("r1/S3/t1/0a", 135_796, "2026-10-22T09:00:00+09:00"), 2)
912
+ expect("the committed excess record carries the sequence recovery is measured from",
913
+ (stop["code"], stop["declaration_seq"], stop["observed"]), (STOP_CODE, 2, 135_796))
914
+ named("the excess record's detail names the call and the bound", [stop["detail"]], "r1/S3/t1/0a")
915
+ expect("dispatch is open before any excess is recorded", blocked(None, []), None)
916
+ named("an excess blocks dispatch", [blocked(stop, []) or ""], f"RUN_STOPPED {STOP_CODE}")
917
+ later_unrelated = [{"seq": 3, "diff": {"caps.S3": 1}}]
918
+ named("control, M4: an amendment of another key does not lift the stop",
919
+ [blocked(stop, later_unrelated) or ""], STOP_CODE)
920
+ earlier = [{"seq": 1, "diff": {"host_allowance.claude:claude-sonnet-5-5/xhigh": 4000}}]
921
+ named("control, M4: a host_allowance amendment recorded EARLIER than the excess does not lift it",
922
+ [blocked(stop, earlier) or ""], STOP_CODE)
923
+ same_seq = [{"seq": 2, "diff": {"host_allowance.x": 1}}]
924
+ named("control, M4: a host_allowance amendment at the same sequence does not lift it",
925
+ [blocked(stop, same_seq) or ""], STOP_CODE)
926
+ later = [{"seq": 3, "diff": {"host_allowance.claude:claude-sonnet-5-5/xhigh": 4200}}]
927
+ expect("M4: a host_allowance amendment recorded after the excess lifts the stop", blocked(stop, later), None)
928
+ expect("M4: ... and the excess record is still there, so recovery does not forget it",
929
+ (stop["call_id"], stop["observed"]), ("r1/S3/t1/0a", 135_796))
930
+ # BD#0: a stop never weakens. Two calls can settle an excess in one run, and the entry kept is the
931
+ # stronger - which is what keeps an unstamped stop from being replaced by a stamped one an amendment
932
+ # can then pass.
933
+ unstamped = {**excess("r1/S3/t1/0a", 135_796, "now"), "stamp": "lock-timeout: declaration"}
934
+ stamped_low = committed(excess("r1/S3/t1/0b", 130_001, "now"), 2)
935
+ stamped_high = committed(excess("r1/S3/t1/0c", 130_002, "now"), 5)
936
+ expect("BD#0: the first stop of a run is kept", strongest(None, unstamped), unstamped)
937
+ expect("BD#0: an unstamped stop is terminal, so no later stamped stop replaces it",
938
+ strongest(unstamped, stamped_high), unstamped)
939
+ expect("control, BD#0: ... and the run is still blocked after an amendment later than that stamp",
940
+ blocked(strongest(unstamped, stamped_high), [{"seq": 9, "diff": {"host_allowance.a": 1}}]) is not None,
941
+ True)
942
+ expect("BD#0: between two stamped stops the higher sequence is kept",
943
+ (strongest(stamped_low, stamped_high), strongest(stamped_high, stamped_low)),
944
+ (stamped_high, stamped_high))
945
+ expect("control, BD#0: ... so an amendment between the two sequences does not lift the run",
946
+ blocked(strongest(stamped_low, stamped_high), [{"seq": 3, "diff": {"host_allowance.a": 1}}]) is not None,
947
+ True)
948
+ expect("BD#0: an equal sequence keeps what is already recorded",
949
+ strongest(stamped_low, committed(excess("x", 1, "now"), 2)), stamped_low)
950
+ expect("BD#0: a stop this rule does not own is terminal and is not replaced",
951
+ strongest({"code": "PROVIDER_DEFERRED", "call_id": "x"}, stamped_high)["code"], "PROVIDER_DEFERRED")
952
+ expect("BD#0: an unstamped stop offered against a stamped one is the stronger",
953
+ strongest(stamped_low, unstamped), unstamped)
954
+ expect("BD#0: terminal is the shape nothing lifts, in both of its forms",
955
+ (terminal(None), terminal(unstamped), terminal(stamped_low),
956
+ terminal({"code": "PROVIDER_DEFERRED", "declaration_seq": 2})),
957
+ (False, True, False, True))
958
+
959
+ other = {"code": "PROVIDER_DEFERRED", "call_id": "r1/S3/t1/0b", "declaration_seq": 2}
960
+ expect("a stop this rule does not own is not lifted by a host_allowance amendment",
961
+ lifted(other, later), False)
962
+ named("... and it still blocks dispatch under its own code", [blocked(other, later) or ""], "RUN_STOPPED")
963
+ expect("a bound stop with no declaration sequence is not lifted by anything",
964
+ lifted({"code": STOP_CODE, "call_id": "x"}, later), False)
965
+ expect("control, BA#0: an uncommitted excess record carries no sequence, so nothing lifts it",
966
+ ("declaration_seq" in excess("x", 1, "now"),
967
+ lifted(excess("x", 1, "now"), later)), (False, False))
968
+ expect("control, BA#0: the sequence a stop is stamped with is the one the COMMIT read, not the call's",
969
+ (committed(excess("x", 1, "now"), 7)["declaration_seq"],
970
+ lifted(committed(excess("x", 1, "now"), 7), [{"seq": 5, "diff": {"host_allowance.a": 1}}]),
971
+ lifted(committed(excess("x", 1, "now"), 7), [{"seq": 8, "diff": {"host_allowance.a": 1}}])),
972
+ (7, False, True))
973
+
974
+ # W r1 F4, W r2 F5-F7: a call's claim, its own stop and its own way back
975
+ def main(observed):
976
+ return {"role": "main", "state": "measured", "input": observed, "cache_read": 0, "cache_creation": 0}
977
+ claim = {"requests_at_most": 2, "first": 43_795, "step": 33_118, "input_at_most": 76_913}
978
+ expect("F4: a first request within its estimate and a retry within its step are no breach, nor is any call "
979
+ "without a claim", (claim_breaches([main(43_795), main(76_913)], claim), claim_breaches([main(10**9)], None)),
980
+ ([], []))
981
+ named("control, F4: a third main request is a breach, named by its count",
982
+ claim_breaches([main(40_000), main(40_000), main(40_000)], claim), "3 main requests, at most 2")
983
+ named("control, F4: a retry past its step is a breach, named by its place",
984
+ claim_breaches([main(40_000), main(76_914)], claim), f"request 2 took {render_count(76_914)} input tokens")
985
+ named("control, W r2 F7: a first request past its reserved estimate is a breach though it is within the last "
986
+ "retry's ceiling", claim_breaches([main(95_000), main(95_600)],
987
+ {"requests_at_most": 2, "first": 53_795, "step": 42_000,
988
+ "input_at_most": 95_795}),
989
+ f"request 1 took {render_count(95_000)} input tokens, at most {render_count(53_795)}")
990
+ # the lead's verification of commit 4, finding 1: each rule applies when the fields IT needs are present
991
+ old_shape = {"requests_at_most": 2, "first": 88_352, "input_at_most": 93_566} # recorded before `step` existed
992
+ named("control, lead v4 1: an old-shape claim (no step), its one request above first, is a breach by name - the "
993
+ "first-request rule needs only first", claim_breaches([main(90_352)], old_shape),
994
+ f"request 1 took {render_count(90_352)} input tokens, at most {render_count(88_352)}")
995
+ named("control, lead v4 1: an old-shape claim with two main requests names the step its retry rule needs "
996
+ "(CLAIM_SHAPE), and is never judged by the per-request ceiling",
997
+ claim_shape([main(80_000), main(81_000)], old_shape), "the claim names no step")
998
+ expect("lead v4 1: an old-shape claim within first, one request: no breach, no shape problem",
999
+ (claim_breaches([main(88_352)], old_shape), claim_shape([main(88_352)], old_shape)), ([], []))
1000
+ expect("lead v4 1: a claim judges no request by input_at_most alone, and names the first it lacks",
1001
+ (claim_breaches([main(76_914)], {"requests_at_most": 2, "input_at_most": 76_913}),
1002
+ claim_problems([main(76_914)], {"requests_at_most": 2, "input_at_most": 76_913})),
1003
+ ([], ["CLAIM_SHAPE: the claim names no first, which request 1 is judged by"]))
1004
+ named("control, F4: a claim that cannot be read is a breach, so the stop fails closed",
1005
+ claim_breaches([main(1)], ["not", "a", "claim"]), "the claim could not be read")
1006
+ named("control, F4: ... and a shape that cannot be read is refused too",
1007
+ claim_shape([main(1)], ["not", "a", "claim"]), "the claim could not be read")
1008
+ claim_stop = committed(claim_excess("r1/S4/form/a0", [main(40_000), main(70_000), main(110_032)], claim, "now"), 4)
1009
+ for want in ("3 main requests, at most 2", f"request 3 took {render_count(110_032)} input tokens"):
1010
+ named("F4: the claim stop names each breach", [claim_stop["detail"]], want)
1011
+ for want in (f"RUN_STOPPED {CLAIM_CODE} at r1/S4/form/a0", "retry.count or retry.margin"):
1012
+ named("control, F4: a claim excess blocks dispatch by name", [blocked(claim_stop, []) or ""], want)
1013
+ named("control, F4: a host_allowance amendment does not lift a claim stop",
1014
+ [blocked(claim_stop, [{"seq": 5, "diff": {"host_allowance.a": 1}}]) or ""], CLAIM_CODE)
1015
+ named("control, F4: a retry amendment recorded before the stop does not lift it",
1016
+ [blocked(claim_stop, [{"seq": 4, "diff": {"retry.count": 2}}]) or ""], CLAIM_CODE)
1017
+ expect("F4: a later amendment of the retry lifts the claim stop, and not a bound stop",
1018
+ (blocked(claim_stop, [{"seq": 5, "diff": {"retry.count": 2}}]),
1019
+ lifted(committed(excess("x", 1, "now"), 4), [{"seq": 5, "diff": {"retry.margin": 4000}}])), (None, False))
1020
+ # one stop per obligation: both stand together, each lifts by its own key in either order (lead decision, W r2)
1021
+ bound_stop = committed(excess("r1/S3/w/a1", 130_000, "now"), 4)
1022
+ both, _kept = kept(kept({}, bound_stop)[0], claim_stop)
1023
+ allowance_5, retry_5 = {"seq": 5, "diff": {"host_allowance.a": 1}}, {"seq": 5, "diff": {"retry.count": 2}}
1024
+ retry_6, allowance_6 = {"seq": 6, "diff": {"retry.count": 2}}, {"seq": 6, "diff": {"host_allowance.a": 1}}
1025
+ expect("W r2: a bound stop and a claim stop of one run are two records, both standing, neither terminal",
1026
+ (sorted(both), [terminal(s) for s in both.values()], len(standing(both, []))),
1027
+ ([CLAIM_CODE, STOP_CODE], [False, False], 2))
1028
+ named("control, W r2 F3: host_allowance alone does not reopen a run a claim stop also stops",
1029
+ [blocked(both, [allowance_5]) or ""], f"RUN_STOPPED {CLAIM_CODE}")
1030
+ named("control, W r2 F3: the retry alone does not reopen a run a bound stop also stops",
1031
+ [blocked(both, [retry_5]) or ""], f"RUN_STOPPED {STOP_CODE}")
1032
+ expect("W r2: each lifts by its own amendment, in either order, and then the run is open",
1033
+ (blocked(both, [allowance_5, retry_6]), blocked(both, [retry_5, allowance_6])), (None, None))
1034
+ # W r2 F6: a lifted stop never combines with a later one of another obligation
1035
+ then_bound, _k = kept(as_stops(claim_stop), committed(excess("r1/S3/w/a2", 130_000, "now"), 5))
1036
+ expect("control, W r2 F6: a claim stop lifted, then a bound stop: the bound stop stands with its own sequence and "
1037
+ "host_allowance alone reopens the run",
1038
+ (then_bound[STOP_CODE].get("declaration_seq"), blocked(then_bound, [retry_5]) is not None,
1039
+ blocked(then_bound, [retry_5, allowance_6])), (5, True, None))
1040
+ then_claim, _k = kept(as_stops(bound_stop), committed(claim_excess("r1/S4/form/a1", [main(1)] * 3, claim, "now"),
1041
+ 5))
1042
+ expect("control, W r2 F6: a bound stop lifted, then a claim stop: the claim stop stands with its own sequence and "
1043
+ "the retry alone reopens the run",
1044
+ (then_claim[CLAIM_CODE].get("declaration_seq"), blocked(then_claim, [allowance_5]) is not None,
1045
+ blocked(then_claim, [allowance_5, retry_6])), (5, True, None))
1046
+ # W r2 F5: a new breach of an obligation whose earlier stop was lifted is persisted and stands
1047
+ again, held_again = kept(as_stops(claim_stop), committed(claim_excess("r1/S4/form/a2", [main(1)] * 3, claim, "now"),
1048
+ 5))
1049
+ expect("control, W r2 F5: a claim stop lifted by a retry amendment, then another claim breach: the new record is "
1050
+ "kept and stands",
1051
+ (held_again.get("call_id"), held_again.get("declaration_seq"), blocked(again, [retry_5]) is not None),
1052
+ ("r1/S4/form/a2", 5, True))
1053
+ expect("W r2: a standing stop of one obligation meets a new one by the strongest rule: an older or equal sequence "
1054
+ "keeps the standing record, an unstamped offer is kept",
1055
+ (kept(as_stops(claim_stop), committed(claim_excess("x", [main(1)] * 3, claim, "now"), 3))[1]["call_id"],
1056
+ kept(as_stops(claim_stop), {**claim_excess("y", [main(1)] * 3, claim, "now"), "stamp": "lock-timeout"})[1]
1057
+ ["call_id"]), ("r1/S4/form/a0", "y"))
1058
+ # the lead's verification of commit 4, finding 2: what a reader of the one-entry ledger shape reads
1059
+ expect("lead v4 2: the one-entry projection of the stops is None, the one standing stop, or one unstamped record "
1060
+ "naming every standing stop",
1061
+ (projection({}, []), projection(as_stops(claim_stop), []) is claim_stop,
1062
+ projection(as_stops(claim_stop), [retry_5]),
1063
+ terminal(projection(both, [])), "several-stops: " in (projection(both, []) or {}).get("stamp", ""),
1064
+ projection(both, [allowance_5]) is both[CLAIM_CODE]),
1065
+ (None, True, None, True, True, True))
1066
+ expect("W r2: a ledger written with one stopped entry reads as the mapping of that one",
1067
+ (as_stops(None), as_stops(claim_stop), as_stops({CLAIM_CODE: claim_stop})),
1068
+ ({}, {CLAIM_CODE: claim_stop}, {CLAIM_CODE: claim_stop}))
1069
+
1070
+ # ... and neither invented number may come back
1071
+ import inspect
1072
+ signature = inspect.signature(limits)
1073
+ for name in ("capacity", "reservation"):
1074
+ if signature.parameters[name].default is not inspect.Parameter.empty:
1075
+ failures.append(f"limits() has a default for {name}, so a caller can fall back on a number nobody chose")
1076
+ # a module-level constant is an assignment at column 0, which is what this looks for - the names
1077
+ # appear in this file's own prose, and a text search would match itself
1078
+ back = re.search(r"^(OUTPUT_RESERVATION|CONTEXT_CAPACITY)\s*=", source_text(), re.M)
1079
+ if back:
1080
+ failures.append(f"a module-level {back.group(1)} constant is back, so a caller can fall back on it")
1081
+
1082
+ # the module is pure: a second opinion about where the run's state lives is what it exists to prevent
1083
+ source = source_text()
1084
+ for forbidden in ("from runlib", "import runlib", "open(", "subprocess"):
1085
+ if forbidden in source.split('"""The window bound', 1)[-1].split("def self_test", 1)[0]:
1086
+ failures.append(f"bound.py reaches for {forbidden!r} outside its self-test, so the rule has state of its own")
1087
+
1088
+ for line in failures:
1089
+ print(f"bound --self-test [FAIL] {line}")
1090
+ if failures:
1091
+ return 1
1092
+ print("bound --self-test: OK (the bound's two pre-dispatch checks, the complete driver payload with its "
1093
+ "uncountable-part refusals, one read per declared part with its conflicting-length and path-form "
1094
+ "refusals, observed-input settlement in both artifact spellings, the single excess record, and the "
1095
+ "recovery rule's five cases, and a call's claim with its own stop and its own way back)")
1096
+ return 0
1097
+
1098
+
1099
+ if __name__ == "__main__":
1100
+ sys.exit(self_test() if "--self-test" in sys.argv else
1101
+ (print(json.dumps({"INPUT_BOUND": INPUT_BOUND, "PACKET_OVERHEAD": PACKET_OVERHEAD,
1102
+ "STOP_CODE": STOP_CODE, "AMENDED_KEY": AMENDED_KEY}, indent=2)) or 0))