agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,924 @@
1
+ #!/usr/bin/env python3
2
+ """S5 retrieve and check (plan WP-10; design §6.2 retrieval, §5.3 counting, §6.4's absence at an incomplete point).
3
+
4
+ Code only: no model is called. For every candidate of S4's population - formed and lifecycle - S5 writes one row of
5
+ `checks.json`:
6
+
7
+ - **Retrieval** (§6.2): BM25 (lifecycle_intake.Library, search.K1/B) over the operative units of the current library
8
+ S2 left, one per text in each layer (identical copies folded and counted), the query being the candidate's situation,
9
+ action and exception and the text of every unit and ledger entry it names (the named hints: a lifecycle candidate's
10
+ `target_unit`, `target_units`, `target_entry`, `entries`; a formed type G candidate's `instance_entry_ids` and the
11
+ hints of the cluster it names). The top PER_LAYER units of each layer, every unit it names, and the top TOP_ENTRIES
12
+ ledger entries by the same query (lifecycle_intake.entry_text), every entry it names among them. A named unit or entry
13
+ the library or ledger does not hold is listed by id, never dropped. Reference units are not indexed: §6.1 splits a
14
+ unit operative or reference, and a reference unit states no requirement a candidate could be covered by.
15
+ - **Quote checks** (plan WP-10 Goal): every quote a formed candidate cites - through its admission and through the
16
+ claims of its events, and the origin quotes S4 verified and kept in `candidates.json` - is verified again against the
17
+ immutable copy (`evidence.verify`); a failure is named by code and evidence id. A candidate citing no quote has
18
+ `quote_ok` null, not true.
19
+ - **Sessions**: each session a candidate names is a census row and the session of one of its events; otherwise
20
+ SESSION_UNKNOWN / SESSION_MISMATCH, by id (the fabricated session id of design §6.5's planted controls).
21
+ - **Recurrence** (§5.3): the affirmed lineages its sessions come from that the census counts - the census's own
22
+ `counted` verdict on the component's root (unique root, `indexed`, owned, of a counted class), read and never
23
+ re-derived - each once however many of its sessions the candidate has. Every other session is excluded by name:
24
+ `unknown_independence` (no single root), `not_indexed` (the root is not in its host's index), `not_counted` (the
25
+ census counts the root out for another reason), `not_in_census`.
26
+ - **Absence** (§6.2, §6.4): an absence conclusion needs a complete reference point; under the table's policy
27
+ (derive.absence) the current point S2 recorded decides, and when it is not complete every candidate is withheld from
28
+ an absence sweep, with the count and the reason travelling by name to the summary and the report (D-20261111-eaa2a8).
29
+
30
+ Three outputs, each with its own boundary. `checks.json` and `controls.json` hold names, ids, hashes, scores and
31
+ counts: no unit text, lesson or quote. `checked-candidates.json` (POPULATION_FILE) is the population S6 builds its
32
+ packets from, and it is evidence-bearing by design: every candidate whole (S4's formed ones with their lessons, the
33
+ lifecycle intake's, the planted controls) and the evidence records S6 shows beside them - the origin quotes S4
34
+ verified and kept, and a planted quote - redacted text included. It is private to the run and goes to a model only through S6's packets (Codex WP-10 X r1 #9:
35
+ a counts-only sentence covered all three).
36
+ stage_retrieve.py --self-test
37
+ """
38
+ import collections
39
+ import json
40
+ import pathlib
41
+ import shutil
42
+ import subprocess
43
+ import sys
44
+ import tempfile
45
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
46
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
47
+ from runlib import census, controls, derive, evidence, lifecycle_intake, lineage, records, stage_form, validate
48
+ from runlib.records import Refused
49
+
50
+ HERE = pathlib.Path(__file__).resolve().parents[1] # session-distill/: the self-test runs the driver from it
51
+ STAGE = "S5"
52
+ SCHEMA_PATH = HERE / "schemas" / "checks.schema.json"
53
+ # What S5 reads, each pinned at admission to the record of the stage that produced it (records.run_stage): S4's
54
+ # candidates, and what S4's subject was read from, so the events, claims and quotes S5 checks again are S3's as S4 read
55
+ # them, and the library and census are the ones S4 was admitted against.
56
+ INPUTS = ({"artifact": "candidates.json", "producer_stage": "S4"},
57
+ {"artifact": "read-results.json", "producer_stage": "S3"},
58
+ {"artifact": "read.json", "producer_stage": "S3"},
59
+ {"artifact": "observations/resolutions.json", "producer_stage": "S3"},
60
+ {"artifact": "census.json", "producer_stage": "S1"},
61
+ {"artifact": "coverage.json", "producer_stage": "S1"},
62
+ {"artifact": "views.json", "producer_stage": "S2"},
63
+ {"artifact": "inventory/current.json", "producer_stage": "S2"})
64
+ # checks.json: one row per candidate; checked-candidates.json: the population S6 judges, natural and planted in one
65
+ # shape, ordered by id, with the evidence records no S3 store holds; the expected verdicts of the planted controls,
66
+ # which no packet carries and S6 never reads (controls.reader_problems)
67
+ POPULATION_FILE = "checked-candidates.json"
68
+ OUTPUTS = ("checks.json", POPULATION_FILE, controls.CONTROLS_FILE)
69
+ # design §6.2 line 411: "top 20 per layer plus every unit a candidate names"
70
+ PER_LAYER = 20
71
+ # design §6.2 line 412 names "the top ledger entries" and no number, nor does the plan: the per-layer count, a declared
72
+ # constant (lead, 2026-11-11), revisited at C3 against the entries the judges relate
73
+ TOP_ENTRIES = 20
74
+ TOP_ENTRIES_BASIS = "the per-layer count (design §6.2 names no number; lead, 2026-11-11); revisit at C3"
75
+ INDEXED_CLASS = "operative"
76
+ HINT_UNITS = ("target_unit", "target_units")
77
+ HINT_ENTRIES = ("target_entry", "entries")
78
+ EXCLUDED = ("unknown_independence", "not_indexed", "not_counted", "not_in_census")
79
+ SCORE_DIGITS = 6
80
+
81
+
82
+ # ---- retrieval -------------------------------------------------------------------------------------
83
+
84
+ class UnitIndex:
85
+ """The current library as retrieval reads it: the operative units, one per text in each layer (the lowest unit id
86
+ stands for its copies), under one BM25 index; `rep_of` maps every indexed unit to the unit that stands for it."""
87
+
88
+ def __init__(self, units):
89
+ self.units = {u["unit_id"]: u for u in units}
90
+ groups = collections.defaultdict(list)
91
+ not_indexed = collections.Counter()
92
+ for u in sorted(units, key=lambda u: u["unit_id"]):
93
+ if u.get("class") != INDEXED_CLASS:
94
+ not_indexed[u.get("class") or "unclassed"] += 1
95
+ continue
96
+ groups[(u["layer"], u["sha"])].append(u)
97
+ self.rep_of, self.copies, self.layer_of = {}, {}, {}
98
+ for members in groups.values():
99
+ rep = members[0]["unit_id"]
100
+ self.copies[rep], self.layer_of[rep] = len(members) - 1, members[0]["layer"]
101
+ for u in members:
102
+ self.rep_of[u["unit_id"]] = rep
103
+ self.library = lifecycle_intake.Library({rep: self.units[rep]["text"] for rep in self.copies})
104
+ self.counts = {"indexed": len(self.copies), "folded_copies": sum(self.copies.values()),
105
+ "not_indexed": dict(sorted(not_indexed.items())),
106
+ "layers": dict(sorted(collections.Counter(self.layer_of.values()).items()))}
107
+
108
+
109
+ class EntryIndex:
110
+ """The ledger's entries under one BM25 index, each by the text lifecycle_intake.entry_text reads."""
111
+
112
+ def __init__(self, entries):
113
+ self.entries = {e["id"]: e for e in entries}
114
+ self.library = lifecycle_intake.Library({i: lifecycle_intake.entry_text(e) for i, e in self.entries.items()})
115
+
116
+
117
+ def keys_of(text):
118
+ return set(lifecycle_intake.keys_tf(text)[0]) if text else set()
119
+
120
+
121
+ def as_list(value):
122
+ if value is None or value == "":
123
+ return []
124
+ return [value] if isinstance(value, str) else [v for v in value if v]
125
+
126
+
127
+ def named(candidate, clusters):
128
+ """`(unit ids, entry ids)` a candidate names: its lifecycle hint fields, and a formed type G candidate's cluster
129
+ entries and the hint fields of the cluster candidate its tension names."""
130
+ units, entries = [], []
131
+ hinted = [candidate.get("lifecycle") or {}]
132
+ tension = candidate.get("tension") or {}
133
+ entries += as_list(tension.get("instance_entry_ids"))
134
+ if tension.get("cluster"):
135
+ hinted.append((clusters.get(tension["cluster"]) or {}).get("lifecycle") or {})
136
+ for hints in hinted:
137
+ for field in HINT_UNITS:
138
+ units += as_list(hints.get(field))
139
+ for field in HINT_ENTRIES:
140
+ entries += as_list(hints.get(field))
141
+ return sorted(set(units)), sorted(set(entries))
142
+
143
+
144
+ def query_keys(candidate, unit_index, entry_index, clusters):
145
+ """The query's keys: situation, action and exception, and the text of every unit and entry the candidate names."""
146
+ names_u, names_e = named(candidate, clusters)
147
+ parts = [candidate.get(f) for f in ("situation", "action", "exception")]
148
+ parts += [unit_index.units[u]["text"] for u in names_u if u in unit_index.units]
149
+ parts += [lifecycle_intake.entry_text(entry_index.entries[e]) for e in names_e if e in entry_index.entries]
150
+ return keys_of(" ".join(p for p in parts if p)), names_u, names_e
151
+
152
+
153
+ def score(value):
154
+ return None if value is None else round(value, SCORE_DIGITS)
155
+
156
+
157
+ def retrieval_of(declaration):
158
+ """The counts S5 keeps (plan WP-11, lead decision on J0's numbers): run.json's `retrieval.per_layer` and
159
+ `retrieval.top_entries` when the run declares them, else PER_LAYER and TOP_ENTRIES, each with where it came from."""
160
+ held = (declaration or {}).get("retrieval") or {}
161
+ return {"per_layer": held.get("per_layer", PER_LAYER), "top_entries": held.get("top_entries", TOP_ENTRIES),
162
+ "basis": {key: "declared" if key in held else "default" for key in ("per_layer", "top_entries")}}
163
+
164
+
165
+ def retrieve_units(keys, names_u, index, per_layer=PER_LAYER):
166
+ """`(rows, named ids the library does not hold)`: the top `per_layer` units of each layer by score (ties by unit
167
+ id), each with its rank, then every named unit outside them, unranked."""
168
+ scores = index.library.scores(keys) if keys else {}
169
+ by_layer = collections.defaultdict(list)
170
+ for rep, value in scores.items():
171
+ if value > 0:
172
+ by_layer[index.layer_of[rep]].append((rep, value))
173
+ wanted = set(names_u)
174
+ rows = []
175
+ for layer in sorted(by_layer):
176
+ ranked = sorted(by_layer[layer], key=lambda pair: (-pair[1], pair[0]))[:per_layer]
177
+ rows += [{"unit_id": rep, "layer": layer, "rank": rank, "score": score(value), "named": rep in wanted,
178
+ "copies": index.copies[rep]} for rank, (rep, value) in enumerate(ranked, 1)]
179
+ have = {r["unit_id"] for r in rows}
180
+ absent = []
181
+ for ident in names_u:
182
+ if ident in have:
183
+ continue
184
+ unit = index.units.get(ident)
185
+ if unit is None:
186
+ absent.append(ident)
187
+ continue
188
+ rep = index.rep_of.get(ident)
189
+ rows.append({"unit_id": ident, "layer": unit["layer"], "rank": None,
190
+ "score": score(scores.get(rep, 0.0)) if rep else None, "named": True,
191
+ "copies": index.copies.get(rep, 0) if rep == ident else 0})
192
+ return rows, absent
193
+
194
+
195
+ def retrieve_entries(keys, names_e, index, top_entries=TOP_ENTRIES):
196
+ """`(rows, named ids the ledger does not hold)`: the top `top_entries` entries by score (ties by id), then every
197
+ named entry outside them, unranked."""
198
+ scores = index.library.scores(keys) if keys else {}
199
+ ranked = sorted(((i, v) for i, v in scores.items() if v > 0), key=lambda pair: (-pair[1], pair[0]))[:top_entries]
200
+ wanted = set(names_e)
201
+ rows = [{"entry_id": i, "status": index.entries[i].get("status"), "rank": rank, "score": score(v), "named": i in wanted}
202
+ for rank, (i, v) in enumerate(ranked, 1)]
203
+ have = {r["entry_id"] for r in rows}
204
+ absent = []
205
+ for ident in names_e:
206
+ if ident in have:
207
+ continue
208
+ if ident not in index.entries:
209
+ absent.append(ident)
210
+ continue
211
+ rows.append({"entry_id": ident, "status": index.entries[ident].get("status"), "rank": None,
212
+ "score": score(scores.get(ident, 0.0)), "named": True})
213
+ return rows, absent
214
+
215
+
216
+ # ---- recurrence ------------------------------------------------------------------------------------
217
+
218
+ def recurrence(sessions, rows):
219
+ """Design §5.3's count over the census `rows` for a candidate's `sessions`: `{count, independent_sessions,
220
+ lineages, excluded}`. A session counts through its component when the component's one root is a row the census
221
+ counted; every other session is excluded under one named reason."""
222
+ by_key = {census.key_of(r): r for r in rows}
223
+ lineages, excluded = {}, {name: [] for name in EXCLUDED}
224
+ for session in sorted(set(sessions)):
225
+ row = by_key.get(session)
226
+ if row is None:
227
+ excluded["not_in_census"].append(session)
228
+ continue
229
+ lin = row.get("lineage") or {}
230
+ if row.get("counted"):
231
+ root = row
232
+ elif lin.get("unique_root") and lin.get("root"):
233
+ root = by_key.get(lin["root"])
234
+ else:
235
+ root = None
236
+ if root is None:
237
+ excluded["unknown_independence"].append(session)
238
+ continue
239
+ if not root.get("counted"):
240
+ excluded["not_indexed" if root.get("provenance") != "indexed" else "not_counted"].append(session)
241
+ continue
242
+ component = (root.get("lineage") or {}).get("component") or census.key_of(root)
243
+ lineages.setdefault(component, {"component": component, "root": census.key_of(root), "sessions": []})["sessions"].append(session)
244
+ ordered = [lineages[c] for c in sorted(lineages)]
245
+ return {"count": len(ordered), "independent_sessions": sorted(min(l["sessions"]) for l in ordered),
246
+ "lineages": ordered, "excluded": excluded}
247
+
248
+
249
+ # ---- quotes and sessions ---------------------------------------------------------------------------
250
+
251
+ def stored_evidence(run_dir, names):
252
+ """Every evidence record of the views' files, by id."""
253
+ out = {}
254
+ for name in names:
255
+ for record in evidence.load(run_dir, name):
256
+ out[record["evidence_id"]] = record
257
+ return out
258
+
259
+
260
+ def cited(candidate, subject_of):
261
+ """`(evidence ids a candidate cites, problems)`: its admission's quotes, and the quotes of every claim it cites - by
262
+ its admission's `claim_ids`, its tension's `instance_claim_ids` and its events' claims - each claim once. Codex WP-10
263
+ r1 #1: the claims cited directly were skipped, so a quote reached only through one was never verified again."""
264
+ events = {r["id"]: r for r in subject_of["events"]}
265
+ ids, problems, claim_ids = set(), [], []
266
+ for requirement in (candidate.get("admission") or {}).values():
267
+ ids.update(requirement.get("evidence_ids") or [])
268
+ claim_ids += list(requirement.get("claim_ids") or [])
269
+ claim_ids += list((candidate.get("tension") or {}).get("instance_claim_ids") or [])
270
+ for event_id in candidate.get("event_ids") or []:
271
+ row = events.get(event_id)
272
+ if row is None:
273
+ continue
274
+ claim_ids += row["claim_ids"] + row["outcome_claim_ids"]
275
+ for claim_id in dict.fromkeys(claim_ids):
276
+ claim = subject_of["claims"].get(claim_id)
277
+ if claim is None:
278
+ problems.append(f"CLAIM_UNKNOWN {claim_id}")
279
+ continue
280
+ ids.update(q["evidence_id"] for q in claim["quotes"])
281
+ return sorted(ids), problems
282
+
283
+
284
+ def quote_problems(run_dir, ids, stored, extra):
285
+ """Each cited quote verified again against the immutable copy: the problems, each `<code> <evidence id>`. A record is
286
+ an S3 store's, or one of `extra`: S4's origin quotes and the planted controls' own."""
287
+ problems = []
288
+ for ident in ids:
289
+ record = stored.get(ident) or extra.get(ident)
290
+ if record is None:
291
+ problems.append(f"EVIDENCE_ABSENT {ident}")
292
+ continue
293
+ problems += [f"{p.split(' ', 1)[0]} {ident}" for p in evidence.verify(run_dir, record)]
294
+ return problems
295
+
296
+
297
+ def session_problems(candidate, subject_of, rows):
298
+ """A candidate's sessions against the census and its events: SESSION_UNKNOWN (no census row), SESSION_MISMATCH
299
+ (a session none of its events is of, or an event's session it does not name), EVENT_UNKNOWN (an event the subject
300
+ does not hold)."""
301
+ known = {census.key_of(r) for r in rows}
302
+ events = {r["id"]: r for r in subject_of["events"]}
303
+ problems = [f"EVENT_UNKNOWN {e}" for e in candidate.get("event_ids") or [] if e not in events]
304
+ named_sessions = set(candidate.get("sessions") or [])
305
+ problems += [f"SESSION_UNKNOWN {s}" for s in sorted(named_sessions - known)]
306
+ of_events = {events[e]["session"] for e in candidate.get("event_ids") or [] if e in events}
307
+ problems += [f"SESSION_MISMATCH {s}" for s in sorted(named_sessions ^ of_events)]
308
+ return problems
309
+
310
+
311
+ # ---- absence ---------------------------------------------------------------------------------------
312
+
313
+ def current_point(current):
314
+ """The current reference point as derive.absence reads one: its completeness flag and its layers' statuses."""
315
+ return {"complete": (current.get("reference") or {}).get("complete"),
316
+ "layers": {row["layer"]: row["status"] for row in current.get("layers") or []}}
317
+
318
+
319
+ def withheld_of(current):
320
+ """The current reference point's withheld would-be units, summed over its layer rows (S2 publishes them per row,
321
+ WP-11b X r1 (i)): how many there were, how many match a unit the point publishes, and how many match none — the
322
+ units this reference point cannot judge. Disclosed beside the completeness, never a threshold (lead)."""
323
+ rows = [row.get("withheld") or {} for row in current.get("layers") or [] if isinstance(row, dict)]
324
+ return {key: sum(int(row.get(key) or 0) for row in rows) for key in ("units", "matched", "unmatched")}
325
+
326
+
327
+ def absence_of(current):
328
+ """`(checks.json's absence, the reason a candidate is withheld or None)`."""
329
+ complete, read = derive.absence(current_point(current))
330
+ layers = read.get("unknown_layers") or []
331
+ doc = {"reference": "current", "policy": read["policy"], "complete": complete, "unknown_layers": layers,
332
+ "withheld": withheld_of(current)}
333
+ if complete:
334
+ return doc, None
335
+ what = (f"completeness of the {', '.join(layers)} layer{'s' if len(layers) > 1 else ''} unknown" if layers
336
+ else "the current reference point records no completeness")
337
+ return doc, what
338
+
339
+
340
+ # ---- the stage -------------------------------------------------------------------------------------
341
+
342
+ def schema_problems(doc):
343
+ return validate.validate_instance(validate.compile_schema(json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))), doc)
344
+
345
+
346
+ def natural_population(run_dir):
347
+ """S4's population as `candidates.json` lists it, formed and lifecycle."""
348
+ return records.read_json(pathlib.Path(run_dir) / "candidates.json")
349
+
350
+
351
+ def build(run_dir, declaration, nonce=None):
352
+ """`(checks.json, checked-candidates.json, controls.json)` for a run: S4's population with the planted controls
353
+ of design §6.5 (controls.plant) among it under ordinary ids, every candidate checked alike."""
354
+ run_dir = pathlib.Path(run_dir)
355
+ cands = natural_population(run_dir)
356
+ current = records.read_json(run_dir / "inventory" / "current.json")
357
+ rows = census.rows(census.load(run_dir))
358
+ subject_of = stage_form.subject(run_dir)
359
+ ledger, read = lifecycle_intake.ledger_of(declaration)
360
+ names = [t["name"] for t in records.read_json(run_dir / "views.json")["transcripts"]]
361
+ stored, origins = stored_evidence(run_dir, names), cands.get("origin_evidence") or {}
362
+ unit_index, entry_index = UnitIndex(current["units"]), EntryIndex(ledger["entries"])
363
+ planted, planted_evidence, planted_doc = controls.plant(
364
+ cands["candidates"], unit_index, lambda k: cited(k, subject_of)[0], lambda i: stored.get(i) or origins.get(i),
365
+ {census.key_of(r) for r in rows}, nonce)
366
+ extra = {**origins, **planted_evidence}
367
+ everyone = sorted(cands["candidates"] + planted, key=lambda k: k["candidate_id"])
368
+ clusters = {c["candidate_id"]: c for c in everyone if c["source"] == "g_cluster"}
369
+ absence, withheld_reason = absence_of(current)
370
+ limits = retrieval_of(declaration)
371
+ out = []
372
+ for k in everyone:
373
+ keys, names_u, names_e = query_keys(k, unit_index, entry_index, clusters)
374
+ units, absent_u = retrieve_units(keys, names_u, unit_index, limits["per_layer"])
375
+ entries, absent_e = retrieve_entries(keys, names_e, entry_index, limits["top_entries"])
376
+ ids, claim_problems = cited(k, subject_of)
377
+ quotes = claim_problems + quote_problems(run_dir, ids, stored, extra)
378
+ out.append({"candidate_id": k["candidate_id"], "source": k["source"], "query_keys": len(keys),
379
+ "retrieved_units": units, "named_units_absent": absent_u, "ledger_entries": entries,
380
+ "named_entries_absent": absent_e, "recurrence": recurrence(k.get("sessions") or [], rows),
381
+ "quote_ok": (not quotes) if (ids or claim_problems) else None, "quotes_checked": len(ids),
382
+ "quote_problems": quotes, "session_problems": session_problems(k, subject_of, rows),
383
+ "absence_withheld": withheld_reason is not None})
384
+ planted_ids = {k["candidate_id"] for k in planted}
385
+ doc = {"constants": {"per_layer": limits["per_layer"], "top_entries": limits["top_entries"],
386
+ "top_entries_basis": TOP_ENTRIES_BASIS, "indexed_class": INDEXED_CLASS, "declared": limits["basis"]},
387
+ "library": unit_index.counts, "ledger_index": {"entries": len(entry_index.entries), "read": read},
388
+ "absence": absence, "candidates": out,
389
+ "summary": summary_of([r for r in out if r["candidate_id"] not in planted_ids], withheld_reason)}
390
+ return doc, {"candidates": everyone, "evidence": dict(sorted(extra.items()))}, planted_doc
391
+
392
+
393
+ def summary_of(rows, withheld_reason):
394
+ excluded = {name: sum(len(r["recurrence"]["excluded"][name]) for r in rows) for name in EXCLUDED}
395
+ withheld = sum(1 for r in rows if r["absence_withheld"])
396
+ return {"candidates": len(rows), "formed": sum(1 for r in rows if r["source"] == "formed"),
397
+ "lifecycle": sum(1 for r in rows if r["source"] != "formed"),
398
+ "retrieved_units": sum(len(r["retrieved_units"]) for r in rows),
399
+ "named_units": sum(1 for r in rows for u in r["retrieved_units"] if u["named"]),
400
+ "ledger_entries": sum(len(r["ledger_entries"]) for r in rows),
401
+ "quotes_checked": sum(r["quotes_checked"] for r in rows),
402
+ "quote_failed": sum(1 for r in rows if r["quote_ok"] is False),
403
+ "session_failed": sum(1 for r in rows if r["session_problems"]),
404
+ "recurrence": {"lineages": sum(r["recurrence"]["count"] for r in rows),
405
+ "sessions": sum(len(l["sessions"]) for r in rows for l in r["recurrence"]["lineages"]),
406
+ "excluded": excluded},
407
+ "absence_withheld": {"candidates": withheld, "reason": withheld_reason if withheld else None}}
408
+
409
+
410
+ def run(run_dir, nonce=None):
411
+ """S5 over S4's population and the planted controls: admitted against its inputs, writes `checks.json`
412
+ (schema-checked), the population S6 judges and the controls' expected verdicts, and records them. `nonce` fixes
413
+ the controls' draw; only a self-test passes it."""
414
+ run_dir = pathlib.Path(run_dir)
415
+ with records.run_stage(run_dir, STAGE, INPUTS) as stage:
416
+ doc, checked, planted_doc = build(run_dir, stage.declaration, nonce)
417
+ problems = schema_problems(doc)
418
+ if problems:
419
+ raise Refused("CHECKS_INVALID " + "; ".join(problems[:5]))
420
+ # a planted control S5 checks and does not fail, or a kind not planted, stops the run here (design §4, §6.5)
421
+ stops = controls.check_s5(planted_doc, {r["candidate_id"]: r for r in doc["candidates"]})
422
+ if stops:
423
+ raise Refused("\n".join(stops))
424
+ records.write_json(run_dir, run_dir / "checks.json", doc)
425
+ records.write_json(run_dir, run_dir / POPULATION_FILE, checked)
426
+ records.write_json(run_dir, run_dir / controls.CONTROLS_FILE, planted_doc)
427
+ for name in OUTPUTS:
428
+ stage.output(name)
429
+ declaration_seq = stage.record["declaration_seq"]
430
+ return {**doc["summary"], "declaration_seq": declaration_seq, "library": doc["library"], "constants": doc["constants"],
431
+ "ledger_index": doc["ledger_index"], "absence": doc["absence"],
432
+ "controls": {"planted": len(planted_doc["planted"]),
433
+ "s5_checked": sum(1 for e in planted_doc["planted"] if "S5" in e),
434
+ "s5_held": sum(1 for e in planted_doc["planted"] if (e.get("S5") or {}).get("ok")),
435
+ "gate_declared": len(planted_doc["gate"])}}
436
+
437
+
438
+ def withheld_line(summary):
439
+ """The withheld count and its reason, by name (D-20261111-eaa2a8), or None when nothing is withheld."""
440
+ w = summary["absence_withheld"]
441
+ return f"{w['candidates']} candidates not advanced to an absence sweep: {w['reason']}" if w["candidates"] else None
442
+
443
+
444
+ def report_lines(summary):
445
+ """What the driver prints of a run of S5: counts and codes, never a unit's text, a lesson or a quote."""
446
+ lib, rec = summary["library"], summary["recurrence"]
447
+ lines = [f"S5 retrieve: declaration_seq {summary['declaration_seq']}; {summary['candidates']} candidates "
448
+ f"({summary['formed']} formed, {summary['lifecycle']} lifecycle)",
449
+ f"library: {lib['indexed']} indexed texts over {len(lib['layers'])} layers, {lib['folded_copies']} identical "
450
+ f"copies folded, not indexed {lib['not_indexed']}; ledger: {summary['ledger_index']['entries']} entries "
451
+ f"({summary['ledger_index']['read']})",
452
+ f"retrieval: {summary['retrieved_units']} unit rows ({summary['named_units']} named), "
453
+ f"{summary['ledger_entries']} ledger entry rows; at most {summary['constants']['per_layer']} per layer "
454
+ f"({summary['constants']['declared']['per_layer']}) and {summary['constants']['top_entries']} entries "
455
+ f"({summary['constants']['declared']['top_entries']})",
456
+ f"quotes: {summary['quotes_checked']} verified again, {summary['quote_failed']} candidates failed; "
457
+ f"sessions: {summary['session_failed']} candidates with a session problem",
458
+ f"recurrence: {rec['lineages']} counted lineages over {rec['sessions']} sessions; excluded "
459
+ + ", ".join(f"{k} {v}" for k, v in rec["excluded"].items())]
460
+ held = (summary.get("absence") or {}).get("withheld") or {}
461
+ lines.append(f"compiled text: {held.get('units', 0)} would-be units withheld at the current reference point, "
462
+ f"{held.get('matched', 0)} matching a unit it publishes, {held.get('unmatched', 0)} matching none "
463
+ f"(units this reference point cannot judge)")
464
+ line = withheld_line(summary)
465
+ lines.append(f"absence: {line}" if line else "absence: the current reference point is complete; none withheld")
466
+ c = summary["controls"]
467
+ lines.append(f"controls (apart from the counts above): {c['planted']} planted; S5 checked {c['s5_checked']}, each "
468
+ f"given its verdict: {c['s5_held']}; {c['gate_declared']} gate controls declared for the dispatching stage")
469
+ return lines
470
+
471
+
472
+ # ---- self-test -------------------------------------------------------------------------------------
473
+
474
+ def fx_current(units, complete=False, statuses=None):
475
+ """An `inventory/current.json` as S2 records one: units, a completeness flag, and its layers' statuses."""
476
+ statuses = {"catalog": "complete", "native_project": "complete", "native_undivided": "complete",
477
+ "native_settings": "unknown"} if statuses is None else statuses
478
+ return {"units": list(units), "reference": {"kind": "current", "complete": complete, "incomplete_reasons": []},
479
+ "layers": [{"layer": k, "status": v} for k, v in sorted(statuses.items())]}
480
+
481
+
482
+ def fx_gold(root, current=None):
483
+ """A golden run through S4 (stage_form's golden S3 run and its formation plan), its current library re-recorded by
484
+ S2's inventory part before S4 reads it. Returns the run directory."""
485
+ run_dir, _summary = stage_form.fx_s3(root)
486
+ doc = fx_current(lifecycle_intake.FX_LIBRARY) if current is None else current
487
+ with records.run_stage(run_dir, "S2", [{"artifact": "census.json", "producer_stage": "S1"}], part="inventory") as stage:
488
+ records.write_json(run_dir, run_dir / "inventory" / "current.json", doc)
489
+ stage.output("inventory/current.json")
490
+ plan = stage_form.fx_form_plan(run_dir, root / "form-plan.json")
491
+ stage_form.run(run_dir, stage_form.supervisor(run_dir, root / "form-cells", plan))
492
+ return run_dir
493
+
494
+
495
+ def fx_census_rows(nodes, indexed=()):
496
+ """Census rows over lineage nodes as S1 links them (lineage.components): each eligible, `indexed` when its id is in
497
+ `indexed`, and counted as the census counts a row - the one root of its component, indexed."""
498
+ linked = lineage.components(nodes)
499
+ rows = []
500
+ for node in nodes:
501
+ host, ident = lineage.split_identity(node["id"])
502
+ lin = {**linked[node["id"]], "measurement_pending": False}
503
+ provenance = "indexed" if node["id"] in indexed else "not_indexed"
504
+ rows.append({"host": host, "id": ident, "status": "eligible", "provenance": provenance, "lineage": lin,
505
+ "counted": bool(lin["unique_root"] and lin["root"] == node["id"] and provenance == "indexed")})
506
+ return rows
507
+
508
+
509
+ def fx_node(ident, ids, root=True, links=()):
510
+ return {"id": ident, "host": "claude", "root": root, "ids": list(ids), "turns": [], "links": list(links)}
511
+
512
+
513
+ def self_test():
514
+ failures, ran = [], []
515
+
516
+ def control(name, condition, detail=""):
517
+ ran.append(name)
518
+ if not condition:
519
+ failures.append(f"{name}: {detail}")
520
+
521
+ def guarded(action, default):
522
+ try:
523
+ return action()
524
+ except Exception as exc: # noqa: BLE001 - reported by the control that reads the default
525
+ return default if not callable(default) else default(exc)
526
+
527
+ def refusal(action):
528
+ try:
529
+ action()
530
+ except Refused as exc:
531
+ return str(exc)
532
+ except Exception as exc: # noqa: BLE001 - a control whose subject raises anything else fails by its own name
533
+ return f"RAISED {exc!r}"
534
+ return ""
535
+
536
+ fx_unit = lifecycle_intake.fx_unit
537
+ # ---- retrieval over a library of its own ---------------------------------------------------------------------
538
+ many = [fx_unit(f"u-z{n:02d}", f"Feed the zebra {'hay ' * n}at noon.") for n in range(1, 23)]
539
+ lib = many + [fx_unit("u-zp", "Feed the zebra at noon in the project.", layer="native_project"),
540
+ fx_unit("u-zref", "Feed the zebra at noon, as the keeper said.", cls="reference"),
541
+ fx_unit("u-twin1", "Okapi visits are booked a week ahead.", layer="native_project"),
542
+ fx_unit("u-twin2", "Okapi visits are booked a week ahead.", layer="native_project"),
543
+ fx_unit("u-ex", "Wash the bucket after the okapi drinks.")]
544
+ index = UnitIndex(lib)
545
+ no_entries = EntryIndex([])
546
+
547
+ def retrieved(candidate, units_index=index, entries_index=no_entries, clusters=None):
548
+ keys, names_u, _names_e = query_keys(candidate, units_index, entries_index, clusters or {})
549
+ return retrieve_units(keys, names_u, units_index)
550
+
551
+ zebra = {"situation": "the zebra is fed", "action": "feed the zebra", "exception": "", "source": "formed"}
552
+ rows, _absent = retrieved(zebra)
553
+ catalog = [r for r in rows if r["layer"] == "catalog"]
554
+ control("§6.2: at most the top 20 units of a layer are retrieved, ranked by score, ties by unit id",
555
+ len(catalog) == PER_LAYER and [r["rank"] for r in catalog] == list(range(1, PER_LAYER + 1))
556
+ and all((-a["score"], a["unit_id"]) <= (-b["score"], b["unit_id"]) for a, b in zip(catalog, catalog[1:])),
557
+ f"{len(catalog)} {[r['rank'] for r in catalog][:3]}")
558
+ control("§6.2: each layer has its own top 20: the one matching project unit is retrieved beside a full catalog layer",
559
+ [r["unit_id"] for r in rows if r["layer"] == "native_project"] == ["u-zp"], f"{rows}")
560
+ control("§6.1: a reference unit is not indexed, and the index says how many were left out",
561
+ "u-zref" not in {r["unit_id"] for r in rows} and index.counts["not_indexed"] == {"reference": 1},
562
+ f"{index.counts}")
563
+ twins, _a = retrieved({"situation": "okapi visits booked", "action": "", "exception": "", "source": "formed"})
564
+ control("identical text in one layer is one retrieved unit, the lowest id standing for its counted copies",
565
+ [(r["unit_id"], r["copies"]) for r in twins if r["layer"] == "native_project"] == [("u-twin1", 1)]
566
+ and index.counts["folded_copies"] == 1, f"{twins}")
567
+ exc_rows, _a = retrieved({"situation": "kiwi", "action": "", "exception": "okapi drinks", "source": "formed"})
568
+ plain_rows, _a = retrieved({"situation": "kiwi", "action": "", "exception": "", "source": "formed"})
569
+ control("§6.2: the query holds the exception: a unit only the exception's words match is retrieved",
570
+ "u-ex" in {r["unit_id"] for r in exc_rows}, f"{exc_rows}")
571
+ control("control: without the exception that unit is not retrieved", "u-ex" not in {r["unit_id"] for r in plain_rows},
572
+ f"{plain_rows}")
573
+ beyond = next((u["unit_id"] for u in many if u["unit_id"] not in {r["unit_id"] for r in catalog}), None)
574
+ hinted = {"source": "redundancy_hint", "lifecycle": {"target_units": [beyond, "u-gone"]}}
575
+ h_rows, h_absent = retrieved(hinted)
576
+ control("§6.2: every unit a candidate names is retrieved, unranked when outside its layer's top 20",
577
+ any(r["unit_id"] == beyond and r["rank"] is None and r["named"] for r in h_rows), f"{h_rows}")
578
+ control("a named unit the library does not hold is listed by id, never dropped", h_absent == ["u-gone"], f"{h_absent}")
579
+ control("the named hints are part of the query: a lifecycle candidate with no text of its own retrieves by its "
580
+ "named units' text", sum(1 for r in h_rows if r["rank"] is not None) > 0, f"{h_rows}")
581
+ control("a candidate with no words and nothing named retrieves nothing, and says its query had no keys",
582
+ retrieved({"source": "legacy", "lifecycle": {}}) == ([], []) and query_keys({}, index, no_entries, {})[0] == set(),
583
+ "retrieved")
584
+ entries = [{"id": f"E-{n}", "status": "placed", "lesson": f"Feed the zebra {'hay ' * n}at noon", "principle": ""}
585
+ for n in range(1, 23)] + [{"id": "E-99", "status": "retired", "lesson": "Paint the fence", "principle": "blue"}]
586
+ e_index = EntryIndex(entries)
587
+ keys, _u, names_e = query_keys({**zebra, "lifecycle": {"target_entry": "E-99", "entries": ["E-0"]}}, index, e_index, {})
588
+ e_rows, e_absent = retrieve_entries(keys, names_e, e_index)
589
+ control("§6.2: the top ledger entries by the same query, at most TOP_ENTRIES, ranked",
590
+ len([r for r in e_rows if r["rank"] is not None]) == TOP_ENTRIES, f"{len(e_rows)}")
591
+ control("... every entry the candidate names among them, unranked when outside, its status shown; an entry the ledger "
592
+ "does not hold is listed by id", any(r["entry_id"] == "E-99" and r["named"] and r["status"] == "retired"
593
+ for r in e_rows) and e_absent == ["E-0"], f"{e_rows[-2:]} {e_absent}")
594
+ gate_index = EntryIndex(entries + [{"id": "E-77", "status": "placed", "lesson": "Keep it shut", "principle":
595
+ "a gate left open lets the animals out"}])
596
+ gate_rows, _ = retrieve_entries(keys_of("the gate"), [], gate_index)
597
+ control("an entry is ranked by its lesson and its principle (lifecycle_intake.entry_text): one only its principle "
598
+ "matches is retrieved", [r["entry_id"] for r in gate_rows if r["score"] and r["entry_id"] == "E-77"] == ["E-77"],
599
+ f"{gate_rows[:3]}")
600
+ outside, _absent = retrieve_entries(keys_of("feed the zebra"), ["E-99"], e_index)
601
+ control("a named entry the query does not match is listed unranked, never dropped",
602
+ [(r["entry_id"], r["rank"], r["named"]) for r in outside if r["entry_id"] == "E-99"] == [("E-99", None, True)]
603
+ and len([r for r in outside if r["rank"] is not None]) == TOP_ENTRIES, f"{outside[-2:]}")
604
+ g = {"source": "formed", "situation": "", "action": "", "exception": "",
605
+ "tension": {"instance_entry_ids": ["E-3"], "cluster": "g_cluster:u-zp"}}
606
+ names_g = named(g, {"g_cluster:u-zp": {"lifecycle": {"target_unit": "u-zp", "entries": ["E-4", "E-5"]}}})
607
+ control("a formed type G candidate names its cluster entries and the hints of the cluster its tension names",
608
+ names_g == (["u-zp"], ["E-3", "E-4", "E-5"]), f"{names_g}")
609
+
610
+ # ---- recurrence over the census's lineages (plan WP-10 done-when 3) -------------------------------------------
611
+ root_n, replay = fx_node("claude:r-1", ["m1", "m2", "m3"]), fx_node("claude:r-1-replay", ["m1", "m2", "m3", "m4"], root=False)
612
+ pair = fx_census_rows([root_n, replay], indexed={"claude:r-1", "claude:r-1-replay"})
613
+ got = recurrence(["claude:r-1", "claude:r-1-replay"], pair)
614
+ control("done-when 3 (O4 F-O4-04): a session pair whose replay hides its ancestry - same root, copied record ids, no "
615
+ "pointer - counts as one lineage", got["count"] == 1 and got["independent_sessions"] == ["claude:r-1"]
616
+ and got["lineages"][0]["sessions"] == ["claude:r-1", "claude:r-1-replay"], f"{got}")
617
+ two = fx_census_rows([fx_node("claude:a-1", ["a1"]), fx_node("claude:b-1", ["b1"])], indexed={"claude:a-1", "claude:b-1"})
618
+ got2 = recurrence(["claude:a-1", "claude:b-1"], two)
619
+ control("control: two genuinely distinct roots count as two", got2["count"] == 2, f"{got2}")
620
+ copy_pair = fx_census_rows([fx_node("claude:c-1", ["c1", "c2"]), fx_node("claude:c-1-copy", ["c1", "c2"])],
621
+ indexed={"claude:c-1", "claude:c-1-copy"})
622
+ got3 = recurrence(["claude:c-1", "claude:c-1-copy"], copy_pair)
623
+ control("§5.3: a copy of a root beside its original has no single root, counts toward nothing, and both sessions are "
624
+ "excluded as unknown independence", got3["count"] == 0
625
+ and got3["excluded"]["unknown_independence"] == ["claude:c-1", "claude:c-1-copy"], f"{got3}")
626
+ unindexed = fx_census_rows([fx_node("claude:d-1", ["d1"])])
627
+ got4 = recurrence(["claude:d-1", "claude:fabricated"], unindexed)
628
+ control("§5.3 (O4): an affirmed lineage whose root its host's index does not hold counts toward nothing; a session the "
629
+ "census does not hold is excluded by id", got4["count"] == 0 and got4["excluded"]["not_indexed"] == ["claude:d-1"]
630
+ and got4["excluded"]["not_in_census"] == ["claude:fabricated"], f"{got4}")
631
+ owned_out = [{**r, "counted": False} for r in fx_census_rows([fx_node("claude:e-1", ["e1"])], indexed={"claude:e-1"})]
632
+ got5 = recurrence(["claude:e-1"], owned_out)
633
+ control("a root the census counts out for another reason (not owned, another class) is excluded as not_counted: the "
634
+ "census's verdict is read, never re-derived", got5["count"] == 0 and got5["excluded"]["not_counted"] == ["claude:e-1"],
635
+ f"{got5}")
636
+
637
+ # ---- absence ---------------------------------------------------------------------------------------------------
638
+ doc_in, why_in = absence_of(fx_current([]))
639
+ doc_ok, why_ok = absence_of(fx_current([], complete=True, statuses={"catalog": "complete"}))
640
+ control("§6.2/§6.4: at an incomplete current point every candidate is withheld from an absence sweep, the reason naming "
641
+ "the layers whose completeness is unknown", why_in == "completeness of the native_settings layer unknown"
642
+ and doc_in["complete"] is False and doc_in["unknown_layers"] == ["native_settings"], f"{doc_in} {why_in}")
643
+ control("control: at a complete point nothing is withheld", why_ok is None and doc_ok["complete"] is True, f"{doc_ok}")
644
+ control("a point that records no completeness is incomplete, and says so",
645
+ absence_of({"units": []})[1] == "the current reference point records no completeness", f"{absence_of({'units': []})}")
646
+ # WP-11b X r1 (i): the withheld would-be units S2 counts per row reach checks.json as one total, disclosed, and
647
+ # the driver's report says them; a point with no withheld row says zero rather than nothing
648
+ held_current = fx_current([], complete=True, statuses={"catalog": "complete"})
649
+ held_current["layers"].append({"layer": "session_injection", "status": "complete", "units": 0, "empty": False,
650
+ "withheld": {"reason": "owner_text_never_enters_a_run", "units": 5, "matched": 2,
651
+ "unmatched": 3}})
652
+ control("(i) the withheld would-be units are summed into the absence block, and a point holding none says zero",
653
+ absence_of(held_current)[0].get("withheld") == {"units": 5, "matched": 2, "unmatched": 3}
654
+ and absence_of(fx_current([], complete=True, statuses={"catalog": "complete"}))[0].get("withheld")
655
+ == {"units": 0, "matched": 0, "unmatched": 0},
656
+ f"{absence_of(held_current)[0].get('withheld')}")
657
+
658
+ # ---- the stage over a golden run through S4 --------------------------------------------------------------------
659
+ root = pathlib.Path(tempfile.mkdtemp(prefix="s5-"))
660
+ try:
661
+ base = guarded(lambda: fx_gold(root / "base"), lambda exc: exc)
662
+ if isinstance(base, Exception):
663
+ failures.append(f"the golden run through S4 could not be made: {base!r}")
664
+ base = None
665
+
666
+ def copy_of(label):
667
+ where = root / f"c-{label}"
668
+ shutil.copytree(base.parent, where)
669
+ return where / base.name
670
+
671
+ def record_of(where):
672
+ return guarded(lambda: records.read_json(records.record_path(where, STAGE)), {})
673
+
674
+ if base is not None:
675
+ gold = copy_of("gold")
676
+ made = guarded(lambda: run(gold), lambda exc: {"problem": repr(exc)})
677
+ doc = guarded(lambda: records.read_json(gold / "checks.json"), {"candidates": []})
678
+ cands = guarded(lambda: records.read_json(gold / "candidates.json")["candidates"], [])
679
+ rows_by = {r["candidate_id"]: r for r in doc["candidates"]}
680
+ control("golden: S5 runs over S4's population, completes, and records its three outputs",
681
+ record_of(gold).get("status") == "complete"
682
+ and [o["artifact"] for o in record_of(gold).get("outputs", [])] == list(OUTPUTS), f"{made}")
683
+ checked = guarded(lambda: records.read_json(gold / POPULATION_FILE), {"candidates": [], "evidence": {}})
684
+ planted_doc = guarded(lambda: records.read_json(gold / controls.CONTROLS_FILE), {"planted": [], "gate": []})
685
+ planted_ids = {e["candidate_id"] for e in planted_doc["planted"]}
686
+ natural_ids = [k["candidate_id"] for k in cands]
687
+ control("golden (done-when 4): the planted controls join the population every run - the six of §6.5 among "
688
+ "S4's candidates, one population ordered by id, one row of checks.json per member",
689
+ len(planted_ids) == 6 and set(natural_ids) | planted_ids == {k["candidate_id"] for k in checked["candidates"]}
690
+ and [k["candidate_id"] for k in checked["candidates"]] == sorted(set(natural_ids) | planted_ids)
691
+ and [r["candidate_id"] for r in doc["candidates"]] == [k["candidate_id"] for k in checked["candidates"]]
692
+ and len(cands) > 2, f"{len(planted_ids)} {len(doc['candidates'])} {len(cands)}")
693
+ control("golden: S5 gives each of its controls its verdict - the paraphrased unit retrieved, the altered quote "
694
+ "QUOTE_MISMATCH, the fabricated session SESSION_UNKNOWN - and the run goes on",
695
+ [e.get("S5", {}).get("ok") for e in planted_doc["planted"] if "S5" in e["checked_at"]] == [True] * 4
696
+ and made.get("controls", {}).get("s5_held") == 4, f"{planted_doc['planted']}")
697
+ gold_ranks = [u["rank"] for r in doc["candidates"] for u in r["retrieved_units"] if u["rank"] is not None]
698
+ control("WP-11: with no retrieval declared, S5 keeps its own counts and says they are its defaults",
699
+ doc.get("constants", {}).get("declared") == {"per_layer": "default", "top_entries": "default"}
700
+ and doc["constants"].get("per_layer") == PER_LAYER and doc["constants"].get("top_entries") == TOP_ENTRIES
701
+ and f"at most {PER_LAYER} per layer (default)" in "\n".join(guarded(lambda: report_lines(made), [])),
702
+ f"{doc.get('constants')}")
703
+ from runlib import declare
704
+ narrow_run = copy_of("narrow")
705
+ # two per layer, under a fixed draw: at one per layer a paraphrase control can lose its unit to another of its
706
+ # layer, and S5 then stops the run by name (CONTROL_FAILED), which is S5's verdict on too narrow a retrieval
707
+ narrowed = guarded(lambda: (declare.amend(narrow_run, [("retrieval", {"per_layer": 2, "top_entries": 1})],
708
+ "narrow S5's retrieval (WP-11)", scope=["S5"]),
709
+ run(narrow_run, "aa" * 8))[1],
710
+ lambda exc: {"problem": repr(exc)})
711
+ narrow = guarded(lambda: records.read_json(narrow_run / "checks.json"), {"problem": narrowed})
712
+ ranked = {u["rank"] for r in narrow.get("candidates", []) for u in r["retrieved_units"] if u["rank"] is not None}
713
+ entry_ranks = {e["rank"] for r in narrow.get("candidates", []) for e in r["ledger_entries"] if e["rank"] is not None}
714
+ control("WP-11: a declared retrieval keeps that many units of each layer and ledger entries, says the counts are "
715
+ "declared, and its checks.json is schema-valid",
716
+ narrow.get("constants", {}).get("declared") == {"per_layer": "declared", "top_entries": "declared"}
717
+ and gold_ranks and max(gold_ranks) > 2 and ranked == {1, 2} and entry_ranks == {1}
718
+ and not guarded(lambda: schema_problems(narrow), ["unreadable"]),
719
+ f"{narrow.get('constants', narrow)} {sorted(ranked)} {sorted(entry_ranks)}")
720
+ control("golden: the summary counts the natural candidates; the controls are reported apart",
721
+ doc.get("summary", {}).get("candidates") == len(cands) and doc["summary"].get("quote_failed") == 0
722
+ and doc["summary"].get("session_failed") == 0, f"{doc.get('summary')}")
723
+ nat_formed = next((k for k in cands if k["source"] == "formed" and k["event_ids"]), {})
724
+ twin = next((k for k in checked["candidates"] if k["candidate_id"] in planted_ids
725
+ and k.get("event_ids") == nat_formed.get("event_ids")), {})
726
+ control("F27: a control's row in checks.json has a natural row's paths and types, and its record in the "
727
+ "population a natural record's", twin and not controls.marker_problems(rows_by.get(twin.get("candidate_id"), {}),
728
+ rows_by.get(nat_formed.get("candidate_id"), {}))
729
+ and not controls.marker_problems(twin, nat_formed), f"{twin.get('candidate_id')}")
730
+ control("golden: checks.json holds to its schema", not schema_problems(doc), f"{schema_problems(doc)[:3]}")
731
+ formed_c = next((k for k in cands if k["source"] == "formed" and k["event_ids"]), {})
732
+ row_c = rows_by.get(formed_c.get("candidate_id"), {})
733
+ control("golden: the formed candidate's quotes - its admission's origin quote and its events' claims' quotes - "
734
+ "are verified again, and verify", row_c.get("quote_ok") is True and row_c.get("quotes_checked", 0) >= 2
735
+ and not row_c.get("quote_problems"), f"{row_c.get('quote_ok')} {row_c.get('quote_problems')}")
736
+ control("golden: its session is a counted census row: recurrence 1, nothing excluded",
737
+ row_c.get("recurrence", {}).get("count") == 1 and not row_c.get("session_problems")
738
+ and not any(row_c.get("recurrence", {}).get("excluded", {}).values()), f"{row_c.get('recurrence')}")
739
+ g_row = next((r for r in doc["candidates"] if r["source"] == "g_cluster"), {})
740
+ g_cand = next((k for k in cands if k["source"] == "g_cluster"), {})
741
+ control("golden: the G cluster's named unit and its entries are retrieved, each named",
742
+ any(u["unit_id"] == g_cand.get("lifecycle", {}).get("target_unit") and u["named"]
743
+ for u in g_row.get("retrieved_units", []))
744
+ and set(g_cand.get("lifecycle", {}).get("entries", []))
745
+ <= {e["entry_id"] for e in g_row.get("ledger_entries", []) if e["named"]}, f"{g_row}")
746
+ lc = [r for r in doc["candidates"] if r["source"] != "formed"]
747
+ control("golden: a lifecycle candidate cites no quote (quote_ok null) and has no session to count",
748
+ lc and all(r["quote_ok"] is None and r["recurrence"]["count"] == 0 for r in lc), f"{lc[:1]}")
749
+ control("golden: at the run's incomplete current point every natural candidate is withheld, and the summary "
750
+ "carries the count and the reason by name",
751
+ doc.get("summary", {}).get("absence_withheld") == {"candidates": len(cands), "reason":
752
+ "completeness of the native_settings layer unknown"}
753
+ and all(r["absence_withheld"] for r in doc["candidates"]), f"{doc.get('summary', {}).get('absence_withheld')}")
754
+ said = guarded(lambda: report_lines(made), ["RAISED", "RAISED"])
755
+ control("golden: the report carries the withheld line: '<n> candidates not advanced to an absence sweep: <reason>'",
756
+ said[-2] == f"absence: {len(cands)} candidates not advanced to an absence sweep: completeness of the "
757
+ "native_settings layer unknown", f"{said[-2:]}")
758
+ control("golden: the report carries the controls apart from the natural counts",
759
+ said[-1].startswith("controls (apart from the counts above): 6 planted; S5 checked 4"), f"{said[-1:]}")
760
+ control("(i) golden: the report says the compiled text's withheld would-be units, before the absence line",
761
+ said[-3].startswith("compiled text: ") and "would-be units withheld" in said[-3], f"{said[-3:]}")
762
+ # a planted S5 control that S5 lets through stops the run before S6 reads anything
763
+ slipped = copy_of("slipped")
764
+ held_alter = controls.alter
765
+ controls.alter = lambda text: text
766
+ try:
767
+ said_slipped = refusal(lambda: run(slipped))
768
+ finally:
769
+ controls.alter = held_alter
770
+ control("CONTROL_FAILED: an altered quote that is not altered passes S5's quote check, and S5 stops the run by "
771
+ "name, writing nothing", "CONTROL_FAILED" in said_slipped and "altered_quote" in said_slipped
772
+ and not (slipped / "checks.json").exists() and record_of(slipped).get("status") == "failed",
773
+ said_slipped[:300])
774
+ # a text short enough to be a JSON word ("true") says nothing about what the file holds
775
+ texts = [t for t in [u["text"] for u in lifecycle_intake.FX_LIBRARY] + [k.get("lesson") for k in cands]
776
+ if t and len(t) > 12]
777
+ raw = guarded(lambda: (gold / "checks.json").read_text(encoding="utf-8"), "")
778
+ control("checks.json holds names, ids, scores and counts: no unit text and no lesson",
779
+ raw and not [t for t in texts if t and t in raw], f"{[t for t in texts if t and t in raw][:2]}")
780
+ # Codex WP-10 X r1 #9: each output's boundary on its own, against the texts the run's stores hold - the
781
+ # library's units, S4's lessons, and the redacted text of every quote S4's formed candidates cite
782
+ cited_q = set()
783
+ for k in cands:
784
+ if k["source"] == "formed":
785
+ cited_q |= set(guarded(lambda k=k: cited(k, stage_form.subject(gold))[0], []))
786
+ quote_texts = []
787
+ for path in sorted((gold / "evidence").glob("*.jsonl")):
788
+ for line in path.read_text(encoding="utf-8").splitlines():
789
+ rec = json.loads(line) if line.strip() else {}
790
+ if rec.get("evidence_id") in cited_q and len(rec.get("redacted_text") or "") > 12:
791
+ quote_texts.append(rec["redacted_text"])
792
+
793
+ def holds(raw_text, text): # as written, or as JSON escapes it
794
+ return any(form in raw_text for form in (text, json.dumps(text)[1:-1],
795
+ json.dumps(text, ensure_ascii=False)[1:-1]))
796
+ outputs = {name: guarded(lambda name=name: (gold / name).read_text(encoding="utf-8"), "") for name in OUTPUTS}
797
+ lessons = [k["lesson"] for k in cands if k["source"] == "formed" and len(k.get("lesson") or "") > 12]
798
+ leaked = {name: [t[:30] for t in texts + quote_texts if holds(outputs[name], t)]
799
+ for name in ("checks.json", controls.CONTROLS_FILE)}
800
+ # what the population carries beyond the candidates: the origin quotes S4 verified and kept
801
+ origin_texts = [r["redacted_text"] for r in (guarded(lambda: records.read_json(gold / "candidates.json"), {})
802
+ .get("origin_evidence") or {}).values()
803
+ if len(r.get("redacted_text") or "") > 12]
804
+ carried = [t[:30] for t in lessons + origin_texts if not holds(outputs[POPULATION_FILE], t)]
805
+ control("Codex WP-10 X r1 #9: checks.json and controls.json hold no unit text, lesson or quote, and "
806
+ "checked-candidates.json, the evidence-bearing population, holds every formed lesson and the redacted "
807
+ "text of every origin quote S4 kept", bool(lessons) and bool(quote_texts) and bool(origin_texts)
808
+ and all(outputs.values()) and not any(leaked.values()) and not carried,
809
+ f"{len(lessons)} lessons {len(quote_texts)} quotes {len(origin_texts)} origins leaked {leaked} "
810
+ f"not carried {carried[:2]}")
811
+
812
+ # quote checks: an altered quote in the store fails by code and id
813
+ altered = copy_of("altered")
814
+ cited_ids = set(guarded(lambda: cited(formed_c, stage_form.subject(altered))[0], []))
815
+ target_id = None
816
+ for path in sorted((altered / "evidence").glob("*.jsonl")):
817
+ lines = path.read_text(encoding="utf-8").splitlines()
818
+ for n, line in enumerate(lines):
819
+ rec = json.loads(line) if line.strip() else {}
820
+ if target_id is None and rec.get("evidence_id") in cited_ids:
821
+ rec["redacted_text"] = rec["redacted_text"] + " (changed)"
822
+ lines[n], target_id = json.dumps(rec, sort_keys=True, ensure_ascii=False), rec["evidence_id"]
823
+ if target_id:
824
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
825
+ break
826
+ guarded(lambda: run(altered), None)
827
+ a_doc = guarded(lambda: records.read_json(altered / "checks.json"), {"candidates": [], "summary": {}})
828
+ a_row = next((r for r in a_doc["candidates"] if r["candidate_id"] == formed_c.get("candidate_id")), {})
829
+ control("an altered quote no longer walks back to the immutable copy: quote_ok false, QUOTE_MISMATCH by evidence id, "
830
+ "counted in the summary", target_id and a_row.get("quote_ok") is False
831
+ and a_row.get("quote_problems") == [f"QUOTE_MISMATCH {target_id}"]
832
+ and a_doc["summary"].get("quote_failed") == 1, f"{target_id} {a_row.get('quote_problems')}")
833
+ # Codex WP-10 r1 #1: the same altered quote, reached only through a claim the candidate cites directly - by
834
+ # its admission's claim_ids, and by its tension's instance_claim_ids - is QUOTE_MISMATCH too
835
+ sub_a = guarded(lambda: stage_form.subject(altered), {"events": [], "claims": {}})
836
+ direct = next((c for c, claim in sub_a["claims"].items()
837
+ if any(q["evidence_id"] == target_id for q in claim["quotes"])), None)
838
+ names_a = [t["name"] for t in guarded(lambda: records.read_json(altered / "views.json")["transcripts"], [])]
839
+ stored_a = guarded(lambda: stored_evidence(altered, names_a), {})
840
+ by_claims = {"candidate_id": "k-direct", "event_ids": [],
841
+ "admission": {"observed_event": {"claim_ids": [direct], "evidence_ids": []}}}
842
+ by_tension = {"candidate_id": "k-tension", "event_ids": [], "admission": {},
843
+ "tension": {"instance_claim_ids": [direct]}}
844
+ got_direct = [guarded(lambda k=k: quote_problems(altered, cited(k, sub_a)[0], stored_a, {}), ["RAISED"])
845
+ for k in (by_claims, by_tension)]
846
+ control("Codex WP-10 r1 #1: an altered quote reached only through a claim cited directly - by the admission's "
847
+ "claim_ids or the tension's instance_claim_ids - is QUOTE_MISMATCH by evidence id",
848
+ direct and target_id and got_direct == [[f"QUOTE_MISMATCH {target_id}"]] * 2,
849
+ f"{direct} {target_id} {got_direct}")
850
+ control("Codex WP-10 r1 #1: a claim cited directly that no store holds is CLAIM_UNKNOWN",
851
+ guarded(lambda: cited({**by_claims, "admission": {"observed_event": {"claim_ids": ["c-none"]}}},
852
+ sub_a)[1], []) == ["CLAIM_UNKNOWN c-none"])
853
+ # a tampered immutable copy, at the function: the record's own copy hashes otherwise
854
+ tampered = copy_of("tampered")
855
+ sub_t = guarded(lambda: stage_form.subject(tampered), None)
856
+ ids_t = guarded(lambda: cited(formed_c, sub_t)[0], [])
857
+ names_t = [t["name"] for t in guarded(lambda: records.read_json(tampered / "views.json")["transcripts"], [])]
858
+ stored_t = guarded(lambda: stored_evidence(tampered, names_t), {})
859
+ plain_id = next((i for i in ids_t if not i.startswith("origin:") and i in stored_t), None)
860
+ if plain_id:
861
+ copy_path = tampered / evidence.copy_rel(stored_t[plain_id]["version_sha"])
862
+ copy_path.chmod(0o600) # the copy is written read-only; this control is the edit that mode does not stop
863
+ copy_path.write_bytes(copy_path.read_bytes() + b"\n")
864
+ got_t = guarded(lambda: quote_problems(tampered, [plain_id], stored_t, {}), ["RAISED"])
865
+ control("a quote whose immutable copy no longer hashes as its version is SOURCE_TAMPERED by evidence id",
866
+ plain_id and got_t == [f"SOURCE_TAMPERED {plain_id}"], f"{plain_id} {got_t}")
867
+ control("a cited quote no store holds is EVIDENCE_ABSENT by id",
868
+ quote_problems(gold, ["e-0000000000000000"], {}, {}) == ["EVIDENCE_ABSENT e-0000000000000000"], "listed")
869
+ # sessions: a fabricated session id, at the function, over the golden subject
870
+ sub_g = guarded(lambda: stage_form.subject(gold), {"events": [], "claims": {}})
871
+ rows_g = guarded(lambda: census.rows(census.load(gold)), [])
872
+ fabricated = {**formed_c, "sessions": list(formed_c.get("sessions", [])) + ["claude:00000000-0000-4000-8000-00000000dead"]}
873
+ control("§6.5: a fabricated session id is SESSION_UNKNOWN and SESSION_MISMATCH by id",
874
+ session_problems(fabricated, sub_g, rows_g) == ["SESSION_UNKNOWN claude:00000000-0000-4000-8000-00000000dead",
875
+ "SESSION_MISMATCH claude:00000000-0000-4000-8000-00000000dead"],
876
+ f"{session_problems(fabricated, sub_g, rows_g)}")
877
+ control("control: the candidate as S4 formed it has no session problem",
878
+ session_problems(formed_c, sub_g, rows_g) == [], f"{session_problems(formed_c, sub_g, rows_g)}")
879
+ # inputs: S5 reads what S4 recorded, and nothing S4 did not finish
880
+ stale = copy_of("stale")
881
+ path = stale / "candidates.json"
882
+ path.write_text(path.read_text(encoding="utf-8") + " ", encoding="utf-8")
883
+ control("an S4 output changed after S4 recorded it is refused by name before anything is written",
884
+ "candidates.json" in refusal(lambda: run(stale)) and not (stale / "checks.json").exists(),
885
+ refusal(lambda: run(stale)))
886
+ # the driver, as a process
887
+ cli = copy_of("cli")
888
+ # The fixture's ledger reference, named for the subprocess: the in-process calls above read
889
+ # it from the module-level value `fx_reader` set, which a child process does not inherit.
890
+ from runlib import stage_read
891
+ done = subprocess.run([sys.executable, "-I", str(HERE / "distill.py"), "retrieve", "--run-id", cli.name,
892
+ "--out", str(cli.parent),
893
+ "--checkout-ledger", stage_read.CHECKOUT_LEDGER],
894
+ capture_output=True, text=True, timeout=600)
895
+ said_cli = done.stdout + done.stderr
896
+ control("the driver's `retrieve` runs S5 as a process, completes, and prints counts with the withheld line",
897
+ done.returncode == 0 and "S5 retrieve: declaration_seq" in said_cli
898
+ and "candidates not advanced to an absence sweep" in said_cli and record_of(cli).get("status") == "complete",
899
+ f"{done.returncode} {said_cli[-600:]}")
900
+ # a run S4 has not completed is refused by name
901
+ bare_root = root / "bare"
902
+ bare, _s = stage_form.fx_s3(bare_root)
903
+ said_bare = refusal(lambda: run(bare))
904
+ control("S5 over a run S4 has not run is refused by name (INPUT_INVALID S4)", "INPUT_INVALID S4" in said_bare,
905
+ said_bare[:300])
906
+ finally:
907
+ shutil.rmtree(root, ignore_errors=True)
908
+ for failure in failures:
909
+ print(f"stage_retrieve --self-test [FAIL] {failure}")
910
+ if failures:
911
+ return 1
912
+ print(f"stage_retrieve --self-test: OK ({len(ran)} controls: §6.2's retrieval - the top {PER_LAYER} of each layer, "
913
+ f"every named unit and entry, the top {TOP_ENTRIES} ledger entries, the exception and the named hints in the "
914
+ "query, reference units and identical copies; done-when 3's recurrence over lineage-linked census rows and its "
915
+ "control; quotes verified again, altered and tampered; a fabricated session; the withheld absence with its "
916
+ "count and reason; the stage over a golden run through S4, its inputs and the driver as a process)")
917
+ return 0
918
+
919
+
920
+ if __name__ == "__main__":
921
+ if sys.argv[1:] == ["--self-test"]:
922
+ sys.exit(self_test())
923
+ print("usage: stage_retrieve.py --self-test (the stage runs as `distill.py retrieve --run-id ID`)", file=sys.stderr)
924
+ sys.exit(2)