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,3080 @@
1
+ #!/usr/bin/env python3
2
+ """S5b, the delivery evidence (WP-11b): the producer of what `delivery_evidence.delivery()` judges.
3
+
4
+ WP-10's `runlib/delivery_evidence.py` answers, for one unit in one session before one decision, whether the unit was
5
+ `delivered`, `exposed_not_read`, `selected_unavailable`, `not_delivered` or `unknown`, by design §6.3. It was built and
6
+ judged on frozen fixtures. This stage is the half that was missing: the evidence itself, assembled from the records the
7
+ run already holds, written as `delivery-evidence.json` under the run so S6 can read one answer per (session, unit,
8
+ decision) instead of recomputing it.
9
+
10
+ The stage runs between S5 and S6 as `distill.py deliver --run-id ID`. It is `S5b` in `records.STAGES`, inserted
11
+ between `S5` and `S6` rather than appended, because `declare.py` derives an amendment's invalidation range from
12
+ `STAGES.index` and sorts by it: a stage appended after `S12` would be invalidated and ordered as though it ran last.
13
+
14
+ **What it reads, and nothing else.** `checks.json` (S5) for the candidates and the decision events they cite, the
15
+ inventory (S2) for pins, selection, injection and native events, the in-force windows and each unit's operative
16
+ context, and the run's own immutable copy of the session records (`sources/<version_sha>.jsonl`, written by S2, mode
17
+ 0444) for the tool calls that read a guide file back. The immutable copy is the only acquisition: this stage never
18
+ reads the owner's `~/.claude` or `~/.codex`.
19
+
20
+ **What it writes.** Names, ids, hashes, line counts, states and reasons, with a per-requirement coverage summary. Never
21
+ the bytes a session read, and never session text. The raw copy is read because the clipped views cannot carry a
22
+ read's returned bytes, and nothing read from it leaves this process except as a count or a hash.
23
+
24
+ **`read_unparsed` means the HOST elided the result.** A tool result this run clipped for a view is not a reason: the
25
+ clip is ours, and this stage does not read views at all. A call whose returned bytes the host truncated or replaced is
26
+ `unknown` with that reason, never `exposed_not_read`, because a miss is not claimed from evidence nobody read.
27
+
28
+ **The pairs it owes an answer for** come from the artifacts' own shapes: a check row's `retrieved_units` and
29
+ `named_units_absent` (`checks.schema.json`), the sessions and decision events of S4's `candidates.json`, and the
30
+ record ordinal in an event record's `at_record`. That ordinal is the scale `delivery()` takes `decision_at` on. The
31
+ inventory's own native and injection events carry an instant and a line instead, and are read where they are used.
32
+
33
+ **The unit's operative context is the judge's one-step set** — `edges.direct` plus `edges.reached`, published on every
34
+ current unit (plan WP-11 D1 (a1)) — never the transitive `operative_context` closure beside it and never a
35
+ recomputation of mentions. An inventory that publishes no edges is refused by name.
36
+
37
+ Commit 1 of this package landed the stage's frame: its place in `records.STAGES`, its admission through
38
+ `records.run_stage`, its two refusals, and the document's shape. Commit 2 anchored the enumeration on the artifacts
39
+ above, and the session evidence follows. Until it does, every pair is `unknown` with the reason
40
+ `delivery_assembly_pending` and the document says `complete: false`. That is this stage's per-pair state inside a file
41
+ that EXISTS; S6's `delivery_assembly_waiting` is its state when no such file exists at all. A pending answer is
42
+ written as one rather than left out, so a reader can tell "no evidence assembled yet" from "evidence that found
43
+ nothing".
44
+
45
+ stage_delivery.py --self-test
46
+ """
47
+ import inspect
48
+ import collections
49
+ import json
50
+ import pathlib
51
+ import re
52
+ import sys
53
+ import tempfile
54
+
55
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
56
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
57
+ from runlib import bound, delivery_evidence, derive, dispatch, projection, records # noqa: E402
58
+ from runlib import stagelock # noqa: E402
59
+ from runlib.records import Refused # noqa: E402
60
+
61
+ HERE = pathlib.Path(__file__).resolve().parents[1]
62
+ STAGE = "S5b"
63
+ OUTPUT = "delivery-evidence.json"
64
+ SOURCES_DIR = "sources"
65
+ EVENTS_DIR = "events"
66
+ VIEWS_FILE = "views.json"
67
+ # Admitted against every producer whose records this stage reads, so the shared staleness judgement applies: a
68
+ # `checks.json` or an inventory written again after this stage ran makes the next reader refuse rather than trust it.
69
+ # Every artifact this stage READS, with the stage that produced it. `checked-candidates.json` is
70
+ # S5's own population — S4's candidates plus the planted controls of design §6.5, which is what S6
71
+ # judges — and it was not declared or read, so a planted control and its retrieved units were
72
+ # excluded from the pairs this stage owes an answer for, silently (the WP-11b review).
73
+ INPUTS = ({"artifact": "checks.json", "producer_stage": "S5"},
74
+ {"artifact": "checked-candidates.json", "producer_stage": "S5"},
75
+ {"artifact": VIEWS_FILE, "producer_stage": "S2"},
76
+ {"artifact": "candidates.json", "producer_stage": "S4"},
77
+ {"artifact": "inventory/current.json", "producer_stage": "S2"},
78
+ {"artifact": "inventory/sessions.json", "producer_stage": "S2"},
79
+ {"artifact": "inventory/release.json", "producer_stage": "S2"})
80
+ # This stage's own per-pair state inside a file that EXISTS, and not to be read as lane E's
81
+ # `delivery_assembly_waiting`, which is S6's state when no such file exists at all. One says "the
82
+ # evidence readers have not answered this pair yet", the other says "there is nothing to read".
83
+ PENDING = "delivery_assembly_pending"
84
+
85
+
86
+ def sources_present(run_dir):
87
+ """The immutable copies S2 left, by file name. Empty is not an error here; `run` decides."""
88
+ root = pathlib.Path(run_dir) / SOURCES_DIR
89
+ if not root.is_dir():
90
+ return []
91
+ return sorted(p.name for p in root.iterdir() if p.is_file())
92
+
93
+
94
+ def standing_stop(run_dir):
95
+ """The run's standing stop as the dispatcher's own rule reads it, or None.
96
+
97
+ Read rather than assumed absent: this stage writes a document S6 will judge candidates by, and a run that stopped
98
+ at a cap has evidence only up to the stop. The source is the supervisor's ledger, through `bound`, so there is one
99
+ reading of "stopped" in the driver and not a second one here."""
100
+ run_dir = pathlib.Path(run_dir)
101
+ ledger_path = dispatch.run_ledger_path(run_dir)
102
+ if not ledger_path.is_file():
103
+ return None
104
+ held = records.read_json(ledger_path)
105
+ stops = bound.as_stops(held.get("stops", held.get("stopped")))
106
+ if not stops:
107
+ return None
108
+ # Only a later amendment of a stop's own key lifts it, so the amendments decide which stops still stand. A
109
+ # declaration this stage cannot read is read as "unread" rather than as "no amendment": `bound` holds every
110
+ # recorded stop standing in that case, which is the direction that cannot read a stopped run as open. The run is
111
+ # refused either way — here by name, or by `run_stage` as undeclared — and never written to.
112
+ try:
113
+ _run, _digest, amendments = records.declaration_state(run_dir, who=STAGE)
114
+ except Refused:
115
+ amendments = None
116
+ return bound.blocked(stops, amendments)
117
+
118
+
119
+ def decisions_of(run_dir):
120
+ """`{event_id: (transcript file stem, record ordinal)}` over the event records S3 wrote.
121
+
122
+ The decision a candidate concerns is an EVENT, and an event record names its place as
123
+ `at_record`, whose first component is the record's ordinal in that transcript ("76837/message/
124
+ content"). That ordinal is the scale `delivery_evidence.delivery()` takes `decision_at` on and
125
+ the scale a read's `at` is on, so the mapping is made once, here, rather than in each reader.
126
+
127
+ The inventory's own events carry an ISO instant in `at` and the line in `line`; they are a
128
+ different record set (the native and injection events of a session) and are read where they are
129
+ used, never mixed with these ids."""
130
+ found = {}
131
+ root = pathlib.Path(run_dir) / EVENTS_DIR
132
+ if not root.is_dir():
133
+ return found
134
+ for path in sorted(root.glob("*.jsonl")):
135
+ # The repository's one JSONL splitter, as every other reader here uses. `splitlines()` also
136
+ # splits U+2028 and U+2029, which `records` writes through unescaped (`ensure_ascii=False`),
137
+ # so a decision whose text carried one would have its record split in half: the ordinal
138
+ # scale this mapping exists to establish would shift, and the record itself would be
139
+ # discarded as unparsable (the WP-11b review, the same defect as the journal's).
140
+ for line in records.jsonl_read(path, errors="replace"):
141
+ if not line.strip():
142
+ continue
143
+ try:
144
+ row = json.loads(line)
145
+ except ValueError:
146
+ continue
147
+ at_record = row.get("at_record")
148
+ head = str(at_record or "").split("/")[0]
149
+ found[row.get("event_id")] = (path.stem, int(head) if head.isdigit() else None)
150
+ return found
151
+
152
+
153
+ def sessions_index(sessions):
154
+ """`{"host:id": session row}` and `{transcript id: session row}` over the inventory's sessions.
155
+
156
+ A candidate names its sessions as `host:id` (S4's spelling) and an event record is named by its
157
+ transcript file; the inventory's rows carry both, so both ways in are built from the one
158
+ document rather than guessed at either end."""
159
+ by_name, by_transcript = {}, {}
160
+ for row in sessions.get("sessions") or []:
161
+ if row.get("session"):
162
+ by_name[row["session"]] = row
163
+ transcript = (row.get("transcript") or {}).get("id")
164
+ if transcript:
165
+ by_transcript[transcript] = row
166
+ return by_name, by_transcript
167
+
168
+
169
+ def view_index(views):
170
+ """`{event-file stem: the views transcript row}` — the EXPLICIT mapping S2 published.
171
+
172
+ The join used to be string surgery on the file stem: `stem.split("_", 1)[-1]`. S2 names a
173
+ transcript's files with `views.safe_name(coverage_key)`, and a Codex coverage key is
174
+ `codex:<id>@<segment>`, which becomes `codex_<id>_<segment>` — so removing the first underscore
175
+ prefix leaves `<id>_<segment>`, which is no transcript id at all and matched nothing. Every
176
+ Codex event therefore joined to no session and was reported `session_unmatched` (the WP-11b
177
+ review). The row carries `name`, `transcript` and `session` itself; this reads them.
178
+
179
+ Keyed on `name` AND on `segment`, because the event files S3 writes are per segment: a
180
+ transcript split across several rollout files has one row per segment, and keying on the
181
+ transcript alone would make the last one win.
182
+ """
183
+ held = {}
184
+ for row in (views or {}).get("transcripts") or []:
185
+ for key in (row.get("name"), row.get("segment")):
186
+ if key:
187
+ held.setdefault(str(key), row)
188
+ return held
189
+
190
+
191
+ def pairs_of(checks, candidates, decisions, by_name, by_transcript, by_view=None,
192
+ population=None):
193
+ """Every (session, unit, decision) this run owes an answer for.
194
+
195
+ Re-anchored on the artifacts' own shapes (WP-11b commit 2). Commit 1 read `session_ref`,
196
+ `unit_ids` and `decision_at` off a check row; `checks.schema.json` has none of those. A check
197
+ row carries `candidate_id`, `retrieved_units` and `named_units_absent`; the sessions and the
198
+ decision events are S4's, in `candidates.json`. The controls then tested a shape chosen here
199
+ rather than one anybody writes, which is why this is anchored to the schema and exercised on a
200
+ real run's artifacts.
201
+
202
+ A pair is owed per (decision event, unit): the event fixes both the session — the transcript its
203
+ record belongs to — and the ordinal. A candidate with no readable event keeps one pair per unit
204
+ with `decision_at` None, and a candidate naming no unit keeps a pair with `unit_id` None:
205
+ either way the pair is answered with a reason rather than dropped, because a denominator that
206
+ shrinks silently is the one number nobody can check."""
207
+ units_by_candidate = {}
208
+ for row in checks.get("candidates") or []:
209
+ named = [u["unit_id"] for u in row.get("retrieved_units") or [] if u.get("unit_id")]
210
+ units_by_candidate[row.get("candidate_id")] = named + list(row.get("named_units_absent") or [])
211
+ owed = []
212
+ for row in candidates.get("candidates") or []:
213
+ cid = row.get("candidate_id")
214
+ units = units_by_candidate.get(cid) or [None]
215
+ events = []
216
+ for event_id in row.get("event_ids") or []:
217
+ stem, ordinal = decisions.get(event_id, (None, None))
218
+ # The views row S2 published for that file, then the session it names. No string
219
+ # surgery: a Codex stem carries the segment as well as the id, and splitting it left
220
+ # neither (the WP-11b review).
221
+ view = (by_view or {}).get(str(stem)) if stem else None
222
+ transcript = view.get("transcript") if view else None
223
+ session = by_transcript.get(transcript) or (
224
+ by_name.get(view.get("session")) if view and view.get("session") else None)
225
+ events.append({"event_id": event_id, "decision_at": ordinal,
226
+ "session_ref": (session or {}).get("session_ref"),
227
+ "session": (session or {}).get("session"),
228
+ # Which half of the join failed, so an unmatched pair says what to fix.
229
+ "reason": None if ordinal is not None and session else
230
+ ("event_record_absent" if ordinal is None else
231
+ "view_unmatched" if view is None else "session_unmatched")})
232
+ if not events:
233
+ # The candidate's own sessions, so the pair still names where it would be judged.
234
+ for name in row.get("sessions") or [None]:
235
+ session = by_name.get(name) if name else None
236
+ events.append({"event_id": None, "decision_at": None,
237
+ "session_ref": (session or {}).get("session_ref"), "session": name,
238
+ "reason": "no_decision_event" if name else NOT_SESSION_DERIVED})
239
+ for event in events:
240
+ for unit in units:
241
+ owed.append({"candidate_id": cid, "unit_id": unit, "producer": "S4", **event})
242
+ # S5's own population: S4's candidates PLUS the planted controls of design §6.5, which is the
243
+ # population S6 judges. Enumerating only S4's excluded every planted control and its retrieved
244
+ # units from the pairs this stage owes — silently, so the denominator shrank with no row saying
245
+ # so (the WP-11b review). A planted control carries a fabricated session id, so its pair is
246
+ # answered with a reason; that is the point, and it is not the same as not being asked.
247
+ seen = {row.get("candidate_id") for row in candidates.get("candidates") or []}
248
+ for row in (population or {}).get("candidates") or []:
249
+ cid = row.get("candidate_id")
250
+ if cid in seen or not cid:
251
+ continue
252
+ units = units_by_candidate.get(cid) or [None]
253
+ for name in row.get("sessions") or [None]:
254
+ session = by_name.get(name) if name else None
255
+ for unit in units:
256
+ owed.append({"candidate_id": cid, "unit_id": unit, "producer": "S5",
257
+ "event_id": None, "decision_at": None,
258
+ "session_ref": (session or {}).get("session_ref"),
259
+ "session": name,
260
+ "reason": NOT_SESSION_DERIVED if not name else
261
+ "no_decision_event" if session else "session_absent_from_inventory"})
262
+ return owed
263
+
264
+
265
+ def selected_items(shared, store):
266
+ """`{item_ref: surface}` of a shared selection inventory, as far as the INVENTORY states it.
267
+
268
+ The items a session received, and the surface each was selected at, are the SNAPSHOT's
269
+ (`inventory.snapshot_shape`: `items`, `output.unavailable`, `output.instruction_text`), and a
270
+ snapshot lives in the owner's state root — not in this run. S2 is what reads it; S5b reads what
271
+ S2 published, because moving that acquisition here would make the stage read the owner's state
272
+ directly and would make S2's recorded failure unverifiable.
273
+
274
+ S2 publishes the snapshot's `items` with their surfaces (the fact-only half of the lead's
275
+ boundary decision), so a published surface is the snapshot's own answer. An item the carriers
276
+ name and the items block does not is held with a surface of None, and the judge then answers the
277
+ levels that need a surface as unknown rather than guessing one — which is what EVERY item read
278
+ as before that block existed."""
279
+ stated = {item.get("ref"): item.get("surface") for item in shared.get("items") or []
280
+ if isinstance(item, dict) and item.get("ref")}
281
+ held = {}
282
+ for carrier in shared.get("carriers") or []:
283
+ version = ((store.get("versions") or {}).get(carrier.get("carrier_id")) or {}).get(
284
+ carrier.get("version_sha256")) or {}
285
+ if version.get("item_ref"):
286
+ held[version["item_ref"]] = stated.get(version["item_ref"])
287
+ return held
288
+
289
+
290
+ def version_universe(current, store):
291
+ """`{path: {version_sha256: [lines]}}` over every carrier version THIS RUN names.
292
+
293
+ `delivery_evidence.delivery` defaults its `versions` to the CURRENT units alone, and this stage
294
+ passed none — so the shared store's historical versions were invisible to the byte binding, and
295
+ a fragment shared by two versions could not be told apart (the WP-11b review). The run does hold
296
+ them: `shared/store.json` keys every carrier version it names, each version lists its
297
+ `unit_refs` in order, and each store unit carries its own projected `text`. The universe is
298
+ assembled from those records, unioned with the current document's units, so a read of an older
299
+ version is matched against the version it actually belongs to instead of against the current one.
300
+
301
+ The lines of one version are its units' lines in the version's own order, which is the same rule
302
+ `delivery_evidence.versions_of` uses for the current document — reached rather than restated
303
+ where the shape allows it.
304
+ """
305
+ held = delivery_evidence.versions_of((current or {}).get("units") or [])
306
+ units = (store or {}).get("units") or {}
307
+ for carrier_id, by_version in ((store or {}).get("versions") or {}).items():
308
+ for version_sha, version in (by_version or {}).items():
309
+ path = (version or {}).get("path")
310
+ if not path:
311
+ continue
312
+ lines = []
313
+ for ref in (version or {}).get("unit_refs") or []:
314
+ unit = units.get(ref) or {}
315
+ if unit.get("text"):
316
+ lines += delivery_evidence.text_lines(unit["text"])
317
+ if not lines:
318
+ continue
319
+ # The current document wins where both hold the same (path, version): it is the same
320
+ # bytes, and its units are the ones the judge's requirements are keyed to.
321
+ held.setdefault(path, {}).setdefault(version_sha, lines)
322
+ return held
323
+
324
+
325
+ def released_items(shared, store):
326
+ """The item refs ONE shared inventory holds, for the release's reference point.
327
+
328
+ Not `selected_items`, which answers a different question: that one is what a SESSION received,
329
+ so it walks the carriers the snapshot gave that session and resolves each through the store —
330
+ an inventory naming no carrier yields nothing there, correctly. The release asks what the
331
+ owner's library HELD at the reference point, which is the inventory's stated items as well as
332
+ whatever its carriers resolve to. Reading the session question's answer for the release question
333
+ is what made `items` empty for every session.
334
+ """
335
+ held = {item.get("ref") for item in shared.get("items") or []
336
+ if isinstance(item, dict) and item.get("ref")}
337
+ held |= set(selected_items(shared, store))
338
+ return held
339
+
340
+
341
+ # A published coverage row whose `r-` reference names no unit of this run. It is NOT a dropped row:
342
+ # a drop is a resolution failure, and a block that lost every row to one would read like a block that
343
+ # was never published — which is a different answer about the same session.
344
+ UNRESOLVED = "coverage_ref_unresolved"
345
+ # A pair one of the judge's inputs is missing for. The reasons already name WHICH input, so this is
346
+ # the statement that the state beside them is this stage's and not §6.3's.
347
+ UNJUDGED = "delivery_unjudged"
348
+ # A pair whose candidate names NO session: a legacy entry or a redundancy hint that arrived by lifecycle intake
349
+ # rather than from a session of this window. Delivery is a question about a session, so the pair is not one this
350
+ # stage could ever judge. It keeps its row (nothing is dropped), is counted on its own, and is outside the
351
+ # denominator `complete` is computed over. Its delivery `state` stays `unknown`: that vocabulary is
352
+ # `tables/unit_outcome.json`'s, and this is a fact about the pair's population, carried in `population`.
353
+ NOT_SESSION_DERIVED = "not_session_derived"
354
+
355
+
356
+ def pointer_facts(shared):
357
+ """`{item_ref: pointer}` from the selection inventory's published predicate over the compiled text.
358
+
359
+ A row whose `pointer` is None says the surface has no pointer to find at all; it is carried as
360
+ None rather than dropped, because the judge's reader distinguishes "nothing to find" from "not
361
+ found" and a dropped row would send it back to a text this run does not hold."""
362
+ return {row["ref"]: row.get("pointer") for row in shared.get("item_pointer_in_compiled_text") or []
363
+ if isinstance(row, dict) and isinstance(row.get("ref"), str)}
364
+
365
+
366
+ def surface_facts(shared):
367
+ """`{unit_ref: surface}` of every unit this selection holds, as S2 published it.
368
+
369
+ Keyed by the inventory's reference, like the coverage counts, and translated per pair. A unit
370
+ with a null surface is held as None: the judge then answers `surface_unclassified`, which is the
371
+ honest answer for a unit whose item neither the snapshot nor the baseline named."""
372
+ return {row["unit_ref"]: row.get("surface") for row in shared.get("unit_surfaces") or []
373
+ if isinstance(row, dict) and isinstance(row.get("unit_ref"), str)}
374
+
375
+
376
+ def coverage_facts(shared, units):
377
+ """`({unit_id: {covered, total}}, [reference nothing here resolves])` from the published counts.
378
+
379
+ The counts S2 publishes are keyed by the inventory's `r-` reference, and the judge asks about a
380
+ `unit_id`, so this translates between them over the units of the run. A reference that resolves
381
+ to no unit is RETURNED rather than dropped, because the two outcomes are not the same claim: a
382
+ fact that could not be attached is a resolution failure this run should say out loud, while
383
+ silence would make a block whose every row failed indistinguishable from a session whose
384
+ inventory published no block at all.
385
+
386
+ The compiled instruction text itself is never in the run (lead decision, WP-11b), so these
387
+ counts are the only way `delivery_evidence.in_compiled_text` can answer at all. A session whose
388
+ inventory publishes none reads unknown by `compiled_text_unavailable`; one whose rows did not
389
+ resolve reads unknown by `coverage_ref_unresolved`; neither is ever `not_delivered`."""
390
+ ids = {}
391
+ for unit in units:
392
+ ids.setdefault(unit.get("unit_ref"), []).append(unit.get("unit_id"))
393
+ facts, unresolved = {}, []
394
+ for row in shared.get("instruction_coverage") or []:
395
+ held = ids.get(row.get("unit_ref")) or []
396
+ if not held:
397
+ unresolved.append(row.get("unit_ref"))
398
+ continue
399
+ for unit_id in held:
400
+ facts[unit_id] = {"covered": row.get("covered"), "total": row.get("total")}
401
+ return facts, sorted(ref for ref in unresolved if isinstance(ref, str))
402
+
403
+
404
+ # The tools whose input NAMES the file it returned. A reader of this kind is unambiguous: the path is
405
+ # the call's own argument, not a guess about a command line.
406
+ NAMED_READERS = {"Read", "NotebookRead", "view", "read_file"}
407
+ # The tools that run a command, where the path has to be read out of the command text.
408
+ SHELL_READERS = {"Bash", "shell", "local_shell", "container.exec", "exec_command"}
409
+ # The argument names a shell tool carries its command under. `exec_command` uses `cmd`, and reading
410
+ # only `command` discarded every one of its calls as non-reading — silently, since a call with no
411
+ # command simply fell through (the WP-11b review). Named as data so a new shape is one entry.
412
+ COMMAND_ARGUMENTS = ("command", "cmd", "commands")
413
+ # What a host writes into a result when the call FAILED or when it elided the bytes. Either way the
414
+ # returned text is not what the file holds, so it is uncertainty rather than a read: a result saying
415
+ # "Process exited with code 1" was being counted as delivered bytes, and a truncation warning as
416
+ # the whole file (the WP-11b review).
417
+ EXIT_MARKER = re.compile(r"Process exited with code (\d+)")
418
+ ELISION_MARKERS = ("Warning: truncated", "[truncated]", "<response clipped>",
419
+ "… +", "... +", "[output elided]", "(output truncated)")
420
+
421
+
422
+ def result_defect(returned):
423
+ """`("result_failed", detail)` / `("result_elided", detail)` / None for one returned text.
424
+
425
+ Read before any read is admitted from it, in both adapters: the bytes a failed or elided result
426
+ carries are not the file's, and admitting them makes a delivery claim out of an error message.
427
+ """
428
+ if not isinstance(returned, str):
429
+ return None
430
+ held = EXIT_MARKER.search(returned)
431
+ if held and held.group(1) != "0":
432
+ return "result_failed", f"exit code {held.group(1)}"
433
+ for marker in ELISION_MARKERS:
434
+ if marker in returned:
435
+ return "result_elided", marker
436
+ return None
437
+ # A command that returns a file's bytes. `grep` is one: it returns the lines it matched, which can
438
+ # cover a requirement.
439
+ READING_VERBS = ("cat", "sed", "head", "tail", "less", "more", "bat", "grep", "rg", "awk")
440
+ PATH_TOKEN = re.compile(r"[\w./@~+-]*\.(?:md|markdown|json|toml|txt|ya?ml)")
441
+
442
+
443
+ def _text_of(content):
444
+ """A tool result's returned text, or None when this run cannot read it back as text.
445
+
446
+ None is `read_unparsed` material: a result the host elided, a structured payload, an image. A
447
+ miss is never claimed from a call whose bytes were not read, so the difference between "no text
448
+ here" and "text that did not cover the requirement" is kept."""
449
+ if isinstance(content, str):
450
+ return content
451
+ if isinstance(content, list):
452
+ parts = [block.get("text") for block in content
453
+ if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str)]
454
+ return "\n".join(parts) if parts else None
455
+ return None
456
+
457
+
458
+ def _paths_in(command):
459
+ """The file paths a shell command names, in order, as far as a conservative reading goes."""
460
+ return [match.group(0) for match in PATH_TOKEN.finditer(command or "")
461
+ if "/" in match.group(0) or match.group(0).startswith(".")]
462
+
463
+
464
+ def _claude_reads(lines):
465
+ """(reads, unparsed, counts) over a Claude transcript version's records.
466
+
467
+ A read is attributed to the line of its RESULT, because that is when the bytes reached the
468
+ session: the call records the intent, the result records what came back, and the judge asks what
469
+ the session had read BEFORE the decision."""
470
+ calls, reads, unparsed = {}, [], []
471
+ counts = {"results": 0, "errors": 0, "no_text": 0, "unnamed_command": 0}
472
+ for at, line in enumerate(lines, 1):
473
+ if not line.strip():
474
+ continue
475
+ try:
476
+ row = json.loads(line)
477
+ except ValueError:
478
+ continue
479
+ content = ((row.get("message") or {}).get("content"))
480
+ if not isinstance(content, list):
481
+ continue
482
+ for block in content:
483
+ if not isinstance(block, dict):
484
+ continue
485
+ if block.get("type") == "tool_use":
486
+ calls[block.get("id")] = (block.get("name"), block.get("input") or {})
487
+ continue
488
+ if block.get("type") != "tool_result":
489
+ continue
490
+ counts["results"] += 1
491
+ name, arguments = calls.get(block.get("tool_use_id"), (None, {}))
492
+ if name is None:
493
+ continue
494
+ if block.get("is_error"):
495
+ counts["errors"] += 1
496
+ continue
497
+ returned = _text_of(block.get("content"))
498
+ # The same judgment as the Codex adapter's: a result whose text says the call failed or
499
+ # that the host elided the bytes is uncertainty, not a read. `is_error` above catches
500
+ # the structured case; a host that writes the failure into the TEXT does not set it.
501
+ defect = result_defect(returned)
502
+ if name in NAMED_READERS:
503
+ path = arguments.get("file_path") or arguments.get("path") or arguments.get("notebook_path")
504
+ if not path:
505
+ continue
506
+ if returned is None:
507
+ counts["no_text"] += 1
508
+ unparsed.append({"at": at, "path": path, "reason": "result_not_text"})
509
+ elif defect:
510
+ counts[defect[0]] = counts.get(defect[0], 0) + 1
511
+ unparsed.append({"at": at, "path": path, "reason": defect[0],
512
+ "detail": defect[1]})
513
+ else:
514
+ reads.append({"at": at, "path": path, "returned": returned})
515
+ elif name in SHELL_READERS:
516
+ command = next((arguments.get(key) for key in COMMAND_ARGUMENTS
517
+ if arguments.get(key) is not None), None) \
518
+ or arguments.get("script") or ""
519
+ if isinstance(command, list):
520
+ command = " ".join(str(part) for part in command)
521
+ if not any(verb in command for verb in READING_VERBS):
522
+ continue
523
+ named = _paths_in(command)
524
+ if not named:
525
+ counts["unnamed_command"] += 1
526
+ unparsed.append({"at": at, "path": None, "reason": "command_names_no_path"})
527
+ elif returned is None:
528
+ counts["no_text"] += 1
529
+ unparsed += [{"at": at, "path": path, "reason": "result_not_text"} for path in named]
530
+ elif defect:
531
+ counts[defect[0]] = counts.get(defect[0], 0) + 1
532
+ unparsed += [{"at": at, "path": path, "reason": defect[0], "detail": defect[1]}
533
+ for path in named]
534
+ else:
535
+ reads += [{"at": at, "path": path, "returned": returned} for path in named]
536
+ return reads, unparsed, counts
537
+
538
+
539
+ def _codex_reads(lines):
540
+ """The same over a Codex rollout: `function_call` / `custom_tool_call` and their outputs."""
541
+ calls, reads, unparsed = {}, [], []
542
+ counts = {"results": 0, "errors": 0, "no_text": 0, "unnamed_command": 0}
543
+ for at, line in enumerate(lines, 1):
544
+ if not line.strip():
545
+ continue
546
+ try:
547
+ row = json.loads(line)
548
+ except ValueError:
549
+ continue
550
+ payload = row.get("payload") or {}
551
+ kind = payload.get("type")
552
+ if kind in ("function_call", "custom_tool_call"):
553
+ arguments = payload.get("arguments") or payload.get("input") or ""
554
+ if isinstance(arguments, str):
555
+ try:
556
+ arguments = json.loads(arguments)
557
+ except ValueError:
558
+ arguments = {"command": arguments}
559
+ calls[payload.get("call_id")] = (payload.get("name"), arguments if isinstance(arguments, dict) else {})
560
+ continue
561
+ if kind not in ("function_call_output", "custom_tool_call_output"):
562
+ continue
563
+ counts["results"] += 1
564
+ name, arguments = calls.get(payload.get("call_id"), (None, {}))
565
+ if name is None:
566
+ continue
567
+ output = payload.get("output")
568
+ returned = output if isinstance(output, str) else _text_of(output)
569
+ command = next((arguments.get(key) for key in COMMAND_ARGUMENTS
570
+ if arguments.get(key) is not None), None)
571
+ if isinstance(command, list):
572
+ command = " ".join(str(part) for part in command)
573
+ elif command is not None and not isinstance(command, str):
574
+ command = str(command)
575
+ defect = result_defect(returned)
576
+ if name in NAMED_READERS:
577
+ path = arguments.get("path") or arguments.get("file_path")
578
+ if not path:
579
+ continue
580
+ if returned is None:
581
+ counts["no_text"] += 1
582
+ unparsed.append({"at": at, "path": path, "reason": "result_not_text"})
583
+ elif defect:
584
+ counts[defect[0]] = counts.get(defect[0], 0) + 1
585
+ unparsed.append({"at": at, "path": path, "reason": defect[0],
586
+ "detail": defect[1]})
587
+ else:
588
+ reads.append({"at": at, "path": path, "returned": returned})
589
+ elif name in SHELL_READERS or command:
590
+ if not any(verb in (command or "") for verb in READING_VERBS):
591
+ if command is None:
592
+ # A shell tool whose argument shape this adapter does not know. Kept as named
593
+ # uncertainty rather than dropped: a discarded call is indistinguishable from a
594
+ # call nobody made, which is how `exec_command` disappeared.
595
+ counts["call_shape_unsupported"] = counts.get("call_shape_unsupported", 0) + 1
596
+ unparsed.append({"at": at, "path": None, "reason": "call_shape_unsupported",
597
+ "detail": f"{name}: {sorted(arguments)}"})
598
+ continue
599
+ named = _paths_in(command)
600
+ if not named:
601
+ counts["unnamed_command"] += 1
602
+ unparsed.append({"at": at, "path": None, "reason": "command_names_no_path"})
603
+ elif returned is None:
604
+ counts["no_text"] += 1
605
+ unparsed += [{"at": at, "path": path, "reason": "result_not_text"} for path in named]
606
+ elif defect:
607
+ counts[defect[0]] = counts.get(defect[0], 0) + 1
608
+ unparsed += [{"at": at, "path": path, "reason": defect[0], "detail": defect[1]}
609
+ for path in named]
610
+ else:
611
+ reads += [{"at": at, "path": path, "returned": returned} for path in named]
612
+ return reads, unparsed, counts
613
+
614
+
615
+ def reads_of(run_dir, copy, host):
616
+ """(reads, unparsed, counts) read from ONE immutable copy of a transcript version.
617
+
618
+ The copy S2 wrote is the only place these bytes are read from: the views are clipped, so they
619
+ cannot carry what a result returned, and the owner's own files are not this stage's to open. The
620
+ bytes stay in this process — the document carries counts, paths and states, never text.
621
+
622
+ `copy` is a LABEL from S2's manifest and is confined before the filesystem is touched. It used
623
+ to be joined with `/`, which discards `run_dir` entirely for an absolute label, follows `..`,
624
+ and follows a symlink out — so a manifest row could point this stage at any file the owner can
625
+ read, and `reads_of` would open it (the WP-11b review). A run artifact is data, and containment
626
+ cannot rest on its producer being honest. The confinement lives HERE rather than at the call
627
+ site because a caller can forget it; `run_dir` is therefore a parameter, not a convenience.
628
+ """
629
+ try:
630
+ path = stagelock.confine(run_dir, pathlib.Path(run_dir) / str(copy))
631
+ except stagelock.Escaped as exc:
632
+ raise Refused(f"EVIDENCE_OUTSIDE_RUN {copy!r}: {exc}. S2's manifest names a copy beneath "
633
+ f"the run; a label that leaves it is refused rather than read") from exc
634
+ if not path.is_file():
635
+ return [], [], {"copy_missing": True}
636
+ # The repository's JSONL splitter, not `str.splitlines()`. `splitlines()` also splits U+2028,
637
+ # U+2029 and U+0085, so one JSONL record carrying a separator inside a JSON string became two
638
+ # lines: the record ordinals this stage reports were on a different scale from S2's, and a
639
+ # record could be discarded as unparsable (the WP-11b review, the same defect as the journal's).
640
+ # `errors="replace"` was the old behaviour and is kept: a transcript byte this stage cannot
641
+ # decode is not a reason to refuse an entire session's evidence.
642
+ lines = records.jsonl_read(path, errors="replace")
643
+ reads, unparsed, counts = (_codex_reads(lines) if host == "codex" else _claude_reads(lines))
644
+ return reads, unparsed, {**counts, "records": len(lines)}
645
+
646
+
647
+ def copies_of(views):
648
+ """`{session or transcript ref: (the copy's path under the run, host)}` from S2's manifest."""
649
+ found = {}
650
+ for row in views.get("transcripts") or []:
651
+ copy = row.get("source_copy")
652
+ if not copy:
653
+ continue
654
+ for key in (row.get("session"), row.get("transcript"), row.get("name")):
655
+ if key:
656
+ found[key] = (copy, row.get("host"))
657
+ return found
658
+
659
+
660
+ def basis_of(session_row, shared_of, store):
661
+ """`(basis, pin_reason, selected, history_selected)` for one session, from the inventory's row.
662
+
663
+ `basis` is what the judge's `_selection` reads: `pin` when the pin was read and a selection
664
+ inventory answers for it, `selection_history` when the owner's library history is what answers,
665
+ and None otherwise — with the reason the inventory recorded, carried through as `pin_reason` so
666
+ the judge's unknown names it rather than reading "unpinned" over an input failure.
667
+
668
+ A pin whose selection inventory is missing is NOT a pin basis. The items a session received are
669
+ the selection's to say, and reading a pin alone as "selected nothing" would turn an input
670
+ failure into an absence — the difference between `unknown` and `not_delivered` for every unit of
671
+ that session. Measured on the lead's C2 run: 39 sessions with a read pin, none with a selection
672
+ inventory, every one `input_failed`."""
673
+ pin = session_row.get("pin") or {}
674
+ selection = session_row.get("selection") or {}
675
+ shared = shared_of(selection.get("inventory_ref")) if selection.get("inventory_ref") else None
676
+ selected = selected_items(shared, store) if shared else {}
677
+ if pin.get("status") == "read" and selection.get("status") == "read" and selected:
678
+ return "pin", None, selected, {}
679
+ reason = selection.get("reason") or pin.get("reason") or "unpinned"
680
+ if selection.get("inventory_ref") and not selected:
681
+ reason = "selection_inventory_names_no_item"
682
+ elif selection.get("status") == "read" and not selection.get("inventory_ref"):
683
+ reason = "selection_read_without_an_inventory"
684
+ elif selection.get("reason"):
685
+ reason = f"selection_{selection['reason']}"
686
+ return None, reason, selected, {}
687
+
688
+
689
+ def units_by_version(units):
690
+ """`{(carrier_id, version_sha256): [unit_id]}` — what an event's member names, as unit ids.
691
+
692
+ A native or injection event records the carrier versions it loaded (`members`), not units; the
693
+ judge asks whether the unit was among them, so the mapping is made here from the inventory's own
694
+ unit records."""
695
+ out = {}
696
+ for unit in units.values():
697
+ key = (unit.get("carrier_id"), unit.get("version_sha256"))
698
+ out.setdefault(key, []).append(unit["unit_id"])
699
+ return out
700
+
701
+
702
+ def native_events_of(session_row, events_by_ref, by_version):
703
+ """The session's native and injection events as the judge takes them: `[{at, unit_ids, kind}]`.
704
+
705
+ `at` is the event's RECORD ORDINAL — the inventory's `line` — because that is the scale
706
+ `decision_at` is on; the event's own `at` is an ISO instant and is not comparable with it. An
707
+ event whose line is unknown is dropped from the comparable set and counted, never placed at an
708
+ ordinal nobody recorded."""
709
+ rows, undated = [], 0
710
+ for event in events_by_ref.get(session_row.get("session_ref")) or []:
711
+ line = event.get("line")
712
+ if not isinstance(line, int):
713
+ undated += 1
714
+ continue
715
+ unit_ids = []
716
+ for member in event.get("members") or []:
717
+ unit_ids += by_version.get((member.get("carrier_id"), member.get("version_sha256"))) or []
718
+ rows.append({"at": line, "kind": event.get("kind"), "unit_ids": sorted(set(unit_ids))})
719
+ return sorted(rows, key=lambda row: row["at"]), undated
720
+
721
+
722
+ def release_of(release_doc, session_ref, segment_ref=None, shared_of=None, store=None):
723
+ """The reference point `derive.absence` reads for this session: `{complete, layers, items}`.
724
+
725
+ Three things were wrong here, and together they made the catalogue absence unreachable (the
726
+ WP-11b review):
727
+
728
+ * `items` was read from `unsegmented.items`, and `release_rows` HAS NO SUCH FIELD — its members
729
+ are `inventory_refs`, `layers`, `complete` and `incomplete_reasons`. So `items` was always
730
+ empty, `_absence` always answered `unknown` rather than `not_delivered`, and no catalogue
731
+ absence could ever be found. Item membership belongs to the shared inventories the row set
732
+ REFERENCES, which is where it is read from now.
733
+ * `segments` was ignored. A session a segment covers has `unsegmented: null`, so the row set
734
+ came out `{}` and every such session was reported incomplete. The applicable row set is the
735
+ segment the decision belongs to — the transcript file the event record was read from, which
736
+ the views row names — and `unsegmented` only for a session no segment covers.
737
+ * `layers` was derived from `incomplete_reasons`, which names only the layers that are NOT
738
+ complete. The per-layer status lives in `layers` (one `release_row` each); a complete layer
739
+ had no entry at all, so a reader could not tell "complete" from "not mentioned".
740
+
741
+ `shared_of` and `store` are how item membership is resolved; without them the items are reported
742
+ as unresolved rather than as empty, because an empty set is the claim that made this reachable.
743
+ """
744
+ held = next((row for row in release_doc.get("sessions") or []
745
+ if row.get("session_ref") == session_ref), None)
746
+ if held is None:
747
+ return {"complete": False, "layers": {}, "items": [],
748
+ "absent_from_release_document": True}
749
+ segments = [row for row in held.get("segments") or [] if isinstance(row, dict)]
750
+ point = None
751
+ if segment_ref is not None:
752
+ point = next((row for row in segments if row.get("segment_ref") == segment_ref), None)
753
+ if point is None and not segments:
754
+ point = held.get("unsegmented")
755
+ if point is None:
756
+ # Segments exist and none of them is the one this decision belongs to. Not an absence and
757
+ # not a completeness: the reference point for this decision was not resolved.
758
+ return {"complete": False, "layers": {}, "items": [],
759
+ "segment_unresolved": segment_ref, "segments": len(segments)}
760
+ layers = {row.get("layer"): row.get("status") for row in point.get("layers") or []
761
+ if isinstance(row, dict) and row.get("layer")}
762
+ refs = [ref for ref in point.get("inventory_refs") or [] if ref]
763
+ for row in point.get("layers") or []:
764
+ source = (row or {}).get("source") or {}
765
+ if source.get("inventory_ref"):
766
+ refs.append(source["inventory_ref"])
767
+ items, unresolved = set(), []
768
+ for ref in sorted(set(refs)):
769
+ shared = shared_of(ref) if shared_of else None
770
+ if shared is None:
771
+ unresolved.append(ref)
772
+ continue
773
+ items.update(released_items(shared, store or {}))
774
+ return {"complete": point.get("complete") is True, "layers": layers,
775
+ "items": sorted(items),
776
+ # The references this run could not open. Reported rather than folded into an empty
777
+ # `items`: an empty set says the release holds nothing, which is an absence claim.
778
+ "items_unresolved": unresolved,
779
+ "items_from": sorted(set(refs)),
780
+ "point": "segment" if point is not held.get("unsegmented") else "unsegmented"}
781
+
782
+
783
+ def session_evidence(session_row, events_by_ref, by_version, release_doc, shared_of, store,
784
+ run_dir=None, copies=None, unit_records=(), segment_ref=None):
785
+ """The judge's `session` input: selection and the snapshot's facts, the events, the release, and
786
+ the bytes the session read back.
787
+
788
+ Three sources, each with its own absence rule. The inventory answers selection, events and the
789
+ release. S2 answers what the session was GIVEN — the items with their surfaces and the per-unit
790
+ coverage of the compiled instruction text, as counts, because that text is the owner's and never
791
+ enters a run. The run's immutable copy answers what the session READ. A key one of them cannot
792
+ fill is absent rather than empty, so no reader can mistake "not assembled" for "nothing there"."""
793
+ basis, pin_reason, selected, history = basis_of(session_row, shared_of, store)
794
+ native, undated = native_events_of(session_row, events_by_ref, by_version)
795
+ evidence = {"session_ref": session_row.get("session_ref"), "basis": basis,
796
+ "selected": selected, "history_selected": history,
797
+ "native_events": native,
798
+ # The reference point for THIS session's segment, with the items resolved through
799
+ # the inventories the row set references.
800
+ "release": release_of(release_doc, session_row.get("session_ref"),
801
+ segment_ref, shared_of, store)}
802
+ # The instant the selected instructions were put in front of the session, on the record-ordinal
803
+ # scale: the FIRST recorded injection, because the ladder asks whether the session had been given
804
+ # the selection before the decision, and the earliest recorded one is the earliest this run can
805
+ # say. Absent when no injection is recorded, which leaves the judge to answer
806
+ # `injection_unrecorded_before_decision` rather than read an unrecorded injection as none. The
807
+ # fixture library is what found this missing: without it every always-surface unit stopped at
808
+ # `selected`, whatever the coverage facts said.
809
+ injections = [row["at"] for row in native if row.get("kind") == "session_injection"]
810
+ if injections:
811
+ evidence["injection_at"] = min(injections)
812
+ if pin_reason:
813
+ evidence["pin_reason"] = pin_reason
814
+ counts = {"native_events": len(native), "events_without_a_line": undated}
815
+ # The snapshot's facts, as S2 published them on this session's selection inventory: the rows a
816
+ # surface could not be routed on, and the per-unit coverage of the compiled instruction text.
817
+ # Looked up here as well as in `basis_of` because the two read the document for different
818
+ # answers, and a basis of None does not mean the facts are absent.
819
+ selection_ref = (session_row.get("selection") or {}).get("inventory_ref")
820
+ shared = shared_of(selection_ref) if selection_ref else None
821
+ if shared is not None:
822
+ facts, unresolved_refs = coverage_facts(shared, unit_records)
823
+ unavailable = [row for row in shared.get("unavailable") or [] if isinstance(row, dict)]
824
+ # Absent rather than empty, by the same rule as `reads`: an empty block is "the text covered
825
+ # nothing", which is a claim, and a missing one is "this run cannot say", which is the truth.
826
+ if facts:
827
+ evidence["instruction_coverage"] = facts
828
+ if unavailable:
829
+ evidence["unavailable"] = unavailable
830
+ # The pointer predicate and the per-unit catalogue surface, both facts S2 publishes because
831
+ # both are read off the compiled text or the owner's baseline. The pointer map goes to the
832
+ # judge as it is; the surfaces are translated per pair, where the unit id is known.
833
+ pointers = pointer_facts(shared)
834
+ if pointers:
835
+ evidence["item_pointer_in_compiled_text"] = pointers
836
+ if shared.get("router_path") is not None:
837
+ evidence["router_path"] = shared["router_path"]
838
+ # WHY a pointer could not be established, which S2 now publishes
839
+ # (`compiled_text_absent` | `catalog_rule_unread`) instead of leaving the list absent. An
840
+ # absent list and an established absence read the same to the judge, and the judge then
841
+ # asserted "no pointer" from an input nobody had read; with the reason it answers
842
+ # `pointer_unavailable:<reason>` instead.
843
+ if shared.get("item_pointer_unavailable"):
844
+ evidence["item_pointer_unavailable"] = shared["item_pointer_unavailable"]
845
+ surfaces = surface_facts(shared)
846
+ counts.update({"coverage_facts": len(facts), "unavailable_rows": len(unavailable),
847
+ "coverage_refs_unresolved": unresolved_refs,
848
+ "pointer_facts": len(pointers), "unit_surfaces": len(surfaces),
849
+ "compiled_text_digest": "present" if shared.get("instruction_text_sha256") else "absent"})
850
+ # The session's own records, from the run's immutable copy. Absent rather than empty when the run
851
+ # holds no copy for this session: an empty `reads` is "it read nothing", which is a claim, and a
852
+ # missing key is "this run cannot say", which is the truth.
853
+ key = session_row.get("session") or session_row.get("session_ref")
854
+ found = (copies or {}).get(key) or (copies or {}).get((session_row.get("transcript") or {}).get("id"))
855
+ if found and run_dir is not None:
856
+ copy, host = found
857
+ reads, unparsed, read_counts = reads_of(run_dir, copy, host)
858
+ if read_counts.get("copy_missing"):
859
+ # The manifest NAMES a copy and the file is not there. Installing `reads = []` here made
860
+ # that "the session read nothing", which is a claim — and the judge then reported an
861
+ # exposed guide as not read, from evidence nobody acquired (the WP-11b review). The
862
+ # acquisition state is carried instead, and the pair is answered unknown by name.
863
+ counts["copy"] = "missing"
864
+ evidence["read_evidence"] = {"status": "unavailable", "reason": "copy_missing",
865
+ "copy": str(copy)}
866
+ else:
867
+ evidence["reads"] = reads
868
+ evidence["unparsed"] = [row for row in unparsed if row.get("path")]
869
+ evidence["read_evidence"] = {"status": "available", "reason": None,
870
+ "copy": str(copy)}
871
+ counts.update({"reads": len(reads), "unparsed": len(unparsed),
872
+ "unparsed_without_a_path": sum(1 for row in unparsed
873
+ if not row.get("path")),
874
+ **{f"records_{k}": v for k, v in read_counts.items()}})
875
+ else:
876
+ # No manifest entry at all: this run holds no copy for the session, which is a different
877
+ # thing from a copy it holds and cannot open. Both are unknown, and the reason says which.
878
+ # No manifest entry at all: `reads` stays ABSENT, which the judge already reads as "this
879
+ # run cannot say" — that half was right. Only a copy the manifest NAMES and this run cannot
880
+ # open was installing an empty `reads` as a claim, so only that half gains a reason.
881
+ counts["copy"] = "absent"
882
+ evidence["read_evidence"] = {"status": "absent", "reason": "copy_absent", "copy": None}
883
+ return evidence, counts
884
+
885
+
886
+ def unit_index(current):
887
+ """`{unit_id: the unit in the judge's input shape}`, built from the inventory's own records.
888
+
889
+ The operative context is the ONE-STEP set the §6.2 judge packet holds — `edges.direct` plus
890
+ `edges.reached`, which the inventory publishes on every current unit since lane E's export
891
+ (plan WP-11 D1 (a1)) — and never the transitive `operative_context` closure beside it, and never
892
+ a recomputation of mentions here. The export is carried by every unit of a document or by none,
893
+ so a document without it is refused by name rather than read with the closure as a stand-in."""
894
+ units, without, misshapen = {}, [], []
895
+ for row in current.get("units") or []:
896
+ edges = row.get("edges")
897
+ if not isinstance(edges, dict):
898
+ without.append(row.get("unit_id"))
899
+ continue
900
+ # `block` is the KIND of block the unit is, a string from the inventory's own enum
901
+ # (`inventory.BLOCK_KINDS`), and `start` is not published in the emitted document at all.
902
+ # This index read `block` as an object and took `start` out of it, so every real S2 unit
903
+ # raised AttributeError here while the frozen fixtures — which carried `block: {"start": …}`,
904
+ # a shape no producer writes — passed. Refusing by name is what makes the next shape change
905
+ # a message instead of a traceback.
906
+ if row.get("block") is not None and not isinstance(row["block"], str):
907
+ misshapen.append(f"{row.get('unit_id')}: block is {type(row['block']).__name__}, not the "
908
+ f"string kind the inventory publishes")
909
+ continue
910
+ context = sorted({row["unit_id"], *(edges.get("direct") or []), *(edges.get("reached") or [])})
911
+ units[row["unit_id"]] = {
912
+ "unit_id": row["unit_id"], "path": row.get("path"), "text": row.get("text"),
913
+ "version_sha256": row.get("version_sha256"), "layer": row.get("layer"),
914
+ "item_ref": row.get("item_ref"), "carrier_id": row.get("carrier_id"),
915
+ "n": row.get("n"),
916
+ # Published if the inventory ever publishes it; today it does not, and the ordering in
917
+ # `delivery_evidence.units_of` falls back to `n`, the occurrence number, which it does
918
+ # publish. Carried as None rather than dropped so a reader can tell "not published"
919
+ # from "zero".
920
+ "start": row.get("start"), "block": row.get("block"),
921
+ "operative_context": context, "context_source": "inventory.edges",
922
+ }
923
+ if misshapen:
924
+ raise Refused(f"DELIVERY_UNIT_SHAPE {len(misshapen)} current unit(s) are not in the shape "
925
+ f"`inventory.emitted_document` writes (first: {misshapen[:2]})")
926
+ if without:
927
+ raise Refused(f"DELIVERY_EDGES_ABSENT {len(without)} current unit(s) carry no `edges` "
928
+ f"(first: {without[:3]}): the one-step context set is the inventory's to "
929
+ f"publish, and reading the transitive closure instead would answer a "
930
+ f"different question than the judge's")
931
+ return units
932
+
933
+
934
+ REDACTED = projection.FLOOR.PLACEHOLDER
935
+
936
+
937
+ def consumed_binding(run_dir, paths):
938
+ """`[{path, sha256}]` for every file this stage READ that its declaration cannot pin.
939
+
940
+ `records.run_stage` pins each DECLARED input against its producer's recorded output digest.
941
+ Three kinds of file this stage reads are not declarable that way: the event records under
942
+ `events/`, `inventory/shared/store.json`, and the per-session
943
+ `inventory/shared/selection-<ref>.json` — the last two because which ones exist depends on the
944
+ run, and a static declaration of a file a run does not hold would refuse the run
945
+ (`INPUT_INVALID`). They determine the verdict all the same, so their bytes are published HERE,
946
+ with the document that rests on them: a reader can then tell whether the evidence moved under a
947
+ later stage, which was not knowable at all before (the WP-11b review).
948
+
949
+ This is a BINDING, not a check. Nothing in this run holds an earlier digest to compare it with,
950
+ and saying so is the honest half; `records.provenance_problems` is what compares, and it can
951
+ only compare what a producer recorded.
952
+ """
953
+ root = pathlib.Path(run_dir)
954
+ held = []
955
+ for path in sorted(set(str(one) for one in paths)):
956
+ path = pathlib.Path(path)
957
+ if not path.is_file():
958
+ continue
959
+ try:
960
+ relative = str(path.relative_to(root))
961
+ except ValueError:
962
+ relative = str(path)
963
+ held.append({"path": relative, "sha256": records.sha256_file(path)})
964
+ return held
965
+
966
+
967
+ def document(run_dir, checks, candidates, current, sessions, release_doc, store, shared_of, sources,
968
+ views=None, population=None):
969
+ """The stage's document: one row per owed pair, and the summary a reader counts from."""
970
+ # Every file read below whose bytes the declaration cannot pin, collected as they are opened.
971
+ consumed = sorted((pathlib.Path(run_dir) / EVENTS_DIR).glob("*.jsonl")) \
972
+ if (pathlib.Path(run_dir) / EVENTS_DIR).is_dir() else []
973
+ consumed.append(pathlib.Path(run_dir) / "inventory" / "shared" / "store.json")
974
+ for held_row in (sessions or {}).get("sessions") or []:
975
+ held_ref = (held_row.get("selection") or {}).get("inventory_ref")
976
+ if held_ref:
977
+ consumed.append(pathlib.Path(run_dir) / "inventory" / "shared"
978
+ / f"selection-{held_ref}.json")
979
+ units = unit_index(current)
980
+ # Every carrier version this run names, with its lines: the binding a read's bytes are matched
981
+ # against. One assembly per document, because it is the same for every pair.
982
+ universe = version_universe(current, store)
983
+ # The inventory's own `r-` reference per unit id: S2 keys its per-unit facts by it, and the judge
984
+ # asks by unit id.
985
+ refs_by_unit = {row.get("unit_id"): row.get("unit_ref") for row in current.get("units") or []}
986
+ by_name, by_transcript = sessions_index(sessions)
987
+ decisions = decisions_of(run_dir)
988
+ by_version = units_by_version(units)
989
+ events_by_ref = {}
990
+ for event in sessions.get("events") or []:
991
+ events_by_ref.setdefault(event.get("session_ref"), []).append(event)
992
+ rows_by_ref, counts_by_ref = {}, {}
993
+ for row in sessions.get("sessions") or []:
994
+ ref = row.get("session_ref")
995
+ rows_by_ref[ref] = row
996
+ rows = []
997
+ for pair in pairs_of(checks, candidates, decisions, by_name, by_transcript,
998
+ view_index(views), population):
999
+ unit = units.get(pair["unit_id"]) if pair["unit_id"] else None
1000
+ session_row = rows_by_ref.get(pair["session_ref"])
1001
+ evidence, session_counts, session_surfaces = None, {}, {}
1002
+ if session_row is not None:
1003
+ if pair["session_ref"] not in counts_by_ref:
1004
+ # The SEGMENT this session's records were read from, as S2's views row names it:
1005
+ # the reference point for a decision belongs to the segment the record is in, and a
1006
+ # session several rollout files cover has one row set per segment.
1007
+ held_view = next((row for row in (views or {}).get("transcripts") or []
1008
+ if row.get("session") == session_row.get("session")
1009
+ or row.get("transcript")
1010
+ == (session_row.get("transcript") or {}).get("id")), None)
1011
+ built, counts = session_evidence(session_row, events_by_ref, by_version, release_doc,
1012
+ shared_of, store, run_dir,
1013
+ copies_of(views or {}), current.get("units") or (),
1014
+ (held_view or {}).get("segment"))
1015
+ # The per-unit catalogue surfaces are kept beside the evidence rather than inside it:
1016
+ # they are keyed by the inventory's `r-` reference and belong to the pair, where the
1017
+ # unit id is known, and the judge's input shape is not widened to carry them.
1018
+ selection_ref = (session_row.get("selection") or {}).get("inventory_ref")
1019
+ shared = shared_of(selection_ref) if selection_ref else None
1020
+ counts_by_ref[pair["session_ref"]] = (built, counts,
1021
+ surface_facts(shared) if shared else {})
1022
+ evidence, session_counts, session_surfaces = counts_by_ref[pair["session_ref"]]
1023
+ # Every reason that holds, in the order a reader would ask them, and never one in place of
1024
+ # another: a pair can lack a decision AND name a unit the inventory does not carry, and a
1025
+ # row that reported only the last of those would send someone to the wrong artifact.
1026
+ reasons = []
1027
+ # Reasons that are RECORDED but do not stop the judge: an input the ladder this pair is
1028
+ # judged on does not need. They reach the row like any other reason, so nothing is hidden;
1029
+ # what they do not do is turn a judgeable pair into an unknown (the WP-11b review).
1030
+ carried = []
1031
+ if pair.get("reason") == NOT_SESSION_DERIVED:
1032
+ rows.append({**{k: v for k, v in pair.items() if k != "reason"}, "state": "unknown", "level": None,
1033
+ "reasons": [NOT_SESSION_DERIVED], "population": NOT_SESSION_DERIVED, "surface": None,
1034
+ "selection": None, "decision_ordinal": None,
1035
+ "requirements": len(unit["operative_context"]) if unit else None, "native_events": 0,
1036
+ "reads": None, "release_complete": None, "coverage": None,
1037
+ "coverage_refs_unresolved": 0})
1038
+ continue
1039
+ if pair.get("reason"):
1040
+ reasons.append(pair["reason"])
1041
+ if pair["unit_id"] and unit is None:
1042
+ reasons.append("unit_absent_from_inventory")
1043
+ elif unit is not None and (unit.get("text") == REDACTED or not unit.get("text")):
1044
+ # A unit whose own text this run cannot see cannot be judged on its lines, and handing the
1045
+ # judge the redaction placeholder would make every comparison fail — a MISS claimed from
1046
+ # evidence nobody read, which is the one thing §6.3 forbids. The pair is answered unknown
1047
+ # by name instead. 14,116 of 26,855 current units are redacted on the lead's C2 run.
1048
+ reasons.append("unit_text_redacted")
1049
+ if evidence is None:
1050
+ reasons.append("session_absent_from_inventory")
1051
+ elif evidence.get("basis") is None:
1052
+ # The missing pin is RECORDED either way, because a reader counts it. Whether it also
1053
+ # stops the judge depends on the LADDER: §6.3's native rung is answered by the session's
1054
+ # own events — an event that loaded this unit's carrier version is evidence of delivery
1055
+ # on its own, and the selection pin says nothing about it. Treating every absent basis
1056
+ # as a missing input made an unpinned session with a native event answer
1057
+ # `unknown: unpinned`, over evidence that was already sufficient (the WP-11b review).
1058
+ held_native = [row for row in evidence.get("native_events") or []
1059
+ if pair["unit_id"] and pair["unit_id"] in (row.get("unit_ids") or ())]
1060
+ if held_native:
1061
+ carried.append(evidence.get("pin_reason") or "unpinned")
1062
+ else:
1063
+ reasons.append(evidence.get("pin_reason") or "unpinned")
1064
+ # Whether the session's RECORDS could be read at all. An empty `reads` from a copy this run
1065
+ # cannot open is not "it read nothing": the pair is named unknown with the acquisition's own
1066
+ # reason, so a missing copy cannot become a claim that an exposed guide went unread.
1067
+ if evidence is not None:
1068
+ held_acquisition = evidence.get("read_evidence") or {}
1069
+ if held_acquisition.get("status") == "unavailable":
1070
+ reasons.append(held_acquisition.get("reason") or "read_evidence_unavailable")
1071
+ # A coverage row S2 published that resolved to no unit of this run. Named on every pair of
1072
+ # that session whose unit the block could not answer for, so a block that lost its rows is
1073
+ # visible as a resolution failure rather than as a session nobody published facts for. It
1074
+ # never changes the state away from unknown: a fact that failed to resolve is not evidence
1075
+ # that the text lacked the unit's lines.
1076
+ if (session_counts.get("coverage_refs_unresolved")
1077
+ and (evidence or {}).get("instruction_coverage", {}).get(pair["unit_id"]) is None):
1078
+ reasons.append(UNRESOLVED)
1079
+ # The judge answers the pair when the four things it reads are all there: the unit with its
1080
+ # own text, the session's evidence, and the decision's ordinal. Any one missing is a pair
1081
+ # this stage can only name, never judge, so the reasons above stand on their own and the
1082
+ # state is the unknown they explain. The judge is never handed a stand-in for a missing
1083
+ # input — that is how a miss gets claimed from evidence nobody read.
1084
+ answer = None
1085
+ if not reasons and unit is not None and evidence is not None and pair.get("decision_at") is not None:
1086
+ # The ladder §6.3 judges a unit on is the surface the SESSION's snapshot selected its item
1087
+ # at, which is a fact about that session and not a property of the unit — two sessions can
1088
+ # hold the same unit at different surfaces, and the native layers are judged by their layer
1089
+ # with no surface at all. So the surface is attached per pair, from the session's own
1090
+ # selection, and a session that states none leaves the judge to answer
1091
+ # `surface_unclassified` rather than be handed a guess.
1092
+ # ONE owner for that rule: `delivery_evidence.attach_surface`. This stage carried its
1093
+ # own copy — the snapshot's selection, then the selection history, then S2's published
1094
+ # catalogue surface, and only where the judge's own classifier cannot place the unit
1095
+ # already — and a rule in two places is what this review keeps finding. The copy is
1096
+ # gone; the stage translates the unit id to its item ref, which is the one thing only
1097
+ # the stage knows, and the rule itself answers.
1098
+ subject = delivery_evidence.attach_surface(
1099
+ unit, evidence, session_surfaces.get(refs_by_unit.get(unit["unit_id"])))
1100
+ # The version universe this run names, not the current units alone: see
1101
+ # `version_universe`. Computed once per document, above the pair loop.
1102
+ answer = delivery_evidence.delivery(subject, units, evidence, pair["decision_at"],
1103
+ versions=universe)
1104
+ else:
1105
+ reasons.append(UNJUDGED)
1106
+ held = (answer or {}).get("requirements") or []
1107
+ rows.append({**{k: v for k, v in pair.items() if k != "reason"},
1108
+ "state": (answer or {}).get("state", "unknown"),
1109
+ "level": (answer or {}).get("level"),
1110
+ # The judge's own reasons, then the pair's, then the ones carried past the
1111
+ # judge: a reader sees the missing pin even when it did not block the answer.
1112
+ "reasons": list(dict.fromkeys(
1113
+ ((answer or {}).get("reasons") or reasons) + carried)),
1114
+ "surface": (answer or {}).get("surface"),
1115
+ "selection": (answer or {}).get("selection"),
1116
+ "decision_ordinal": "event.at_record" if pair.get("decision_at") is not None else None,
1117
+ "requirements": len(unit["operative_context"]) if unit else None,
1118
+ "native_events": len((evidence or {}).get("native_events") or []),
1119
+ "reads": None if evidence is None or "reads" not in evidence
1120
+ else len(evidence["reads"]),
1121
+ "release_complete": ((evidence or {}).get("release") or {}).get("complete"),
1122
+ # The per-requirement coverage, as counts of what each requirement's own status
1123
+ # was. Never the lines themselves and never the bytes: a count is what a reader
1124
+ # of this file is owed, and the judge's own rows hold the rest.
1125
+ "coverage": None if answer is None else {
1126
+ "requirements": len(held),
1127
+ "met": sum(1 for row in held if row.get("status") == "met"),
1128
+ "unmet": sum(1 for row in held if row.get("status") == "unmet"),
1129
+ "unknown": sum(1 for row in held if row.get("status") == "unknown")},
1130
+ "coverage_refs_unresolved": len(session_counts.get("coverage_refs_unresolved") or ())})
1131
+ states = {}
1132
+ for row in rows:
1133
+ states[row["state"]] = states.get(row["state"], 0) + 1
1134
+ # The resolution failures, per session and in total: a count a reader can see, and the refs
1135
+ # themselves, which are inventory ids rather than anything a session wrote.
1136
+ unresolved_by_session = {ref: counts.get("coverage_refs_unresolved") or []
1137
+ for ref, (_built, counts, _surfaces) in counts_by_ref.items()
1138
+ if counts.get("coverage_refs_unresolved")}
1139
+ unjudged = sum(1 for row in rows if UNJUDGED in row["reasons"])
1140
+ apart = sum(1 for row in rows if row.get("population") == NOT_SESSION_DERIVED)
1141
+ # The installer surface is not a unit's: §6.3 answers it from the installation binding and its
1142
+ # receipt, through `installer_exposure` rather than through a ladder. This run holds neither —
1143
+ # the binding is a verdict over the owner's state root and the receipt lives beside it, and S2
1144
+ # publishes no part of either today — so the judge is called with the inputs as they are and
1145
+ # answers `unknown: unbound`. The inputs are NOT invented here, and the absent producer is named
1146
+ # in the document, because an installer row that read `delivered` from nothing would be the one
1147
+ # claim §6.3 forbids. Raised with the lead as the same boundary question the compiled text had.
1148
+ installer = {**delivery_evidence.installer_exposure(None, None, None),
1149
+ "inputs": {"binding": "no_producer_in_the_run", "receipt": "no_producer_in_the_run",
1150
+ "snapshot_artifacts": "no_producer_in_the_run"},
1151
+ "producer_absent": "the installation binding is a verdict over the owner's state root "
1152
+ "and S2 publishes no part of it; acquiring it here would move the "
1153
+ "boundary this package was told to keep at S2"}
1154
+ return {"stage": STAGE, "complete": not unjudged,
1155
+ # A pair this stage could not hand to the judge is `unknown` with the input it lacked
1156
+ # named, and is counted here. It is a state INSIDE a file that exists, never S6's
1157
+ # `delivery_assembly_waiting`, which is S6's state when no such file exists at all —
1158
+ # the two must stay distinguishable, because one says the evidence was assembled and
1159
+ # answered nothing for this pair and the other says nobody assembled any.
1160
+ "pending_reason": None if not unjudged else
1161
+ f"{unjudged} of {len(rows) - apart} session-derived pairs lack one of the judge's inputs and are "
1162
+ f"`unknown` naming it ({PENDING}); this is the per-pair state inside a file "
1163
+ f"that exists, not S6's `delivery_assembly_waiting`",
1164
+ "sources": {"count": len(sources), "dir": SOURCES_DIR},
1165
+ # The bytes this stage read that its declaration cannot pin. See `consumed_binding`:
1166
+ # published rather than checked, because nothing here holds an earlier digest.
1167
+ "consumed": consumed_binding(run_dir, consumed),
1168
+ "consumed_unpinnable": ("the event records, the shared store and the per-session "
1169
+ "selection inventories are read by this stage and are not "
1170
+ "declarable inputs; their digests are published here so a "
1171
+ "later reader can tell whether they moved"),
1172
+ "context_source": "inventory.edges",
1173
+ "ordinal_source": {"decision": "the first component of an event record's at_record",
1174
+ "events": "the inventory event's line; its `at` is an ISO instant and "
1175
+ "is not on this scale"},
1176
+ "rows": rows,
1177
+ "installer": installer,
1178
+ "summary": {"pairs": len(rows), "states": states,
1179
+ # Which producer's population each pair came from, so a reader can see the
1180
+ # planted controls were asked about rather than left out of the denominator.
1181
+ "pairs_by_producer": dict(sorted(collections.Counter(
1182
+ row.get("producer") or "unknown" for row in rows).items())),
1183
+ "sessions": len({row["session_ref"] for row in rows if row["session_ref"]}),
1184
+ "units": len({row["unit_id"] for row in rows if row["unit_id"]}),
1185
+ "decisions": len({row["decision_at"] for row in rows if row["decision_at"] is not None}),
1186
+ "pairs_without_a_decision": sum(1 for row in rows if row["decision_at"] is None),
1187
+ "coverage_refs_unresolved": sum(len(refs) for refs in unresolved_by_session.values()),
1188
+ "sessions_with_an_unresolved_coverage_ref": len(unresolved_by_session),
1189
+ "pairs_named_" + UNRESOLVED: sum(1 for row in rows if UNRESOLVED in row["reasons"]),
1190
+ # Outside the denominator: no session, so no delivery question (NOT_SESSION_DERIVED).
1191
+ "pairs_" + NOT_SESSION_DERIVED: apart,
1192
+ "pairs_session_derived": len(rows) - apart,
1193
+ "pairs_judged": len(rows) - apart - unjudged,
1194
+ "pairs_" + UNJUDGED: unjudged},
1195
+ "coverage_refs_unresolved": {ref: refs for ref, refs in sorted(unresolved_by_session.items())}}
1196
+
1197
+
1198
+ def run(run_dir):
1199
+ """S5b over S5's checks and S2's inventory. Refuses before any write; writes one document."""
1200
+ run_dir = pathlib.Path(run_dir)
1201
+ stopped = standing_stop(run_dir)
1202
+ if stopped:
1203
+ raise Refused(f"DELIVERY_RUN_STOPPED {stopped}: the evidence after a stop is the evidence of a run that did "
1204
+ f"not finish, and this document is read as though it were whole")
1205
+ sources = sources_present(run_dir)
1206
+ if not sources:
1207
+ raise Refused(f"DELIVERY_SOURCES_MISSING {run_dir / SOURCES_DIR}: the bytes a session read back are read from "
1208
+ f"the run's immutable copy, which S2 writes; nothing else is an acquisition this stage may make")
1209
+ # BEFORE the stage record is published. `run_stage` writes `status: running` on entry and
1210
+ # `status: failed` on the way out of a refusal, so a prerequisite checked inside it leaves a
1211
+ # failed attempt behind for a condition that was knowable first — and a stage record that says
1212
+ # an attempt failed is read as an attempt (the WP-11b review). The edges export is S2's, so
1213
+ # whether it is there is decidable from S2's own document with nothing of this stage's written.
1214
+ held_current = records.read_json(run_dir / "inventory" / "current.json")
1215
+ unit_index(held_current)
1216
+ with records.run_stage(run_dir, STAGE, INPUTS) as stage:
1217
+ checks = records.read_json(run_dir / "checks.json")
1218
+ candidates = records.read_json(run_dir / "candidates.json")
1219
+ current = records.read_json(run_dir / "inventory" / "current.json")
1220
+ sessions = records.read_json(run_dir / "inventory" / "sessions.json")
1221
+ release_doc = records.read_json(run_dir / "inventory" / "release.json")
1222
+ store_path = run_dir / "inventory" / "shared" / "store.json"
1223
+ store = records.read_json(store_path) if store_path.is_file() else {}
1224
+
1225
+ def shared_of(inventory_ref):
1226
+ """The shared selection inventory a session names, or None when the run does not hold it."""
1227
+ path = run_dir / "inventory" / "shared" / f"selection-{inventory_ref}.json"
1228
+ return records.read_json(path) if path.is_file() else None
1229
+
1230
+ views = records.read_json(run_dir / VIEWS_FILE)
1231
+ doc = document(run_dir, checks, candidates, current, sessions, release_doc, store, shared_of,
1232
+ sources, views)
1233
+ records.write_json(run_dir, run_dir / OUTPUT, doc)
1234
+ stage.output(OUTPUT)
1235
+ declaration_seq = stage.record["declaration_seq"]
1236
+ return {**doc["summary"], "complete": doc["complete"], "declaration_seq": declaration_seq}
1237
+
1238
+
1239
+ def report_lines(summary):
1240
+ return [f"S5b delivery evidence: {summary['pairs']} pair(s) over {summary['sessions']} session(s) and "
1241
+ f"{summary['units']} unit(s); states {summary['states']}",
1242
+ f"S5b: complete={summary['complete']} (the evidence readers land in the following commits)"]
1243
+
1244
+
1245
+ # ---- the §6.3 fixture library, at the RECORDS level ---------------------------------------------
1246
+
1247
+ FIXTURES_PATH = HERE / "tables" / "stage_delivery_fixtures.json"
1248
+ # One fixture per state path this stage can write. W2 froze the judge's own fixtures per TABLE ROW
1249
+ # (`tables/delivery_evidence_fixtures.json`); these are the same states reached the long way, from
1250
+ # run-shaped artifacts through `document`, which is the only way to tell a judge that answers from a
1251
+ # producer that assembles the right evidence. The two stage-level paths are this stage's own states,
1252
+ # not §6.3's, and are named as such.
1253
+ STATE_PATHS = ("delivered", "exposed_not_read", "not_delivered",
1254
+ "not_delivered/selection_lacks_item", "selected_unavailable",
1255
+ "unknown/absent_from_compiled_text", f"unknown/{UNRESOLVED}", f"unknown/{UNJUDGED}")
1256
+
1257
+
1258
+ def _producer_current(text="# Guide\n\n- the rule\n", path="claude/guides/g.md",
1259
+ layer="catalog", item_ref="claude:guides/g"):
1260
+ """A real `current` document, from S2's own producer over a carrier written here.
1261
+
1262
+ The fixtures used to carry a hand-written unit whose `block` was an object with a `start` in it.
1263
+ No producer writes that: `block` is a string kind and `start` is not published at all, so
1264
+ `unit_index` worked on every fixture and raised AttributeError on every real document. The shape
1265
+ must come from the producer, and it does not need the owner's data to do so — a carrier built
1266
+ from this text, under a fixture home, goes through `inventory.emitted_document`, which is THE
1267
+ production path (`reference_of` calls the same function).
1268
+ """
1269
+ from runlib import inventory
1270
+
1271
+ # Removed before returning: the umbrella fails a leg that leaves an entry in TMPDIR, and it is
1272
+ # right to — a suite that litters cannot tell its own leftovers from a run's.
1273
+ with tempfile.TemporaryDirectory(prefix="s5b-fx-home-") as home:
1274
+ ctx = {"home": home, "state_root": None, "notes": {}, "commit": None,
1275
+ "release_ref": None, "snapshot": {}, "events": []}
1276
+ held = inventory.carrier(layer, path, text, item_ref=item_ref)
1277
+ document, _units = inventory.emitted_document(
1278
+ "current", [{"layer": layer, "producer": "the S5b fixture producer",
1279
+ "status": "complete", "reasons": [], "carriers": [held]}], ctx)
1280
+ operative = [unit for unit in document["units"] if unit.get("class") == "operative"]
1281
+ if not operative:
1282
+ raise Refused("FIXTURE_PRODUCER_EMPTY: the producer published no operative unit, so a "
1283
+ "fixture built from it would assert nothing")
1284
+ return document, operative[0]
1285
+
1286
+
1287
+ def _records_fixture(path_id):
1288
+ """The run-shaped artifacts that drive `document` to one state path, and what it must answer.
1289
+
1290
+ Every fixture is a whole set of artifacts in the spellings their producers write, because that is
1291
+ what this stage reads: a fixture written in the judge's input shape would test the judge again
1292
+ and say nothing about the assembly. The session, the unit and the decision are the same in all of
1293
+ them; what differs is the evidence, which is the point.
1294
+ """
1295
+ # The unit and the document around it come from S2's producer, not from this file. Every id the
1296
+ # other artifacts have to agree with is then read OFF the produced unit, because a fixture whose
1297
+ # carrier id is a row of zeros agrees only with itself.
1298
+ current_doc, unit = _producer_current()
1299
+ carrier_id = unit["carrier_id"]
1300
+ version = unit["version_sha256"]
1301
+ item_ref = unit["item_ref"]
1302
+ unit_ref = unit["unit_ref"]
1303
+ unit_id = unit["unit_id"]
1304
+ session_ref = "p-" + "1" * 24
1305
+ base = {
1306
+ "events": [{"event_id": "v-1", "at_record": "500/message/content", "kind": "request"}],
1307
+ "checks": {"candidates": [{"candidate_id": "k-1", "named_units_absent": [],
1308
+ "retrieved_units": [{"unit_id": unit_id, "layer": "catalog", "rank": 1,
1309
+ "score": 1.0, "named": True, "copies": 1}]}]},
1310
+ "candidates": {"candidates": [{"candidate_id": "k-1", "sessions": ["claude:t-1"],
1311
+ "event_ids": ["v-1"]}]},
1312
+ "current": current_doc,
1313
+ "sessions": {"sessions": [{"session_ref": session_ref, "session": "claude:t-1",
1314
+ "transcript": {"host": "claude", "id": "t-1", "source": "claude_projects"},
1315
+ "pin": {"status": "read", "content_ref": "b" * 64, "baseline_ref": None,
1316
+ "include_global_instructions": True, "reason": None},
1317
+ "selection": {"status": "read", "reason": None,
1318
+ "inventory_ref": "i-" + "a" * 24},
1319
+ "delivery": {"status": "unknown", "reason": None, "event_refs": []}}],
1320
+ "events": [{"event_id": "e-1", "kind": "session_injection", "session_ref": session_ref,
1321
+ "line": 10, "at": "2026-09-16T07:44:40+00:00", "members": []}]},
1322
+ # The row set in the shape `inventory.schema.json` `release_rows` REQUIRES: the item
1323
+ # membership is the referenced inventory's, not a field of this row set (it has none), and
1324
+ # `layers` carries the per-layer status with `minItems: 1`. The fixture carried `items` and
1325
+ # no `layers`, which no producer writes — and `release_of` read exactly that invented shape
1326
+ # (the WP-11b review).
1327
+ "release": {"sessions": [{"session_ref": session_ref, "segments": [],
1328
+ "unsegmented": {"inventory_refs": ["i-" + "b" * 24],
1329
+ "layers": [{"layer": "catalog",
1330
+ "status": "complete", "reasons": [],
1331
+ "source": {"inventory_ref":
1332
+ "i-" + "b" * 24,
1333
+ "layer": "catalog",
1334
+ "basis":
1335
+ "selection_history"}}],
1336
+ "complete": True,
1337
+ "incomplete_reasons": []}}]},
1338
+ # The release's own inventory, keyed by its ref: what the owner's library HELD at the
1339
+ # session's reference point, which is not what the session received.
1340
+ # ITEMS only, no carriers: `selected_items` resolves a carrier's version through the store,
1341
+ # and this fixture's store deliberately maps that version to another item — so carrying the
1342
+ # carrier here would overwrite the release's own membership with the selection's.
1343
+ "shared_by_ref": {"i-" + "b" * 24: {"items": [{"ref": item_ref, "surface": "always"}]}},
1344
+ "store": {"versions": {carrier_id: {version: {"item_ref": item_ref}}}, "units": {}},
1345
+ "shared": {"carriers": [{"carrier_id": carrier_id, "version_sha256": version}],
1346
+ "items": [{"ref": item_ref, "surface": "always"}],
1347
+ "instruction_text_sha256": "d" * 64,
1348
+ "instruction_coverage": [{"unit_ref": unit_ref, "covered": 1, "total": 1}],
1349
+ "item_pointer_in_compiled_text": [{"ref": item_ref, "pointer": None,
1350
+ "basis": "surface_has_no_pointer"}],
1351
+ "router_path": None,
1352
+ "unit_surfaces": [{"unit_ref": unit_ref, "surface": "always",
1353
+ "source": "snapshot"}],
1354
+ "unavailable": []},
1355
+ "copy": [],
1356
+ }
1357
+ if path_id == "delivered":
1358
+ # The always surface, whose top level is the compiled text holding the unit's lines: the
1359
+ # injection is recorded before the decision and the counts say every line was there.
1360
+ return base, {"state": "delivered", "level": "exposed"}
1361
+ if path_id == "unknown/absent_from_compiled_text":
1362
+ return ({**base, "shared": {**base["shared"],
1363
+ "instruction_coverage": [{"unit_ref": unit_ref, "covered": 0,
1364
+ "total": 1}]}},
1365
+ {"state": "unknown", "reason": "absent_from_compiled_text"})
1366
+ if path_id == "selected_unavailable":
1367
+ return ({**base, "shared": {**base["shared"],
1368
+ "unavailable": [{"ref": item_ref, "surface": "always",
1369
+ "reason": "route_absent"}]}},
1370
+ {"state": "selected_unavailable", "level": "selected"})
1371
+ if path_id == "not_delivered/selection_lacks_item":
1372
+ # The catalogue route, reachable since S2 publishes the catalogue surface of a unit whose
1373
+ # item the session was NOT given: the selection was read and holds another item, the release
1374
+ # holds this one at a complete reference point, and the ladder is classified from the
1375
+ # baseline. Before those facts the judge answered `surface_unclassified` and §6.3's absence
1376
+ # could not be found at all.
1377
+ return ({**base,
1378
+ "store": {"versions": {carrier_id: {version: {"item_ref": "claude:other"}}},
1379
+ "units": {}},
1380
+ "shared": {**base["shared"],
1381
+ "items": [{"ref": "claude:other", "surface": "always"}],
1382
+ "instruction_coverage": [],
1383
+ "item_pointer_in_compiled_text": [{"ref": "claude:other", "pointer": None,
1384
+ "basis": "surface_has_no_pointer"}],
1385
+ "unit_surfaces": [{"unit_ref": unit_ref, "surface": "always",
1386
+ "source": "baseline"}]}},
1387
+ {"state": "not_delivered", "reason": "selection_lacks_item"})
1388
+ if path_id == "not_delivered":
1389
+ # Reached through the NATIVE layer, which is the only place an absence is a finding from what
1390
+ # a run holds: a native unit's ladder is classified by its layer and needs no surface, and a
1391
+ # recorded injection before the decision that does not carry the unit, over a complete
1392
+ # release, is `not_in_recorded_injection`.
1393
+ #
1394
+ # The catalogue route cannot reach this state from records, and the reason is worth keeping:
1395
+ # `_absence` is for an item the selection does not hold, while a unit's SURFACE — the ladder
1396
+ # it is judged on — is published only for the items the snapshot DID select. An item the
1397
+ # session was not given therefore has no classified ladder here, and the judge answers
1398
+ # `surface_unclassified` rather than an absence. Raised with the lead beside the pointer
1399
+ # question: S2 publishing each unit's catalogue surface, not only the selected ones, would
1400
+ # open it.
1401
+ # The native route gets its own PRODUCED document, from a carrier in the native layer: a
1402
+ # unit copied from the catalogue one and relabelled would carry a carrier id derived from
1403
+ # the catalogue layer, which no producer would ever emit for a native unit.
1404
+ native_doc, _native_unit = _producer_current(text="- the rule\n", path="CLAUDE.md",
1405
+ layer="native_global", item_ref="native:global")
1406
+ native_operative = [u for u in native_doc["units"] if u.get("class") == "operative"]
1407
+ native_id = native_operative[0]["unit_id"]
1408
+ return ({**base,
1409
+ "current": native_doc,
1410
+ # The pair is owed for the NATIVE document's unit: leaving the catalogue id here
1411
+ # left the fixture owing no pair at all, and `run_fixture` then reported
1412
+ # FIXTURE_NO_ROW rather than the state this fixture exists to pin.
1413
+ "checks": {"candidates": [{"candidate_id": "k-1", "named_units_absent": [],
1414
+ "retrieved_units": [{"unit_id": native_id,
1415
+ "layer": "native_global", "rank": 1,
1416
+ "score": 1.0, "named": True,
1417
+ "copies": 1}]}]},
1418
+ "sessions": {**base["sessions"],
1419
+ "events": [{"event_id": "e-1", "kind": "native", "session_ref": session_ref,
1420
+ "line": 10, "at": "2026-09-16T07:44:40+00:00",
1421
+ "members": [{"carrier_id": "c-" + "9" * 24,
1422
+ "version_sha256": "f" * 64, "ordinal": 0}]}]},
1423
+ # A native unit's item is not a catalogue item, so no surface is published for it;
1424
+ # the ladder comes from its layer, which is the point of this fixture.
1425
+ "shared": {**base["shared"],
1426
+ # No coverage rows: coverage is published per catalogue unit, and the
1427
+ # base block's row names the catalogue reference, which resolves to
1428
+ # nothing in this document. Carrying it made the fixture answer
1429
+ # `coverage_ref_unresolved` instead of the absence it exists to pin.
1430
+ "instruction_coverage": [],
1431
+ "unit_surfaces": [{"unit_ref": native_operative[0]["unit_ref"],
1432
+ "surface": None,
1433
+ "source": "unpublished"}]}},
1434
+ {"state": "not_delivered", "reason": "not_in_recorded_injection"})
1435
+ if path_id == f"unknown/{UNRESOLVED}":
1436
+ return ({**base, "shared": {**base["shared"],
1437
+ "instruction_coverage": [{"unit_ref": "r-" + "9" * 24, "covered": 1,
1438
+ "total": 1}]}},
1439
+ {"state": "unknown", "reason": UNRESOLVED})
1440
+ if path_id == f"unknown/{UNJUDGED}":
1441
+ # No decision event at all: one of the judge's four inputs is missing, so this stage answers
1442
+ # and says that it did.
1443
+ return ({**base, "candidates": {"candidates": [{"candidate_id": "k-1", "sessions": ["claude:t-1"],
1444
+ "event_ids": []}]}},
1445
+ {"state": "unknown", "reason": UNJUDGED})
1446
+ if path_id == "exposed_not_read":
1447
+ # A requested guide: its ladder delivers only at a read of the unit's own bytes, and S2's
1448
+ # pointer fact says the compiled text held its emitted path. Nothing read the file, so the
1449
+ # unit is exposed and not delivered. Reachable since S2 publishes the pointer predicate;
1450
+ # before that the state could not be produced from records at all, and the fixture said so.
1451
+ return ({**base,
1452
+ "shared": {**base["shared"],
1453
+ "items": [{"ref": "claude:guides/g", "surface": "requested"}],
1454
+ "item_pointer_in_compiled_text": [{"ref": "claude:guides/g", "pointer": True,
1455
+ "basis": "emitted_path"}],
1456
+ "unit_surfaces": [{"unit_ref": unit_ref, "surface": "requested",
1457
+ "source": "snapshot"}]}},
1458
+ {"state": "exposed_not_read", "level": "pointer exposed"})
1459
+ raise Refused(f"FIXTURE_UNKNOWN {path_id}: no records fixture is written for this state path")
1460
+
1461
+
1462
+ def generate_fixtures(path=FIXTURES_PATH):
1463
+ """Write the records fixtures once; a second call refuses, as W2's generator does."""
1464
+ path = pathlib.Path(path)
1465
+ if path.exists():
1466
+ raise Refused(f"FIXTURES_FROZEN {path}: generated once and committed; delete it by hand to regenerate")
1467
+ fixtures = []
1468
+ for path_id in STATE_PATHS:
1469
+ artifacts, expected = _records_fixture(path_id)
1470
+ subject = None
1471
+ if artifacts is not None:
1472
+ operative = [u for u in (artifacts["current"].get("units") or [])
1473
+ if u.get("class") == "operative"]
1474
+ subject = operative[0]["unit_id"] if operative else None
1475
+ fixtures.append({"id": path_id, "artifacts": artifacts, "expected": expected,
1476
+ "subject_unit": subject})
1477
+ doc = {"$comment": "design §6.3 at the records level: one frozen fixture per state path "
1478
+ "`runlib/stage_delivery.py` can write, each a whole set of run-shaped artifacts "
1479
+ "driven through `document`. Written once by `stage_delivery.py "
1480
+ "--generate-fixtures`; the self-test never regenerates them.",
1481
+ "fixtures": fixtures}
1482
+ path.write_text(json.dumps(doc, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
1483
+ return len(fixtures)
1484
+
1485
+
1486
+ # Which schema judges each frozen artifact, and for the ones no schema judges, why. The review of
1487
+ # this package found the fixtures built from shapes no producer emits; a schema check is what makes
1488
+ # that decidable rather than remembered. `current` is the one artifact with a published schema for
1489
+ # the whole document, and it is the one the finding was about.
1490
+ FIXTURE_SCHEMAS = {"current": ("inventory.schema.json", "current_document")}
1491
+ FIXTURE_UNSCHEMAED = {
1492
+ "checks": "the fixture carries only the `candidates` block this stage reads; checks.schema.json "
1493
+ "describes the WHOLE S5 document, so validating a deliberate subset against it would "
1494
+ "fail on the blocks this stage never touches",
1495
+ "candidates": "S4's document is described by form.schema.json at the whole-document level, and "
1496
+ "the fixture carries the two rows this stage reads",
1497
+ "sessions": "S2's session document has no published schema in session-distill/schemas",
1498
+ "release": "the release document has no published schema",
1499
+ "store": "the instruction store is state, not a stage document",
1500
+ "shared": "the selection inventory's shared block has no published schema of its own",
1501
+ "events": "an event record is validated by event.schema.json per LINE, not as a list; the "
1502
+ "fixture's rows are written into a .jsonl by `run_fixture` and read back by the stage",
1503
+ "copy": "a list of file names",
1504
+ "shared_by_ref": "one selection-inventory block per inventory ref, and that block has no "
1505
+ "published schema of its own (the same reason as `shared`); the REFS are "
1506
+ "judged by `release_of` reading them, and the fixture would fail its own "
1507
+ "state path if a ref it names were not the one the release points at",
1508
+ }
1509
+
1510
+
1511
+ def fixture_schema_problems(frozen=None):
1512
+ """Every frozen artifact judged by its producer's schema, or named with why none judges it.
1513
+
1514
+ An artifact nobody validates is how a fixture drifts from its producer: this library's `current`
1515
+ documents carried `block` as an object with a `start` in it, which `inventory.schema.json` would
1516
+ have refused the day it was written.
1517
+ """
1518
+ from runlib import validate
1519
+
1520
+ frozen = frozen or json.loads(pathlib.Path(FIXTURES_PATH).read_text(encoding="utf-8"))
1521
+ problems, validators = [], {}
1522
+ for artifact, (schema_file, definition) in FIXTURE_SCHEMAS.items():
1523
+ schema = json.loads((HERE / "schemas" / schema_file).read_text(encoding="utf-8"))
1524
+ held = dict(schema["$defs"][definition])
1525
+ held["$defs"] = schema["$defs"]
1526
+ held["$schema"] = "https://json-schema.org/draft/2020-12/schema"
1527
+ validators[artifact] = validate.compile_schema(held)
1528
+ judged = 0
1529
+ for fixture in frozen.get("fixtures") or []:
1530
+ artifacts = fixture.get("artifacts")
1531
+ if artifacts is None:
1532
+ continue
1533
+ for artifact, value in artifacts.items():
1534
+ if artifact in validators:
1535
+ judged += 1
1536
+ for problem in validate.validate_instance(validators[artifact], value):
1537
+ problems.append(f"FIXTURE_SHAPE {fixture['id']} {artifact}: {problem}")
1538
+ elif artifact not in FIXTURE_UNSCHEMAED:
1539
+ problems.append(f"FIXTURE_UNJUDGED {fixture['id']} {artifact}: no schema judges this "
1540
+ f"artifact and no reason is declared for it, so it can drift from "
1541
+ f"its producer unnoticed")
1542
+ if not judged:
1543
+ problems.append("FIXTURE_SCHEMA_SCOPE_EMPTY: no artifact was judged by a schema, so a "
1544
+ "green answer here would be about nothing")
1545
+ return problems
1546
+
1547
+
1548
+ def run_fixture(root, fixture):
1549
+ """`document` over one frozen fixture's artifacts, against what it must answer.
1550
+
1551
+ A fixture declared unreachable carries its reason and no artifacts; it is executed as that
1552
+ declaration, so the library still accounts for every state path and the reason is in the file
1553
+ rather than in somebody's memory."""
1554
+ if fixture.get("artifacts") is None:
1555
+ why = (fixture.get("expected") or {}).get("unreachable")
1556
+ return [] if why else [f"FIXTURE_UNREACHABLE_UNEXPLAINED {fixture['id']}: a state path with no "
1557
+ f"artifacts and no reason"]
1558
+ artifacts = fixture["artifacts"]
1559
+ run_dir = pathlib.Path(root) / f"fx-{fixture['id'].replace('/', '-')}"
1560
+ (run_dir / EVENTS_DIR).mkdir(parents=True)
1561
+ # The event file is named the way the PRODUCER names it, and the views row the fixture hands
1562
+ # `document` carries that same name. Both come from `views.safe_name`, imported rather than
1563
+ # imitated: the join these fixtures exercise is the name mapping S2 publishes, and a fixture
1564
+ # that spelled the name itself would be testing a spelling nobody writes (the WP-11b review,
1565
+ # whose finding was exactly that the spelling and the reader disagreed).
1566
+ from runlib import views as _views
1567
+ session = dict(artifacts["sessions"])
1568
+ transcript_id = ((session.get("sessions") or [{}])[0].get("transcript") or {}).get("id") \
1569
+ or "claude:t-1"
1570
+ stem = _views.safe_name(transcript_id)
1571
+ (run_dir / EVENTS_DIR / f"{stem}.jsonl").write_text(
1572
+ "".join(json.dumps(row) + "\n" for row in artifacts["events"]), encoding="utf-8")
1573
+ fixture_views = {"transcripts": [
1574
+ {"name": stem, "segment": stem, "transcript": transcript_id,
1575
+ "session": (session.get("sessions") or [{}])[0].get("session"),
1576
+ "host": (session.get("sessions") or [{}])[0].get("host") or "claude"}]}
1577
+ # One answer per REF, not one answer for every ref: the release's reference point and the
1578
+ # session's selection are different inventories, and a `shared_of` that answered alike could not
1579
+ # express a release holding an item the session was not given — which is §6.3's catalogue
1580
+ # absence (the WP-11b review).
1581
+ by_ref = artifacts.get("shared_by_ref") or {}
1582
+
1583
+ def fixture_shared_of(ref):
1584
+ return by_ref.get(ref, artifacts["shared"])
1585
+
1586
+ doc = document(run_dir, artifacts["checks"], artifacts["candidates"], artifacts["current"], session,
1587
+ artifacts["release"], artifacts["store"], fixture_shared_of,
1588
+ artifacts["copy"] or ["aa.jsonl"], fixture_views)
1589
+ # The subject is named by the fixture, because the unit id now comes from the producer and is a
1590
+ # digest, not "u-1". A hardcoded id here would silently select nothing and the fixture would
1591
+ # report FIXTURE_NO_ROW for every path.
1592
+ subject = fixture.get("subject_unit")
1593
+ if not subject:
1594
+ return [f"FIXTURE_SUBJECT_UNNAMED {fixture['id']}: the fixture does not say which unit its "
1595
+ f"expectation is about, so no row can be selected"]
1596
+ rows = [row for row in doc["rows"] if row["unit_id"] == subject]
1597
+ if not rows:
1598
+ return [f"FIXTURE_NO_ROW {fixture['id']}: the artifacts owe no pair for the unit"]
1599
+ row = rows[0]
1600
+ got = {"state": row["state"]}
1601
+ want = dict(fixture["expected"])
1602
+ if "level" in want:
1603
+ got["level"] = row["level"]
1604
+ if "reason" in want:
1605
+ got["reason"] = want["reason"] if want["reason"] in (row["reasons"] or []) else (row["reasons"] or [None])[0]
1606
+ return [] if got == want else [f"FIXTURE_FAILED {fixture['id']}: expected {want}, got {got} "
1607
+ f"(reasons {row['reasons']})"]
1608
+
1609
+
1610
+ # ---- self-test ----------------------------------------------------------------------------------
1611
+
1612
+ def self_test():
1613
+ """Positive control first, then one planted violation per rule, each refused BY NAME."""
1614
+ failures, ran = [], []
1615
+
1616
+ def _body():
1617
+ return _self_test_body(failures, ran)
1618
+
1619
+ # A crash must not swallow what the suite already knows. The defect this package was fixed for
1620
+ # raised AttributeError inside `unit_index`, so a revert trial over it reported an exit code and
1621
+ # nothing else: the controls that would have NAMED the defect had already run, and their
1622
+ # failures were printed only at the end. Printing them before re-raising is what turns a
1623
+ # traceback into evidence.
1624
+ try:
1625
+ return _body()
1626
+ except BaseException as exc:
1627
+ # Printed even when nothing had failed yet, because the crash itself is the finding: the
1628
+ # defect this package was fixed for raised inside `unit_index` on the FIRST document call,
1629
+ # so a revert trial saw an exit code with no text and reported the control as silent.
1630
+ print(f"stage_delivery --self-test: INCOMPLETE ({len(ran)} controls ran, "
1631
+ f"{len(failures)} already failing when the suite died)", file=sys.stderr)
1632
+ print(f"stage_delivery --self-test [FAIL] the suite died: "
1633
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
1634
+ for held in failures:
1635
+ print(f"stage_delivery --self-test [FAIL] {held}", file=sys.stderr)
1636
+ raise
1637
+
1638
+
1639
+ def _self_test_body(failures, ran):
1640
+ """The suite itself. Split out only so a crash can report the failures already collected."""
1641
+
1642
+ def control(label, got, want):
1643
+ ran.append(label)
1644
+ if want not in got:
1645
+ failures.append(f"{label}: expected {want!r} in {got!r}")
1646
+
1647
+ def equals(label, got, want):
1648
+ """A control whose expectation is the WHOLE answer, not a fragment of it.
1649
+
1650
+ `control` asks `want in got`, which is right for a refusal's name inside a longer message
1651
+ and wrong for a value: a longer wrong answer contains the shorter right one."""
1652
+ ran.append(label)
1653
+ if str(got) != str(want):
1654
+ failures.append(f"{label}: expected exactly {want!r}, got {str(got)[:400]!r}")
1655
+
1656
+ def clean(label, got):
1657
+ """An absence asserted as an absence: `want=""` cannot fail, since every string holds it."""
1658
+ ran.append(label)
1659
+ if got:
1660
+ failures.append(f"{label}: expected nothing, got {got!r}")
1661
+
1662
+ def refusal(call):
1663
+ try:
1664
+ call()
1665
+ except Refused as exc:
1666
+ return str(exc)
1667
+ except Exception as exc: # a non-refusal comes back to its control instead of ending the suite
1668
+ return f"{type(exc).__name__}: {exc}"
1669
+ return ""
1670
+
1671
+ if STAGE not in records.STAGES:
1672
+ failures.append(f"{STAGE} is not in records.STAGES, so run_stage would refuse it as unknown")
1673
+ else:
1674
+ order = list(records.STAGES)
1675
+ if not order.index("S5") < order.index(STAGE) < order.index("S6"):
1676
+ failures.append(f"records.STAGES orders {STAGE} outside (S5, S6): {order}; declare.py derives an "
1677
+ f"amendment's invalidation range and its ordering from this index")
1678
+ ran.append("the stage is registered between S5 and S6")
1679
+
1680
+ with tempfile.TemporaryDirectory() as tmp:
1681
+ root = pathlib.Path(tmp)
1682
+ # The document's shape over the artifacts' OWN spellings, taken from `checks.schema.json`, S4's
1683
+ # `candidates.json` and an event record's `at_record`, as a real run writes them (measured on the
1684
+ # lead's C2 run, 2026-11-11). The first commit of this package read fields no producer writes —
1685
+ # `session_ref`, `unit_ids`, `decision_at` on a check row — and its controls passed because they
1686
+ # judged that invented shape and no real file.
1687
+ fixture = root / "fx"
1688
+ (fixture / EVENTS_DIR).mkdir(parents=True)
1689
+ (fixture / EVENTS_DIR / "claude_t-1.jsonl").write_text(
1690
+ json.dumps({"event_id": "v-1", "at_record": "76837/message/content", "kind": "request"}) + "\n"
1691
+ + json.dumps({"event_id": "v-2", "at_record": "9/message/content/0", "kind": "request"}) + "\n",
1692
+ encoding="utf-8")
1693
+ checks = {"candidates": [
1694
+ {"candidate_id": "k-1",
1695
+ "retrieved_units": [{"unit_id": None, "layer": "catalog", "rank": 1, "score": 1.0,
1696
+ "named": True, "copies": 1}], # filled with u1 below
1697
+ "named_units_absent": ["u-gone"]},
1698
+ {"candidate_id": "k-2", "retrieved_units": [], "named_units_absent": []}]}
1699
+ candidates = {"candidates": [
1700
+ {"candidate_id": "k-1", "sessions": ["claude:t-1"], "event_ids": ["v-1", "v-2"]},
1701
+ {"candidate_id": "k-2", "sessions": ["claude:t-1"], "event_ids": []}]}
1702
+ # The document comes from S2's producer over a guide written here, not from a unit shape
1703
+ # typed into this suite. The one it replaced carried `block` as an object with a `start` in
1704
+ # it, which no producer emits: every control below passed over that shape while
1705
+ # `unit_index` raised AttributeError on every real document. Ids are digests now, so the
1706
+ # suite binds names to them instead of spelling them.
1707
+ current, _subject = _producer_current(
1708
+ text="# Guide\n\n- the first rule\n- the second rule\n")
1709
+ operative_units = [u for u in current["units"] if u.get("class") == "operative"]
1710
+ u1, u2 = operative_units[0]["unit_id"], operative_units[1]["unit_id"]
1711
+ heading_unit = next(u["unit_id"] for u in current["units"] if u.get("class") != "operative")
1712
+ # An id the producer did not emit, for the control that the closure is not substituted for
1713
+ # the one-step set.
1714
+ u_absent = "u-" + "0" * 16
1715
+ carrier_fx = operative_units[0]["carrier_id"]
1716
+ version_fx = operative_units[0]["version_sha256"]
1717
+ item_fx = operative_units[0]["item_ref"]
1718
+ ref_u1 = operative_units[0]["unit_ref"]
1719
+ ref_u2 = operative_units[1]["unit_ref"]
1720
+ checks["candidates"][0]["retrieved_units"][0]["unit_id"] = u1
1721
+ sessions = {"sessions": [{"session_ref": "p-" + "1" * 24, "session": "claude:t-1",
1722
+ "transcript": {"host": "claude", "id": "t-1", "source": "claude_projects"},
1723
+ "pin": {"status": "read", "content_ref": "b" * 64, "baseline_ref": None,
1724
+ "include_global_instructions": True, "reason": None},
1725
+ "selection": {"status": "unknown", "reason": "input_failed",
1726
+ "inventory_ref": None},
1727
+ "delivery": {"status": "unknown", "reason": "input_failed", "event_refs": []}}]}
1728
+ release_doc = {"sessions": [{"session_ref": "p-" + "1" * 24, "segments": [],
1729
+ "unsegmented": {"inventory_refs": [],
1730
+ "layers": [{"layer": "catalog",
1731
+ "status": "unknown",
1732
+ "reasons": [
1733
+ "release_history_deferred"],
1734
+ "source": None}],
1735
+ "complete": False,
1736
+ "incomplete_reasons": [
1737
+ {"layer": "catalog", "status": "unknown",
1738
+ "reasons": ["release_history_deferred"],
1739
+ "inventory_ref": None}]}}]}
1740
+ store = {"versions": {}, "units": {}}
1741
+ # The views document S2 publishes, named with the producer's own namer so the suite cannot
1742
+ # spell the join differently from the stage. `claude:t-1` -> `claude_t-1`, which is also
1743
+ # what the event file above is called.
1744
+ from runlib import views as _views_mod
1745
+ suite_views = {"transcripts": [
1746
+ {"name": _views_mod.safe_name("claude:t-1"), "segment": _views_mod.safe_name("claude:t-1"),
1747
+ "transcript": "t-1", "session": "claude:t-1", "host": "claude"}]}
1748
+ doc = document(fixture, checks, candidates, current, sessions, release_doc, store,
1749
+ lambda ref: None, ["aa.jsonl"], suite_views)
1750
+ # k-1: two events x two units (one retrieved, one named-absent) = 4; k-2: one session, no event, no unit = 1.
1751
+ control("a pair is owed per decision event and unit", str(doc["summary"]["pairs"]), "5")
1752
+ control("an event's ordinal is read from its at_record", json.dumps((doc.get("rows") or [{}])[0]),
1753
+ '"decision_at": 76837')
1754
+ control("and the session comes from the transcript the event record belongs to",
1755
+ json.dumps((doc.get("rows") or [{}])[0]), '"session_ref": "p-111111111111111111111111"')
1756
+ # ---- the version universe this run names --------------------------------------------------
1757
+ #
1758
+ # `delivery` defaults `versions` to the CURRENT units alone and this stage passed none, so
1759
+ # the shared store's historical versions were invisible to the byte binding: a read of an
1760
+ # older version of a carrier was matched against the current text only (the WP-11b review).
1761
+ # The run holds those versions — the store keys each one, lists its `unit_refs` in order,
1762
+ # and each store unit carries its own projected text.
1763
+ older = "a" * 64
1764
+ store_with_history = {
1765
+ "versions": {"c-" + "1" * 24: {older: {"layer": "catalog", "path": "claude/guides/g.md",
1766
+ "item_ref": "claude:guides/g",
1767
+ "package_id": None, "form": "guide",
1768
+ "length": 20, "split": True,
1769
+ "unit_refs": ["r-" + "1" * 24]}}},
1770
+ "units": {"r-" + "1" * 24: {"carrier_id": "c-" + "1" * 24, "version_sha256": older,
1771
+ "n": 0, "start": 0, "end": 20, "sha": "b" * 64,
1772
+ "heading": None, "text": "- the older line\n",
1773
+ "class": "operative", "block": "list-item",
1774
+ "redaction_version": "r22"}}}
1775
+ held_universe = version_universe(current, store_with_history)
1776
+ control("the store's historical version is in the universe, keyed by its own path",
1777
+ json.dumps(sorted(held_universe.get("claude/guides/g.md") or {})), older)
1778
+ control("and its lines are the version's own units, in the version's order",
1779
+ json.dumps((held_universe.get("claude/guides/g.md") or {}).get(older)),
1780
+ "- the older line")
1781
+ clean("the current document's versions are still there, so the universe is a union and not "
1782
+ "a replacement",
1783
+ [] if len(held_universe.get(
1784
+ [unit["path"] for unit in current["units"]][0]) or {}) >= 1
1785
+ else ["the current version was lost from the universe"])
1786
+ control("a store version whose units this run holds no text for is left out rather than "
1787
+ "entered with an empty line set, since empty lines match everything",
1788
+ json.dumps(sorted(version_universe(current, {
1789
+ "versions": {"c-" + "2" * 24: {"c" * 64: {"path": "claude/guides/h.md",
1790
+ "unit_refs": ["r-gone"]}}},
1791
+ "units": {}}).get("claude/guides/h.md") or {})),
1792
+ "[]")
1793
+ control("the line rule is the judge's own, reached rather than restated",
1794
+ next((line.strip() for line in inspect.getsource(version_universe).splitlines()
1795
+ if "versions_of(" in line), "<no such line>"),
1796
+ "delivery_evidence.versions_of(")
1797
+ control("and the document hands the judge that universe rather than letting it default to "
1798
+ "the current units",
1799
+ next((line.strip() for line in inspect.getsource(document).splitlines()
1800
+ if "versions=" in line), "<no such line>"),
1801
+ "versions=universe")
1802
+
1803
+ # ---- the bytes that decided the verdict, published ---------------------------------------
1804
+ #
1805
+ # `run_stage` pins every DECLARED input against its producer's recorded output digest. The
1806
+ # event records, the shared store and the per-session selection inventories are read by
1807
+ # this stage and are not declarable that way — which ones exist depends on the run — so a
1808
+ # change to them between S2 and a later reader was not knowable at all (the WP-11b review).
1809
+ # Their digests are published with the document that rests on them.
1810
+ bound_doc = document(fixture, checks, candidates, current, sessions, release_doc, store,
1811
+ lambda ref: None, ["aa.jsonl"], suite_views)
1812
+ control("the event records this stage read are bound by digest in its own document",
1813
+ json.dumps([row["path"] for row in bound_doc["consumed"]]),
1814
+ f"{EVENTS_DIR}/claude_t-1.jsonl")
1815
+ clean("every bound row carries a full sha256, so the binding is a value and not a label",
1816
+ [row for row in bound_doc["consumed"]
1817
+ if len(row.get("sha256") or "") != 64])
1818
+ control("the digest is the file's own, not a recomputation of something else",
1819
+ [row["sha256"] for row in bound_doc["consumed"]
1820
+ if row["path"].endswith("claude_t-1.jsonl")][0],
1821
+ records.sha256_file(fixture / EVENTS_DIR / "claude_t-1.jsonl"))
1822
+ clean("a file the run does not hold is not bound, since a digest of nothing is a claim",
1823
+ [row for row in bound_doc["consumed"] if "store.json" in row["path"]])
1824
+ control("and the document says why these are published rather than declared",
1825
+ bound_doc["consumed_unpinnable"], "not declarable inputs")
1826
+ # The binding MOVES when the bytes move: this is what makes it worth publishing.
1827
+ (fixture / EVENTS_DIR / "claude_t-1.jsonl").write_text(
1828
+ json.dumps({"event_id": "v-1", "at_record": "76837/message/content",
1829
+ "kind": "request"}) + "\n"
1830
+ + json.dumps({"event_id": "v-2", "at_record": "9/message/content/0",
1831
+ "kind": "request"}) + "\n"
1832
+ + json.dumps({"event_id": "v-3", "at_record": "11/message", "kind": "request"}) + "\n",
1833
+ encoding="utf-8")
1834
+ moved_doc = document(fixture, checks, candidates, current, sessions, release_doc, store,
1835
+ lambda ref: None, ["aa.jsonl"], suite_views)
1836
+ control("a change to an event record changes the binding, which is the whole point of "
1837
+ "publishing it",
1838
+ json.dumps(bound_doc["consumed"] != moved_doc["consumed"]), "true")
1839
+
1840
+ # ---- S5's checked population, planted controls included ----------------------------------
1841
+ #
1842
+ # S5 publishes `checked-candidates.json`: S4's candidates PLUS the planted controls of
1843
+ # design §6.5, which is the population S6 judges. This stage enumerated only S4's, so a
1844
+ # planted control and its retrieved units were never pairs it owed an answer for — silently,
1845
+ # so the denominator shrank with no row saying so (the WP-11b review). A planted control
1846
+ # carries a fabricated session id, so its pair is answered with a reason; that is the point,
1847
+ # and it is not the same as never being asked.
1848
+ planted_population = {"candidates": [
1849
+ {"candidate_id": "k-1", "source": "g_cluster", "sessions": ["claude:t-1"]},
1850
+ {"candidate_id": "k-planted", "source": "control_absence",
1851
+ "sessions": ["claude:fabricated-0001"]}]}
1852
+ planted_checks = {"candidates": checks["candidates"] + [
1853
+ {"candidate_id": "k-planted", "source": "control_absence",
1854
+ "retrieved_units": [{"unit_id": u1, "layer": "catalog", "rank": 1, "score": 1.0,
1855
+ "named": True, "copies": 1}],
1856
+ "named_units_absent": []}]}
1857
+ doc_pl = document(fixture, planted_checks, candidates, current, sessions, release_doc,
1858
+ store, lambda ref: None, ["aa.jsonl"], suite_views, planted_population)
1859
+ pl_rows = [row for row in doc_pl["rows"] if row["candidate_id"] == "k-planted"]
1860
+ control("a planted control S5 checked is a pair this stage owes an answer for",
1861
+ json.dumps([row["unit_id"] for row in pl_rows]), u1)
1862
+ control("and the row says which producer's population it came from",
1863
+ json.dumps([row["producer"] for row in pl_rows]), "S5")
1864
+ control("its fabricated session is answered with a reason, which is not the same as the "
1865
+ "pair never being asked",
1866
+ json.dumps([row["reasons"] for row in pl_rows]), "session_absent_from_inventory")
1867
+ control("the summary counts the pairs by producer, so a shrinking denominator is visible",
1868
+ json.dumps(doc_pl["summary"]["pairs_by_producer"]), '"S5": 1')
1869
+ # A candidate that names no session - a legacy entry, a redundancy hint - beside the formed one. Both rows
1870
+ # are built by the path that produces them (`lifecycle_intake`), so the shape is theirs and not this suite's.
1871
+ from runlib import lifecycle_intake
1872
+ same_text = ("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho "
1873
+ "sigma tau")
1874
+ apart_rows = lifecycle_intake.legacy_incubation({"entries": [
1875
+ {"id": "L-1", "status": "incubating", "decisions": [], "classification": {"type": "A"}}]})
1876
+ apart_rows += lifecycle_intake.redundancy_pairs([
1877
+ {"unit_id": name, "class": "operative", "layer": "catalog", "path": path, "sha": "s1", "text": same_text}
1878
+ for name, path in (("u-a", "a.md"), ("u-b", "b.md"))])[0]
1879
+ apart_population = {"candidates": planted_population["candidates"][:1] + apart_rows}
1880
+ apart_checks = {"candidates": checks["candidates"] + [
1881
+ {"candidate_id": row["candidate_id"], "source": row["source"],
1882
+ "retrieved_units": [{"unit_id": u1, "layer": "catalog", "rank": 1, "score": 1.0, "named": True,
1883
+ "copies": 1}], "named_units_absent": []} for row in apart_rows]}
1884
+ doc_ap = document(fixture, apart_checks, candidates, current, sessions, release_doc,
1885
+ store, lambda ref: None, ["aa.jsonl"], suite_views, apart_population)
1886
+ ap_rows = [row for row in doc_ap["rows"] if row["candidate_id"] in {r["candidate_id"] for r in apart_rows}]
1887
+ control("the producing path gives a legacy entry and a redundancy hint, and neither names a session",
1888
+ json.dumps([sorted(r["source"] for r in apart_rows), [r.get("sessions") for r in apart_rows]]),
1889
+ json.dumps([["legacy", "redundancy_hint"], [None, None]]))
1890
+ control("a pair whose candidate names no session keeps its row, says so and nothing else, and its delivery "
1891
+ "state stays in the outcome table's vocabulary",
1892
+ json.dumps(sorted((row["candidate_id"].split(":")[0], row["state"], row["reasons"],
1893
+ row.get("population")) for row in ap_rows)),
1894
+ json.dumps([["legacy", "unknown", [NOT_SESSION_DERIVED], NOT_SESSION_DERIVED],
1895
+ ["redundancy_hint", "unknown", [NOT_SESSION_DERIVED], NOT_SESSION_DERIVED]]))
1896
+ base_summary = document(fixture, checks, candidates, current, sessions, release_doc, store,
1897
+ lambda ref: None, ["aa.jsonl"], suite_views,
1898
+ {"candidates": planted_population["candidates"][:1]})
1899
+ control("it is counted on its own and is outside the denominator: the session-derived pairs, the judged "
1900
+ "ones and `complete` are what they are without it",
1901
+ json.dumps([doc_ap["summary"]["pairs_" + NOT_SESSION_DERIVED],
1902
+ doc_ap["summary"]["pairs"] - doc_ap["summary"]["pairs_session_derived"],
1903
+ doc_ap["summary"]["pairs_judged"] == base_summary["summary"]["pairs_judged"],
1904
+ doc_ap["summary"]["pairs_" + UNJUDGED] == base_summary["summary"]["pairs_" + UNJUDGED],
1905
+ doc_ap["complete"] == base_summary["complete"]]),
1906
+ json.dumps([2, 2, True, True, True]))
1907
+ control("and a pair that DOES name a session is never set apart",
1908
+ json.dumps(sorted({row.get("population") for row in doc_pl["rows"]}, key=str)), "[null]")
1909
+ clean("a candidate S4 already names is not enumerated twice",
1910
+ [cid for cid in {row["candidate_id"] for row in doc_pl["rows"]}
1911
+ if len([row for row in doc_pl["rows"]
1912
+ if row["candidate_id"] == cid and row["unit_id"] == u1
1913
+ and row["event_id"] is None]) > 1])
1914
+ control("and without the population nothing is lost for S4's own pairs, so the enumeration "
1915
+ "only adds",
1916
+ str(len([row for row in document(
1917
+ fixture, planted_checks, candidates, current, sessions, release_doc, store,
1918
+ lambda ref: None, ["aa.jsonl"], suite_views)["rows"]
1919
+ if row["candidate_id"] == "k-planted"])),
1920
+ "0")
1921
+ control("the stage declares that artifact with its producer, so a change to it invalidates "
1922
+ "this stage",
1923
+ json.dumps([row for row in INPUTS if "checked" in row["artifact"]]),
1924
+ '"producer_stage": "S5"')
1925
+
1926
+ # ---- the required inputs depend on the LADDER, not on the pin ----------------------------
1927
+ #
1928
+ # Any `basis is None` added a reason, and the judge was called only when NO reason held: an
1929
+ # unpinned session with a native event that explicitly loaded the unit answered
1930
+ # `unknown: unpinned` over evidence that was already sufficient (the WP-11b review). §6.3's
1931
+ # native rung is answered by the session's own events; the selection pin says nothing about
1932
+ # it. The reason is still CARRIED onto the row, because a reader counts it.
1933
+ native_doc, native_unit = _producer_current(text="- the native rule\n", path="CLAUDE.md",
1934
+ layer="native_global", item_ref="native:global")
1935
+ native_id = native_unit["unit_id"]
1936
+ native_carrier = native_unit["carrier_id"]
1937
+ native_version = native_unit["version_sha256"]
1938
+ unpinned_ref = "p-" + "7" * 24
1939
+ unpinned_sessions = {"sessions": [
1940
+ {"session_ref": unpinned_ref, "session": "claude:t-np", "host": "claude",
1941
+ "transcript": {"host": "claude", "id": "t-np", "source": "claude_projects"},
1942
+ # NOT pinned: the inventory could not read the pin at all.
1943
+ "pin": {"status": "unknown", "content_ref": None, "baseline_ref": None,
1944
+ "include_global_instructions": True, "reason": "pin_unreadable"},
1945
+ "selection": {"status": "unknown", "reason": "input_failed", "inventory_ref": None},
1946
+ "delivery": {"status": "unknown", "reason": "input_failed", "event_refs": []}}],
1947
+ "events": [{"event_id": "e-np", "kind": "native", "session_ref": unpinned_ref,
1948
+ "line": 3, "at": "2026-11-01T00:00:00+00:00",
1949
+ "members": [{"carrier_id": native_carrier,
1950
+ "version_sha256": native_version, "ordinal": 0}]}]}
1951
+ (fixture / EVENTS_DIR / "claude_t-np.jsonl").write_text(
1952
+ json.dumps({"event_id": "v-np", "at_record": "9/message/content",
1953
+ "kind": "request"}) + "\n", encoding="utf-8")
1954
+ unpinned_views = {"transcripts": [
1955
+ {"name": "claude_t-np", "segment": "claude_t-np", "transcript": "t-np",
1956
+ "session": "claude:t-np", "host": "claude"}]}
1957
+ unpinned_doc = document(
1958
+ fixture,
1959
+ {"candidates": [{"candidate_id": "k-np", "named_units_absent": [],
1960
+ "retrieved_units": [{"unit_id": native_id, "layer": "native_global",
1961
+ "rank": 1, "score": 1.0, "named": True,
1962
+ "copies": 1}]}]},
1963
+ {"candidates": [{"candidate_id": "k-np", "sessions": ["claude:t-np"],
1964
+ "event_ids": ["v-np"]}]},
1965
+ native_doc, unpinned_sessions,
1966
+ {"sessions": [{"session_ref": unpinned_ref, "segments": [],
1967
+ "unsegmented": {"inventory_refs": [], "complete": True,
1968
+ "layers": [{"layer": "catalog", "status": "complete",
1969
+ "reasons": [], "source": None}],
1970
+ "incomplete_reasons": []}}]},
1971
+ {"versions": {}, "units": {}}, lambda ref: None, ["aa.jsonl"], unpinned_views)
1972
+ np_rows = [row for row in unpinned_doc["rows"] if row["unit_id"] == native_id]
1973
+ clean("an unpinned session whose own event loaded the unit is JUDGED rather than answered "
1974
+ "unknown for want of a pin",
1975
+ [row["state"] for row in np_rows if row["state"] == "unknown"])
1976
+ # `basis_of` reports the SELECTION's reason first, which is the one that actually failed
1977
+ # here; the control names what the code says rather than what the fixture's pin field says.
1978
+ control("and the missing basis is still on the row, because a reader counts it",
1979
+ json.dumps([row["reasons"] for row in np_rows]), "selection_input_failed")
1980
+ control("the judge answered on the native rung, which needs no selection",
1981
+ json.dumps([row["state"] for row in np_rows]), "delivered")
1982
+ # And the other direction: a unit the session's events do NOT load still needs the pin,
1983
+ # because nothing else in this run can say whether the session was given it.
1984
+ other_doc, other_unit = _producer_current(text="- another rule\n", path="CLAUDE.md",
1985
+ layer="native_global", item_ref="native:other")
1986
+ unloaded_doc = document(
1987
+ fixture,
1988
+ {"candidates": [{"candidate_id": "k-nq", "named_units_absent": [],
1989
+ "retrieved_units": [{"unit_id": other_unit["unit_id"],
1990
+ "layer": "native_global", "rank": 1,
1991
+ "score": 1.0, "named": True, "copies": 1}]}]},
1992
+ {"candidates": [{"candidate_id": "k-nq", "sessions": ["claude:t-np"],
1993
+ "event_ids": ["v-np"]}]},
1994
+ other_doc, unpinned_sessions,
1995
+ {"sessions": [{"session_ref": unpinned_ref, "segments": [],
1996
+ "unsegmented": {"inventory_refs": [], "complete": True,
1997
+ "layers": [{"layer": "catalog", "status": "complete",
1998
+ "reasons": [], "source": None}],
1999
+ "incomplete_reasons": []}}]},
2000
+ {"versions": {}, "units": {}}, lambda ref: None, ["aa.jsonl"], unpinned_views)
2001
+ nq_rows = [row for row in unloaded_doc["rows"]
2002
+ if row["unit_id"] == other_unit["unit_id"]]
2003
+ control("a unit no event of that session loaded still needs the basis, and says so",
2004
+ json.dumps([row["reasons"] for row in nq_rows]), "selection_input_failed")
2005
+ control("and that unjudged pair says the judge was not called",
2006
+ json.dumps([row["reasons"] for row in nq_rows]), "delivery_unjudged")
2007
+ control("and that pair is unknown, since nothing in this run can say it was given",
2008
+ json.dumps([row["state"] for row in nq_rows]), "unknown")
2009
+
2010
+ # ---- the session join reads S2's mapping, not the file stem's spelling -------------------
2011
+ #
2012
+ # `views.safe_name` turns a Codex coverage key `codex:<id>@<segment>` into
2013
+ # `codex_<id>_<segment>`. The join removed the first underscore prefix and used the rest as
2014
+ # a transcript id, which for Codex left `<id>_<segment>` — no transcript at all — so every
2015
+ # Codex event joined to nothing and was reported `session_unmatched` (the WP-11b review).
2016
+ # The key below is built with `census.coverage_key`'s own shape through `safe_name`, so the
2017
+ # control cannot spell it differently from the producer.
2018
+ codex_key = "codex:0199c3f7-aaaa-bbbb-cccc-00000000@rollout-2026-11-01"
2019
+ codex_stem = _views_mod.safe_name(codex_key)
2020
+ control("a Codex event file's name carries the segment as well as the id, which is why "
2021
+ "splitting it left neither",
2022
+ f"{codex_stem} -> {codex_stem.split('_', 1)[-1]}",
2023
+ "codex_0199c3f7-aaaa-bbbb-cccc-00000000_rollout-2026-11-01 -> "
2024
+ "0199c3f7-aaaa-bbbb-cccc-00000000_rollout-2026-11-01")
2025
+ (fixture / EVENTS_DIR / f"{codex_stem}.jsonl").write_text(
2026
+ json.dumps({"event_id": "v-cx", "at_record": "41/message/content",
2027
+ "kind": "request"}) + "\n", encoding="utf-8")
2028
+ codex_views = {"transcripts": suite_views["transcripts"] + [
2029
+ {"name": codex_stem, "segment": codex_stem, "transcript": "cx-1",
2030
+ "session": codex_key, "host": "codex"}]}
2031
+ codex_sessions = {"sessions": sessions["sessions"] + [
2032
+ {**sessions["sessions"][0], "session_ref": "p-" + "2" * 24, "session": codex_key,
2033
+ "transcript": {"host": "codex", "id": "cx-1", "source": "codex_sessions"}}],
2034
+ "events": sessions.get("events") or []}
2035
+ codex_candidates = {"candidates": candidates["candidates"] + [
2036
+ {"candidate_id": "k-cx", "sessions": [codex_key], "event_ids": ["v-cx"]}]}
2037
+ codex_checks = {"candidates": checks["candidates"] + [
2038
+ {"candidate_id": "k-cx", "retrieved_units": [], "named_units_absent": []}]}
2039
+ doc_cx = document(fixture, codex_checks, codex_candidates, current, codex_sessions,
2040
+ release_doc, store, lambda ref: None, ["aa.jsonl"], codex_views)
2041
+ cx_rows = [row for row in doc_cx["rows"] if row["event_id"] == "v-cx"]
2042
+ control("a Codex event joins to its session through that mapping",
2043
+ json.dumps(cx_rows), '"session_ref": "p-222222222222222222222222"')
2044
+ clean("and is not reported unmatched, which is what every Codex pair was",
2045
+ [row for row in cx_rows if row.get("reason") in ("session_unmatched",
2046
+ "view_unmatched")])
2047
+ control("and its ordinal comes from its own event record", json.dumps(cx_rows),
2048
+ '"decision_at": 41')
2049
+ # A stem no views row names is `view_unmatched`, which says WHICH half of the join failed.
2050
+ (fixture / EVENTS_DIR / "codex_unlisted.jsonl").write_text(
2051
+ json.dumps({"event_id": "v-un", "at_record": "7/message", "kind": "request"}) + "\n",
2052
+ encoding="utf-8")
2053
+ doc_un = document(fixture, {"candidates": checks["candidates"] + [
2054
+ {"candidate_id": "k-un", "retrieved_units": [], "named_units_absent": []}]},
2055
+ {"candidates": candidates["candidates"] + [
2056
+ {"candidate_id": "k-un", "sessions": [], "event_ids": ["v-un"]}]},
2057
+ current, codex_sessions, release_doc, store, lambda ref: None, ["aa.jsonl"],
2058
+ codex_views)
2059
+ # The reason reaches the row's `reasons` list, which is where a reader counts them.
2060
+ un_reasons = [row["reasons"] for row in doc_un["rows"] if row["event_id"] == "v-un"]
2061
+ control("an event file no views row names is reported as the view half failing, not as an "
2062
+ "unmatched session",
2063
+ json.dumps(un_reasons), "view_unmatched")
2064
+ clean("and it is NOT reported as an unmatched session, which would point at the wrong half",
2065
+ [reasons for reasons in un_reasons if "session_unmatched" in reasons])
2066
+ control("a Codex pair whose view IS named reports neither half failing",
2067
+ json.dumps(sorted({reason for row in cx_rows for reason in row["reasons"]
2068
+ if reason in ("view_unmatched", "session_unmatched")})),
2069
+ "[]")
2070
+
2071
+ control("a candidate with no decision event keeps its pair and says why",
2072
+ json.dumps((doc.get("rows") or [{}])[-1]), "no_decision_event")
2073
+ control("and a candidate naming no unit keeps it too", json.dumps((doc.get("rows") or [{}])[-1]),
2074
+ '"unit_id": null')
2075
+ control("a unit the inventory does not carry is named, not dropped",
2076
+ json.dumps([r for r in doc["rows"] if r["unit_id"] == "u-gone"]), "unit_absent_from_inventory")
2077
+ control("a pair one of the judge's inputs is missing for is an unknown naming that input",
2078
+ json.dumps((doc.get("rows") or [{}])[0]), "selection_input_failed")
2079
+ control("and saying the state beside it is this stage's, not the judge's",
2080
+ json.dumps((doc.get("rows") or [{}])[0]), UNJUDGED)
2081
+ clean("such a pair carries no judge fields it never got",
2082
+ [key for key in ("surface", "selection", "coverage")
2083
+ if ((doc.get("rows") or [{}])[0] or {}).get(key) is not None])
2084
+ control("and the document says so of itself", json.dumps({"complete": doc["complete"]}), '"complete": false')
2085
+ control("the pending state is not S6's waiting state", str(doc["pending_reason"]),
2086
+ "not S6's `delivery_assembly_waiting`")
2087
+ control("and it counts the pairs it could not hand over", json.dumps(doc["summary"]),
2088
+ '"pairs_delivery_unjudged": 5')
2089
+ clean("no row carries bytes or session text",
2090
+ [key for row in doc["rows"] for key in row if key in ("returned", "text", "bytes")])
2091
+
2092
+ # The context set is the judge's one-step set, and the closure beside it is never read.
2093
+ held_said = None
2094
+ try:
2095
+ units = unit_index(current)
2096
+ except BaseException as exc:
2097
+ held_said = f"{type(exc).__name__}: {exc}"
2098
+ failures.append("the index reads a produced document without raising: " + held_said)
2099
+ units = {}
2100
+ # The expectation is the producer's own edges for that unit, read off the document that was
2101
+ # handed in — an input, not something this function computed.
2102
+ want_context = sorted({u1, *(operative_units[0]["edges"]["direct"] or []),
2103
+ *(operative_units[0]["edges"]["reached"] or [])})
2104
+ control("the operative context is direct plus one-step reached",
2105
+ json.dumps(units[u1]["operative_context"]), json.dumps(want_context))
2106
+ clean("and the transitive closure is not what was read",
2107
+ [u for u in units.values() if u_absent in u["operative_context"]])
2108
+ control("the source of that set is named in the row", units[u1]["context_source"], "inventory.edges")
2109
+ # `block` is the KIND, a string, and `start` is not published at all. This index read
2110
+ # `block` as an object and took `start` out of it, so it worked on every frozen fixture --
2111
+ # which carried that invented shape -- and raised AttributeError on every real document.
2112
+ # Asked BEFORE anything that could crash on the same shape, and asked through a guard, so
2113
+ # a revert of the fix produces a named failure here rather than only an exit code.
2114
+ def said(call):
2115
+ try:
2116
+ call()
2117
+ except BaseException as exc: # the exception IS this control's answer
2118
+ return f"{type(exc).__name__}: {exc}"
2119
+ return "no exception"
2120
+
2121
+ control("the index reads a produced document without raising: `block` is a string and "
2122
+ "digging `start` out of it is what crashed on every real document",
2123
+ said(lambda: unit_index(current)), "no exception")
2124
+ held_index = units[u1]
2125
+ control("the unit carries the producer's block KIND, a string",
2126
+ json.dumps({"block": held_index["block"]}),
2127
+ json.dumps({"block": operative_units[0]["block"]}))
2128
+ control("and `start` is None because the emitted document does not publish it, rather than "
2129
+ "being dug out of `block`",
2130
+ json.dumps({"start": held_index["start"]}), '{"start": null}')
2131
+ control("a unit whose `block` is an object -- the shape the old fixtures carried -- is "
2132
+ "refused by name instead of raising AttributeError",
2133
+ refusal(lambda: unit_index(
2134
+ {"units": [{**operative_units[0], "block": {"start": 100}}]})),
2135
+ "DELIVERY_UNIT_SHAPE")
2136
+ no_edges = {"units": [{**operative_units[0], "edges": None}]}
2137
+ control("an inventory that publishes no edges is refused by name",
2138
+ refusal(lambda: unit_index(no_edges)), "DELIVERY_EDGES_ABSENT")
2139
+
2140
+ # ---- the inventory's half of the session evidence (commit 3) ----
2141
+ session_row = sessions["sessions"][0]
2142
+ events_by_ref = {"p-" + "1" * 24: [
2143
+ {"event_id": "e-1", "kind": "native", "session_ref": "p-" + "1" * 24, "line": 12,
2144
+ "at": "2026-09-16T07:44:40.323000+00:00",
2145
+ "members": [{"carrier_id": carrier_fx, "version_sha256": version_fx, "ordinal": 0}]},
2146
+ {"event_id": "e-2", "kind": "native", "session_ref": "p-" + "1" * 24, "line": None,
2147
+ "at": "2026-09-16T07:45:00.000000+00:00", "members": []}]}
2148
+ evidence, counts = session_evidence(session_row, events_by_ref,
2149
+ units_by_version(unit_index(current)), release_doc,
2150
+ lambda ref: None, store)
2151
+ control("a native event is placed at its record line, not its instant",
2152
+ json.dumps((evidence.get("native_events") or [{}])[0]), '"at": 12')
2153
+ control("and its carrier version is resolved to the units it loaded",
2154
+ json.dumps((evidence.get("native_events") or [{}])[0]),
2155
+ f'"unit_ids": {json.dumps(sorted([u1, u2, heading_unit]))}')
2156
+ control("an event with no line is counted, not placed at an ordinal nobody recorded",
2157
+ str(counts.get("events_without_a_line", "no such count")), "1")
2158
+ clean("and it is not in the comparable set",
2159
+ [row for row in evidence.get("native_events") or [] if row.get("at") is None])
2160
+ control("a read pin with no selection inventory is not a pin basis",
2161
+ json.dumps({"basis": evidence.get("basis")}), '"basis": null')
2162
+ # `.get` with an absence VALUE, not `[...]`: a revert that makes this a pin basis removes the
2163
+ # key, and indexing it ended the run with a KeyError before either control could speak —
2164
+ # the same shape as the unguarded `[0]` this repo fixed in the ledger migrator's suite.
2165
+ control("and the reason the inventory recorded is what the unknown will name",
2166
+ evidence.get("pin_reason") or "no pin_reason was recorded", "selection_input_failed")
2167
+ # ---- the snapshot's facts, as S2 publishes them (commit 5b, the lead's fact-only decision).
2168
+ # A selection inventory with items, surfaces and per-unit coverage counts: the compiled text is
2169
+ # never in the run, so these counts are the only thing that can answer whether the session was
2170
+ # given a unit's lines. Keyed by the inventory's `r-` reference, translated here to the unit ids
2171
+ # the judge asks about.
2172
+ facts_shared = {
2173
+ "carriers": [{"carrier_id": carrier_fx, "version_sha256": version_fx}],
2174
+ "items": [{"ref": item_fx, "surface": "always"}],
2175
+ "instruction_text_sha256": "d" * 64,
2176
+ "instruction_coverage": [{"unit_ref": ref_u1, "covered": 1, "total": 2},
2177
+ {"unit_ref": "r-" + "9" * 24, "covered": 5, "total": 5}],
2178
+ "unavailable": [{"ref": item_fx, "surface": "always", "reason": "route_absent"}]}
2179
+ # The OPERATIVE units, with the refs the producer gave them: `current["units"][0]` is the
2180
+ # heading unit now, and attaching u1's reference to it put the coverage counts on the wrong
2181
+ # id while every control still passed.
2182
+ facts_units = [operative_units[0], operative_units[1]]
2183
+ facts_store = {"versions": {carrier_fx: {version_fx: {"item_ref": item_fx}}}, "units": {}}
2184
+ facts_row = {**session_row, "selection": {"status": "read", "reason": None,
2185
+ "inventory_ref": "i-" + "a" * 24}}
2186
+ facts_evidence, facts_counts = session_evidence(
2187
+ facts_row, events_by_ref, units_by_version(unit_index(current)), release_doc,
2188
+ lambda ref: facts_shared, facts_store, None, None, facts_units)
2189
+ control("the per-unit coverage counts reach the judge under the unit ids it asks about",
2190
+ json.dumps(facts_evidence.get("instruction_coverage")),
2191
+ f'"{u1}": ' + '{"covered": 1, "total": 2}')
2192
+ # A published row whose reference resolves to no unit here: named and counted, never dropped.
2193
+ # The lead's correction (2026-11-11): a drop is a resolution failure, and a block that lost
2194
+ # every row to one would read like a session nobody published facts for.
2195
+ control("a coverage row naming a unit this run does not carry is named, not dropped",
2196
+ json.dumps(facts_counts.get("coverage_refs_unresolved")), "r-" + "9" * 24)
2197
+ clean("and no unit id is invented for it",
2198
+ [ref for ref in facts_evidence.get("instruction_coverage") or ()
2199
+ if ref not in (u1, u2, heading_unit)])
2200
+ facts_sessions = {"sessions": [{**facts_row}]}
2201
+ # The producer already gave every unit its `unit_ref`; zipping fresh constants onto the
2202
+ # document's units overwrote them, and the heading unit took u1's reference.
2203
+ facts_current = {"units": list(current["units"])}
2204
+
2205
+ def facts_document(shared, current=None):
2206
+ """The rows and summary this stage writes when the session's inventory publishes `shared`."""
2207
+ doc_f = document(fixture, checks, candidates, current or facts_current, facts_sessions,
2208
+ release_doc, facts_store, lambda ref: shared, ["aa.jsonl"],
2209
+ suite_views)
2210
+ return {row["unit_id"]: row for row in doc_f["rows"]}, doc_f
2211
+
2212
+ # The pair this fixture owes is u-1's, so the block that cannot answer for it is the one
2213
+ # naming another unit's reference.
2214
+ missed = {**facts_shared, "instruction_coverage": [{"unit_ref": "r-" + "9" * 24, "covered": 1, "total": 1}]}
2215
+ missed_rows, missed_doc = facts_document(missed)
2216
+ control("the pair whose coverage the block could not answer for names the failure",
2217
+ json.dumps(missed_rows.get(u1) or {}), UNRESOLVED)
2218
+ # Both kinds of row at once, which is what makes the next assertion about the PAIR rather
2219
+ # than about the session: the block answers for u-1 and also carries a reference nothing here
2220
+ # resolves, so only the per-pair clause can keep the failure off u-1's row.
2221
+ answered = {**facts_shared,
2222
+ "instruction_coverage": [{"unit_ref": ref_u1, "covered": 1, "total": 2},
2223
+ {"unit_ref": "r-" + "9" * 24, "covered": 1, "total": 1}]}
2224
+ answered_rows, answered_doc = facts_document(answered)
2225
+ clean("and the pair the block did answer for does not, though its session has an unresolved one",
2226
+ ([UNRESOLVED] if UNRESOLVED in ((answered_rows.get(u1) or {}).get("reasons") or []) else [])
2227
+ + ([] if answered_doc["summary"]["coverage_refs_unresolved"] == 1
2228
+ else ["the fixture's session has no unresolved reference, so the clause is untested"]))
2229
+
2230
+ # ---- the judge's own answer (commit 7). The session here has a read pin, a selection
2231
+ # inventory and the facts, so every input §6.3 reads is present and the row is ITS answer
2232
+ # rather than this stage's unknown.
2233
+ judged_row = answered_rows.get(u1) or {}
2234
+ clean("a pair with every input present is handed to the judge",
2235
+ [UNJUDGED] if UNJUDGED in (judged_row.get("reasons") or []) else [])
2236
+ control("and the row carries the surface the judge answered on", json.dumps(judged_row),
2237
+ '"surface": "always_rule"')
2238
+ control("with the selection basis it read", json.dumps(judged_row), '"selection": "pin"')
2239
+ control("and the per-requirement coverage as counts", json.dumps(judged_row.get("coverage")),
2240
+ '"requirements"')
2241
+ clean("the judged row carries no line of any unit and no byte any session read",
2242
+ [key for key in judged_row if key in ("text", "returned", "bytes", "instruction_text")])
2243
+ # The installer surface, which no ladder answers.
2244
+ # ---- the §6.3 fixture library at the records level (done-when 1). The ids are the state
2245
+ # paths, the frozen file is the authority, and the three sets must be one bijection:
2246
+ # a path with no fixture, a fixture for no path, and a fixture the run never executed are
2247
+ # each named by `derive.coverage_problems`, so the library cannot drift from the code.
2248
+ frozen = records.read_json(FIXTURES_PATH)
2249
+ # `frozen_case`, not `fixture`: this suite's `fixture` is its run directory, and a loop
2250
+ # variable of that name rebinds it for every line after this block (the shadowing trap this
2251
+ # file's suite has paid for once already).
2252
+ frozen_ids = [case["id"] for case in frozen.get("fixtures") or []]
2253
+ executed, fixture_problems = [], []
2254
+ for frozen_case in frozen.get("fixtures") or []:
2255
+ fixture_problems += run_fixture(root, frozen_case)
2256
+ executed.append(frozen_case["id"])
2257
+ clean("every frozen §6.3 fixture answers from the records what it was frozen with",
2258
+ fixture_problems)
2259
+ clean("and the state paths, the frozen fixtures and the executed cases are one set",
2260
+ derive.coverage_problems(STATE_PATHS, frozen_ids, executed))
2261
+ control("a state path with no frozen fixture is named",
2262
+ "; ".join(derive.coverage_problems(
2263
+ tuple(STATE_PATHS) + ("delivered/by_another_route",), frozen_ids, executed)),
2264
+ "ROW_UNFIXTURED")
2265
+ control("and the generator refuses to overwrite the frozen file",
2266
+ refusal(lambda: generate_fixtures(FIXTURES_PATH)), "FIXTURES_FROZEN")
2267
+ control("a fixture declared unreachable with no reason is named",
2268
+ "; ".join(run_fixture(root, {"id": "x", "artifacts": None, "expected": {}})),
2269
+ "FIXTURE_UNREACHABLE_UNEXPLAINED")
2270
+ # Every frozen artifact held against its producer's schema, and each artifact no schema
2271
+ # judges named with its reason. This is what makes "the fixture is in the producer's shape"
2272
+ # decidable: `inventory.schema.json` would have refused the old `block: {"start": …}` unit
2273
+ # the day it was written.
2274
+ clean("every frozen artifact is judged by its producer's schema or says why not",
2275
+ fixture_schema_problems())
2276
+ planted_shape = {"fixtures": [{"id": "planted", "subject_unit": "u-x",
2277
+ "artifacts": {**frozen["fixtures"][0]["artifacts"],
2278
+ "current": {"units": [
2279
+ {**operative_units[0],
2280
+ "block": {"start": 100}}]}},
2281
+ "expected": {"state": "delivered"}}]}
2282
+ control("a frozen unit in a shape the producer does not emit is refused by name — the "
2283
+ "defect this library was built with",
2284
+ "; ".join(fixture_schema_problems(planted_shape)), "FIXTURE_SHAPE planted current")
2285
+ control("and an artifact nobody judges and nobody excuses is named too",
2286
+ "; ".join(fixture_schema_problems(
2287
+ {"fixtures": [{"id": "planted", "subject_unit": "u-x",
2288
+ "artifacts": {**frozen["fixtures"][0]["artifacts"],
2289
+ "invented": {"what": "nothing produces this"}},
2290
+ "expected": {}}]})),
2291
+ "FIXTURE_UNJUDGED planted invented")
2292
+ control("a run that judged no artifact at all is refused, so a green answer cannot be "
2293
+ "about nothing",
2294
+ "; ".join(fixture_schema_problems({"fixtures": []})),
2295
+ "FIXTURE_SCHEMA_SCOPE_EMPTY")
2296
+ control("a fixture that does not name its subject unit is refused by name, since the ids "
2297
+ "are the producer's digests and no literal can stand in for them",
2298
+ "; ".join(run_fixture(root, {"id": "no-subject",
2299
+ "artifacts": frozen["fixtures"][0]["artifacts"],
2300
+ "expected": {"state": "delivered"}})),
2301
+ "FIXTURE_SUBJECT_UNNAMED")
2302
+ control("and a fixture whose artifacts owe no pair for its unit is named",
2303
+ "; ".join(run_fixture(root, {"id": "y", "artifacts": {
2304
+ **(frozen["fixtures"][0]["artifacts"]),
2305
+ "candidates": {"candidates": [{"candidate_id": "k-1", "sessions": ["claude:t-1"],
2306
+ "event_ids": ["v-1"]}]},
2307
+ "checks": {"candidates": [{"candidate_id": "k-1", "retrieved_units": [],
2308
+ "named_units_absent": []}]}},
2309
+ "expected": {"state": "delivered"},
2310
+ # Named, so the refusal is about the missing ROW and not about the missing name:
2311
+ # with the subject unnamed the control met FIXTURE_SUBJECT_UNNAMED instead and
2312
+ # stopped testing what it was written for.
2313
+ "subject_unit": frozen["fixtures"][0]["subject_unit"]})),
2314
+ "FIXTURE_NO_ROW")
2315
+ control("the installer surface is answered by the judge's own reader, not by a ladder",
2316
+ json.dumps(doc["installer"]), "receipt_live_waiting_wp15")
2317
+ control("and it is unknown by name while the run holds no binding",
2318
+ json.dumps(doc["installer"]), '"reasons": ["unbound"]')
2319
+ control("with the absent producer named rather than an input invented for it",
2320
+ json.dumps(doc["installer"]), "no_producer_in_the_run")
2321
+ clean("no installer answer claims a delivery from inputs this run does not hold",
2322
+ [doc["installer"]["state"]] if doc["installer"]["state"] != "unknown" else [])
2323
+ control("the summary says how many pairs the judge answered", json.dumps(answered_doc["summary"]),
2324
+ '"pairs_judged": 2')
2325
+ # End to end: the unroutable row S2 published is why this pair's state is what it is, which no
2326
+ # part of this stage decides on its own.
2327
+ control("and the unroutable row S2 published is what the state rests on", json.dumps(judged_row),
2328
+ '"state": "selected_unavailable"')
2329
+ control("with the reason the judge gives for it", json.dumps(judged_row), "route_unavailable")
2330
+ control("the document counts the unresolved references for a reader to see",
2331
+ json.dumps(missed_doc["summary"]), '"coverage_refs_unresolved": 1')
2332
+ control("and says which session they belong to", json.dumps(missed_doc["coverage_refs_unresolved"]),
2333
+ facts_row["session_ref"])
2334
+ # All of them unresolved: every unit of that session is unknown by name, and NOT ONE is
2335
+ # not_delivered — the state a block read as empty would have produced for all of them.
2336
+ gone_shared = {**facts_shared, "unavailable": [],
2337
+ "instruction_coverage": [{"unit_ref": "r-" + "8" * 24, "covered": 1, "total": 1},
2338
+ {"unit_ref": "r-" + "9" * 24, "covered": 1, "total": 1}]}
2339
+ gone_evidence, gone_counts = session_evidence(
2340
+ facts_row, events_by_ref, units_by_version(unit_index(current)), release_doc,
2341
+ lambda ref: gone_shared, facts_store, None, None, facts_units)
2342
+ # The always surface, whose top level is the compiled text holding the unit's lines: the one
2343
+ # the coverage facts answer. Defined here because this block runs before the §6.3 pair below.
2344
+ gone_unit = {"unit_id": "u-1", "path": "claude/guides/g.md", "text": "- x", "surface": "always",
2345
+ "version_sha256": "a" * 64, "layer": "catalog", "item_ref": "claude:guides/g",
2346
+ "carrier_id": "c-" + "0" * 24, "n": 1, "start": 1, "operative_context": ["u-1"]}
2347
+ gone_session = {**gone_evidence, "basis": "pin", "selected": {"claude:guides/g": "always"},
2348
+ "injection_at": 1, "release": {"complete": True, "layers": {}, "items": []}}
2349
+ gone_states = [delivery_evidence.delivery(
2350
+ {**gone_unit, "unit_id": unit_id}, {unit_id: {**gone_unit, "unit_id": unit_id}},
2351
+ gone_session, 10) for unit_id in ("u-1", "u-2")]
2352
+ control("a block whose every row failed to resolve is counted in full",
2353
+ str(len(gone_counts.get("coverage_refs_unresolved") or ())), "2")
2354
+ clean("and not one unit of that session reads not_delivered because of it",
2355
+ [answer for answer in gone_states if answer["state"] == "not_delivered"])
2356
+ clean("while every one of them is unknown with a reason",
2357
+ [answer for answer in gone_states if answer["state"] != "unknown" or not answer["reasons"]])
2358
+ # The one case that IS not_delivered, so the row above is not simply the absence of that
2359
+ # state: a readable snapshot that selected the item's carrier for nothing.
2360
+ empty_answer = delivery_evidence.delivery(
2361
+ gone_unit, {"u-1": gone_unit},
2362
+ {**gone_session, "selected": {}, "instruction_coverage": {},
2363
+ "release": {"complete": True, "layers": {}, "items": ["claude:guides/g"]}}, 10)
2364
+ control("a readable snapshot that selected no unit is not_delivered, not unknown",
2365
+ json.dumps(empty_answer), '"state": "not_delivered"')
2366
+ control("the surface the snapshot selected an item at is published, so the judge need not guess one",
2367
+ json.dumps(facts_evidence.get("selected")), '"claude:guides/g": "always"')
2368
+ control("the rows the selection could not route are carried as the judge reads them",
2369
+ json.dumps(facts_evidence.get("unavailable")), "route_absent")
2370
+ control("and the counts say the digest was published", json.dumps(facts_counts), '"compiled_text_digest": "present"')
2371
+ # The two facts the ladders needed, carried to the judge as facts rather than as text.
2372
+ pointer_shared = {**facts_shared, "unavailable": [],
2373
+ "items": [{"ref": "claude:guides/g", "surface": "requested"}],
2374
+ "item_pointer_in_compiled_text": [{"ref": "claude:guides/g", "pointer": True,
2375
+ "basis": "emitted_path"}],
2376
+ "router_path": "/x/router/relevant.md",
2377
+ "unit_surfaces": [{"unit_ref": ref_u1, "surface": "requested",
2378
+ "source": "snapshot"}]}
2379
+ pointer_evidence, pointer_counts = session_evidence(
2380
+ facts_row, events_by_ref, units_by_version(unit_index(current)), release_doc,
2381
+ lambda ref: pointer_shared, facts_store, None, None, facts_units)
2382
+ control("the pointer predicate reaches the judge as a fact about the item",
2383
+ json.dumps(pointer_evidence.get("item_pointer_in_compiled_text")), '"claude:guides/g": true')
2384
+ control("and the router the compiled text named comes with it",
2385
+ json.dumps(pointer_evidence.get("router_path")), "router/relevant.md")
2386
+ clean("no part of the compiled text reaches the judge with them",
2387
+ [key for key in pointer_evidence if key == "instruction_text"])
2388
+ # The REASON a pointer could not be established, which S2 publishes and this stage used to
2389
+ # drop. An absent list and an established absence read the same to the judge, and the judge
2390
+ # asserted "no pointer" from an input nobody had read (lane E's probe, P1).
2391
+ unavailable_shared = {**pointer_shared, "item_pointer_in_compiled_text": [],
2392
+ "item_pointer_unavailable": "compiled_text_absent"}
2393
+ unavailable_evidence, _unavailable_counts = session_evidence(
2394
+ facts_row, events_by_ref, units_by_version(unit_index(current)), release_doc,
2395
+ lambda ref: unavailable_shared, facts_store, None, None, facts_units)
2396
+ control("the reason S2 publishes for a pointer it could not establish reaches the judge",
2397
+ json.dumps(unavailable_evidence.get("item_pointer_unavailable")),
2398
+ '"compiled_text_absent"')
2399
+ control("and the other reason it can publish reaches it the same way, since the two are "
2400
+ "different situations for a reader",
2401
+ json.dumps(session_evidence(
2402
+ facts_row, events_by_ref, units_by_version(unit_index(current)), release_doc,
2403
+ lambda ref: {**unavailable_shared,
2404
+ "item_pointer_unavailable": "catalog_rule_unread"},
2405
+ facts_store, None, None, facts_units)[0].get("item_pointer_unavailable")),
2406
+ '"catalog_rule_unread"')
2407
+ clean("while a session whose pointers WERE established carries no reason, so the key is the "
2408
+ "unavailability and not a field that is always there",
2409
+ [key for key in pointer_evidence if key == "item_pointer_unavailable"])
2410
+
2411
+ unplaced_unit = {"unit_id": "u-u", "path": "claude/guides/z.md", "text": "- z",
2412
+ "version_sha256": "b" * 64, "layer": "catalog",
2413
+ "item_ref": "claude:guides/z", "carrier_id": "c-" + "1" * 24, "n": 1,
2414
+ "operative_context": ["u-u"]}
2415
+
2416
+ # ONE owner for the surface rule, held by source: the stage translates the unit id to its
2417
+ # item ref and the rule answers. The copy this stage carried is the class of defect the
2418
+ # review found, so the control is that the stage no longer makes that decision itself.
2419
+ held_source = pathlib.Path(__file__).read_text(encoding="utf-8")
2420
+ control("the stage attaches a pair's surface through the one rule, not a copy of it",
2421
+ "yes" if "delivery_evidence.attach_surface(" in held_source else "no", "yes")
2422
+ # The stage still PUBLISHES `history_selected` as evidence, which is its job; what it may
2423
+ # no longer do is read it to decide a surface. That is the exact text of the copy that was
2424
+ # here, so the control names it rather than any mention of the field.
2425
+ # Assembled from pieces so that the pattern itself never appears as a literal in this
2426
+ # file: spelled whole, the control's own line matched it and the control failed on itself.
2427
+ held_copy = 'get("history_selected") or {}).' + 'get(unit'
2428
+ clean("and keeps no surface decision of its own: the copy read the session's selection, "
2429
+ "then its history, then the catalogue",
2430
+ [line.strip() for line in held_source.splitlines() if held_copy in line])
2431
+ # The native layers are the ones the TABLE names, read from it rather than spelled here:
2432
+ # a unit the table already places is returned untouched, because attaching a surface to one
2433
+ # moves it onto an item ladder (the frozen native fixture found that).
2434
+ held_native = next(row["layers"][0] for row in delivery_evidence.table()["surfaces"]
2435
+ if row.get("layers"))
2436
+ control("the rule places a native unit by its layer, leaving it untouched rather than "
2437
+ "moving it onto an item ladder",
2438
+ json.dumps("surface" in delivery_evidence.attach_surface(
2439
+ {"unit_id": "u-n", "layer": held_native, "item_ref": "claude:x"},
2440
+ {"selected": {"claude:x": "requested"}}, None)),
2441
+ "false")
2442
+ control("and a unit no layer places takes the session's own surface",
2443
+ json.dumps(delivery_evidence.attach_surface(
2444
+ {"unit_id": "u-s", "layer": "guides", "item_ref": "claude:guides/g"},
2445
+ {"selected": {"claude:guides/g": "requested"}}, None).get("surface")),
2446
+ '"requested"')
2447
+ control("a unit with no surface from the session, the history or the catalogue stays "
2448
+ "unplaced, and the judge NAMES that rather than answering unknown silently",
2449
+ # Its own row, built here with every field a unit carries: a unit whose layer
2450
+ # places nothing and whose session names no surface. `attach_surface` returns it
2451
+ # unchanged, and what the judge then says is the point — a named state, not a
2452
+ # silent unknown.
2453
+ json.dumps((delivery_evidence.delivery(
2454
+ delivery_evidence.attach_surface(unplaced_unit,
2455
+ {"basis": "pin", "selected": {}}, None),
2456
+ {"u-u": unplaced_unit},
2457
+ {"basis": "pin", "selected": {}, "injection_at": 1,
2458
+ "release": {"complete": True, "layers": {}, "items": []}}, 10)
2459
+ or {}).get("reasons") or []),
2460
+ "surface_unclassified")
2461
+ control("the counts say how many pointer facts and unit surfaces were published",
2462
+ json.dumps(pointer_counts), '"pointer_facts": 1')
2463
+ control("and how many surfaces", json.dumps(pointer_counts), '"unit_surfaces": 1')
2464
+ surface_rows, _surface_doc = facts_document(pointer_shared)
2465
+ control("a unit the session was not given is judged on the catalogue surface S2 published",
2466
+ json.dumps((surface_rows.get(u1) or {}).get("surface")), "guide")
2467
+ # A native unit is matched by its LAYER, and attaching a published surface to one moved it
2468
+ # onto another ladder entirely; the classifier is asked first, and this row is why.
2469
+ native_rows, _native_doc = facts_document(
2470
+ {**pointer_shared,
2471
+ "unit_surfaces": [{"unit_ref": ref_u1, "surface": "requested", "source": "snapshot"}]},
2472
+ current={"units": [{**operative_units[0],
2473
+ "layer": "native_global", "item_ref": "native:global"}]})
2474
+ control("a native unit keeps its layer's ladder, whatever surface is published for it",
2475
+ json.dumps((native_rows.get(u1) or {}).get("surface")), "native_layer")
2476
+ # Absence rather than emptiness: a session whose inventory publishes no facts carries NO
2477
+ # coverage key, and `delivery_evidence` then answers unknown by name. An empty block would be
2478
+ # the claim that the text covered nothing, which is `not_delivered` for every unit of it.
2479
+ bare_evidence, _bare_counts = session_evidence(
2480
+ facts_row, events_by_ref, units_by_version(unit_index(current)), release_doc,
2481
+ lambda ref: {"carriers": facts_shared["carriers"]}, facts_store, None, None, facts_units)
2482
+ clean("a selection inventory that publishes no facts leaves the evidence with no coverage key",
2483
+ [key for key in bare_evidence if key in ("instruction_coverage", "unavailable")])
2484
+ # The equivalence the lead named: the same k-of-n snapshot answers the same through the facts
2485
+ # path as through the text path. Judged by calling the judge itself, because "the same state"
2486
+ # is its answer and not this stage's.
2487
+ # The always surface, whose ladder ends at `exposed`: its top level is the compiled text
2488
+ # holding the unit's lines, which is exactly what the two paths answer differently.
2489
+ eq_unit = {"unit_id": "u-1", "path": "claude/guides/g.md", "text": "- x\n- y",
2490
+ "version_sha256": "a" * 64, "layer": "catalog", "surface": "always",
2491
+ "item_ref": "claude:guides/g", "carrier_id": "c-" + "0" * 24, "n": 1, "start": 1,
2492
+ "operative_context": ["u-1"]}
2493
+ eq_session = {"session_ref": "claude:s", "basis": "pin", "selected": {"claude:guides/g": "always"},
2494
+ "native_events": [], "injection_at": 1,
2495
+ "release": {"complete": True, "layers": {}, "items": []}}
2496
+
2497
+ def eq_state(text=None, facts=None):
2498
+ """The judge's state for this unit under one of the two paths."""
2499
+ answer = delivery_evidence.delivery(
2500
+ eq_unit, {"u-1": eq_unit},
2501
+ {**eq_session, **({"instruction_text": text} if text is not None else {})},
2502
+ 10, instruction_coverage=facts)
2503
+ return answer.get("state"), tuple(answer.get("reasons") or ())
2504
+
2505
+ eq_whole = (eq_state(text="- x\n- y"), eq_state(facts={"u-1": {"covered": 2, "total": 2}}))
2506
+ eq_partial = (eq_state(text="- x"), eq_state(facts={"u-1": {"covered": 1, "total": 2}}))
2507
+ clean("a snapshot covering all of a unit's lines answers the same through the facts path as "
2508
+ "through the text path",
2509
+ [f"text={eq_whole[0]} facts={eq_whole[1]}"] if eq_whole[0] != eq_whole[1] else [])
2510
+ clean("and a snapshot covering k of n answers the same through both, with the same reason",
2511
+ [f"text={eq_partial[0]} facts={eq_partial[1]}"] if eq_partial[0] != eq_partial[1] else [])
2512
+ clean("and the two paths are not the same answer for every input, so the comparison can fail",
2513
+ [] if eq_whole[0] != eq_partial[0] else [f"both paths answered {eq_whole[0]} for k of n and n of n"])
2514
+ control("a session with neither the text nor the facts is unknown by name, never a miss",
2515
+ json.dumps(delivery_evidence.delivery(eq_unit, {"u-1": eq_unit}, eq_session, 10)),
2516
+ "compiled_text_unavailable")
2517
+ clean("and that answer is not not_delivered",
2518
+ [delivery_evidence.delivery(eq_unit, {"u-1": eq_unit}, eq_session, 10).get("state")]
2519
+ if delivery_evidence.delivery(eq_unit, {"u-1": eq_unit}, eq_session,
2520
+ 10).get("state") == "not_delivered" else [])
2521
+
2522
+ control("the release is read as the point derive.absence judges",
2523
+ json.dumps(evidence.get("release") or {}), '"complete": false')
2524
+ control("a layer the release leaves unresolved is carried with its status",
2525
+ json.dumps((evidence.get("release") or {}).get("layers")), '"catalog": "unknown"')
2526
+ incomplete = derive.absence(evidence.get("release") or {})
2527
+ clean("and the absence policy reads it as incomplete", [] if not incomplete[0] else ["complete"])
2528
+ absent = release_of({"sessions": []}, "p-nobody")
2529
+ control("a session the release document does not carry is named, not read as complete",
2530
+ json.dumps(absent), "absent_from_release_document")
2531
+
2532
+ # ---- the reference point, against `release_rows` as it is PUBLISHED -----------------------
2533
+ #
2534
+ # Three defects met here and together made the catalogue absence unreachable (the WP-11b
2535
+ # review): `items` was read from a field `release_rows` does not have, `segments` was
2536
+ # ignored so every segmented session came out incomplete, and `layers` was derived from
2537
+ # `incomplete_reasons`, which names only the layers that are NOT complete.
2538
+ held_ref_a, held_ref_b = "i-" + "e" * 24, "i-" + "f" * 24
2539
+ rel_doc = {"sessions": [{"session_ref": "p-seg", "segments": [
2540
+ {"segment_ref": "rollout-one", "inventory_refs": [held_ref_a],
2541
+ "layers": [{"layer": "catalog", "status": "complete", "reasons": [],
2542
+ "source": {"inventory_ref": held_ref_a, "layer": "catalog",
2543
+ "basis": "pin"}}],
2544
+ "complete": True, "incomplete_reasons": []},
2545
+ {"segment_ref": "rollout-two", "inventory_refs": [held_ref_b],
2546
+ "layers": [{"layer": "catalog", "status": "unknown",
2547
+ "reasons": ["release_history_deferred"], "source": None}],
2548
+ "complete": False,
2549
+ "incomplete_reasons": [{"layer": "catalog", "status": "unknown",
2550
+ "reasons": ["release_history_deferred"],
2551
+ "inventory_ref": None}]}], "unsegmented": None}]}
2552
+ inventories = {held_ref_a: {"items": [{"ref": "claude:one", "surface": "always"}]},
2553
+ held_ref_b: {"items": [{"ref": "claude:two", "surface": "always"}]}}
2554
+ first = release_of(rel_doc, "p-seg", "rollout-one", lambda ref: inventories.get(ref), {})
2555
+ second = release_of(rel_doc, "p-seg", "rollout-two", lambda ref: inventories.get(ref), {})
2556
+ control("the reference point is the SEGMENT the decision belongs to",
2557
+ json.dumps(first["items"]), "claude:one")
2558
+ control("and another segment of the same session answers differently, which is why one "
2559
+ "answer per session was wrong",
2560
+ json.dumps(second["items"]), "claude:two")
2561
+ control("each segment's own completeness is read, not the session's",
2562
+ json.dumps({"one": first["complete"], "two": second["complete"]}),
2563
+ '{"one": true, "two": false}')
2564
+ control("the point it answered on is named, so a reader knows which row set was used",
2565
+ first["point"], "segment")
2566
+ control("a COMPLETE layer carries its status, which deriving from incomplete_reasons could "
2567
+ "not say at all",
2568
+ json.dumps(first["layers"]), '"catalog": "complete"')
2569
+ control("and an incomplete one carries its own", json.dumps(second["layers"]),
2570
+ '"catalog": "unknown"')
2571
+ control("a segmented session whose segment this decision names none of is reported "
2572
+ "unresolved, not complete and not absent",
2573
+ json.dumps(release_of(rel_doc, "p-seg", "rollout-gone",
2574
+ lambda ref: inventories.get(ref), {})),
2575
+ '"segment_unresolved": "rollout-gone"')
2576
+ control("an inventory this run cannot open is named rather than folded into an empty item "
2577
+ "set, because an empty set is the absence claim",
2578
+ json.dumps(release_of(rel_doc, "p-seg", "rollout-one", lambda ref: None, {})),
2579
+ f'"items_unresolved": ["{held_ref_a}"]')
2580
+ clean("and `items` is not claimed for it",
2581
+ release_of(rel_doc, "p-seg", "rollout-one", lambda ref: None, {})["items"])
2582
+ # `unsegmented` is for a session NO segment covers, and only then.
2583
+ unseg_doc = {"sessions": [{"session_ref": "p-un", "segments": [],
2584
+ "unsegmented": {"inventory_refs": [held_ref_a],
2585
+ "layers": [{"layer": "catalog",
2586
+ "status": "complete",
2587
+ "reasons": [], "source": None}],
2588
+ "complete": True,
2589
+ "incomplete_reasons": []}}]}
2590
+ control("a session no segment covers is answered from `unsegmented`",
2591
+ release_of(unseg_doc, "p-un", None, lambda ref: inventories.get(ref), {})["point"],
2592
+ "unsegmented")
2593
+ control("and its items come from the inventory that row set references",
2594
+ json.dumps(release_of(unseg_doc, "p-un", None,
2595
+ lambda ref: inventories.get(ref), {})["items"]),
2596
+ "claude:one")
2597
+ control("the release's item reader is not the SESSION's: one asks what the library held, "
2598
+ "the other what the session received",
2599
+ json.dumps(sorted(released_items(
2600
+ {"items": [{"ref": "claude:stated"}]}, {}))),
2601
+ '["claude:stated"]')
2602
+ clean("and the session reader answers nothing for the same inventory, which is correct for "
2603
+ "its own question and was the bug for this one",
2604
+ sorted(selected_items({"items": [{"ref": "claude:stated"}]}, {})))
2605
+
2606
+ # A unit whose text this run cannot see is answered unknown by name rather than judged on a
2607
+ # placeholder: the comparison would fail for every line and claim a miss from nothing read.
2608
+ redacted = {"units": [{**unit, "text": REDACTED} if unit["unit_id"] == u1 else unit
2609
+ for unit in current["units"]]}
2610
+ doc_red = document(fixture, checks, candidates, redacted, sessions, release_doc, store,
2611
+ lambda ref: None, ["aa.jsonl"], suite_views)
2612
+ control("a redacted unit is not judged on its placeholder",
2613
+ json.dumps(([r["reasons"] for r in doc_red["rows"] if r["unit_id"] == u1]
2614
+ or [["NO_ROW_FOR_THE_SUBJECT_UNIT"]])[0]),
2615
+ "unit_text_redacted")
2616
+ control("each row names the ordinal it used", json.dumps((doc.get("rows") or [{}])[0]),
2617
+ '"decision_ordinal": "event.at_record"')
2618
+
2619
+ # ---- the bytes a session read back, from the run's immutable copy (commit 4) ----
2620
+ # Records in both hosts' own shapes. The returned text of a read is what covers a
2621
+ # requirement, so a result that cannot be read back as text is `unparsed`, never a miss.
2622
+ claude_copy = fixture / SOURCES_DIR / "cc.jsonl"
2623
+ claude_copy.parent.mkdir(parents=True, exist_ok=True)
2624
+ claude_copy.write_text("\n".join(json.dumps(row) for row in [
2625
+ {"type": "assistant", "message": {"content": [
2626
+ {"type": "tool_use", "id": "t1", "name": "Read",
2627
+ "input": {"file_path": "/x/guides/g.md"}}]}},
2628
+ {"type": "user", "message": {"content": [
2629
+ {"type": "tool_result", "tool_use_id": "t1",
2630
+ "content": [{"type": "text", "text": " 1\t- Read the log before you retry."}]}]}},
2631
+ {"type": "assistant", "message": {"content": [
2632
+ {"type": "tool_use", "id": "t2", "name": "Bash",
2633
+ "input": {"command": "sed -n '1,40p' /x/guides/h.md"}}]}},
2634
+ {"type": "user", "message": {"content": [
2635
+ {"type": "tool_result", "tool_use_id": "t2", "content": "- h"}]}},
2636
+ {"type": "assistant", "message": {"content": [
2637
+ {"type": "tool_use", "id": "t3", "name": "Read", "input": {"file_path": "/x/guides/i.md"}}]}},
2638
+ {"type": "user", "message": {"content": [
2639
+ {"type": "tool_result", "tool_use_id": "t3", "is_error": True, "content": "No such file"}]}},
2640
+ {"type": "assistant", "message": {"content": [
2641
+ {"type": "tool_use", "id": "t4", "name": "Read", "input": {"file_path": "/x/guides/j.md"}}]}},
2642
+ {"type": "user", "message": {"content": [
2643
+ {"type": "tool_result", "tool_use_id": "t4",
2644
+ "content": [{"type": "image", "source": {}}]}]}},
2645
+ {"type": "assistant", "message": {"content": [
2646
+ {"type": "tool_use", "id": "t5", "name": "Bash", "input": {"command": "cat $KNOWN_FILE"}}]}},
2647
+ {"type": "user", "message": {"content": [
2648
+ {"type": "tool_result", "tool_use_id": "t5", "content": "- opaque"}]}},
2649
+ ]) + "\n", encoding="utf-8")
2650
+ reads, unparsed, counts = reads_of(fixture, claude_copy.relative_to(fixture), "claude")
2651
+ control("a named reader's path is its own argument", json.dumps((reads or [{}])[0]),
2652
+ '"path": "/x/guides/g.md"')
2653
+ control("and the read is attributed to the line its RESULT arrived on",
2654
+ json.dumps((reads or [{}])[0]), '"at": 2')
2655
+ control("the returned text is kept as returned, prefixes and all",
2656
+ json.dumps((reads or [{}])[0].get("returned")), "1\\t- Read the log")
2657
+ control("a reading command's path is read out of the command",
2658
+ json.dumps(reads[1:2]), '"path": "/x/guides/h.md"')
2659
+ clean("a failed call is not a read",
2660
+ [r for r in reads if (r.get("path") or "").endswith("i.md")])
2661
+ control("a result that is not text is unparsed, not a miss",
2662
+ json.dumps([r for r in unparsed if r["path"] and r["path"].endswith("j.md")]),
2663
+ "result_not_text")
2664
+ control("and a reading command naming no path is unparsed too",
2665
+ json.dumps(unparsed), "command_names_no_path")
2666
+ control("the counts say how many results were seen",
2667
+ str((counts or {}).get("results", "no such count")), "5")
2668
+
2669
+ codex_copy = fixture / SOURCES_DIR / "cx.jsonl"
2670
+ codex_copy.write_text("\n".join(json.dumps(row) for row in [
2671
+ {"type": "response_item", "payload": {"type": "function_call", "call_id": "c1", "name": "shell",
2672
+ "arguments": json.dumps({"command": ["cat", "/x/guides/g.md"]})}},
2673
+ {"type": "response_item", "payload": {"type": "function_call_output", "call_id": "c1",
2674
+ "output": "- Read the log before you retry."}},
2675
+ ]) + "\n", encoding="utf-8")
2676
+ codex_reads, _codex_unparsed, _codex_counts = reads_of(fixture, codex_copy.relative_to(fixture), "codex")
2677
+ # Dumped whole rather than indexed: a revert that returns no read would end the suite with an
2678
+ # IndexError here and print nothing, which is the control-that-cannot-speak shape this branch
2679
+ # has now paid for twice (the ledger migrator's `[0]`, and `evidence["pin_reason"]`).
2680
+ control("a Codex shell call is read the same way", json.dumps(codex_reads),
2681
+ '"path": "/x/guides/g.md"')
2682
+ control("and at the line of its output", json.dumps((codex_reads or [{}])[0]), '"at": 2')
2683
+
2684
+ # ---- Codex's exec_command, and a result that failed or was elided ------------------------
2685
+ #
2686
+ # `exec_command` carries its command under `cmd` and was absent from SHELL_READERS, so
2687
+ # every one of its calls fell through as non-reading — silently, since a call with no
2688
+ # `command` simply continued (the WP-11b review). And neither adapter read the result's own
2689
+ # text for a failure or an elision: "Process exited with code 1" was counted as the file's
2690
+ # delivered bytes, and a truncation warning as the whole file.
2691
+ shapes_copy = fixture / SOURCES_DIR / "shapes.jsonl"
2692
+ shapes_copy.write_text("\n".join(json.dumps(row) for row in [
2693
+ {"type": "response_item", "payload": {
2694
+ "type": "function_call", "call_id": "e1", "name": "exec_command",
2695
+ "arguments": json.dumps({"cmd": "cat /x/guides/exec.md"})}},
2696
+ {"type": "response_item", "payload": {
2697
+ "type": "function_call_output", "call_id": "e1",
2698
+ "output": "- the text of exec.md"}},
2699
+ {"type": "response_item", "payload": {
2700
+ "type": "function_call", "call_id": "e2", "name": "shell",
2701
+ "arguments": json.dumps({"command": ["cat", "/x/guides/failed.md"]})}},
2702
+ {"type": "response_item", "payload": {
2703
+ "type": "function_call_output", "call_id": "e2",
2704
+ "output": "cat: no such file\nProcess exited with code 1"}},
2705
+ {"type": "response_item", "payload": {
2706
+ "type": "function_call", "call_id": "e3", "name": "shell",
2707
+ "arguments": json.dumps({"command": ["cat", "/x/guides/elided.md"]})}},
2708
+ {"type": "response_item", "payload": {
2709
+ "type": "function_call_output", "call_id": "e3",
2710
+ "output": "- the first line\nWarning: truncated output"}},
2711
+ {"type": "response_item", "payload": {
2712
+ "type": "function_call", "call_id": "e4", "name": "shell",
2713
+ "arguments": json.dumps({"command": ["cat", "/x/guides/ok.md"]})}},
2714
+ {"type": "response_item", "payload": {
2715
+ "type": "function_call_output", "call_id": "e4",
2716
+ "output": "- all of it\nProcess exited with code 0"}},
2717
+ {"type": "response_item", "payload": {
2718
+ "type": "function_call", "call_id": "e5", "name": "local_shell",
2719
+ "arguments": json.dumps({"invocation": {"argv": ["cat", "/x/guides/odd.md"]}})}},
2720
+ {"type": "response_item", "payload": {
2721
+ "type": "function_call_output", "call_id": "e5", "output": "- something"}},
2722
+ ]) + "\n", encoding="utf-8")
2723
+ shape_reads, shape_unparsed, shape_counts = reads_of(
2724
+ fixture, shapes_copy.relative_to(fixture), "codex")
2725
+
2726
+ def read_paths(held):
2727
+ return sorted(row["path"] for row in held if row.get("path"))
2728
+
2729
+ control("an exec_command call carrying its command under `cmd` is a read",
2730
+ json.dumps(read_paths(shape_reads)), "/x/guides/exec.md")
2731
+ control("a result whose text says the call FAILED is uncertainty, not delivered bytes",
2732
+ json.dumps([row for row in shape_unparsed
2733
+ if row.get("path") == "/x/guides/failed.md"]),
2734
+ '"reason": "result_failed"')
2735
+ control("and the refusal says which exit code it read",
2736
+ json.dumps([row for row in shape_unparsed
2737
+ if row.get("path") == "/x/guides/failed.md"]),
2738
+ "exit code 1")
2739
+ clean("so the failed call contributes no read",
2740
+ [row for row in shape_reads if row["path"] == "/x/guides/failed.md"])
2741
+ control("a result the host ELIDED is uncertainty too, since the bytes are not the file's",
2742
+ json.dumps([row for row in shape_unparsed
2743
+ if row.get("path") == "/x/guides/elided.md"]),
2744
+ '"reason": "result_elided"')
2745
+ clean("and it contributes no read either",
2746
+ [row for row in shape_reads if row["path"] == "/x/guides/elided.md"])
2747
+ control("an exit code of ZERO is not a failure, which is what makes the marker a status "
2748
+ "rather than a word to look for",
2749
+ json.dumps(read_paths(shape_reads)), "/x/guides/ok.md")
2750
+ control("a shell call whose argument shape this adapter does not know is kept as named "
2751
+ "uncertainty, not discarded as a call nobody made",
2752
+ json.dumps([row for row in shape_unparsed
2753
+ if row.get("reason") == "call_shape_unsupported"]),
2754
+ "local_shell")
2755
+ control("and the counts say how many of each there were",
2756
+ json.dumps({key: shape_counts.get(key) for key in
2757
+ ("result_failed", "result_elided", "call_shape_unsupported")}),
2758
+ '{"result_failed": 1, "result_elided": 1, "call_shape_unsupported": 1}')
2759
+ control("the command argument names are data, so a new shape is one entry",
2760
+ json.dumps(list(COMMAND_ARGUMENTS)), '["command", "cmd", "commands"]')
2761
+ # What the SHELL_READERS entry itself buys: a call of that tool whose argument shape this
2762
+ # adapter does not know is VISIBLE rather than dropped. Without the entry it matches neither
2763
+ # branch and falls through, which is how every `exec_command` call disappeared.
2764
+ odd_exec = fixture / SOURCES_DIR / "odd-exec.jsonl"
2765
+ odd_exec.write_text("\n".join(json.dumps(row) for row in [
2766
+ {"type": "response_item", "payload": {
2767
+ "type": "function_call", "call_id": "x1", "name": "exec_command",
2768
+ "arguments": json.dumps({"shell": {"argv": ["cat", "/x/guides/odd2.md"]}})}},
2769
+ {"type": "response_item", "payload": {
2770
+ "type": "function_call_output", "call_id": "x1", "output": "- bytes"}},
2771
+ ]) + "\n", encoding="utf-8")
2772
+ _odd_reads, odd_unparsed, odd_counts = reads_of(fixture, odd_exec.relative_to(fixture),
2773
+ "codex")
2774
+ control("an exec_command call whose argument shape is unknown is named, which is what "
2775
+ "listing the tool buys: without it the call matches no branch and is dropped",
2776
+ json.dumps(odd_unparsed), '"reason": "call_shape_unsupported"')
2777
+ control("and it says which tool and which arguments, so the next shape is one entry",
2778
+ json.dumps(odd_unparsed), "exec_command: ['shell']")
2779
+ control("the tools whose calls are read as shell commands are named in one place",
2780
+ json.dumps(sorted(SHELL_READERS)),
2781
+ json.dumps(sorted(["Bash", "shell", "local_shell", "container.exec",
2782
+ "exec_command"])))
2783
+
2784
+ # The SAME judgment on the Claude side: a host that writes the failure into the text does
2785
+ # not set `is_error`, so the structured check above it does not catch this one.
2786
+ cl_defect = fixture / SOURCES_DIR / "cl-defect.jsonl"
2787
+ cl_defect.write_text("\n".join(json.dumps(row) for row in [
2788
+ {"type": "assistant", "message": {"content": [
2789
+ {"type": "tool_use", "id": "d1", "name": "Bash",
2790
+ "input": {"command": "cat /x/guides/cl-failed.md"}}]}},
2791
+ {"type": "user", "message": {"content": [
2792
+ {"type": "tool_result", "tool_use_id": "d1",
2793
+ "content": "cat: missing\nProcess exited with code 2"}]}},
2794
+ {"type": "assistant", "message": {"content": [
2795
+ {"type": "tool_use", "id": "d2", "name": "Read",
2796
+ "input": {"file_path": "/x/guides/cl-elided.md"}}]}},
2797
+ {"type": "user", "message": {"content": [
2798
+ {"type": "tool_result", "tool_use_id": "d2",
2799
+ "content": "- the head\n<response clipped>"}]}},
2800
+ ]) + "\n", encoding="utf-8")
2801
+ cl_reads, cl_unparsed, cl_counts = reads_of(fixture, cl_defect.relative_to(fixture),
2802
+ "claude")
2803
+ clean("a Claude result that failed in its TEXT rather than in `is_error` admits no read",
2804
+ [row for row in cl_reads if "cl-failed" in row["path"]])
2805
+ control("and is named as the failure it is",
2806
+ json.dumps([row for row in cl_unparsed if "cl-failed" in (row.get("path") or "")]),
2807
+ '"reason": "result_failed"')
2808
+ clean("an elided Read result admits no read either",
2809
+ [row for row in cl_reads if "cl-elided" in row["path"]])
2810
+ control("and the one judgment serves both adapters, named in one place",
2811
+ next((line.strip() for line in inspect.getsource(_claude_reads).splitlines()
2812
+ if "result_defect(" in line), "<no such line>"),
2813
+ "result_defect(returned)")
2814
+ control("with the Codex adapter reaching the same function",
2815
+ next((line.strip() for line in inspect.getsource(_codex_reads).splitlines()
2816
+ if "result_defect(" in line), "<no such line>"),
2817
+ "result_defect(returned)")
2818
+
2819
+ missing = reads_of(fixture, pathlib.PurePosixPath(SOURCES_DIR) / "nope.jsonl", "claude")
2820
+ control("a copy the run does not hold is named, not read as an empty session",
2821
+ json.dumps(missing[2]), "copy_missing")
2822
+
2823
+ # ---- the label is CONFINED before the filesystem is touched -----------------------------
2824
+ #
2825
+ # The path was `pathlib.Path(run_dir) / copy`, which discards `run_dir` entirely for an
2826
+ # absolute label, follows `..`, and follows a symlink out. S2's manifest is a run artifact
2827
+ # and therefore DATA: a row in it could point this stage at any file the owner can read,
2828
+ # and it would open it and report its reads (the WP-11b review). The confinement lives in
2829
+ # `reads_of` rather than at the call site, because a caller can forget it.
2830
+ outside = pathlib.Path(fixture).parent / "outside-the-run.jsonl"
2831
+ outside.write_text(json.dumps(
2832
+ {"type": "assistant",
2833
+ "message": {"content": [{"type": "tool_use", "id": "x1", "name": "Read",
2834
+ "input": {"file_path": "/x/guides/secret.md"}}]}}) + "\n",
2835
+ encoding="utf-8")
2836
+
2837
+ def _linked_label(root, target):
2838
+ """A label INSIDE the run whose own path is a symlink pointing at `target`.
2839
+
2840
+ No string test catches this one: the label is relative, holds no `..` and starts with
2841
+ no slash. Only resolving it does.
2842
+ """
2843
+ link = pathlib.Path(root) / SOURCES_DIR / "linked.jsonl"
2844
+ if link.is_symlink() or link.exists():
2845
+ link.unlink()
2846
+ link.symlink_to(target)
2847
+ return str(link.relative_to(root))
2848
+
2849
+ def document_probe_reads(root):
2850
+ """Every read of every copy this fixture's manifest names, as the stage would gather it.
2851
+
2852
+ Used to assert that the file outside the run contributed nothing — an assertion about
2853
+ the OUTPUT, not only about the refusal, since a refusal that is caught somewhere above
2854
+ would still leave the read in the document.
2855
+ """
2856
+ held = []
2857
+ for label in (claude_copy.relative_to(root), codex_copy.relative_to(root)):
2858
+ try:
2859
+ held.extend(reads_of(root, label, "claude")[0])
2860
+ except Exception: # noqa: BLE001 - a refusal contributes nothing, which is the point
2861
+ continue
2862
+ return held
2863
+
2864
+ def escaped(label):
2865
+ try:
2866
+ reads_of(fixture, label, "claude")
2867
+ except Exception as exc: # noqa: BLE001 - the refusal IS the answer
2868
+ return f"{type(exc).__name__}: {exc}"
2869
+ return "<no refusal>"
2870
+
2871
+ control("an ABSOLUTE label is refused rather than read, which is the case `/` silently "
2872
+ "allowed by discarding the run",
2873
+ escaped(str(outside)), "EVIDENCE_OUTSIDE_RUN")
2874
+ control("a traversing label is refused", escaped("../outside-the-run.jsonl"),
2875
+ "EVIDENCE_OUTSIDE_RUN")
2876
+ control("and a label inside the run that SYMLINKS out, which no string test catches",
2877
+ escaped(_linked_label(fixture, outside)), "EVIDENCE_OUTSIDE_RUN")
2878
+ clean("the file outside the run was never opened: it still holds exactly what the control "
2879
+ "wrote, and no read of it reached any document",
2880
+ [] if "secret.md" not in json.dumps(document_probe_reads(fixture))
2881
+ else ["a read of the file outside the run reached the document"])
2882
+ control("and an ordinary label still works, so the confinement is not refusing everything",
2883
+ json.dumps(reads_of(fixture, claude_copy.relative_to(fixture), "claude")[0]),
2884
+ '"path": "/x/guides/g.md"')
2885
+
2886
+ # ---- the JSONL splitter, not `str.splitlines()` ------------------------------------------
2887
+ #
2888
+ # `splitlines()` also splits U+2028, U+2029 and U+0085, so ONE record carrying a separator
2889
+ # inside a JSON string became two lines: the record ordinals this stage reports were on a
2890
+ # different scale from S2's, and the second half was discarded as unparsable. The same
2891
+ # defect as the journal's, in a different file (the WP-11b review).
2892
+ sep_copy = fixture / SOURCES_DIR / "sep.jsonl"
2893
+ sep_copy.write_text("\n".join([
2894
+ json.dumps({"type": "assistant", "message": {"content": [
2895
+ {"type": "tool_use", "id": "s1", "name": "Read",
2896
+ "input": {"file_path": "/x/guides/sep\u2028ated.md"}}]}}),
2897
+ json.dumps({"type": "user", "message": {"content": [
2898
+ {"type": "tool_result", "tool_use_id": "s1", "content": "- the text"}]}}),
2899
+ ]) + "\n", encoding="utf-8")
2900
+ sep_reads, sep_unparsed, sep_counts = reads_of(fixture,
2901
+ sep_copy.relative_to(fixture), "claude")
2902
+ control("a record carrying a Unicode line separator inside a JSON string is ONE record",
2903
+ str(sep_counts.get("records")), "2")
2904
+ control("and its read is attributed to the physical line its result arrived on, which is "
2905
+ "the ordinal S2 counts in",
2906
+ json.dumps((sep_reads or [{}])[0]), '"at": 2')
2907
+ clean("and nothing was discarded as unparsable", [row for row in sep_unparsed])
2908
+ control("the splitter is the repository's one, reached rather than re-implemented",
2909
+ next((line.strip() for line in inspect.getsource(reads_of).splitlines()
2910
+ if "lines = " in line), "<no such line>"),
2911
+ "records.jsonl_read(path")
2912
+
2913
+ # The event records S3 wrote go through the same splitter, and for the same reason: this
2914
+ # mapping's whole job is to establish the ordinal SCALE a read's `at` is compared on, so a
2915
+ # record split in half moves every ordinal after it. `records` writes these files with
2916
+ # `ensure_ascii=False`, so a separator inside a decision's text reaches the file as itself.
2917
+ sep_run = fixture / "sep-run"
2918
+ (sep_run / EVENTS_DIR).mkdir(parents=True, exist_ok=True)
2919
+ (sep_run / EVENTS_DIR / "t-sep.jsonl").write_text(
2920
+ "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in [
2921
+ {"event_id": "e-sep", "at_record": "76837/message/content",
2922
+ "text": "a decision whose text carries \u2028 inside it"},
2923
+ {"event_id": "e-after", "at_record": "76900/message/content"},
2924
+ ]), encoding="utf-8")
2925
+ held_decisions = decisions_of(sep_run)
2926
+ equals("an event record carrying a Unicode line separator inside a JSON string is ONE "
2927
+ "record, so the ordinal scale this mapping establishes does not shift",
2928
+ json.dumps(held_decisions, sort_keys=True),
2929
+ json.dumps({"e-sep": ["t-sep", 76837], "e-after": ["t-sep", 76900]}, sort_keys=True))
2930
+ control("and the splitter is the repository's one, reached rather than re-implemented",
2931
+ next((line.strip() for line in inspect.getsource(decisions_of).splitlines()
2932
+ if "for line in " in line), "<no such line>"),
2933
+ "records.jsonl_read(path")
2934
+
2935
+ # The manifest is what says which copy belongs to which session.
2936
+ # The manifest row's SESSION is what the session row names; its transcript string is deliberately
2937
+ # a different value here, so a lookup that only ever reads the transcript key fails this control
2938
+ # instead of passing on a fixture where the two happen to be equal.
2939
+ views = {"transcripts": [{"session": "claude:t-1", "transcript": "claude:other-1",
2940
+ "name": "claude_other-1", "host": "claude",
2941
+ "source_copy": f"{SOURCES_DIR}/cc.jsonl", "version_sha": "c" * 64}]}
2942
+ with_reads, read_counts = session_evidence(session_row, events_by_ref,
2943
+ units_by_version(unit_index(current)), release_doc,
2944
+ lambda ref: None, store, fixture, copies_of(views))
2945
+ control("the session's reads come from the copy its manifest row names",
2946
+ str(len(with_reads.get("reads") or [])), "2")
2947
+ control("and an unparsed call with no path is counted rather than dropped",
2948
+ str(read_counts.get("unparsed_without_a_path", "no such count")), "1")
2949
+ clean("no unparsed row without a path reaches the judge",
2950
+ [row for row in with_reads.get("unparsed") or [] if not row.get("path")])
2951
+ without, no_copy = session_evidence(session_row, events_by_ref,
2952
+ units_by_version(unit_index(current)), release_doc,
2953
+ lambda ref: None, store, fixture, {})
2954
+ clean("a session with no copy carries no `reads` key at all", [k for k in without if k == "reads"])
2955
+ control("and the counts say the copy is absent", json.dumps(no_copy), '"copy": "absent"')
2956
+
2957
+ # ---- a copy the manifest NAMES and this run cannot open ----------------------------------
2958
+ #
2959
+ # `reads_of` returns empty reads plus `copy_missing`, and this installed `reads = []` —
2960
+ # "the session read nothing", which is a claim. The judge then reported an exposed guide as
2961
+ # NOT READ from evidence nobody acquired (the WP-11b review). The no-entry case was already
2962
+ # right, and the two are different answers: one says this run holds no copy, the other that
2963
+ # it holds a copy it cannot open.
2964
+ gone_views = {"transcripts": [{**views["transcripts"][0],
2965
+ "source_copy": f"{SOURCES_DIR}/not-written.jsonl"}]}
2966
+ gone, gone_counts = session_evidence(session_row, events_by_ref,
2967
+ units_by_version(unit_index(current)), release_doc,
2968
+ lambda ref: None, store, fixture,
2969
+ copies_of(gone_views))
2970
+ clean("a copy the manifest names and the run cannot open installs NO reads, so nothing "
2971
+ "claims the session read nothing",
2972
+ [key for key in gone if key == "reads"])
2973
+ control("and the acquisition is carried as unavailable, with its own reason",
2974
+ json.dumps(gone.get("read_evidence")),
2975
+ '"status": "unavailable"')
2976
+ control("named `copy_missing`, which is not the same answer as holding no copy",
2977
+ json.dumps(gone.get("read_evidence")), '"reason": "copy_missing"')
2978
+ control("the counts distinguish the two", json.dumps(gone_counts), '"copy": "missing"')
2979
+ control("while holding no copy at all is `absent`, and says so in the evidence too",
2980
+ json.dumps(without.get("read_evidence")), '"reason": "copy_absent"')
2981
+ control("and an available copy records that it was read", json.dumps(
2982
+ with_reads.get("read_evidence")), '"status": "available"')
2983
+ # And the judge's side: the pair is answered unknown with that reason rather than judged.
2984
+ gone_doc = document(fixture, checks, candidates, current, sessions, release_doc, store,
2985
+ lambda ref: None, ["aa.jsonl"],
2986
+ {"transcripts": suite_views["transcripts"] + gone_views["transcripts"]})
2987
+ control("a pair whose session's records could not be acquired is answered unknown naming "
2988
+ "the acquisition, not judged against an empty read set",
2989
+ json.dumps([row["reasons"] for row in gone_doc["rows"]
2990
+ if row.get("session") == "claude:t-1"]),
2991
+ "copy_missing")
2992
+ clean("and no such pair comes out delivered or missed",
2993
+ [row["state"] for row in gone_doc["rows"]
2994
+ if row.get("session") == "claude:t-1" and row["state"] != "unknown"])
2995
+
2996
+ # The two refusals, each before any write.
2997
+ empty = root / "r-empty"
2998
+ (empty / SOURCES_DIR).mkdir(parents=True)
2999
+ control("a run whose immutable copy holds nothing is refused by name",
3000
+ refusal(lambda: run(empty)), "DELIVERY_SOURCES_MISSING")
3001
+ clean("and nothing is written for it", sorted(p.name for p in empty.iterdir() if p.is_file()))
3002
+ gone = root / "r-nosources"
3003
+ gone.mkdir()
3004
+ control("so is a run with no copy at all", refusal(lambda: run(gone)), "DELIVERY_SOURCES_MISSING")
3005
+
3006
+ # The EDGES prerequisite, through `run`, before any stage record is published. It used to
3007
+ # be checked inside `document`, after `run_stage` had written `status: running` — so a
3008
+ # condition knowable from S2's own document left a FAILED attempt behind, and a stage record
3009
+ # that says an attempt failed is read as an attempt (the WP-11b review).
3010
+ no_edge_run = root / "r-noedges"
3011
+ (no_edge_run / SOURCES_DIR).mkdir(parents=True)
3012
+ (no_edge_run / SOURCES_DIR / "aa.jsonl").write_text("{}\n", encoding="utf-8")
3013
+ (no_edge_run / "inventory").mkdir(parents=True)
3014
+ stripped = {"units": [{key: value for key, value in unit.items() if key != "edges"}
3015
+ for unit in current["units"]]}
3016
+ records.write_json(no_edge_run, no_edge_run / "inventory" / "current.json", stripped)
3017
+ control("a run whose current units carry no `edges` is refused by name",
3018
+ refusal(lambda: run(no_edge_run)), "DELIVERY_EDGES_ABSENT")
3019
+ clean("and NO stage record was published for it, so the refusal is not read as an attempt",
3020
+ sorted(str(held.relative_to(no_edge_run))
3021
+ for held in (no_edge_run / "stages").rglob("*")
3022
+ if held.is_file()) if (no_edge_run / "stages").is_dir() else [])
3023
+ clean("and this stage's output is not there either",
3024
+ [OUTPUT] if (no_edge_run / OUTPUT).is_file() else [])
3025
+ control("the prerequisite is read before the stage is entered, from S2's own document",
3026
+ next((line.strip() for line in inspect.getsource(run).splitlines()
3027
+ if "unit_index(" in line), "<no such line>"),
3028
+ "unit_index(held_current)")
3029
+ clean("and the line that reads it comes BEFORE the one that enters the stage",
3030
+ [] if [n for n, line in enumerate(inspect.getsource(run).splitlines())
3031
+ if "unit_index(held_current)" in line][0]
3032
+ < [n for n, line in enumerate(inspect.getsource(run).splitlines())
3033
+ if "records.run_stage(" in line][0]
3034
+ else ["the prerequisite is read after the stage is entered"])
3035
+
3036
+ stopped = root / "r-stopped"
3037
+ (stopped / SOURCES_DIR).mkdir(parents=True)
3038
+ (stopped / SOURCES_DIR / "aa.jsonl").write_text("{}\n", encoding="utf-8")
3039
+ (stopped / "supervisor").mkdir()
3040
+ records.write_json(stopped, dispatch.run_ledger_path(stopped),
3041
+ {"stages": {}, "stops": {"INPUT_BOUND_EXCEEDED": {
3042
+ "code": "INPUT_BOUND_EXCEEDED", "call_id": "r1/S3/read/a0", "observed": 1,
3043
+ "declaration_seq": 0}}})
3044
+ said = refusal(lambda: run(stopped))
3045
+ control("a run with a standing stop is refused by name", said, "DELIVERY_RUN_STOPPED")
3046
+ control("and the refusal carries the stop's own code", said, "INPUT_BOUND_EXCEEDED")
3047
+ clean("and nothing is written for it either",
3048
+ sorted(p.name for p in stopped.iterdir() if p.is_file()))
3049
+ # A declaration this stage cannot read holds the stop standing, rather than reading the run open: the
3050
+ # fixture above has no run.json at all, and the stop was still named. Asserted here as its own control,
3051
+ # because the direction is the whole point — the other reading would let an unreadable run.json turn a
3052
+ # stopped run into a complete-looking document.
3053
+ control("an unreadable declaration holds a recorded stop standing",
3054
+ standing_stop(stopped) or "", "INPUT_BOUND_EXCEEDED")
3055
+
3056
+ # The stop reading is the dispatcher's, not a second one: an empty ledger is not a stop.
3057
+ open_run = root / "r-open"
3058
+ (open_run / SOURCES_DIR).mkdir(parents=True)
3059
+ (open_run / "supervisor").mkdir()
3060
+ records.write_json(open_run, dispatch.run_ledger_path(open_run), {"stages": {}, "stops": {}})
3061
+ clean("a ledger with no stop is not read as stopped", standing_stop(open_run))
3062
+
3063
+ for failure in failures:
3064
+ print(f"stage_delivery --self-test [FAIL] {failure}", file=sys.stderr)
3065
+ if failures:
3066
+ return 1
3067
+ print(f"stage_delivery --self-test: OK ({len(ran)} controls: the stage's place in STAGES, the pairs owed over "
3068
+ f"the artifacts' own shapes with every pending one answered by name, the judge's one-step context set "
3069
+ f"and the refusal when the inventory publishes none, the inventory's half of the session "
3070
+ f"evidence — native events at their record line, the release as the absence policy reads it, a read "
3071
+ f"pin with no selection inventory kept out of the pin basis, and a redacted unit not judged on its "
3072
+ f"placeholder, the bytes a session read back from the run's immutable copy on both hosts "
3073
+ f"with a failed call no read, a non-text result unparsed and a missing copy named, and the two run "
3074
+ f"refusals with nothing written)")
3075
+ return 0
3076
+
3077
+
3078
+ if __name__ == "__main__":
3079
+ sys.exit(self_test() if "--self-test" in sys.argv[1:] else
3080
+ print("usage: stage_delivery.py --self-test (the stage runs as `distill.py deliver`)") or 2)