agent-bios 0.19.3 → 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 (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,1145 @@
1
+ #!/usr/bin/env python3
2
+ """The delivery evidence of design §6.3 (WP-10): for one unit, one session and the instant of the decision an event
3
+ concerns, the delivery state - `delivered`, `exposed_not_read`, `selected_unavailable`, `not_delivered` or `unknown` -
4
+ with the evidence level reached and every reason, read from `tables/delivery_evidence.json`.
5
+
6
+ Selection is not delivery. A unit is `delivered` only at the level its surface needs, before the decision:
7
+
8
+ - a rule on the always surface when the pin's selection holds its item, the compiled instruction text holds its
9
+ lines, its route is not unavailable, and the injection was recorded at or before the decision;
10
+ - a guide when its **unit read** holds: every requirement of the unit's operative context (the inventory's
11
+ `operative_context`: the unit, its frontmatter, the enclosing conditions, every operative unit it names, in any
12
+ guide) is covered by bytes a read actually returned before the decision - line-number prefixes removed, a
13
+ requested offset never enough - and each covering read is of the requirement's own version. A fragment that two
14
+ versions of its source share binds to the version the pin or release names (`bound_versions`), and is `unknown`
15
+ otherwise;
16
+ - a native layer when the session's most recent recorded injection at or before the decision loaded it.
17
+
18
+ `exposed_not_read` is a guide whose pointer was exposed (the router path, or a requested item's own path, in an
19
+ injection recorded before the decision) or which the session partly read, while its unit read does not hold. A
20
+ tool call before the decision that names the guide but whose returned bytes could not be read as a read makes the
21
+ state `unknown` (`read_unparsed`), never `exposed_not_read`: a failure is not claimed from evidence this code did
22
+ not read. `selected_unavailable` is a selected item whose route the compiled output lists as unavailable.
23
+ `not_delivered` - the release holds the item and the selection lacks it - is an absence, held to the absence policy
24
+ of `tables/unit_outcome.json` (`derive.absence`, D-20261111-eaa2a8): at an incomplete release it is `unknown`, and
25
+ the reason names the layers whose completeness is unknown.
26
+
27
+ A session with no pin answers from the evidence that exists: a unit read delivers, a partial read exposes, and
28
+ nothing else is claimed; its selection stays `unknown`. A row the selection history answers (D-20261110-9c60bc) is
29
+ the licensed level `library_selected`: the owner's library held it, delivery `unknown`. A Codex pin that names no
30
+ rollout stays `unknown` with the inventory's reason (F-22), and a joined Codex pin is a pin like any other. A surface
31
+ whose evidence no producer reads yet (`producer: absent`) answers `unknown` naming that, and an executable that
32
+ produces consumed artifacts - the installer - is read from its installation binding (`installer_exposure`), golden
33
+ until WP-15's receipt is installed and read live.
34
+
35
+ delivery_evidence.py --self-test
36
+ delivery_evidence.py --generate-fixtures [PATH]
37
+ """
38
+ import copy
39
+ import json
40
+ import pathlib
41
+ import re
42
+ import sys
43
+ import tempfile
44
+
45
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
46
+ from runlib import derive # noqa: E402
47
+ from runlib.records import Refused # noqa: E402
48
+
49
+ HERE = pathlib.Path(__file__).resolve().parents[1]
50
+ TABLE_PATH = HERE / "tables" / "delivery_evidence.json"
51
+ FIXTURES_PATH = HERE / "tables" / "delivery_evidence_fixtures.json"
52
+ SECTIONS = ("surfaces", "licensed_levels")
53
+ PREFIX = re.compile(r"^\s*\d+(?:\t|→)")
54
+ ROUTER = "router/relevant.md"
55
+
56
+ _TABLES = {}
57
+
58
+
59
+ def table():
60
+ """The §6.3 table, read once per process; a control may hold a scratch copy in `_TABLES["t"]`."""
61
+ if "t" not in _TABLES:
62
+ _TABLES["t"] = json.loads(TABLE_PATH.read_text(encoding="utf-8"))
63
+ return _TABLES["t"]
64
+
65
+
66
+ def row_ids(held=None):
67
+ held = held or table()
68
+ return [f"{section}/{row['id']}" for section in SECTIONS for row in held[section]]
69
+
70
+
71
+ # ---- returned bytes and versions ----------------------------------------------------------------
72
+
73
+ def returned_lines(text):
74
+ """A read's returned text as its non-blank lines, with the line-number prefix a reading tool adds removed - but only
75
+ when every non-blank line carries one, so a digit that begins a line of the file is never taken for a prefix."""
76
+ lines = [line for line in (text or "").splitlines() if line.strip()]
77
+ if lines and all(PREFIX.match(line) for line in lines):
78
+ lines = [PREFIX.sub("", line, count=1) for line in lines]
79
+ return [line.rstrip() for line in lines if line.strip()]
80
+
81
+
82
+ def returned_against(text, known):
83
+ """A read's returned text as its non-blank lines, each in the form that IS a line of the carrier (`known`).
84
+
85
+ The asymmetric rule S2's counts use (`inventory._held_forms`): a unit's line is the file's own bytes and is
86
+ compared as written; a returned line may have been numbered by the tool that returned it, so it is held both
87
+ ways - as written first, then with the prefix removed. `returned_lines` stripped only when EVERY line was
88
+ numbered, so a header line before a numbered body left the body unmatched, and a unit line that itself reads
89
+ `1\tfoo` was stripped away from itself (the WP-11b review, #11). A line that is the carrier's in neither form
90
+ is kept as written, for the trimming of what the tool added around the file."""
91
+ out = []
92
+ for raw in (text or "").splitlines():
93
+ if not raw.strip():
94
+ continue
95
+ line = raw.rstrip()
96
+ stripped = PREFIX.sub("", raw, count=1).rstrip()
97
+ out.append(line if line in known or not stripped.strip() or stripped not in known else stripped)
98
+ return out
99
+
100
+
101
+ def text_lines(text):
102
+ return [line.rstrip() for line in (text or "").splitlines() if line.strip()]
103
+
104
+
105
+ def contains(haystack, needle):
106
+ """Whether `needle`'s lines occur as one contiguous run of `haystack`'s."""
107
+ if not needle:
108
+ return False
109
+ first = needle[0]
110
+ return any(haystack[i:i + len(needle)] == needle for i, line in enumerate(haystack) if line == first)
111
+
112
+
113
+ def versions_of(units):
114
+ """`{path: {version_sha256: lines}}`: each carrier version's text as its units' lines in order. The order is the
115
+ inventory's published one, `n` (lead decision 2026-11-12): the emitted document carries no `start`, so a key on it
116
+ was always 0, and a unit that did carry one could reorder its carrier's lines against `n`."""
117
+ out = {}
118
+ for unit in sorted(units, key=lambda u: (u["path"], u["version_sha256"], u.get("n", 0))):
119
+ out.setdefault(unit["path"], {}).setdefault(unit["version_sha256"], []).extend(text_lines(unit["text"]))
120
+ return out
121
+
122
+
123
+ def delivered_suffix(path):
124
+ """The part of a catalog path a deployed copy keeps: `claude/guides/x.md` is read as `.../guides/x.md`."""
125
+ head, _, rest = path.partition("/")
126
+ return rest if head in ("claude", "codex") and rest else path
127
+
128
+
129
+ def of_carrier(read, unit, session):
130
+ """Whether a read is of the unit's carrier: the path the compiled output emitted for its item, or a path ending in
131
+ the part of the carrier's path a deployed copy keeps. The returned bytes then decide the version."""
132
+ emitted = (session.get("emitted") or {}).get(read["path"])
133
+ if emitted is not None:
134
+ return emitted == unit.get("item_ref") and read["path"].endswith("/" + delivered_suffix(unit["path"]))
135
+ return read["path"] == unit["path"] or read["path"].endswith("/" + delivered_suffix(unit["path"]))
136
+
137
+
138
+ def occurrences(haystack, needle):
139
+ """The indices at which `needle`'s lines occur as one contiguous run of `haystack`'s."""
140
+ if not needle:
141
+ return []
142
+ return [i for i in range(len(haystack) - len(needle) + 1) if haystack[i:i + len(needle)] == needle]
143
+
144
+
145
+ def requirement(req_id, units, reads, session, versions):
146
+ """`(status, reason)` of one requirement of a unit's operative context: `met`, `unmet` or `unknown`.
147
+
148
+ Its lines are met when the reads of its carrier before the decision returned all of them between them, of the
149
+ requirement's own version (§6.3: covered across reads, Codex WP-10 r1 #2). A read covers the lines it returned at the
150
+ one place of that version they occur; a read whose lines occur at more than one place covers nothing, since which of
151
+ them it returned is not known, unless it returned the requirement whole. A fragment the requirement's version shares
152
+ with another binds by the pin or the release (`bound_versions`): `bound_by_pin_or_release` when one was needed,
153
+ `version_unbound` when it was and none names a version; when even binding every shared fragment leaves a line
154
+ uncovered it is unmet - `version_mismatch` when a read returned it of another version only, `not_returned` else."""
155
+ if req_id.startswith("k-"):
156
+ return "unknown", "context_unresolved"
157
+ req = units.get(req_id)
158
+ if req is None:
159
+ return "unknown", "requirement_absent"
160
+ want = text_lines(req["text"])
161
+ held = versions.get(req["path"], {})
162
+ known = {line for lines in held.values() for line in lines}
163
+ own = held.get(req["version_sha256"], [])
164
+ bound = (session.get("bound_versions") or {}).get(req["path"])
165
+ targets = [set(range(i, i + len(want))) for i in occurrences(own, want)]
166
+ sole, by_binding, unbound, seen = set(), set(), set(), []
167
+ for read in reads:
168
+ if not of_carrier(read, req, session):
169
+ continue
170
+ got = returned_against(read["returned"], known)
171
+ whole = contains(got, want)
172
+ while got and got[0] not in known: # what the tool added around the file's bytes is not the file
173
+ got = got[1:]
174
+ while got and got[-1] not in known:
175
+ got = got[:-1]
176
+ if not got or not (whole or set(got) & set(want)):
177
+ continue
178
+ matching = sorted(version for version, lines in held.items() if contains(lines, got))
179
+ if req["version_sha256"] not in matching:
180
+ seen.append("version_mismatch")
181
+ continue
182
+ places = occurrences(own, got)
183
+ span = set().union(*targets) if whole and len(places) != 1 else \
184
+ (set(range(places[0], places[0] + len(got))) if len(places) == 1 else set())
185
+ if matching == [req["version_sha256"]]:
186
+ sole |= span
187
+ elif bound == req["version_sha256"]:
188
+ by_binding |= span
189
+ elif bound is None:
190
+ unbound |= span
191
+ seen.append("version_unbound")
192
+ else:
193
+ seen.append("version_mismatch")
194
+ if any(t <= sole for t in targets):
195
+ return "met", None
196
+ if any(t <= sole | by_binding for t in targets):
197
+ return "met", "bound_by_pin_or_release"
198
+ if any(t <= sole | by_binding | unbound for t in targets):
199
+ return "unknown", "version_unbound"
200
+ # not covered even with every shared fragment bound: a line of it no read returned, or one returned of another version
201
+ return ("unmet", "version_mismatch") if "version_mismatch" in seen else ("unmet", "not_returned")
202
+
203
+
204
+ def unit_read(unit, units, reads, session, versions):
205
+ """`(status, rows)`: `met` when every requirement is met, `unknown` when none is unmet but one is unknown."""
206
+ context = unit.get("operative_context") or [unit["unit_id"]]
207
+ rows = [{"unit_id": req, "status": status, "reason": reason}
208
+ for req in context for status, reason in [requirement(req, units, reads, session, versions)]]
209
+ if all(row["status"] == "met" for row in rows):
210
+ return "met", rows
211
+ if any(row["status"] == "unmet" for row in rows):
212
+ return "unmet", rows
213
+ return "unknown", rows
214
+
215
+
216
+ # ---- the surfaces -------------------------------------------------------------------------------
217
+
218
+ def surface_row(unit):
219
+ for row in table()["surfaces"]:
220
+ if unit.get("layer") in row.get("layers", []) or unit.get("surface") in row["item_surfaces"]:
221
+ return row
222
+ return None
223
+
224
+
225
+ def attach_surface(unit, session, catalogue_surface=None):
226
+ """The unit as §6.3 judges it in THIS session, by S5b's rule, held here so that the frozen fixtures and the
227
+ stage attach a surface the same way.
228
+
229
+ The surface is a fact about the session, not the unit: two sessions can hold one unit at different surfaces.
230
+ A unit the table already places (a native layer, matched by its layer) is returned as it is, since a surface
231
+ attached to it would move it onto an item ladder. Otherwise the surface is the one the session's snapshot
232
+ selected its item at, else the one its selection history names, else the item's catalogue surface S2
233
+ published for this unit (`unit_surfaces`, which the caller translates to this unit). With none of them the
234
+ unit stays unplaced, and `delivery` answers `surface_unclassified` rather than be handed a guess."""
235
+ if surface_row(unit) is not None:
236
+ return unit
237
+ ref = unit.get("item_ref")
238
+ surface = ((session.get("selected") or {}).get(ref) or (session.get("history_selected") or {}).get(ref)
239
+ or catalogue_surface)
240
+ return {**unit, "surface": surface} if surface else unit
241
+
242
+
243
+ def _selection(unit, session):
244
+ """What selection evidence the session has for the unit's item: `(basis, selected, surface)`."""
245
+ basis = session.get("basis")
246
+ if basis == "pin":
247
+ selected = session.get("selected") or {}
248
+ return "pin", unit.get("item_ref") in selected, selected.get(unit.get("item_ref"))
249
+ if basis == "selection_history":
250
+ held = session.get("history_selected") or {}
251
+ return "selection_history", unit.get("item_ref") in held, held.get(unit.get("item_ref"))
252
+ return None, None, None
253
+
254
+
255
+ def _before(rows, decision_at):
256
+ return [row for row in rows or [] if isinstance(row.get("at"), int) and row["at"] < decision_at]
257
+
258
+
259
+ def _injected(session, decision_at):
260
+ at = session.get("injection_at")
261
+ return isinstance(at, int) and at <= decision_at
262
+
263
+
264
+ def _result(unit, session, row, state, level, reasons, selection, requirements=None):
265
+ return {"unit_id": unit["unit_id"], "session": session.get("session_ref"), "surface": row["id"] if row else None,
266
+ "state": state, "level": level, "reasons": reasons, "selection": selection or "unknown",
267
+ "requirements": requirements or []}
268
+
269
+
270
+ def _absence(unit, session, row, selection):
271
+ """The selection lacks the item: `not_delivered` only where the release holds it at a complete reference point."""
272
+ release = session.get("release") or {}
273
+ if unit.get("item_ref") not in (release.get("items") or []):
274
+ return _result(unit, session, row, "unknown", None, ["not_in_release"], selection)
275
+ complete, read = derive.absence(release)
276
+ if not complete:
277
+ return _result(unit, session, row, "unknown", None,
278
+ ["absence_withheld: completeness unknown for " + (", ".join(read["unknown_layers"]) or "the release")],
279
+ selection)
280
+ return _result(unit, session, row, "not_delivered", None, ["selection_lacks_item"], selection)
281
+
282
+
283
+ def _always(unit, units, session, decision_at, versions, row):
284
+ basis, selected, surface = _selection(unit, session)
285
+ if basis == "selection_history":
286
+ return _history(unit, session, row, selected)
287
+ if basis != "pin":
288
+ return _result(unit, session, row, "unknown", None, [session.get("pin_reason") or "unpinned"], None)
289
+ if not selected:
290
+ return _absence(unit, session, row, "pin")
291
+ if _unavailable(unit, session, surface):
292
+ return _result(unit, session, row, "selected_unavailable", "selected", ["route_unavailable"], "pin")
293
+ if not _injected(session, decision_at):
294
+ return _result(unit, session, row, "unknown", "selected", ["injection_unrecorded_before_decision"], "pin")
295
+ held, why = in_compiled_text(unit, session)
296
+ if held is None:
297
+ return _result(unit, session, row, "unknown", "selected", [why], "pin")
298
+ if not held:
299
+ return _result(unit, session, row, "unknown", "selected", ["absent_from_compiled_text"], "pin")
300
+ if _rank(row, "exposed") >= _rank(row, row["delivered_at"]):
301
+ return _result(unit, session, row, "delivered", "exposed", [], "pin")
302
+ return _result(unit, session, row, "unknown", "exposed", ["below_the_level_the_table_delivers_at"], "pin")
303
+
304
+
305
+ def in_compiled_text(unit, session):
306
+ """`(verdict, reason)` for "the unit's lines are in the compiled instruction text".
307
+
308
+ Two sources, one answer. The compiled text itself is the fixture path and stays supported. The
309
+ production path is FACTS: S2 reads the session's snapshot where the snapshot is readable and
310
+ publishes, per unit, how many of its operative-context lines appear in that text under the same
311
+ prefix-stripping rule, with the text's sha256 — so the run never carries the owner's compiled
312
+ instructions and a later stage never reaches outside the run for them (lead decision, WP-11b).
313
+
314
+ Neither source is `unknown` by name, never a miss: a unit absent from a text nobody could read
315
+ is not an absence, and reading it as one would turn an input failure into `not_delivered`."""
316
+ facts = (session.get("instruction_coverage") or {}).get(unit["unit_id"])
317
+ if facts is not None:
318
+ total, covered = facts.get("total"), facts.get("covered")
319
+ if not isinstance(total, int) or not isinstance(covered, int) or total < 0 or covered < 0:
320
+ return None, "instruction_coverage_malformed"
321
+ if total == 0:
322
+ return None, "instruction_coverage_counts_no_line"
323
+ return covered >= total, None
324
+ if session.get("instruction_text") is not None:
325
+ return contains(text_lines(session.get("instruction_text")), text_lines(unit["text"])), None
326
+ return None, "compiled_text_unavailable"
327
+
328
+
329
+ def _rank(row, level):
330
+ """A level's place on its surface's ladder, -1 for none."""
331
+ return row["levels"].index(level) if level in row["levels"] else -1
332
+
333
+
334
+ def _unavailable(unit, session, surface):
335
+ return any(r.get("ref") == unit.get("item_ref") and (surface is None or r.get("surface") == surface)
336
+ for r in session.get("unavailable") or [])
337
+
338
+
339
+ def licensed(ident):
340
+ """One licensed level's row of the table (`licensed_levels`): its level, the state it gives and its basis."""
341
+ return next(r for r in table()["licensed_levels"] if r["id"] == ident)
342
+
343
+
344
+ def _history(unit, session, row, selected):
345
+ if selected:
346
+ # the level, its state and its basis as the table licenses them (Codex WP-10 r1 #5: written here as literals,
347
+ # so the table's row decided nothing)
348
+ held = licensed("library_selected")
349
+ return _result(unit, session, row, held["state"], held["level"], ["selection_history"], held["basis"])
350
+ return _result(unit, session, row, "unknown", None, ["not_in_selection_history"], "selection_history")
351
+
352
+
353
+ def _guide(unit, units, session, decision_at, versions, row):
354
+ basis, selected, surface = _selection(unit, session)
355
+ reads = _before(session.get("reads"), decision_at)
356
+ status, requirements = unit_read(unit, units, reads, session, versions)
357
+ selection = basis if basis in ("pin", "selection_history") and selected else None
358
+ level = None
359
+ unread = None
360
+ if basis == "pin" and selected:
361
+ level = "selected"
362
+ if _unavailable(unit, session, surface):
363
+ return _result(unit, session, row, "selected_unavailable", level, ["route_unavailable"], "pin", requirements)
364
+ pointer = _pointer(unit, session, surface) if _injected(session, decision_at) else None
365
+ if isinstance(pointer, str): # no pointer fact could be read, and the reason why
366
+ unread = pointer
367
+ elif pointer:
368
+ level = "pointer exposed"
369
+ if _router_read(unit, session, reads):
370
+ level = "router read"
371
+ if status == "met":
372
+ level = "unit read"
373
+ if level is not None and _rank(row, level) >= _rank(row, row["delivered_at"]):
374
+ return _result(unit, session, row, "delivered", level, [] if selection else ["selection_unknown"],
375
+ selection, requirements)
376
+ # a tool call whose bytes could not be read, naming the unit's carrier or the carrier of any requirement of its
377
+ # operative context not met, leaves the state unknown (Codex WP-10 r1 #3: only the unit's own carrier was asked)
378
+ pending = [units[r["unit_id"]] for r in requirements if r["status"] != "met" and r["unit_id"] in units]
379
+ unparsed = [m for m in _before(session.get("unparsed"), decision_at)
380
+ if any(of_carrier(m, carrier, session) for carrier in [unit] + pending)]
381
+ partly = any(of_carrier(read, unit, session) for read in reads)
382
+ exposed = row.get("exposed_at") is not None and (_rank(row, level) >= _rank(row, row["exposed_at"]) or partly)
383
+ if exposed:
384
+ if unparsed:
385
+ return _result(unit, session, row, "unknown", level, ["read_unparsed"], selection, requirements)
386
+ if status == "unknown":
387
+ return _result(unit, session, row, "unknown", level,
388
+ sorted({r["reason"] for r in requirements if r["status"] == "unknown"}), selection, requirements)
389
+ return _result(unit, session, row, "exposed_not_read", level,
390
+ sorted({r["reason"] for r in requirements if r["status"] != "met"}
391
+ | ({"partly_read"} if partly and _rank(row, level) < _rank(row, row["exposed_at"]) else set())),
392
+ selection, requirements)
393
+ if basis == "selection_history":
394
+ return _history(unit, session, row, selected)
395
+ if basis == "pin" and not selected:
396
+ return _absence(unit, session, row, "pin")
397
+ if basis == "pin":
398
+ return _result(unit, session, row, "unknown", level, [unread or "not_exposed_before_decision"], "pin",
399
+ requirements)
400
+ return _result(unit, session, row, "unknown", None, [session.get("pin_reason") or "unpinned"], None, requirements)
401
+
402
+
403
+ def _pointer(unit, session, surface):
404
+ """The guide's pointer in the compiled text: the router path for a relevant item, its own emitted path for a
405
+ requested one.
406
+
407
+ Answered from the FACT when the session carries one (`item_pointer_in_compiled_text`, published by S2 where
408
+ the snapshot is readable), because the compiled text is the owner's and does not enter a run; the text path
409
+ below stays for the frozen fixtures and for a caller that holds the text. A fact of None is "this surface has
410
+ no pointer to find", which is not the same as a pointer that is missing, so it is returned as given.
411
+
412
+ Where there is no fact, the answer is a REASON (a string), never False: S2's `item_pointer_unavailable` when
413
+ it says why it published none, else `pointer_unread` when the session holds no text either. Read off an
414
+ empty text, every pointer was "missing", which is a claim about a text nobody read (WP-11b X r1)."""
415
+ stated = session.get("item_pointer_in_compiled_text") or {}
416
+ if unit.get("item_ref") in stated:
417
+ return stated[unit["item_ref"]]
418
+ if session.get("item_pointer_unavailable"):
419
+ return f"pointer_unavailable:{session['item_pointer_unavailable']}"
420
+ if not isinstance(session.get("instruction_text"), str):
421
+ return "pointer_unread"
422
+ text = session["instruction_text"]
423
+ if surface == "relevant":
424
+ return bool(session.get("router_path")) and f"Relevant procedures: {session['router_path']}" in text
425
+ emitted = [path for path, ref in (session.get("emitted") or {}).items() if ref == unit.get("item_ref")]
426
+ return any(path in text for path in emitted)
427
+
428
+
429
+ def _router_read(unit, session, reads):
430
+ """A read of the router whose returned content holds the guide's own line (the line ends with its item ref)."""
431
+ marker = f"({unit.get('item_ref')})"
432
+ return any(read["path"].endswith("/" + ROUTER) and any(line.endswith(marker) for line in returned_lines(read["returned"]))
433
+ for read in reads)
434
+
435
+
436
+ def _native(unit, units, session, decision_at, versions, row):
437
+ events = [e for e in session.get("native_events") or [] if isinstance(e.get("at"), int) and e["at"] <= decision_at]
438
+ if not events:
439
+ return _result(unit, session, row, "unknown", None, ["no_recorded_injection_before_decision"], None)
440
+ latest = max(events, key=lambda e: e["at"])
441
+ if unit["unit_id"] in (latest.get("unit_ids") or []):
442
+ # a recorded injection evidences `loaded`; whether that is delivery is the table's `delivered_at` (Codex WP-10
443
+ # r1 #5: the handler said delivered whatever the row's level was)
444
+ if _rank(row, "loaded") >= _rank(row, row["delivered_at"]):
445
+ return _result(unit, session, row, "delivered", "loaded", [], "native")
446
+ return _result(unit, session, row, "unknown", "loaded", ["below_the_level_the_table_delivers_at"], "native")
447
+ release = session.get("release") or {}
448
+ complete, read = derive.absence(release)
449
+ if not complete:
450
+ return _result(unit, session, row, "unknown", "identity",
451
+ ["absence_withheld: completeness unknown for " + (", ".join(read["unknown_layers"]) or "the release")],
452
+ "native")
453
+ return _result(unit, session, row, "not_delivered", "identity", ["not_in_recorded_injection"], "native")
454
+
455
+
456
+ HANDLERS = {"always_rule": _always, "guide": _guide, "native_layer": _native}
457
+ # the installer's row is answered by `installer_exposure`, which reads a binding rather than a unit
458
+ OTHER_ENTRIES = {"executable_consumed": "installer_exposure"}
459
+
460
+
461
+ def delivery(unit, units, session, decision_at, versions=None, instruction_coverage=None):
462
+ """§6.3's answer for one unit in one session before `decision_at` (a record ordinal of that session).
463
+
464
+ `instruction_coverage` is the per-unit coverage of the compiled instruction text as FACTS
465
+ (`{unit_id: {covered, total, text_sha256}}`), which S2 publishes because the text itself is the
466
+ owner's and does not enter the run. Passed here or carried on the session; absent, the fixture's
467
+ `instruction_text` answers; absent too, the state is `unknown` naming that."""
468
+ if not isinstance(decision_at, int):
469
+ raise Refused(f"DELIVERY_INPUT_INVALID decision_at {decision_at!r}: a record ordinal of the session")
470
+ if instruction_coverage is not None:
471
+ session = {**session, "instruction_coverage": instruction_coverage}
472
+ versions = versions if versions is not None else versions_of(units.values())
473
+ row = surface_row(unit)
474
+ if row is None:
475
+ return _result(unit, session, None, "unknown", None, ["surface_unclassified"], None)
476
+ if row["producer"] == "absent":
477
+ return _result(unit, session, row, "unknown", None, [f"producer_absent:{row['id']}"], None)
478
+ handler = HANDLERS.get(row["id"])
479
+ if handler is None:
480
+ raise Refused(f"SURFACE_UNHANDLED {row['id']}: the table says implemented and no handler answers it")
481
+ return handler(unit, units, session, decision_at, versions, row)
482
+
483
+
484
+ def installer_exposure(binding, receipt, snapshot_artifacts):
485
+ """The installer row (§6.3): `consumed` when the store's `installation_binding()` is bound, its receipt is a
486
+ success receipt, and the receipt's release artifacts hold every artifact the snapshot records; `unknown` with the
487
+ reason otherwise. Exposure is judged against the executing installer and, for a recovered transaction, the one
488
+ that began it."""
489
+ row = next(r for r in table()["surfaces"] if r["id"] == "executable_consumed")
490
+ out = {"surface": row["id"], "realization": "golden", "waiting": "receipt_live_waiting_wp15"}
491
+ if not (binding or {}).get("bound"):
492
+ return {**out, "state": "unknown", "level": None, "reasons": ["unbound"]}
493
+ if (receipt or {}).get("schema") != "InstallationReceipt/v1" or receipt.get("transaction_id") != binding.get("transaction_id"):
494
+ return {**out, "state": "unknown", "level": None, "reasons": ["receipt_not_the_binding's"]}
495
+ if receipt.get("result") != "success":
496
+ return {**out, "state": "unknown", "level": "identity of the producing version", "reasons": ["receipt_not_success"]}
497
+ released = {(a.get("path"), a.get("sha256")) for a in receipt.get("artifacts") or [] if a.get("role") == "release"}
498
+ missing = [a for a in snapshot_artifacts or [] if (a.get("path"), a.get("sha256")) not in released]
499
+ if missing or not snapshot_artifacts:
500
+ return {**out, "state": "unknown", "level": "identity of the producing version",
501
+ "reasons": ["artifacts_unmatched" if missing else "snapshot_records_no_artifact"]}
502
+ digests = [binding.get("installer_digest")] + ([binding["begun_by_installer_digest"]]
503
+ if binding.get("begun_by_installer_digest") else [])
504
+ return {**out, "state": "delivered", "level": "consumed", "reasons": [], "installer_digests": digests}
505
+
506
+
507
+ # ---- the table's checks and the frozen fixtures -------------------------------------------------
508
+
509
+ def table_problems(held=None):
510
+ """An implemented surface no handler answers, a handler for no implemented surface, an absent surface with no
511
+ reason, a level the row's ladder does not hold, a licensed level whose state is not one of the five."""
512
+ held = held or table()
513
+ problems = []
514
+ implemented = {r["id"] for r in held["surfaces"] if r["producer"] == "implemented"}
515
+ answered = set(HANDLERS) | set(OTHER_ENTRIES)
516
+ problems += [f"SURFACE_UNHANDLED {i}: implemented, and no handler answers it" for i in sorted(implemented - answered)]
517
+ problems += [f"HANDLER_ORPHAN {i}: a handler for no implemented surface" for i in sorted(answered - implemented)]
518
+ for r in held["surfaces"]:
519
+ if r["producer"] == "absent" and not r.get("reason_absent"):
520
+ problems.append(f"TABLE_INVALID surfaces/{r['id']}: absent with no reason")
521
+ for key in ("delivered_at", "exposed_at"):
522
+ if r.get(key) is not None and r[key] not in r["levels"]:
523
+ problems.append(f"TABLE_INVALID surfaces/{r['id']}: {key} {r[key]!r} is not one of its levels")
524
+ for r in held["licensed_levels"]:
525
+ if r["state"] not in held["states"] or not r.get("decision"):
526
+ problems.append(f"TABLE_INVALID licensed_levels/{r['id']}: a state of the five and a decision are required")
527
+ return problems
528
+
529
+
530
+ def expected_state(row, level):
531
+ """The state the table's own fields give a unit that reached `level` on `row`'s surface and no further."""
532
+ if level == row["delivered_at"]:
533
+ return "delivered"
534
+ if row.get("exposed_at") is not None and row["levels"].index(level) >= row["levels"].index(row["exposed_at"]):
535
+ return "exposed_not_read"
536
+ return "unknown"
537
+
538
+
539
+ def _unit(uid, path, text, version="a" * 64, layer="catalog", surface="relevant", ref="claude:guides/g", context=None, n=1):
540
+ return {"unit_id": uid, "path": path, "text": text, "version_sha256": version, "layer": layer, "surface": surface,
541
+ "item_ref": ref, "operative_context": context or [uid], "n": n}
542
+
543
+
544
+ def _builder(row, level):
545
+ """One case that reaches exactly `level` on `row`'s surface: `(unit, units, session, decision_at)`."""
546
+ if row["id"] == "always_rule":
547
+ unit = _unit("u-a", "claude/CLAUDE.md", "- Verify before you claim.", surface="always", ref="claude:core")
548
+ session = {"session_ref": "claude:s", "basis": "pin", "selected": {"claude:core": "always"},
549
+ "instruction_text": "# Activated private instructions\n- Verify before you claim.\n"}
550
+ if level == "exposed":
551
+ session["injection_at"] = 1
552
+ return unit, {unit["unit_id"]: unit}, session, 5
553
+ if row["id"] == "guide":
554
+ unit = _unit("u-g", "claude/guides/g.md", "- Read the log before you retry.")
555
+ session = {"session_ref": "claude:s", "basis": "pin", "selected": {"claude:guides/g": "relevant"},
556
+ "router_path": "/state/runtime/x/router/relevant.md",
557
+ "instruction_text": "Relevant procedures: /state/runtime/x/router/relevant.md\n", "reads": []}
558
+ at = row["levels"].index(level)
559
+ if at >= 1:
560
+ session["injection_at"] = 1
561
+ if at >= 2:
562
+ session["reads"].append({"at": 2, "path": "/state/runtime/x/router/relevant.md",
563
+ "returned": "- [g](/state/runtime/x/items/item-g/guides/g.md) — retries (claude:guides/g)\n"})
564
+ if at >= 3:
565
+ session["reads"].append({"at": 3, "path": "/state/runtime/x/items/item-g/guides/g.md",
566
+ "returned": " 1\t- Read the log before you retry.\n"})
567
+ return unit, {unit["unit_id"]: unit}, session, 5
568
+ if row["id"] == "native_layer":
569
+ unit = _unit("u-n", "native_global", "- Answer in Korean.", layer="native_global", surface=None, ref=None)
570
+ session = {"session_ref": "claude:s", "native_events": [{"at": 1, "unit_ids": ["u-n"] if level == "loaded" else []}],
571
+ "release": {"complete": False, "layers": {"native_settings": "unknown"}, "items": []}}
572
+ return unit, {unit["unit_id"]: unit}, session, 5
573
+ unit = _unit(f"u-{row['id']}", "claude/x", "- x", surface=(row["item_surfaces"] or [None])[0])
574
+ return unit, {unit["unit_id"]: unit}, {"session_ref": "claude:s", "basis": "pin"}, 5
575
+
576
+
577
+ def _held(unit, session):
578
+ """`(unit, catalogue_surface)`: a builder's unit as S5b holds it, with no surface of its own, and the catalogue
579
+ surface S2 would publish for it where the session's own selection does not name its item."""
580
+ bare = {key: value for key, value in unit.items() if key != "surface"}
581
+ if surface_row(bare) is not None or attach_surface(bare, session).get("surface") == unit.get("surface"):
582
+ return bare, None
583
+ return bare, unit.get("surface")
584
+
585
+
586
+ def _delivery_case(unit, session, at, expected):
587
+ bare, catalogue = _held(unit, session)
588
+ case = {"kind": "delivery", "unit": bare, "units": {bare["unit_id"]: bare}, "session": session,
589
+ "decision_at": at, "expected": expected}
590
+ if catalogue is not None:
591
+ case["catalogue_surface"] = catalogue
592
+ return case
593
+
594
+
595
+ def _cases(section, row, held):
596
+ if section == "licensed_levels":
597
+ unit = _unit("u-h", "claude/guides/h.md", "- h", ref="claude:guides/h")
598
+ session = {"session_ref": "claude:s", "basis": row["basis"], "history_selected": {"claude:guides/h": "relevant"}}
599
+ return [_delivery_case(unit, session, 5, {"state": row["state"], "level": row["level"]})]
600
+ if row["id"] == "executable_consumed":
601
+ binding = {"bound": True, "receipt_id": "r" * 64, "transaction_id": "t1", "installer_digest": "d1",
602
+ "release_digest": "rd", "begun_by_installer_digest": None}
603
+ receipt = {"schema": "InstallationReceipt/v1", "transaction_id": "t1", "result": "success",
604
+ "artifacts": [{"path": "runtime/baselines/b/inventory.json", "sha256": "s1", "role": "release"},
605
+ {"path": "launch/bin/x", "sha256": "s2", "role": "owned"}]}
606
+ artifacts = [{"path": "runtime/baselines/b/inventory.json", "sha256": "s1"}]
607
+ return [{"kind": "installer", "binding": binding, "receipt": receipt, "artifacts": artifacts,
608
+ "expected": {"state": "delivered", "level": row["delivered_at"]}},
609
+ {"kind": "installer", "binding": {"bound": False}, "receipt": None, "artifacts": artifacts,
610
+ "expected": {"state": "unknown", "level": None}}]
611
+ if row["producer"] == "absent":
612
+ unit, _units, session, at = _builder(row, row["levels"][0])
613
+ return [_delivery_case(unit, session, at,
614
+ {"state": "unknown", "level": None, "reason": f"producer_absent:{row['id']}"})]
615
+ cases = []
616
+ for level in row["levels"]:
617
+ unit, _units, session, at = _builder(row, level)
618
+ cases.append(_delivery_case(unit, session, at, {"state": expected_state(row, level), "level": level}))
619
+ if row["id"] == "guide":
620
+ # the unit whose item no source names: neither the session's selection, its history nor S2's catalogue
621
+ # surface places it, so the stage's rule attaches nothing and §6.3 is not asked to guess a ladder
622
+ unit = _unit("u-q", "claude/guides/q.md", "- An item no source names.", ref="claude:guides/q")
623
+ session = {"session_ref": "claude:s", "basis": "pin", "selected": {"claude:guides/g": "relevant"}}
624
+ case = _delivery_case(unit, session, 5, {"state": "unknown", "level": None, "reason": "surface_unclassified"})
625
+ case.pop("catalogue_surface", None)
626
+ cases.append(case)
627
+ return cases
628
+
629
+
630
+ def generate_fixtures(path=FIXTURES_PATH):
631
+ """Write one fixture per row of the table, once; a second call refuses."""
632
+ path = pathlib.Path(path)
633
+ if path.exists():
634
+ raise Refused(f"FIXTURES_FROZEN {path}: generated once and committed; delete it by hand to regenerate")
635
+ held = table()
636
+ fixtures = [{"id": f"{section}/{row['id']}", "cases": _cases(section, row, held)}
637
+ for section in SECTIONS for row in held[section]]
638
+ doc = {"$comment": "design §6.3: one frozen fixture per row of tables/delivery_evidence.json, written once by "
639
+ "`runlib/delivery_evidence.py --generate-fixtures`; the self-test never regenerates them.",
640
+ "fixtures": fixtures}
641
+ path.write_text(json.dumps(doc, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
642
+ return len(fixtures)
643
+
644
+
645
+ def run_fixture(fixture):
646
+ problems = []
647
+ for n, case in enumerate(fixture["cases"]):
648
+ try:
649
+ if case["kind"] == "installer":
650
+ result = installer_exposure(case["binding"], case["receipt"], case["artifacts"])
651
+ else:
652
+ # the surface attached per (session, unit) by the stage's own rule, never carried on the unit
653
+ unit = attach_surface(case["unit"], case["session"], case.get("catalogue_surface"))
654
+ result = delivery(unit, case["units"], case["session"], case["decision_at"])
655
+ got = {"state": result["state"], "level": result["level"]}
656
+ if "reason" in case["expected"]:
657
+ got["reason"] = (result["reasons"] or [None])[0]
658
+ except Refused as exc:
659
+ got = f"refused {str(exc).split()[0]}"
660
+ if got != case["expected"]:
661
+ problems.append(f"FIXTURE_FAILED {fixture['id']} case {n}: expected {case['expected']}, got {got}")
662
+ return problems
663
+
664
+
665
+ # ---- the self-test ------------------------------------------------------------------------------
666
+
667
+ # The design's §6.3, copied here once (WP-10 done-when 5): each surface with its levels in order, and the five states.
668
+ DESIGN_6_3_SURFACES = (
669
+ ("Rule on the always surface", ("selected", "exposed")),
670
+ ("Guide", ("selected", "pointer exposed", "router read", "unit read")),
671
+ ("Executable invoked directly (hook script, skill script, tool, wrapper)", ("identity", "invoked", "completed")),
672
+ ("Executable producing consumed artifacts (catalog compiler, installer)", ("identity of the producing version", "consumed")),
673
+ ("Skill", ("selected", "listed", "invoked")),
674
+ ("Hook", ("selected", "registered for the route", "fired")),
675
+ ("Native layer", ("identity", "loaded")),
676
+ ("Child session (subagent reach)", ("the child's own record",)),
677
+ )
678
+ DESIGN_6_3_STATES = ("delivered", "exposed_not_read", "selected_unavailable", "not_delivered", "unknown")
679
+
680
+
681
+ def fidelity_problems(held=None):
682
+ held = held or table()
683
+ problems = []
684
+ surfaces = tuple((r["design"], tuple(r["levels"])) for r in held["surfaces"])
685
+ for n, (have, want) in enumerate(zip(surfaces, DESIGN_6_3_SURFACES)):
686
+ if have != want:
687
+ problems.append(f"CONTRACT_DRIFT surface {n + 1}: the table says {have}, §6.3 says {want}")
688
+ if len(surfaces) != len(DESIGN_6_3_SURFACES):
689
+ problems.append(f"CONTRACT_DRIFT surfaces: {len(surfaces)} rows, §6.3 has {len(DESIGN_6_3_SURFACES)}")
690
+ if tuple(held["states"]) != DESIGN_6_3_STATES:
691
+ problems.append(f"CONTRACT_DRIFT states: {held['states']}")
692
+ return problems
693
+
694
+
695
+ def self_test():
696
+ failures, ran = [], []
697
+
698
+ def expect(label, got, want):
699
+ ran.append(label)
700
+ if got != want:
701
+ failures.append(f"{label}: expected {want!r}, got {got!r}")
702
+
703
+ def named(label, lines, needle):
704
+ ran.append(label)
705
+ if not any(needle in line for line in lines):
706
+ failures.append(f"{label}: expected {needle!r} in {lines}")
707
+
708
+ def refused(label, action, code):
709
+ ran.append(label)
710
+ try:
711
+ action()
712
+ except Refused as exc:
713
+ if not str(exc).startswith(code):
714
+ failures.append(f"{label}: refused {str(exc)[:160]!r}, expected {code}")
715
+ return
716
+ except Exception as exc: # noqa: BLE001 - anything else fails this control by name, never the suite
717
+ failures.append(f"{label}: raised {type(exc).__name__}: {exc}, expected {code}")
718
+ return
719
+ failures.append(f"{label}: not refused, expected {code}")
720
+
721
+ held = table()
722
+ expect("the table's surfaces each have their handler, and its rows are well formed", table_problems(), [])
723
+ expect("the table holds §6.3's surfaces, levels and states", fidelity_problems(), [])
724
+ moved = copy.deepcopy(held)
725
+ moved["surfaces"][1]["levels"] = ["selected", "router read", "pointer exposed", "unit read"]
726
+ named("control: a guide ladder reordered", fidelity_problems(moved), "CONTRACT_DRIFT surface 2")
727
+ claimed = copy.deepcopy(held)
728
+ claimed["surfaces"][4]["producer"] = "implemented"
729
+ named("control: a surface marked implemented with no handler", table_problems(claimed), "SURFACE_UNHANDLED skill")
730
+ silent = copy.deepcopy(held)
731
+ silent["surfaces"][5].pop("reason_absent")
732
+ named("control: an absent surface that does not say why", table_problems(silent), "absent with no reason")
733
+
734
+ fixtures = json.loads(FIXTURES_PATH.read_text(encoding="utf-8"))["fixtures"]
735
+ executed = set()
736
+ for fixture in fixtures:
737
+ failures.extend(run_fixture(fixture))
738
+ executed.add(fixture["id"]) # recorded after its cases ran through the production functions
739
+ frozen = {f["id"] for f in fixtures}
740
+ expect("table rows, frozen fixtures and executed cases are one set", derive.coverage_problems(row_ids(), frozen, executed), [])
741
+ added = copy.deepcopy(held)
742
+ added["surfaces"].append({**added["surfaces"][0], "id": "plugin"})
743
+ named("control: a surface added to a scratch copy, the frozen fixtures unchanged",
744
+ derive.coverage_problems(row_ids(added), frozen, executed), "ROW_UNFIXTURED surfaces/plugin")
745
+ named("control: an executed case removed from the run's record",
746
+ derive.coverage_problems(row_ids(), frozen, executed - {"surfaces/guide"}), "CASE_NOT_EXECUTED surfaces/guide")
747
+ by_id = {f["id"]: f for f in fixtures}
748
+ _TABLES["t"] = {**held, "surfaces": [{**r, "exposed_at": None} if r["id"] == "guide" else r for r in held["surfaces"]]}
749
+ try:
750
+ named("control: a frozen guide fixture against a table that no longer exposes at the pointer",
751
+ run_fixture(by_id["surfaces/guide"]), "FIXTURE_FAILED surfaces/guide")
752
+ finally:
753
+ _TABLES["t"] = held
754
+ with tempfile.TemporaryDirectory() as td:
755
+ target = pathlib.Path(td) / "fixtures.json"
756
+ expect("the generator writes one fixture per row", generate_fixtures(target), len(row_ids()))
757
+ expect("the generator's fixtures are the frozen ones", json.loads(target.read_text(encoding="utf-8"))["fixtures"],
758
+ fixtures)
759
+ refused("a second generation", lambda: generate_fixtures(target), "FIXTURES_FROZEN")
760
+
761
+ # ---- WP-11b X r1: the surface is attached per (session, unit) by the stage's rule, never carried on a unit
762
+ cases = [case for fixture in fixtures for case in fixture["cases"] if case["kind"] == "delivery"]
763
+ expect("every frozen delivery case holds its unit as S5b does, with no surface of its own",
764
+ (bool(cases), sorted(case["unit"]["unit_id"] for case in cases if "surface" in case["unit"])), (True, []))
765
+ expect("and exactly one frozen case is a unit no source places, expected `surface_unclassified`",
766
+ [case["unit"]["unit_id"] for case in cases if case["expected"].get("reason") == "surface_unclassified"],
767
+ ["u-q"])
768
+ bare = {"unit_id": "u-b", "layer": "catalog", "item_ref": "claude:guides/b"}
769
+ expect("the surface the session's selection names comes first, then its history, then S2's catalogue surface",
770
+ [attach_surface(bare, {"selected": {"claude:guides/b": "requested"},
771
+ "history_selected": {"claude:guides/b": "always"}}, "relevant").get("surface"),
772
+ attach_surface(bare, {"history_selected": {"claude:guides/b": "always"}}, "relevant").get("surface"),
773
+ attach_surface(bare, {}, "relevant").get("surface"),
774
+ "surface" in attach_surface(bare, {"selected": {"claude:other": "always"}})],
775
+ ["requested", "always", "relevant", False])
776
+ native_bare = {"unit_id": "u-nb", "layer": "native_global", "item_ref": None}
777
+ expect("control: a native unit is placed by its layer, and nothing the session names moves it onto an item ladder",
778
+ attach_surface(native_bare, {"selected": {None: "always"}}, "always"), native_bare)
779
+ expect("control: the frozen always-rule fixture with its session's selection emptied and no catalogue surface is unplaced",
780
+ [line.split(":")[0] for line in run_fixture({"id": "surfaces/always_rule", "cases": [
781
+ {**case, "session": {**case["session"], "selected": {}}} for case in by_id["surfaces/always_rule"]["cases"]]})],
782
+ ["FIXTURE_FAILED surfaces/always_rule case 0", "FIXTURE_FAILED surfaces/always_rule case 1"])
783
+
784
+ # ---- WP-11b X r1: a pointer S2 could not compute is a named unknown, never "missing" read off an empty text
785
+ guide_row = next(r for r in held["surfaces"] if r["id"] == "guide")
786
+ p_unit, p_units, p_session, p_at = _builder(guide_row, "pointer exposed")
787
+ p_unit = attach_surface(_held(p_unit, p_session)[0], p_session)
788
+
789
+ def pointer_answer(session):
790
+ result = delivery(p_unit, p_units, session, p_at)
791
+ return result["state"], result["level"], result["reasons"]
792
+ textless = {key: value for key, value in p_session.items() if key != "instruction_text"}
793
+ expect("a selected, injected guide whose snapshot published no pointer fact names S2's reason",
794
+ pointer_answer({**textless, "item_pointer_unavailable": "compiled_text_absent"}),
795
+ ("unknown", "selected", ["pointer_unavailable:compiled_text_absent"]))
796
+ expect("and with neither a fact, a reason nor a text, the pointer is unread rather than missing",
797
+ pointer_answer(textless), ("unknown", "selected", ["pointer_unread"]))
798
+ expect("control: the published fact answers where it is there, the reason beside it notwithstanding",
799
+ pointer_answer({**textless, "item_pointer_unavailable": "compiled_text_absent",
800
+ "item_pointer_in_compiled_text": {"claude:guides/g": True}})[:2],
801
+ (expected_state(guide_row, "pointer exposed"), "pointer exposed"))
802
+ expect("control: and a fact of False is a pointer that is missing, as before",
803
+ pointer_answer({**textless, "item_pointer_in_compiled_text": {"claude:guides/g": False}}),
804
+ ("unknown", "selected", ["not_exposed_before_decision"]))
805
+
806
+ # returned bytes
807
+ expect("a reading tool's line-number prefixes are removed", returned_lines(" 1\t- a\n 2→- b\n"), ["- a", "- b"])
808
+ expect("control: a line that begins with a digit is kept when not every line has a prefix",
809
+ returned_lines("12 rules\n- a\n"), ["12 rules", "- a"])
810
+
811
+ expect("against a carrier's lines, a returned line is held as written first and then without its prefix: a header "
812
+ "before a numbered body, a unit line that itself looks numbered, and a line that is neither",
813
+ [returned_against("header\n 1\tfoo\n", {"foo"}), returned_against("1\tfoo\n", {"1\tfoo", "foo"}),
814
+ returned_against(" 7\tbar\n\n", {"foo"})],
815
+ [["header", "foo"], ["1\tfoo"], [" 7\tbar"]])
816
+ mixed_unit = {"unit_id": "u-mx", "path": "claude/guides/mx.md", "version_sha256": "9" * 64, "text": "foo", "n": 0}
817
+ literal_unit = {**mixed_unit, "unit_id": "u-lit", "path": "claude/guides/lit.md", "text": "1\tfoo"}
818
+ for label, unit, returned in (
819
+ ("a read that returned a header and then the numbered line covers the unit", mixed_unit, "header\n1\tfoo\n"),
820
+ ("a unit whose own line looks numbered is covered by a read that returned it unchanged", literal_unit,
821
+ "1\tfoo\n")):
822
+ expect(label, requirement(unit["unit_id"], {unit["unit_id"]: unit},
823
+ [{"path": unit["path"], "returned": returned}], {}, versions_of([unit])),
824
+ ("met", None))
825
+ expect("and a numbered line of ANOTHER text does not cover it",
826
+ requirement("u-lit", {"u-lit": literal_unit}, [{"path": literal_unit["path"], "returned": "2\tfoo\n"}], {},
827
+ versions_of([literal_unit]))[0], "unmet")
828
+
829
+ # ---- done-when 2: the O3 verdicts that rest on delivery evidence, each with its flipped control
830
+ v1, v2 = "1" * 64, "2" * 64
831
+ path, path2 = "claude/guides/review.md", "claude/guides/second.md"
832
+ deployed = "/state/runtime/s/items/item-claude_guides_review/guides/review.md"
833
+ deployed2 = "/state/runtime/s/items/item-claude_guides_second/guides/second.md"
834
+ heading = _unit("u-h1", path, "## Review", v1, n=1, ref="claude:guides/review")
835
+ rule = _unit("u-r1", path, "- Read the diff twice.", v1, n=2, ref="claude:guides/review",
836
+ context=["u-r1", "u-h1", "u-x1", "u-s1"])
837
+ exception = _unit("u-x1", path, "### Exceptions\n- except a one-line typo fix.", v1, n=3, ref="claude:guides/review")
838
+ second = _unit("u-s1", path2, "- Name the reviewer.", v1, n=1, ref="claude:guides/second")
839
+ units = {u["unit_id"]: u for u in (heading, rule, exception, second)}
840
+ other_second = [_unit("u-s2", path2, "- Name the reviewer.", v2, n=1, ref="claude:guides/second"),
841
+ _unit("u-s3", path2, "- And name who reviews them.", v2, n=2, ref="claude:guides/second")]
842
+ versions = versions_of(list(units.values())) # one version of each guide
843
+ both_versions = versions_of(list(units.values()) + other_second) # the second guide at two versions
844
+ full = "\n".join(f"{n:>6}\t{line}" for n, line in enumerate(["## Review", "- Read the diff twice.", "### Exceptions",
845
+ "- except a one-line typo fix."], 1))
846
+ second_read = {"at": 4, "path": deployed2, "returned": " 1\t- Name the reviewer.\n"}
847
+ pinned = {"session_ref": "claude:p", "host": "claude", "basis": "pin",
848
+ "selected": {"claude:guides/review": "relevant", "claude:guides/second": "relevant"},
849
+ "router_path": "/state/runtime/s/router/relevant.md",
850
+ "instruction_text": "Relevant procedures: /state/runtime/s/router/relevant.md\n", "injection_at": 1,
851
+ "reads": [{"at": 3, "path": deployed, "returned": full}, second_read]}
852
+
853
+ def state(session, unit=rule, at=10, held_units=units, held_versions=None):
854
+ return delivery(unit, held_units, session, at, held_versions or versions)
855
+
856
+ expect("O3: an operative context across two guides read completely is delivered", state(pinned)["state"], "delivered")
857
+ expect("O3: the second guide unread is exposed_not_read",
858
+ state({**pinned, "reads": pinned["reads"][:1]})["state"], "exposed_not_read")
859
+ other_version = {**pinned, "reads": pinned["reads"][:1] + [
860
+ {**second_read, "returned": " 1\t- Name the reviewer.\n 2\t- And name who reviews them.\n"}]}
861
+ expect("O3: the second guide read at a different version than the requirement names is exposed_not_read",
862
+ (state(other_version, held_versions=both_versions)["state"],
863
+ state(other_version, held_versions=both_versions)["requirements"][-1]),
864
+ ("exposed_not_read", {"unit_id": "u-s1", "status": "unmet", "reason": "version_mismatch"}))
865
+ expect("control: the second guide's line read where two versions share it, the pin naming none, is unknown",
866
+ state(pinned, held_versions=both_versions)["requirements"][-1]["reason"], "version_unbound")
867
+ expect("control: ... and delivered when the pin names its version",
868
+ state({**pinned, "bound_versions": {path2: v1}}, held_versions=both_versions)["state"], "delivered")
869
+ no_exception = "\n".join(full.splitlines()[:2])
870
+ expect("O3: a read returning the unit and its heading but not the enclosing exception is exposed_not_read",
871
+ state({**pinned, "reads": [{"at": 3, "path": deployed, "returned": no_exception}, second_read]})["state"],
872
+ "exposed_not_read")
873
+ truncated = "\n".join(full.splitlines()[:1])
874
+ expect("O3: a guide read spanning the unit but truncated before it is exposed_not_read",
875
+ state({**pinned, "reads": [{"at": 3, "path": deployed, "returned": truncated}, second_read]})["state"],
876
+ "exposed_not_read")
877
+ expect("control: the same reads after the decision expose only the pointer, never deliver",
878
+ (state(pinned, at=3)["state"], state(pinned, at=3)["level"]), ("exposed_not_read", "pointer exposed"))
879
+ pointer_only = {**pinned, "reads": []}
880
+ expect("O3: a guide pointer exposed and never read is exposed_not_read, at the pointer",
881
+ (state(pointer_only)["state"], state(pointer_only)["level"]), ("exposed_not_read", "pointer exposed"))
882
+ expect("control: the pointer in an injection recorded after the decision is not exposure",
883
+ state({**pointer_only, "injection_at": 20})["state"], "unknown")
884
+ routed = {**pointer_only, "reads": [{"at": 2, "path": "/state/runtime/s/router/relevant.md",
885
+ "returned": f"- [Review]({deployed}) — reviews (claude:guides/review)\n"}]}
886
+ expect("the router read is a level of its own and still not a unit read", (state(routed)["state"], state(routed)["level"]),
887
+ ("exposed_not_read", "router read"))
888
+ unparsed = {**pointer_only, "unparsed": [{"at": 2, "path": deployed}]}
889
+ expect("a tool call naming the guide whose bytes could not be read leaves the state unknown, never a claimed miss",
890
+ (state(unparsed)["state"], state(unparsed)["reasons"]), ("unknown", ["read_unparsed"]))
891
+ unavailable = {**pinned, "reads": [], "unavailable": [{"ref": "claude:guides/review", "surface": "relevant",
892
+ "reason": "native consumption is disabled"}]}
893
+ expect("O3: a selected item whose route is unavailable is selected_unavailable", state(unavailable)["state"],
894
+ "selected_unavailable")
895
+ expect("control: the same item with no unavailable row is exposed_not_read", state({**unavailable, "unavailable": []})["state"],
896
+ "exposed_not_read")
897
+ unpinned = {"session_ref": "claude:u", "host": "claude", "basis": None, "pin_reason": "unpinned"}
898
+ expect("O3: an unpinned session with no read is unknown, naming why",
899
+ (state(unpinned)["state"], state(unpinned)["reasons"]), ("unknown", ["unpinned"]))
900
+ read_unpinned = {**unpinned, "reads": pinned["reads"]}
901
+ expect("O3: an unpinned session that read the unit before the decision is delivered, its selection unknown",
902
+ (state(read_unpinned)["state"], state(read_unpinned)["selection"], state(read_unpinned)["reasons"]),
903
+ ("delivered", "unknown", ["selection_unknown"]))
904
+ expect("control: the same reads after the decision deliver nothing", state(read_unpinned, at=3)["state"], "unknown")
905
+ # identical fragment in two versions with different contexts: the pin or the release binds it
906
+ rule_v2 = _unit("u-r2", path, "- Read the diff twice.", v2, n=2, ref="claude:guides/review", context=["u-r2", "u-x2"])
907
+ exception_v2 = _unit("u-x2", path, "### Exceptions\n- except a docs-only change.", v2, n=3, ref="claude:guides/review")
908
+ twin = {**units, "u-r2": rule_v2, "u-x2": exception_v2}
909
+ twin_versions = versions_of(list(twin.values()))
910
+ just_rule = {"at": 3, "path": deployed, "returned": " 2\t- Read the diff twice.\n"}
911
+ v1_exception = {"at": 4, "path": deployed, "returned": " 3\t### Exceptions\n 4\t- except a one-line typo fix.\n"}
912
+ lone = _unit("u-r1", path, "- Read the diff twice.", v1, n=2, ref="claude:guides/review", context=["u-r1", "u-x1"])
913
+ twins = {**twin, "u-r1": lone}
914
+
915
+ def twin_state(bound):
916
+ session = {**pinned, "reads": [just_rule, v1_exception], "bound_versions": bound}
917
+ return delivery(lone, twins, session, 10, twin_versions)
918
+ expect("O3: an identical fragment in two versions binds to the version the pin names: delivered",
919
+ twin_state({path: v1})["state"], "delivered")
920
+ expect("O3: ... and is unknown when nothing binds it", (twin_state({})["state"], twin_state({})["reasons"]),
921
+ ("unknown", ["version_unbound"]))
922
+ expect("control: bound to the other version, the requirement is unmet", twin_state({path: v2})["state"], "exposed_not_read")
923
+ # Codex WP-10 r1 #2: a requirement returned across reads is covered by them together, of its own version
924
+ head_rule = {"at": 2, "path": deployed, "returned": " 1\t## Review\n 2\t- Read the diff twice.\n"}
925
+ line3 = {"at": 3, "path": deployed, "returned": " 3\t### Exceptions\n"}
926
+ line4 = {"at": 5, "path": deployed, "returned": " 4\t- except a one-line typo fix.\n"}
927
+ split = {**pinned, "reads": [head_rule, line3, line4, second_read]}
928
+ expect("Codex WP-10 r1 #2: an enclosing exception returned across two reads, a line each, is covered: delivered",
929
+ (state(split)["state"], [r["status"] for r in state(split)["requirements"]]),
930
+ ("delivered", ["met", "met", "met", "met"]))
931
+ expect("control: one of its two lines never returned leaves it unmet, not_returned",
932
+ (state({**split, "reads": [head_rule, line3, second_read]})["state"],
933
+ state({**split, "reads": [head_rule, line3, second_read]})["requirements"][2]),
934
+ ("exposed_not_read", {"unit_id": "u-x1", "status": "unmet", "reason": "not_returned"}))
935
+ expect("control: the line the two versions share and the other version's own line do not combine into the "
936
+ "requirement's version",
937
+ delivery(lone, twins, {**pinned, "reads": [just_rule, line3,
938
+ {**line4, "returned": " 4\t- except a docs-only change.\n"}],
939
+ "bound_versions": {}}, 10, twin_versions)["requirements"][-1],
940
+ {"unit_id": "u-x1", "status": "unmet", "reason": "not_returned"})
941
+ expect("control: ... and with the pin naming the requirement's version, its shared line binds and its own is still "
942
+ "missing", delivery(lone, twins, {**pinned, "reads": [just_rule, line3,
943
+ {**line4, "returned": " 4\t- except a docs-only change.\n"}],
944
+ "bound_versions": {path: v1}}, 10, twin_versions)["requirements"][-1],
945
+ {"unit_id": "u-x1", "status": "unmet", "reason": "not_returned"})
946
+ expect("control: the shared line and the requirement's own line, read apart, bind by the pin: delivered",
947
+ delivery(lone, twins, {**pinned, "reads": [just_rule, line3, line4], "bound_versions": {path: v1}}, 10,
948
+ twin_versions)["state"], "delivered")
949
+ # Codex WP-10 r1 #3: an unparsed call naming the carrier of a requirement not met is a read nobody could judge
950
+ unparsed_second = {**pinned, "reads": pinned["reads"][:1], "unparsed": [{"at": 2, "path": deployed2}]}
951
+ expect("Codex WP-10 r1 #3: the unit's guide read whole and an unparsed call for the second guide its context needs "
952
+ "is unknown, read_unparsed, never exposed_not_read",
953
+ (state(unparsed_second)["state"], state(unparsed_second)["reasons"]), ("unknown", ["read_unparsed"]))
954
+ expect("control: an unparsed call for a guide no unmet requirement lives in leaves exposed_not_read",
955
+ state({**unparsed_second, "unparsed": [{"at": 2, "path": "/state/runtime/s/items/other/guides/other.md"}]})["state"],
956
+ "exposed_not_read")
957
+ # the always surface
958
+ core = _unit("u-c1", "claude/CLAUDE.md", "- Verify before you claim.", surface="always", ref="claude:core")
959
+ core_units = {"u-c1": core}
960
+ always = {"session_ref": "claude:p", "basis": "pin", "selected": {"claude:core": "always"}, "injection_at": 1,
961
+ "instruction_text": "# Activated private instructions\n\n## Always in this environment\n\n- Verify before you claim.\n"}
962
+ expect("O3: a rule on the always surface exposed in a recorded injection is delivered",
963
+ delivery(core, core_units, always, 5)["state"], "delivered")
964
+ expect("control: the same rule absent from the compiled text is unknown",
965
+ delivery(core, core_units, {**always, "instruction_text": "# Activated\n"}, 5)["state"], "unknown")
966
+ # the full O3 verdicts through the derivation
967
+ met = {n: "met" for n in derive.table()["requirements"]}
968
+
969
+ def verdict(state_row, following="not_followed", contribution="harmed"):
970
+ judged = {"situation": "yes", "action": "yes", "following": following, "contribution": contribution}
971
+ point = {"complete": True, "layers": {}, "units": {"u": {"A": judged, "B": judged}}}
972
+ return derive.unit_outcome({"candidate": {"candidate_id": "k1", "type": "A", "lifecycle": None},
973
+ "judges": {"A": {"requirements": met}, "B": {"requirements": met}},
974
+ "points": {"release": point, "current": point}, "checks_pass": True, "lineages": 2},
975
+ {"u": [{"session": state_row["session"], "state": state_row["state"]}]},
976
+ "untested: s8_deferred")["kind"]["kind"]
977
+ expect("O3 end to end: a pinned session violating a delivered rule is a misfire",
978
+ verdict(delivery(core, core_units, always, 5)), "misfire")
979
+ expect("O3 end to end: a pointer exposed and never read is a misfire (trigger)",
980
+ derive.unit_outcome({"candidate": {"candidate_id": "k1", "type": "A", "lifecycle": None},
981
+ "judges": {"A": {"requirements": met}, "B": {"requirements": met}},
982
+ "points": {p: {"complete": True, "layers": {}, "units": {"u-r1": {
983
+ who: {"situation": "yes", "action": "yes", "following": "not_followed",
984
+ "contribution": "harmed"} for who in ("A", "B")}}} for p in ("release", "current")},
985
+ "checks_pass": True, "lineages": 2},
986
+ {"u-r1": [{"session": "claude:p", "state": state(pointer_only)["state"]}]},
987
+ "untested: s8_deferred")["unit_outcomes"][0]["outcome"], "misfire (trigger)")
988
+ expect("O3 end to end: selected_unavailable is not delivered", verdict(state(unavailable)), "not delivered")
989
+ expect("O3 end to end: an unpinned session is unclassified", verdict(state(unpinned)), "unclassified")
990
+ expect("O3 end to end: an unpinned session that read the unit before violating is a misfire",
991
+ verdict(state(read_unpinned)), "misfire")
992
+ # the selection history, Codex pins, and an absence under the literal policy
993
+ history = {"session_ref": "claude:h", "basis": "selection_history", "history_selected": {"claude:core": "always"}}
994
+ expect("a row the selection history answers is library_selected, delivery unknown",
995
+ (delivery(core, core_units, history, 5)["state"], delivery(core, core_units, history, 5)["level"]),
996
+ ("unknown", "library_selected"))
997
+ expect("control: the same item under a pin and a recorded injection is delivered",
998
+ delivery(core, core_units, always, 5)["state"], "delivered")
999
+ # lead decision 2026-11-12: a carrier's lines are its units' in `n` order, on units as the inventory's production
1000
+ # path emits them (no `start`); a stray `start` on each, numbered against `n`, changes nothing
1001
+ from runlib import inventory
1002
+ order_ctx = {"home": "/nonexistent-fixture-home", "state_root": None, "notes": {}, "commit": None,
1003
+ "release_ref": None, "snapshot": {}, "events": []}
1004
+ ordered = inventory.carrier("catalog", "claude/guides/order.md", "# Order\n\n- first rule\n- second rule\n- third rule\n")
1005
+ try:
1006
+ emitted = inventory.emitted_document("current", [
1007
+ {"layer": "catalog", "producer": "this suite's fixture producer", "status": "complete", "reasons": [],
1008
+ "carriers": [ordered]}], order_ctx)[0]["units"]
1009
+ except Exception as exc: # noqa: BLE001 - the control below names it
1010
+ emitted = []
1011
+ failures.append(f"the inventory's production path made no units: {exc!r}")
1012
+ by_n = [line for u in sorted(emitted, key=lambda u: u["n"]) for line in text_lines(u["text"])]
1013
+ stray = [{**u, "start": 1000 - u["n"]} for u in reversed(emitted)]
1014
+ lines_of = {name: (versions_of(given).get("claude/guides/order.md") or {}).get(ordered["version_sha256"])
1015
+ for name, given in (("emitted", emitted), ("reversed", list(reversed(emitted))), ("stray", stray))}
1016
+ expect("lead decision 2026-11-12: a carrier's lines follow `n` on producer-shaped units (no `start`), listed in any "
1017
+ "order and with a stray `start` against `n`",
1018
+ (len(emitted) >= 3 and not any("start" in u for u in emitted) and by_n[-1] == "- third rule",
1019
+ lines_of["emitted"] == by_n, lines_of["reversed"] == by_n, lines_of["stray"] == by_n),
1020
+ (True, True, True, True))
1021
+ # Codex WP-10 r1 #5: the licensed level's row and the native layer's level decide, read from a scratch table
1022
+ held_t = table()
1023
+ _TABLES["t"] = {**held_t, "licensed_levels": [{**r, "state": "exposed_not_read", "level": "library_listed",
1024
+ "basis": "history_basis"} if r["id"] == "library_selected" else r
1025
+ for r in held_t["licensed_levels"]]}
1026
+ try:
1027
+ moved = delivery(core, core_units, history, 5)
1028
+ finally:
1029
+ _TABLES["t"] = held_t
1030
+ expect("Codex WP-10 r1 #5: the selection history's answer is the licensed level's row: its state, level and basis",
1031
+ (moved["state"], moved["level"], moved["selection"]), ("exposed_not_read", "library_listed", "history_basis"))
1032
+ native_row = next(r for r in held_t["surfaces"] if r["id"] == "native_layer")
1033
+ native_unit, native_units, native_session, native_at = _builder(native_row, "loaded")
1034
+ _TABLES["t"] = {**held_t, "surfaces": [{**r, "levels": r["levels"] + ["acted on"], "delivered_at": "acted on"}
1035
+ if r["id"] == "native_layer" else r for r in held_t["surfaces"]]}
1036
+ try:
1037
+ raised = delivery(native_unit, native_units, native_session, native_at)
1038
+ finally:
1039
+ _TABLES["t"] = held_t
1040
+ expect("Codex WP-10 r1 #5: a native unit in the recorded injection is delivered only when the table delivers at "
1041
+ "`loaded`: with the row's level moved above it, the same session is unknown below the level",
1042
+ (delivery(native_unit, native_units, native_session, native_at)["state"], raised["state"], raised["reasons"]),
1043
+ ("delivered", "unknown", ["below_the_level_the_table_delivers_at"]))
1044
+ codex = {"session_ref": "codex:t", "host": "codex", "basis": None, "pin_reason": "pin_predates_rollout_binding"}
1045
+ expect("a Codex pin naming no rollout is unknown with the F-22 reason",
1046
+ delivery(core, core_units, codex, 5)["reasons"], ["pin_predates_rollout_binding"])
1047
+ expect("golden: a joined Codex pin answers as a pin does",
1048
+ delivery(core, core_units, {**always, "session_ref": "codex:j", "host": "codex"}, 5)["state"], "delivered")
1049
+ absent_item = {**always, "selected": {}, "release": {"complete": False, "layers": {"catalog": "complete",
1050
+ "native_settings": "unknown"},
1051
+ "items": ["claude:core"]}}
1052
+ expect("an item the release holds and the selection lacks is withheld under the literal policy, naming the layer",
1053
+ (delivery(core, core_units, absent_item, 5)["state"], delivery(core, core_units, absent_item, 5)["reasons"]),
1054
+ ("unknown", ["absence_withheld: completeness unknown for native_settings"]))
1055
+ expect("control: at a complete release it is not_delivered",
1056
+ delivery(core, core_units, {**absent_item, "release": {**absent_item["release"], "complete": True}}, 5)["state"],
1057
+ "not_delivered")
1058
+ # native layers and absent producers
1059
+ native = _unit("u-n1", "native_global", "- Answer in Korean.", layer="native_global", surface=None, ref=None)
1060
+ loaded = {"session_ref": "claude:p", "native_events": [{"at": 1, "unit_ids": ["u-n1"]}, {"at": 8, "unit_ids": []}]}
1061
+ expect("a native layer loaded by the most recent injection at or before the decision is delivered",
1062
+ delivery(native, {"u-n1": native}, loaded, 5)["state"], "delivered")
1063
+ expect("control: a later injection without it, before the decision, does not deliver it",
1064
+ delivery(native, {"u-n1": native}, {**loaded, "release": {"complete": True, "layers": {}}}, 9)["state"],
1065
+ "not_delivered")
1066
+ hook = _unit("u-k1", "claude/hooks/h.py", "x", surface="event", ref="claude:hooks/h")
1067
+ expect("a surface no producer reads answers unknown naming it",
1068
+ delivery(hook, {"u-k1": hook}, always, 5)["reasons"], ["producer_absent:hook"])
1069
+ # the installer row (golden)
1070
+ binding = {"bound": True, "receipt_id": "r" * 64, "transaction_id": "t1", "installer_digest": "dY",
1071
+ "release_digest": "rd", "begun_by_installer_digest": "dX"}
1072
+ receipt = {"schema": "InstallationReceipt/v1", "transaction_id": "t1", "result": "success",
1073
+ "artifacts": [{"path": "a", "sha256": "1", "role": "release"}, {"path": "b", "sha256": "2", "role": "owned"}]}
1074
+ exposure = installer_exposure(binding, receipt, [{"path": "a", "sha256": "1"}])
1075
+ expect("golden: a bound success receipt holding the snapshot's artifacts is consumed, judged against both installers",
1076
+ (exposure["state"], exposure["installer_digests"], exposure["waiting"]), ("delivered", ["dY", "dX"], "receipt_live_waiting_wp15"))
1077
+ expect("control: an owned row never stands in for a release artifact",
1078
+ installer_exposure(binding, receipt, [{"path": "b", "sha256": "2"}])["reasons"], ["artifacts_unmatched"])
1079
+ expect("control: an unbound snapshot leaves installer exposure unknown",
1080
+ installer_exposure({"bound": False}, receipt, [{"path": "a", "sha256": "1"}])["reasons"], ["unbound"])
1081
+ expect("control: a failed transaction's receipt is not consumption",
1082
+ installer_exposure(binding, {**receipt, "result": "failed"}, [{"path": "a", "sha256": "1"}])["reasons"],
1083
+ ["receipt_not_success"])
1084
+ refused("a decision instant that is not an ordinal", lambda: delivery(core, core_units, always, None),
1085
+ "DELIVERY_INPUT_INVALID")
1086
+
1087
+ # The compiled instruction text as FACTS (lead decision, WP-11b): S2 counts the lines where the
1088
+ # snapshot is readable and publishes the counts, so the owner's compiled instructions never enter
1089
+ # the run and no later stage reaches outside it. The two paths must answer alike.
1090
+ no_text = {k: v for k, v in always.items() if k != "instruction_text"}
1091
+ covered = {core["unit_id"]: {"covered": 1, "total": 1, "text_sha256": "f" * 64}}
1092
+ expect("the facts path delivers what the text path delivers",
1093
+ delivery(core, core_units, no_text, 5, instruction_coverage=covered)["state"],
1094
+ delivery(core, core_units, always, 5)["state"])
1095
+ partial = {core["unit_id"]: {"covered": 1, "total": 2, "text_sha256": "f" * 64}}
1096
+ expect("a unit the text covers in part is not in the compiled text",
1097
+ (delivery(core, core_units, no_text, 5, instruction_coverage=partial)["state"],
1098
+ delivery(core, core_units, no_text, 5, instruction_coverage=partial)["reasons"]),
1099
+ ("unknown", ["absent_from_compiled_text"]))
1100
+ expect("k of n lines is a count, not a judgement: k == n delivers",
1101
+ delivery(core, core_units, no_text, 5,
1102
+ instruction_coverage={core["unit_id"]: {"covered": 2, "total": 2,
1103
+ "text_sha256": "f" * 64}})["state"],
1104
+ "delivered")
1105
+ expect("neither facts nor text is unknown by name, never an absence",
1106
+ (delivery(core, core_units, no_text, 5)["state"],
1107
+ delivery(core, core_units, no_text, 5)["reasons"]),
1108
+ ("unknown", ["compiled_text_unavailable"]))
1109
+ expect("facts for another unit do not answer for this one",
1110
+ delivery(core, core_units, no_text, 5,
1111
+ instruction_coverage={"u-somebody-else": {"covered": 1, "total": 1,
1112
+ "text_sha256": "f" * 64}})["reasons"],
1113
+ ["compiled_text_unavailable"])
1114
+ expect("counts that are not counts are refused by name rather than read as coverage",
1115
+ delivery(core, core_units, no_text, 5,
1116
+ instruction_coverage={core["unit_id"]: {"covered": None, "total": 1}})["reasons"],
1117
+ ["instruction_coverage_malformed"])
1118
+ expect("and a unit whose context counts no line at all is unknown, not covered",
1119
+ delivery(core, core_units, no_text, 5,
1120
+ instruction_coverage={core["unit_id"]: {"covered": 0, "total": 0}})["reasons"],
1121
+ ["instruction_coverage_counts_no_line"])
1122
+ expect("the facts may ride on the session instead of the argument",
1123
+ delivery(core, core_units, {**no_text, "instruction_coverage": covered}, 5)["state"],
1124
+ "delivered")
1125
+
1126
+ for failure in failures:
1127
+ print(f"delivery_evidence --self-test [FAIL] {failure}")
1128
+ if failures:
1129
+ return 1
1130
+ print(f"delivery_evidence --self-test: OK ({len(ran)} controls, {len(fixtures)} frozen fixtures over the table's {len(row_ids())} "
1131
+ "rows: §6.3's surfaces and states as the design states them, every implemented surface handled and every absent "
1132
+ "one named, the unit read over returned bytes with prefixes removed and versions bound by pin or release, the O3 "
1133
+ "delivery verdicts each with its flipped control and five through the derivation, the selection history, Codex "
1134
+ "pins, the literal absence, native layers, the golden installer row)")
1135
+ return 0
1136
+
1137
+
1138
+ if __name__ == "__main__":
1139
+ if sys.argv[1:2] == ["--generate-fixtures"]:
1140
+ target = pathlib.Path(sys.argv[2]) if len(sys.argv) > 2 else FIXTURES_PATH
1141
+ print(f"wrote {generate_fixtures(target)} fixtures to {target}")
1142
+ sys.exit(0)
1143
+ if "--self-test" not in sys.argv[1:]:
1144
+ sys.exit("usage: delivery_evidence.py --self-test | --generate-fixtures [PATH]")
1145
+ sys.exit(self_test())