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,2576 @@
1
+ #!/usr/bin/env python3
2
+ """S4 form (plan WP-09; design §4 S4, §7.4 type G, §9): the formation packet, its labels, and the stage's check of an
3
+ answer.
4
+
5
+ One formation call receives the window's events - each with the claims that describe it, the claims that show its
6
+ outcome, and their quotes - and the clusters of placed learnings that share a principle (design §7.4's upward
7
+ distillation; built by the lifecycle intake). It answers candidates (situation / action / exception, the eight admission
8
+ fields, type A-G, a one-line `lesson` naming the cluster, as the v1 consolidator wrote), rejected findings (each naming the requirements it fails), and
9
+ non-findings (each with one reason from design §9's fixed list). Lifecycle candidates are formed by code and never sent
10
+ (lead decision D7, WP-09 stage 0 M8).
11
+
12
+ The packet names every event, claim, quote, session and cluster by a label of its own (v1, ...; c1, ...; q1, ...;
13
+ s1, ...; u1, ...: `FormLabels`), as S3's packets do (WP-08b), and the answer names its candidates and rejected findings
14
+ k1, ... and r1, .... A label the packet does not show is UNKNOWN_LABEL, in the stage's check and again where an
15
+ accepted answer is read (`FormLabels.resolve`), so no label can reach a store.
16
+
17
+ The stage's check (`answer_problems`), beside what the schema holds, refuses by name:
18
+ - UNKNOWN_LABEL: an event, claim, quote or cluster label the packet does not show;
19
+ - RECORD_INTEGRITY: a candidate or rejected-finding id given twice;
20
+ - G_ANTI_ABSTRACTION: a type G candidate without two distinct sides, an ordering, what it forbids, or at least three
21
+ distinct claims as instances (design §7.4);
22
+ - TENSION_OUTSIDE_G: a tension field filled on a candidate of another type;
23
+ - NON_FINDING_DUPLICATE: a duplicate that names no other event, or a duplicate named under another reason;
24
+ - SET_MISMATCH: an event the packet lists placed nowhere, or in more than one place (design §9's partition: each event
25
+ is a candidate's member, a rejected finding's, or a non-finding, exactly once).
26
+
27
+ What S4 forms from (`subject`, lead decisions D1 and D2 of WP-09 stage 0): the events of the units S3 processed
28
+ (`read_complete`), each by its stored id, whose current outcome is `resolved` - an event a window resolved, one the
29
+ stitch joined to its outcome, and an event an earlier run left pending that this run's stitch resolved, under its earlier
30
+ id. An event a processed unit hands on (`unresolved`, coverage's next pending event) is listed `carried_forward` and is
31
+ formed by the run that resolves it. A unit S3 did not process (`read_partial`, `deferred`, `failed`) is listed with its
32
+ status and reasons and none of its events is formed: S3 credited nothing of it, so the next run reads it again. A
33
+ processed unit whose open events are not the ones its result hands on, or whose resolved carried events are not its
34
+ result's, is refused by name (SET_MISMATCH), as is an event id two units hold.
35
+
36
+ `population` is design §9's one population as an explicit set (plan WP-09 Artifacts, N#12): every candidate - formed
37
+ and, from commit 4, the lifecycle intake - with its events, every rejected finding and every non-finding, the event
38
+ membership, the carried-forward events and the units not formed; `population_problems` refuses by name (SET_MISMATCH) a
39
+ lifecycle candidate the intake holds and the population does not, a membership naming no listed candidate, and an event
40
+ of the subject missing or placed twice. `partition_rows` are `partition.jsonl`'s rows.
41
+
42
+ The contract's closed lists (plan WP-09 done-when 7) are copied below from the sections that own them, each cited, and
43
+ the self-test holds the schema and the code to them.
44
+
45
+ stage_form.py --self-test
46
+ """
47
+ import collections
48
+ import copy
49
+ import json
50
+ import math
51
+ import os
52
+ import pathlib
53
+ import re
54
+ import shutil
55
+ import subprocess
56
+ import sys
57
+ import tempfile
58
+
59
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
60
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
61
+ from runlib import bound, census, coverage, evidence, gate, lifecycle_intake, packet, projection, records, usage, validate, views
62
+ from runlib.records import Refused, RunStopped
63
+
64
+ HERE = pathlib.Path(__file__).resolve().parents[1] # session-distill/: the self-test runs the driver from it
65
+ STAGE = "S4"
66
+ TEMPLATE = "form"
67
+ SCHEMA_PATH = pathlib.Path(__file__).resolve().parents[1] / "schemas" / "form.schema.json"
68
+
69
+ # ---- the contract's closed lists (plan WP-09 done-when 7) ---------------------------------------
70
+ # design 2026-10-20T1942--9684f05--mechanism-design.md §9 lines 921-924: "a member of a candidate, a non-finding ...,
71
+ # or a rejected finding"
72
+ PARTITION_CLASSES = ("candidate", "non_finding", "rejected_finding")
73
+ # the same lines: "one of a fixed list of reasons: no consequence, routine step, duplicate of another event"
74
+ NON_FINDING_REASONS = ("no_consequence", "routine_step", "duplicate_of_another_event")
75
+ DUPLICATE = "duplicate_of_another_event"
76
+ # design §7.1 lines 520-523 and 527-546, as the implementation plan's WP-09 Artifacts names them ("due decision, legacy,
77
+ # obsolete hint, redundancy hint, G cluster")
78
+ INTAKE_SOURCES = ("due_decision", "legacy", "obsolete_hint", "redundancy_hint", "g_cluster")
79
+ # purpose record 2026-10-20T1133--02a6ba2--purpose-and-outcomes.md lines 47-66 (D-20261020-71699d), in its order
80
+ ADMISSION = ("observed_event", "consequence", "causal_support", "recognizable_in_advance", "actionable", "bounded",
81
+ "positioned", "audience")
82
+ # design/session-distill/PLACEMENT-FRAMEWORK.md lines 32-45, kept as the second axis by design §7.4 line 610
83
+ TYPES = ("A", "B", "C", "D", "E", "F", "G")
84
+ # design §7.4 lines 633-634: "at least three claim ids as instances"
85
+ G_MIN_INSTANCES = 3
86
+
87
+ QUOTE_BYTES = views.OVERLAP_ITEM_BYTES # what the packet shows of a quote, as S3's stitch shows one
88
+
89
+
90
+ def form_schema():
91
+ return json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
92
+
93
+
94
+ def schema_problems(answer, schema=None):
95
+ """The gate's schema step over `answer` (gate.schema): every violation as `SCHEMA_INVALID <path>: <message>`."""
96
+ validator = validate.compile_schema(form_schema() if schema is None else schema)
97
+ return [f"SCHEMA_INVALID {line}" for line in validate.validate_instance(validator, answer)]
98
+
99
+
100
+ def quote_row(quote):
101
+ """A quote as the packet shows it: where it stands, its role, and its text, cut as an overlap item is."""
102
+ text, cut = views.cap_text(quote["text"], QUOTE_BYTES)
103
+ return {"record": quote["record"], "window_role": quote["window_role"], "text": text, **({"cut": True} if cut else {})}
104
+
105
+
106
+ class FormLabels:
107
+ """What one formation packet labels: its events v1, v2, ... in the order it lists them, the sessions they come from
108
+ s1, ... in first appearance, the claims c1, ... in the order the events name them (describing claims, then outcome
109
+ claims), their quotes q1, ... in first appearance and then the quotes of the events' origins, the placed clusters
110
+ u1, ... in theirs, and each cluster's entries u1.1, u1.2, ... (lead decision after X round 1, F2). The labels follow
111
+ from what the packet lists, so a retry's packet shows the same ones and nothing stores them.
112
+
113
+ `events` are `{id, session, kind, description, claim_ids, outcome_claim_ids, origin?}` (stored ids; a carried event
114
+ resolved in this run describes itself by no claim of this run, shows where it began by its `origin` quotes and its
115
+ outcome by the stitch's claims), `claims` map a stored claim id to `{fact, interpretation, uncertainty, quotes:
116
+ [{evidence_id, record, window_role, text}]}`, and `clusters` are `{id, members: [{entry, lesson, evidence}]}`."""
117
+
118
+ def __init__(self, events, claims, clusters=()):
119
+ self.rows, self.claim_rows, self.cluster_rows = list(events), claims, list(clusters)
120
+ self.events = {f"v{n}": ev["id"] for n, ev in enumerate(self.rows, 1)}
121
+ sessions = list(dict.fromkeys(ev["session"] for ev in self.rows))
122
+ self.sessions = {f"s{n}": s for n, s in enumerate(sessions, 1)}
123
+ named = list(dict.fromkeys(c for ev in self.rows for c in [*ev["claim_ids"], *ev["outcome_claim_ids"]]))
124
+ missing = [c for c in named if c not in claims]
125
+ if missing:
126
+ raise Refused(f"RECORD_INTEGRITY S4 packet: events name claims no row carries: {missing[:5]}")
127
+ self.claims = {f"c{n}": c for n, c in enumerate(named, 1)}
128
+ quotes = list(dict.fromkeys([q["evidence_id"] for c in named for q in claims[c]["quotes"]]
129
+ + [o["evidence_id"] for ev in self.rows for o in ev.get("origin", []) if o.get("evidence_id")]))
130
+ self.quotes = {f"q{n}": e for n, e in enumerate(quotes, 1)}
131
+ self.clusters = {f"u{n}": c["id"] for n, c in enumerate(self.cluster_rows, 1)}
132
+ self.entries, self.entry_cluster = {}, {}
133
+ for n, c in enumerate(self.cluster_rows, 1):
134
+ for m, member in enumerate(c["members"], 1):
135
+ self.entries[f"u{n}.{m}"] = member["entry"]
136
+ self.entry_cluster[f"u{n}.{m}"] = f"u{n}"
137
+ self.of_event, self.of_session, self.of_claim, self.of_quote, self.of_cluster = (
138
+ {v: k for k, v in table.items()} for table in (self.events, self.sessions, self.claims, self.quotes,
139
+ self.clusters))
140
+
141
+ def origin_rows(self, ev):
142
+ """An event's origin as the packet shows it: a citable block by its quote label, one that cannot be stored as a
143
+ quote by its text alone."""
144
+ return [{**({"evidence_id": self.of_quote[o["evidence_id"]]} if o.get("evidence_id") else {"citable": False}),
145
+ "record": o["record"], "window_role": "origin", "text": o["text"], **({"cut": True} if o.get("cut") else {})}
146
+ for o in ev.get("origin", [])]
147
+
148
+ def events_text(self):
149
+ if not self.rows:
150
+ return "none"
151
+ return "\n".join(json.dumps({"event_id": self.of_event[ev["id"]], "session": self.of_session[ev["session"]],
152
+ "kind": ev["kind"], "description": ev["description"],
153
+ **({"origin": self.origin_rows(ev)} if "origin" in ev else {}),
154
+ "claims": [self.of_claim[c] for c in ev["claim_ids"]],
155
+ "outcome_claims": [self.of_claim[c] for c in ev["outcome_claim_ids"]]},
156
+ ensure_ascii=False) for ev in self.rows)
157
+
158
+ def claims_text(self):
159
+ if not self.claims:
160
+ return "none"
161
+ rows = []
162
+ for label, ident in self.claims.items():
163
+ c = self.claim_rows[ident]
164
+ rows.append(json.dumps({"claim_id": label, "fact": c["fact"], "interpretation": c["interpretation"],
165
+ "uncertainty": c["uncertainty"],
166
+ "quotes": [{"evidence_id": self.of_quote[q["evidence_id"]], **quote_row(q)}
167
+ for q in c["quotes"]]}, ensure_ascii=False))
168
+ return "\n".join(rows)
169
+
170
+ def clusters_text(self):
171
+ if not self.cluster_rows:
172
+ return "none"
173
+ return "\n".join(json.dumps({"cluster_id": self.of_cluster[c["id"]], "entries": [
174
+ {"entry_id": f"{self.of_cluster[c['id']]}.{m}", "lesson": member["lesson"], "evidence": member.get("evidence") or []}
175
+ for m, member in enumerate(c["members"], 1)]}, ensure_ascii=False) for c in self.cluster_rows)
176
+
177
+ def resolve(self, answer):
178
+ """`answer` with every packet label turned into the stored id it labels; one the packet does not show is refused
179
+ by name (UNKNOWN_LABEL). Candidate and finding ids are the answer's own and stay as written."""
180
+ def of(table, label, path, what):
181
+ if label not in table:
182
+ raise Refused(f"UNKNOWN_LABEL {label!r} at {path}: this packet shows no {what} so labelled")
183
+ return table[label]
184
+ out = copy.deepcopy(answer)
185
+ for k in out["candidates"]:
186
+ where = f"candidates/{k['candidate_id']}"
187
+ k["event_ids"] = [of(self.events, v, f"{where}/event_ids", "event") for v in k["event_ids"]]
188
+ for name in ADMISSION:
189
+ req = k["admission"][name]
190
+ req["claim_ids"] = [of(self.claims, c, f"{where}/admission/{name}", "claim") for c in req["claim_ids"]]
191
+ req["evidence_ids"] = [of(self.quotes, q, f"{where}/admission/{name}", "quote") for q in req["evidence_ids"]]
192
+ t = k["tension"]
193
+ t["instance_claim_ids"] = [of(self.claims, c, f"{where}/tension", "claim") for c in t["instance_claim_ids"]]
194
+ t["instance_entry_ids"] = [of(self.entries, e, f"{where}/tension", "cluster entry") for e in t["instance_entry_ids"]]
195
+ t["cluster"] = of(self.clusters, t["cluster"], f"{where}/tension/cluster", "cluster") if t["cluster"] else ""
196
+ for r in out["rejected_findings"]:
197
+ r["event_ids"] = [of(self.events, v, f"rejected_findings/{r['finding_id']}/event_ids", "event")
198
+ for v in r["event_ids"]]
199
+ for n in out["non_findings"]:
200
+ where = f"non_findings/{n['event_id']}"
201
+ n["event_id"] = of(self.events, n["event_id"], f"{where}/event_id", "event")
202
+ n["duplicate_of"] = of(self.events, n["duplicate_of"], f"{where}/duplicate_of", "event") if n["duplicate_of"] else ""
203
+ return out
204
+
205
+
206
+ def payload(labels):
207
+ return packet.render(TEMPLATE, {"events": labels.events_text(), "claims": labels.claims_text(),
208
+ "clusters": labels.clusters_text()})
209
+
210
+
211
+ def g_problems(where, tension, labels):
212
+ """Design §7.4's anti-abstraction guard over one type G candidate's tension, each missing part by name. Its
213
+ instances are at least three distinct claims the packet shows, or - for a principle distilled from a placed cluster
214
+ (lead decision after X round 1, F2) - at least three distinct entries of the cluster it names, whatever claims it
215
+ cites beside them (X round 2, F1); an entry of another cluster is no instance of it."""
216
+ errors = []
217
+ sides = [s.strip() for s in tension["sides"]]
218
+ if len(sides) != 2 or not all(sides) or sides[0] == sides[1]:
219
+ errors.append(f"G_ANTI_ABSTRACTION {where}/tension/sides: a type G candidate names both sides of its tension, two "
220
+ f"distinct texts; it gives {len(sides)}")
221
+ if not tension["ordering"].strip():
222
+ errors.append(f"G_ANTI_ABSTRACTION {where}/tension/ordering: a type G candidate states which side is preferred to "
223
+ "which")
224
+ if not tension["forbids"].strip():
225
+ errors.append(f"G_ANTI_ABSTRACTION {where}/tension/forbids: a type G candidate states what the preference now "
226
+ "forbids")
227
+ claims = {c for c in tension["instance_claim_ids"] if c in labels.claims}
228
+ entries = {e for e in tension["instance_entry_ids"] if e in labels.entries}
229
+ foreign = sorted(e for e in entries if labels.entry_cluster[e] != tension["cluster"])
230
+ if foreign:
231
+ errors.append(f"G_ANTI_ABSTRACTION {where}/tension/instance_entry_ids: {foreign} are not entries of the cluster it "
232
+ f"names ({tension['cluster'] or 'none'})")
233
+ own = cluster_entries(tension, labels)
234
+ if tension["instance_entry_ids"]: # the cluster path: its entries are its instances, whatever claims are beside them
235
+ if len(own) < G_MIN_INSTANCES:
236
+ errors.append(f"G_ANTI_ABSTRACTION {where}/tension/instance_entry_ids: a type G candidate citing entries of a "
237
+ f"placed cluster cites at least {G_MIN_INSTANCES} distinct entries of the cluster it names, claims "
238
+ f"or no claims beside them; it cites {len(own)}")
239
+ elif len(claims) < G_MIN_INSTANCES:
240
+ errors.append(f"G_ANTI_ABSTRACTION {where}/tension/instance_claim_ids: a type G candidate cites at least "
241
+ f"{G_MIN_INSTANCES} distinct claims, or at least {G_MIN_INSTANCES} entries of the placed cluster it "
242
+ f"names, as instances; it cites {len(claims)} claims")
243
+ return errors
244
+
245
+
246
+ def cluster_entries(tension, labels):
247
+ """The distinct entries a tension cites that the packet shows under the cluster it names."""
248
+ return {e for e in tension["instance_entry_ids"]
249
+ if e in labels.entries and tension["cluster"] and labels.entry_cluster[e] == tension["cluster"]}
250
+
251
+
252
+ def from_cluster(candidate, labels):
253
+ """A type G candidate distilled from a placed cluster: it names the cluster and cites at least three distinct entries
254
+ of it as instances (X round 2, F1), and only it may rest on no event of the window."""
255
+ return candidate["type"] == "G" and len(cluster_entries(candidate["tension"], labels)) >= G_MIN_INSTANCES
256
+
257
+
258
+ def answer_problems(labels, answer):
259
+ """The stage's check of one formation answer, read in the packet's labels (`FormLabels`): every line names what the
260
+ answer wrote, so a retry's correction shows labels; empty when it holds. Run only on an answer the schema passed."""
261
+ errors = []
262
+
263
+ def known(label, table, path, what):
264
+ if label in table:
265
+ return True
266
+ errors.append(f"UNKNOWN_LABEL {label!r} at {path}: this packet shows no {what} so labelled")
267
+ return False
268
+
269
+ for kind, items, key in (("candidate", answer["candidates"], "candidate_id"),
270
+ ("rejected finding", answer["rejected_findings"], "finding_id")):
271
+ found = [item[key] for item in items]
272
+ repeated = sorted({i for i in found if found.count(i) > 1})
273
+ if repeated:
274
+ errors.append(f"RECORD_INTEGRITY {kind} ids repeat: {repeated}")
275
+ for k in answer["candidates"]:
276
+ where = f"candidates/{k['candidate_id']}"
277
+ if not k["event_ids"] and not from_cluster(k, labels):
278
+ errors.append(f"CANDIDATE_WITHOUT_EVENTS {where}/event_ids: a candidate rests on the events it names; only a "
279
+ "type G candidate distilled from a placed cluster, citing that cluster's entries, names none")
280
+ for v in k["event_ids"]:
281
+ known(v, labels.events, f"{where}/event_ids", "event")
282
+ for name in ADMISSION:
283
+ req = k["admission"][name]
284
+ for c in req["claim_ids"]:
285
+ known(c, labels.claims, f"{where}/admission/{name}/claim_ids", "claim")
286
+ for q in req["evidence_ids"]:
287
+ known(q, labels.quotes, f"{where}/admission/{name}/evidence_ids", "quote")
288
+ t = k["tension"]
289
+ for c in t["instance_claim_ids"]:
290
+ known(c, labels.claims, f"{where}/tension/instance_claim_ids", "claim")
291
+ for e in t["instance_entry_ids"]:
292
+ known(e, labels.entries, f"{where}/tension/instance_entry_ids", "cluster entry")
293
+ if t["cluster"]:
294
+ known(t["cluster"], labels.clusters, f"{where}/tension/cluster", "cluster")
295
+ if k["type"] == "G":
296
+ errors.extend(g_problems(where, t, labels))
297
+ elif t["sides"] or t["ordering"] or t["forbids"] or t["instance_claim_ids"] or t["instance_entry_ids"] or t["cluster"]:
298
+ errors.append(f"TENSION_OUTSIDE_G {where}/tension: a type {k['type']} candidate leaves every list of its "
299
+ "tension empty and every text \"\"; the tension is type G's")
300
+ for r in answer["rejected_findings"]:
301
+ for v in r["event_ids"]:
302
+ known(v, labels.events, f"rejected_findings/{r['finding_id']}/event_ids", "event")
303
+ for n in answer["non_findings"]:
304
+ where = f"non_findings/{n['event_id']}"
305
+ known(n["event_id"], labels.events, f"{where}/event_id", "event")
306
+ if n["reason"] == DUPLICATE:
307
+ if not n["duplicate_of"] or n["duplicate_of"] == n["event_id"]:
308
+ errors.append(f"NON_FINDING_DUPLICATE {where}/duplicate_of: a duplicate names the other event it repeats; "
309
+ f"it names {n['duplicate_of']!r}")
310
+ else:
311
+ known(n["duplicate_of"], labels.events, f"{where}/duplicate_of", "event")
312
+ elif n["duplicate_of"]:
313
+ errors.append(f"NON_FINDING_DUPLICATE {where}/duplicate_of: only a {DUPLICATE} names another event; reason "
314
+ f"{n['reason']} names {n['duplicate_of']!r}")
315
+ placed = collections.Counter()
316
+ for k in answer["candidates"]:
317
+ placed.update(k["event_ids"])
318
+ for r in answer["rejected_findings"]:
319
+ placed.update(r["event_ids"])
320
+ placed.update(n["event_id"] for n in answer["non_findings"])
321
+ nowhere = [v for v in labels.events if placed[v] == 0]
322
+ twice = {v: n for v, n in sorted(placed.items()) if n > 1 and v in labels.events}
323
+ if nowhere:
324
+ errors.append(f"SET_MISMATCH events placed nowhere: {nowhere}; every event above goes in exactly one place: a "
325
+ "candidate's event_ids, a rejected finding's event_ids, or one non-finding")
326
+ if twice:
327
+ errors.append(f"SET_MISMATCH events placed more than once: {twice}; every event above goes in exactly one place")
328
+ return errors
329
+
330
+
331
+ def judge(labels, capacity):
332
+ """The stage's check of the formation's attempts, as `Supervisor.item(stage_check=)` asks it: pure code over the
333
+ attempt's call directory, which it only reads. An attempt whose record does not carry the capacity S4 was admitted
334
+ against stops the stage by name (`recorded_capacity`), before any retry or reuse: no answer of it is judged."""
335
+ from runlib import stage_read
336
+
337
+ def check(call_dir):
338
+ recorded_capacity(call_dir, capacity)
339
+ return answer_problems(labels, stage_read.answer_of(call_dir))
340
+ return check
341
+
342
+
343
+ def recorded_capacity(call_dir, capacity):
344
+ """`capacity` when an attempt's call record carries it as the capacity it was admitted against, else
345
+ CAPACITY_UNRECORDED by name (W review of WP-09 r2, F1). The gate compares the context window the host reports
346
+ with that record (CAPACITY_DRIFT); a record without it is compared with nothing, and is how the catalogue's
347
+ capacity would go unchecked by the first live call."""
348
+ held = ((records.read_json(pathlib.Path(call_dir) / "call.json").get("bound")) or {}).get("context_capacity")
349
+ if held != capacity:
350
+ raise Refused(f"CAPACITY_UNRECORDED {pathlib.Path(call_dir).name}: its call record carries the capacity {held!r}, "
351
+ f"and S4 was admitted against {capacity}; the context window the host reports would be compared "
352
+ "with nothing")
353
+ return capacity
354
+
355
+
356
+ def form_claim(driver_bytes, limits):
357
+ """The claim S4 holds its formation call of `driver_bytes` to under `limits` (W r1 F4, W r2 F7; lead decisions):
358
+ `{requests_at_most, first, step, input_at_most}` - at most the first request and the claimed retries, the first
359
+ within its estimate, the k-th retry within first + k x (cap + margin); None without limits or bytes."""
360
+ if not limits or not (usage.countable(driver_bytes) and driver_bytes):
361
+ return None
362
+ first, at_most = input_at_most(driver_bytes, limits)
363
+ return {"requests_at_most": 1 + limits.get("retries", 1), "first": first,
364
+ "step": limits["output_cap"] + limits["retry_margin"], "input_at_most": at_most}
365
+
366
+
367
+ def within_claim(requests, claim):
368
+ """Whether a call stayed within `claim` (`form_claim`; `bound.claim_problems` decides: a breach, or a field a rule
369
+ needs that the claim lacks), or None without a claim or a measured request."""
370
+ largest = bound.observed_input(requests)[0] if requests is not None else 0
371
+ if claim is None or not largest:
372
+ return None
373
+ return not bound.claim_problems(requests, claim)
374
+
375
+
376
+ def usage_rows(call_dir):
377
+ """A call's usage request rows, None when it has no usage record, refused by name when the record holds none it can
378
+ read (`RECORD_UNREADABLE`; the lead's verification of WP-08e commit 4, finding 4) - never a KeyError."""
379
+ path = pathlib.Path(call_dir) / "usage.json"
380
+ if not path.is_file():
381
+ return None
382
+ held = records.read_json(path)
383
+ rows = held.get("requests") if isinstance(held, dict) else None
384
+ if not isinstance(rows, list):
385
+ raise Refused(f"RECORD_UNREADABLE {path}: no request rows (requests: {type(rows).__name__})")
386
+ return rows
387
+
388
+
389
+ def observed(call_dir, limits=None, rows=None):
390
+ """What an accepted formation call measured of S4's two assumptions (W review of WP-09 r2, F1): the context window
391
+ the host reports per model, beside the capacity the call was admitted against; and the input tokens the host
392
+ reported for the call's FIRST main request, beside the driver bytes the call sent, with their ratio (the bytes a
393
+ token covered, the host's own context included, so a low reading). The first request carries the packet alone; a
394
+ later one is the host's retry of a refused structured output and carries the first answer and the error on top, so
395
+ it is counted apart (WP-08e): the main requests the call made, the largest of them, and, with the `limits` S4 was
396
+ admitted under, the input it claimed at most for one request of this call's driver bytes (`input_at_most`) and
397
+ whether the call stayed within it (`within_claim`, `breaches`: the first request within its estimate, each retry
398
+ within its step, and no more main requests than the first and its claimed retries; W r1 F4, W r2 F7)."""
399
+ call_dir = pathlib.Path(call_dir)
400
+ held = records.read_json(call_dir / "call.json").get("bound") or {}
401
+ result = gate.Call(call_dir).result
402
+ model_usage = result.get("modelUsage") if isinstance(result, dict) else None
403
+ windows = {m: u.get("contextWindow") for m, u in sorted((model_usage or {}).items()) if isinstance(u, dict)}
404
+ requests = rows if rows is not None else usage_rows(call_dir) # the rows in hand, or read by name
405
+ largest, missing = bound.observed_input(requests) if requests is not None else (None, ["no usage.json"])
406
+ first = usage.first_input(requests) if requests is not None else None
407
+ driver = held.get("driver_bytes")
408
+ claim = form_claim(driver, limits)
409
+ return {"admitted_capacity": held.get("context_capacity"), "context_window": windows,
410
+ "driver_bytes": held.get("driver_bytes"), "input_tokens": first,
411
+ "bytes_per_token": round(held["driver_bytes"] / first, 3) if first and held.get("driver_bytes") else None,
412
+ "requests": len(usage.main_requests(requests)), "largest_input": largest or None,
413
+ "first_request_at_most": (claim or {}).get("first"), "input_tokens_at_most": (claim or {}).get("input_at_most"),
414
+ "requests_at_most": (claim or {}).get("requests_at_most"), "within_claim": within_claim(requests, claim),
415
+ "breaches": bound.claim_problems(requests, claim) if claim and requests is not None else [],
416
+ "missing": [str(m) for m in missing] if missing else []}
417
+
418
+
419
+
420
+ # ---- what S4 forms from, and the population it leaves (lead decisions D1, D2) -----------------------
421
+
422
+ PROCESSED = "read_complete"
423
+
424
+
425
+ def sid(prefix, run_id, label):
426
+ """A stored id of what the answer named by its own label, in the run that formed it."""
427
+ from runlib import stage_read
428
+ return stage_read.sid(prefix, run_id, label)
429
+
430
+
431
+ def unit_of_file(rows, units):
432
+ """`{coverage key of a file: its unit}` for the units S3 answered, as S3 reads each unit's files."""
433
+ from runlib import stage_read
434
+ return {key: unit for unit, keys in stage_read.unit_files(rows, units).items() for key in keys}
435
+
436
+
437
+ def origin_of(run_dir, view, event):
438
+ """The first record of a carried event, as this run's copy holds it (lead decision after X round 1, F3): each block
439
+ of it the stitch showed when it resolved the event (`stage_read.projected_blocks`, cut where the stitch cut it).
440
+ Every block is first held to the immutable copy - the copy's hash, then the block's whole projected text against
441
+ what the copy projects there - whether or not it can be quoted (X round 2, F2); a first record the projection does
442
+ not hold, or holds otherwise than the copy, is RECORD_INTEGRITY. Only then is a block made an evidence record
443
+ (`evidence.make`), so an origin quote is verified as every other quote is; its stored id is `origin:<view>#<record>`.
444
+ A block whose text names a secret cannot be stored as a quote (EVIDENCE_QUOTE_SENSITIVE): having passed the same
445
+ check, it is shown and cannot be cited."""
446
+ from runlib import stage_read
447
+ line = int(re.match(r"[0-9]+", event["at_record"]).group())
448
+ blocks = stage_read.projected_blocks(run_dir, view, line)
449
+ if not blocks:
450
+ raise Refused(f"RECORD_INTEGRITY {event['event_id']}: its first record, line {line} of {view['name']}, holds no block "
451
+ "in this run's projection, so where it began cannot be shown")
452
+ copy_path, problem = evidence.copy_problem(run_dir, view["version_sha"])
453
+ if problem:
454
+ raise Refused(f"RECORD_INTEGRITY {event['event_id']}: its origin cannot be held to the immutable copy of "
455
+ f"{view['name']} ({problem.split(' ', 1)[0]})")
456
+ rows = []
457
+ for pointer, text in blocks:
458
+ where = f"{line}{pointer}"
459
+ if evidence.projection_of(copy_path, line, pointer, projection.CURRENT) != text:
460
+ raise Refused(f"RECORD_INTEGRITY {event['event_id']}: the projection's text at {where} of {view['name']} is not "
461
+ "what the immutable copy projects there, so its origin is not shown")
462
+ cut, was_cut = views.cap_text(text, QUOTE_BYTES)
463
+ if not cut:
464
+ continue
465
+ row = {"evidence_id": f"origin:{view['name']}#{where}", "record": where, "window_role": "origin", "text": cut,
466
+ **({"cut": True} if was_cut else {})}
467
+ try:
468
+ made = evidence.make(run_dir, view["version_sha"], line, pointer, [0, len(cut)], "context")
469
+ except Refused as exc:
470
+ if str(exc).startswith("EVIDENCE_QUOTE_SENSITIVE"):
471
+ rows.append({**row, "evidence_id": None, "withheld": "EVIDENCE_QUOTE_SENSITIVE"})
472
+ continue
473
+ raise Refused(f"RECORD_INTEGRITY {event['event_id']}: its origin at {where} of {view['name']} does not resolve in "
474
+ f"the immutable copy ({str(exc).split(' ', 1)[0]})") from exc
475
+ rows.append({**row, "evidence": made})
476
+ return rows
477
+
478
+
479
+ def s3_outputs(run_dir):
480
+ """`{artifact: sha256}` of the outputs S3's record holds, refused by name unless it is the record of the results S4
481
+ reads (INPUT_INVALID): the read records are held to it (W review of WP-09 r1, F1)."""
482
+ held = records.stage_records(run_dir).get("S3") or {}
483
+ outputs = {o["artifact"]: o["sha256"] for o in held.get("outputs") or []}
484
+ path = pathlib.Path(run_dir) / "read-results.json"
485
+ if not path.is_file() or outputs.get("read-results.json") != records.sha256_file(path):
486
+ raise Refused("INPUT_INVALID S3: read-results.json is not the output S3's record holds, so the read records it "
487
+ "names cannot be held to that record")
488
+ return outputs
489
+
490
+
491
+ def processed_record(run_dir, result, outputs):
492
+ """The read record of a unit S3 processed, held to S3's record (W review of WP-09 r1, F1): S3 recorded it as an
493
+ output, it is that output byte for byte, and it lists exactly the files the unit's result read. A unit whose
494
+ record is missing, edited or short of a file is refused by its name, never formed from what is left."""
495
+ from runlib import stage_read
496
+ unit = result["transcript"]
497
+ rel = stage_read.read_rel(unit)
498
+ path = pathlib.Path(run_dir) / rel
499
+ if rel not in outputs:
500
+ raise Refused(f"RECORD_INTEGRITY {unit}: S3 processed it and recorded no read record of it, so its events cannot "
501
+ "be accounted for")
502
+ if not path.is_file() or records.sha256_file(path) != outputs.get(rel):
503
+ raise Refused(f"RECORD_INTEGRITY {unit}: its read record {rel} is "
504
+ f"{'missing' if not path.is_file() else 'not the one S3 recorded'}, so its events cannot be "
505
+ "accounted for")
506
+ record = records.read_json(path)
507
+ read = sorted(r["transcript"] for r in result["readings"])
508
+ listed = sorted(f["transcript"] for f in record["files"])
509
+ if listed != read:
510
+ raise Refused(f"SET_MISMATCH {unit}: its read record lists the files {listed[:5]}, and its result read {read[:5]}")
511
+ return record
512
+
513
+
514
+ def subject(run_dir):
515
+ """The events S4 forms from, the claims and quotes they name, and what is listed instead (module docstring):
516
+ `{events, claims, origins, carried_forward, not_formed, units, pending_outside}`. Read from S3's stores through S3's
517
+ own readers, which refuse an edited store by name, and from the coverage state S1 pinned.
518
+
519
+ `carried_forward` is every pending event of the window's units that leaves this run pending (X round 1, F1): the
520
+ events a processed unit hands on (`this_run`), the pending events earlier runs left on its files that its stitch
521
+ did not resolve, unresolved or not stitched (`earlier_run`), and the earlier pending events of a unit S3 did not
522
+ process (`unit_not_formed`). A processed unit whose stitch did not decide exactly the earlier pending events of its
523
+ files, or not each of them once, is SET_MISMATCH. `pending_outside` counts the pending events on files of no unit of
524
+ this window."""
525
+ from runlib import stage_read
526
+ run_dir = pathlib.Path(run_dir)
527
+ results = records.read_json(run_dir / "read-results.json")["results"]
528
+ rows_c = census.rows(census.load(run_dir))
529
+ state = coverage.load(run_dir / "coverage.json")[0]
530
+ by_name = {t["name"]: t for t in records.read_json(run_dir / "views.json")["transcripts"]}
531
+ owner = unit_of_file(rows_c, [r["transcript"] for r in results])
532
+ prior_of = collections.defaultdict(list)
533
+ for p in state["pending_events"]:
534
+ if p["transcript"] in owner:
535
+ prior_of[owner[p["transcript"]]].append(p)
536
+ rows, claims, origins, carried_forward, not_formed, held_by = [], {}, {}, [], [], {}
537
+
538
+ def forward(p, unit, origin, why):
539
+ return {"event_id": p["id"], "unit": unit, "file": p["transcript"], "window": p["window"],
540
+ "first_record": p["first_record"], "origin": origin, "why": why}
541
+ outputs = s3_outputs(run_dir)
542
+ for result in sorted(results, key=lambda r: r["transcript"]):
543
+ unit = result["transcript"]
544
+ prior = sorted(prior_of.get(unit, []), key=lambda p: p["id"])
545
+ if result["status"] == PROCESSED:
546
+ record = processed_record(run_dir, result, outputs)
547
+ else:
548
+ path = run_dir / stage_read.read_rel(unit)
549
+ record = records.read_json(path) if path.is_file() else {"files": [], "reasons": ["S3 left no read record of it"]}
550
+ names = [f["name"] for f in record["files"]]
551
+ events = [(name, e) for name in names for e in stage_read.current_events(run_dir, name)]
552
+ if result["status"] != PROCESSED:
553
+ not_formed.append({"unit": unit, "status": result["status"], "reasons": list(record.get("reasons", [])),
554
+ "events": len(events)})
555
+ carried_forward += [forward(p, unit, "earlier_run", "unit_not_formed") for p in prior]
556
+ continue
557
+ handed = {p["id"] for p in result["pending_events"]}
558
+ still_open = {e["event_id"] for _n, e in events if e["outcome"] != "resolved"}
559
+ if still_open != handed:
560
+ raise Refused(f"SET_MISMATCH {unit}: it holds open {sorted(still_open - handed)[:5]} that its result does not hand "
561
+ f"on, or hands on {sorted(handed - still_open)[:5]} that it does not hold open")
562
+ carried = {e["event_id"] for _n, e in events if "carried_from" in e and e["outcome"] == "resolved"}
563
+ if carried != set(result["resolved_events"]):
564
+ raise Refused(f"SET_MISMATCH {unit}: its resolved carried events {sorted(carried)[:5]} are not its result's "
565
+ f"resolved_events {sorted(result['resolved_events'])[:5]}")
566
+ stitch = record.get("stitch") or {}
567
+ decided = collections.Counter(r["event_id"] for r in stitch.get("resolutions", []) if r.get("carried"))
568
+ decided.update(r["event_id"] for r in stitch.get("not_stitched", []))
569
+ earlier = {p["id"] for p in prior}
570
+ if set(decided) != earlier or any(n > 1 for n in decided.values()):
571
+ raise Refused(f"SET_MISMATCH {unit}: earlier runs left {sorted(earlier)[:5]} pending on its files, and its stitch "
572
+ f"decided or left unstitched {sorted(decided)[:5]}; each is decided once")
573
+ not_stitched = {r["event_id"] for r in stitch.get("not_stitched", [])}
574
+ carried_forward += [forward(p, unit, "earlier_run", "not_stitched" if p["id"] in not_stitched else "unresolved")
575
+ for p in prior if p["id"] not in carried]
576
+ carried_forward += [forward({"window": None, **p}, unit, "this_run", "unresolved")
577
+ for p in sorted(result["pending_events"], key=lambda p: p["id"])]
578
+ quotes = {r["evidence_id"]: r for name in names for r in evidence.load(run_dir, name)}
579
+ for name in names:
580
+ for c in stage_read.stored_claims(run_dir, name):
581
+ missing = [e for e in c["evidence_ids"] if e not in quotes]
582
+ if missing:
583
+ raise Refused(f"RECORD_INTEGRITY {c['claim_id']}: its evidence {missing[:3]} is in no store of unit {unit}")
584
+ claims[c["claim_id"]] = {"fact": c["fact"], "interpretation": c["interpretation"], "uncertainty": c["uncertainty"],
585
+ "unit": unit,
586
+ "quotes": [{"evidence_id": e, "record": f"{quotes[e]['line']}{quotes[e]['json_pointer']}",
587
+ "window_role": quotes[e]["window_role"], "text": quotes[e]["redacted_text"]}
588
+ for e in c["evidence_ids"]]}
589
+ for name, e in events:
590
+ if e["outcome"] != "resolved":
591
+ continue
592
+ if e["event_id"] in held_by:
593
+ raise Refused(f"SET_MISMATCH {e['event_id']}: held by {held_by[e['event_id']]} and by {unit}")
594
+ held_by[e["event_id"]] = unit
595
+ row = {"id": e["event_id"], "session": unit, "kind": e["kind"], "description": e["description"],
596
+ "claim_ids": list(e["claim_ids"]), "outcome_claim_ids": list(e["stitched_from"]), "file": name}
597
+ if "carried_from" in e:
598
+ row["origin"] = origin_of(run_dir, by_name[name], e)
599
+ origins.update({o["evidence_id"]: o for o in row["origin"] if o.get("evidence_id")})
600
+ rows.append(row)
601
+ return {"events": rows, "claims": claims, "origins": origins, "carried_forward": carried_forward,
602
+ "not_formed": not_formed, "units": dict(sorted(collections.Counter(r["status"] for r in results).items())),
603
+ "pending_outside": sum(1 for p in state["pending_events"] if p["transcript"] not in owner)}
604
+
605
+
606
+ def membership_of(candidates, findings, non_findings):
607
+ """`{event: candidate id | class}` as the rows place each event."""
608
+ membership = {}
609
+ for c in candidates:
610
+ membership.update({e: c["candidate_id"] for e in c["event_ids"]})
611
+ for f in findings:
612
+ membership.update({e: "rejected_finding" for e in f["event_ids"]})
613
+ membership.update({n["event_id"]: "non_finding" for n in non_findings})
614
+ return dict(sorted(membership.items()))
615
+
616
+
617
+ def population_counts(candidates, findings, non_findings, subject_of):
618
+ """The population's counts, from its rows and the subject: the one place they are computed."""
619
+ formed = [c for c in candidates if c["source"] == "formed"]
620
+ return {"events": len(subject_of["events"]), "candidate_members": sum(len(c["event_ids"]) for c in formed),
621
+ "rejected_finding_members": sum(len(f["event_ids"]) for f in findings),
622
+ "non_findings": dict(sorted(collections.Counter(n["reason"] for n in non_findings).items())),
623
+ "candidates": {"formed": len(formed), **dict(sorted(collections.Counter(
624
+ c["source"] for c in candidates if c["source"] != "formed").items()))},
625
+ "carried_forward": len(subject_of["carried_forward"]),
626
+ "carried_forward_why": dict(sorted(collections.Counter(r["why"] for r in subject_of["carried_forward"]).items())),
627
+ "pending_outside": subject_of.get("pending_outside", 0),
628
+ "units": dict(subject_of["units"]), "events_not_formed": sum(u["events"] for u in subject_of["not_formed"])}
629
+
630
+
631
+ def population(answer, subject_of, run_id, intake=()):
632
+ """Design §9's one population from a resolved accepted `answer` (stored event ids), the `subject_of` it was formed
633
+ over, and the lifecycle `intake` (`{candidate_id, source}`), each with no events of the window."""
634
+ formed = [{"candidate_id": sid("k", run_id, k["candidate_id"]), "source": "formed", "event_ids": list(k["event_ids"])}
635
+ for k in answer["candidates"]]
636
+ lifecycle = [{"candidate_id": i["candidate_id"], "source": i["source"], "event_ids": []} for i in intake]
637
+ findings = [{"finding_id": sid("r", run_id, r["finding_id"]), "event_ids": list(r["event_ids"]), "failed": list(r["failed"])}
638
+ for r in answer["rejected_findings"]]
639
+ non_findings = [{"event_id": n["event_id"], "reason": n["reason"], "duplicate_of": n["duplicate_of"]}
640
+ for n in answer["non_findings"]]
641
+ candidates = formed + lifecycle
642
+ return {"candidates": candidates, "candidate_ids": [c["candidate_id"] for c in candidates],
643
+ "rejected_findings": findings, "rejected_finding_ids": [f["finding_id"] for f in findings],
644
+ "non_findings": non_findings, "non_finding_ids": [n["event_id"] for n in non_findings],
645
+ "event_membership": membership_of(candidates, findings, non_findings),
646
+ "carried_forward": copy.deepcopy(subject_of["carried_forward"]), "not_formed": copy.deepcopy(subject_of["not_formed"]),
647
+ "counts": population_counts(candidates, findings, non_findings, subject_of)}
648
+
649
+
650
+ # the population's fields, each of the kind `population` writes it
651
+ POPULATION_FIELDS = (("candidates", list), ("candidate_ids", list), ("rejected_findings", list), ("rejected_finding_ids", list),
652
+ ("non_findings", list), ("non_finding_ids", list), ("event_membership", dict), ("carried_forward", list),
653
+ ("not_formed", list), ("counts", dict))
654
+
655
+
656
+ def population_problems(pop, subject_of, intake=()):
657
+ """The population's set accounting (plan WP-09 done-when 1, N#12; X round 1, F4), each break by name (SET_MISMATCH),
658
+ every list held to the rows it lists: the candidate, finding and non-finding ids are exactly their rows' ids; the
659
+ lifecycle rows are exactly the intake's candidates, each with its source and no event; the membership is exactly
660
+ what the rows place; every event of the subject is placed exactly once; the carried-forward events and the units
661
+ not formed are the subject's; and the counts are the ones the rows and the subject give. Empty when all hold. A
662
+ field that is absent, or not of its kind, is named and nothing else is judged (X round 2, F4)."""
663
+ absent = [(name, kind) for name, kind in POPULATION_FIELDS if not isinstance(pop.get(name), kind)]
664
+ if absent:
665
+ return [f"SET_MISMATCH {name}: absent from the population, or not a {kind.__name__}, so it cannot be held to the "
666
+ "rows and the subject" for name, kind in absent]
667
+ errors = []
668
+ rows, findings, non_findings = pop["candidates"], pop["rejected_findings"], pop["non_findings"]
669
+ for name, have, want in (("candidate_ids", pop["candidate_ids"], [c["candidate_id"] for c in rows]),
670
+ ("rejected_finding_ids", pop["rejected_finding_ids"], [f["finding_id"] for f in findings]),
671
+ ("non_finding_ids", pop["non_finding_ids"], [n["event_id"] for n in non_findings])):
672
+ if have != want:
673
+ errors.append(f"SET_MISMATCH {name} are not the ids of the rows it lists: ids with no row {sorted(set(have) - set(want))[:5]}, "
674
+ f"rows with no id {sorted(set(want) - set(have))[:5]}")
675
+ listed = collections.Counter(c["candidate_id"] for c in rows)
676
+ repeated = sorted(c for c, n in listed.items() if n > 1)
677
+ if repeated:
678
+ errors.append(f"SET_MISMATCH candidate ids listed more than once: {repeated[:5]}")
679
+ lifecycle = {c["candidate_id"]: c for c in rows if c["source"] != "formed"}
680
+ want = {i["candidate_id"]: i["source"] for i in intake}
681
+ for ident in sorted(set(want) - set(lifecycle)):
682
+ errors.append(f"SET_MISMATCH {ident}: a lifecycle candidate the intake holds is not in the population")
683
+ for ident in sorted(set(lifecycle) - set(want)):
684
+ errors.append(f"SET_MISMATCH {ident}: a lifecycle row the intake does not hold")
685
+ for ident in sorted(set(lifecycle) & set(want)):
686
+ if lifecycle[ident]["source"] != want[ident] or lifecycle[ident]["event_ids"]:
687
+ errors.append(f"SET_MISMATCH {ident}: its row's source {lifecycle[ident]['source']!r} or events are not the "
688
+ f"intake's ({want[ident]!r}, none)")
689
+ derived = membership_of(rows, findings, non_findings)
690
+ for event in sorted(set(derived) | set(pop["event_membership"])):
691
+ named = pop["event_membership"].get(event)
692
+ if named is not None and named not in PARTITION_CLASSES[1:] and named not in listed:
693
+ errors.append(f"SET_MISMATCH {event}: its membership names {named}, which the population does not list")
694
+ elif named != derived.get(event):
695
+ errors.append(f"SET_MISMATCH {event}: its membership names {named}, and the rows place it in {derived.get(event)}")
696
+ placed = collections.Counter()
697
+ for c in rows:
698
+ placed.update(c["event_ids"])
699
+ for f in findings:
700
+ placed.update(f["event_ids"])
701
+ placed.update(n["event_id"] for n in non_findings)
702
+ subjects = {r["id"] for r in subject_of["events"]}
703
+ missing, extra = sorted(subjects - set(placed)), sorted(set(placed) - subjects)
704
+ twice = sorted(e for e, n in placed.items() if n > 1)
705
+ if missing or extra or twice:
706
+ errors.append(f"SET_MISMATCH the population places the subject's events otherwise: missing {missing[:5]}, not the "
707
+ f"subject's {extra[:5]}, more than once {twice[:5]}")
708
+ for name in ("carried_forward", "not_formed"):
709
+ if pop[name] != subject_of[name]:
710
+ errors.append(f"SET_MISMATCH {name}: the population lists {len(pop[name])}, and the subject {len(subject_of[name])}; "
711
+ "the lists are the subject's")
712
+ counted = population_counts(rows, findings, non_findings, subject_of)
713
+ off = sorted(k for k in set(counted) | set(pop["counts"]) if counted.get(k) != pop["counts"].get(k))
714
+ if off:
715
+ errors.append(f"SET_MISMATCH counts {off}: they are not what the rows and the subject give")
716
+ return errors
717
+
718
+
719
+ def partition_rows(pop):
720
+ """`partition.jsonl`'s rows, one per event of the subject, in event id order: `{event_id, class, candidate_id}`,
721
+ `{event_id, class, finding_id}` or `{event_id, class, reason, duplicate_of}`."""
722
+ finding_of = {e: f["finding_id"] for f in pop["rejected_findings"] for e in f["event_ids"]}
723
+ reason_of = {n["event_id"]: n for n in pop["non_findings"]}
724
+ rows = []
725
+ for event, member in pop["event_membership"].items():
726
+ if member == "rejected_finding":
727
+ rows.append({"event_id": event, "class": "rejected_finding", "finding_id": finding_of[event]})
728
+ elif member == "non_finding":
729
+ rows.append({"event_id": event, "class": "non_finding", "reason": reason_of[event]["reason"],
730
+ "duplicate_of": reason_of[event]["duplicate_of"]})
731
+ else:
732
+ rows.append({"event_id": event, "class": "candidate", "candidate_id": member})
733
+ return rows
734
+
735
+
736
+ # ---- what an accepted answer's candidates carry beside it ----------------------------------------
737
+
738
+ def origin_evidence(run_dir, answer, subject_of):
739
+ """The evidence records of the origin quotes an accepted, resolved answer cites, each verified again against the
740
+ immutable copy as every stored quote is (`evidence.verify`: the copy's hash, the locator, the projection's span);
741
+ one that no longer verifies is RECORD_INTEGRITY. Returns `{origin id: evidence record}` for candidates.json, so a
742
+ later stage verifies the same record (lead decision after X round 1, F3)."""
743
+ cited = sorted({q for k in answer["candidates"] for name in ADMISSION for q in k["admission"][name]["evidence_ids"]
744
+ if q.startswith("origin:")})
745
+ out = {}
746
+ for ident in cited:
747
+ record = subject_of["origins"][ident]["evidence"]
748
+ problems = evidence.verify(run_dir, record)
749
+ if problems:
750
+ raise Refused(f"RECORD_INTEGRITY {ident}: the origin quote a candidate cites no longer verifies: "
751
+ + "; ".join(str(p) for p in problems[:3]))
752
+ out[ident] = record
753
+ return out
754
+
755
+
756
+ # plan WP-09 done-when 4: a type G proposal needs at least three independent lineages resolving its tension the same way
757
+ G_LINEAGES = 3
758
+
759
+
760
+ def lineages(candidate, subject_of):
761
+ """The lineage-count interface (lead decision D6): `(how many independent lineages the instances of a type G
762
+ candidate come from, or None when that is not known here, the basis)`. S5 counts lineages and runs after S4, so
763
+ S4's count is a disclosed stand-in: a claim's S3 unit is one lineage component (the census joins a session's
764
+ members into its unit). The entries of a placed cluster are passed by id (lead decision after X round 1, F2); the
765
+ ledger records each entry's own lineages and not whether two entries share one, so their count is not known."""
766
+ t = candidate["tension"]
767
+ if t["instance_entry_ids"]:
768
+ return None, (f"placed entries {list(t['instance_entry_ids'])}: the ledger's provenance records each entry's own "
769
+ "lineages, not whether two entries share one")
770
+ units = {subject_of["claims"][c]["unit"] for c in t["instance_claim_ids"] if c in subject_of["claims"]}
771
+ return len(units), "the S3 units of the instance claims, one lineage component each: a stand-in until S5 counts lineages"
772
+
773
+
774
+ def evidence_bar(candidate, subject_of):
775
+ """Done-when 4's evidence bar for a type G candidate: at the bar with at least G_LINEAGES lineages, held below it
776
+ otherwise, and held whenever the count is not known (an arc the owner confirmed would also meet it; the
777
+ declaration names none)."""
778
+ count, basis = lineages(candidate, subject_of)
779
+ at_bar = count is not None and count >= G_LINEAGES
780
+ return {"status": "at_bar" if at_bar else "held", "lineages": count, "needed": G_LINEAGES, "basis": basis}
781
+
782
+
783
+ # ---- the stage: its barrier, its bound, its one call and what it leaves (lead decisions D1, D7, D9) ----
784
+
785
+ CASE = "form" # the formation call's class (dispatch.class_key)
786
+ ITEM = "form" # one formation call per run: formation is across sessions and is not sharded (WP-09 stage 0 M9)
787
+ # lead decision D9 (WP-09 stage 0 M9): the output-token cap every formation call declares (CLAUDE_CODE_MAX_OUTPUT_TOKENS,
788
+ # design §3.1), from stage 0's estimate of 10-16k output for 11-36 events. Only S4 reads it, so it is this module's and
789
+ # not the declaration's: `output_caps` holds S3's, which S2 cuts its windows against.
790
+ OUTPUT_CAP = 32_000
791
+ # What S4 reads, each pinned at admission to the record of the stage that produced it (records.run_stage): S3's results,
792
+ # its counts and its follow-up's resolutions, the census the barrier holds the results to, and S2's current library.
793
+ # The event, claim and evidence stores are S3's and are read through S3's own readers, which refuse an edited line.
794
+ INPUTS = ({"artifact": "read-results.json", "producer_stage": "S3"},
795
+ {"artifact": "read.json", "producer_stage": "S3"},
796
+ {"artifact": "observations/resolutions.json", "producer_stage": "S3"},
797
+ {"artifact": "census.json", "producer_stage": "S1"},
798
+ {"artifact": "coverage.json", "producer_stage": "S1"},
799
+ {"artifact": "views.json", "producer_stage": "S2"},
800
+ {"artifact": "inventory/current.json", "producer_stage": "S2"})
801
+ OUTPUTS = ("intake.json", "candidates.json", "partition.jsonl", "population.json", "form.json")
802
+ DRY_PACKET, DRY_RECORD = "form/packet.md", "form/dry.json"
803
+
804
+
805
+ def barrier(document, results):
806
+ """Plan WP-09 done-when 5 as lead decision D1 reads it: S4 runs only over a window S3 accounted for whole. Every
807
+ unit the census made eligible has one result, and every result is terminal (INPUT_PARTIAL naming the unit); a result
808
+ for a unit the census did not make eligible, or two for one, is SET_MISMATCH. A terminal result S3 did not process
809
+ (`read_partial`, `deferred`, `failed`) blocks nothing: it is listed, not formed (`subject`). That S3's record is
810
+ running, partial or stale is refused where S4 is admitted (records.run_stage: INPUT_PARTIAL, INPUT_STALE)."""
811
+ eligible = {census.key_of(e) for e in census.rows(document) if e["status"] == "eligible"}
812
+ got = collections.Counter(r["transcript"] for r in results["results"])
813
+ errors = []
814
+ if results.get("window") != document.get("window"):
815
+ errors.append(f"INPUT_INVALID read-results.json: window {results.get('window')!r}, and the census's is "
816
+ f"{document.get('window')!r}")
817
+ for unit in sorted(eligible - set(got)):
818
+ errors.append(f"INPUT_PARTIAL S3 {unit}: the census made it eligible and read-results.json holds no result for "
819
+ "it; S4 forms only over a window S3 accounted for whole")
820
+ for r in results["results"]:
821
+ if r["status"] not in coverage.TERMINAL:
822
+ errors.append(f"INPUT_PARTIAL S3 {r['transcript']}: its result is {r['status']!r}, not one of the terminal "
823
+ f"statuses {list(coverage.TERMINAL)}")
824
+ extra, twice = sorted(set(got) - eligible), sorted(u for u, n in got.items() if n > 1)
825
+ if extra or twice:
826
+ errors.append(f"SET_MISMATCH read-results.json: results for units the census did not make eligible {extra[:5]}, "
827
+ f"or more than one for a unit {twice[:5]}")
828
+ return errors
829
+
830
+
831
+ def form_budget(seat, seats_path=None, density=None, retry=None):
832
+ """The limits the one formation call keeps (W review of WP-09 r1, F5; lead decision; WP-08e): its packet's driver
833
+ bytes taken as tokens at `density`, the fewest bytes a token covered over the run's own formation calls of the host
834
+ (`dispatch.measured_density`; the floor of a byte a token when none is measured, or when `density` is None), plus
835
+ the host's measured hermetic allowance - the first request - and on top of it one answer at the output cap S4
836
+ declares (OUTPUT_CAP) and the error share of the host's one retry of a refused structured output (`retry`, from
837
+ `dispatch.retry_share`; RETRY_ERROR_TOKENS when None), which is at most what one request of the call takes; then the
838
+ output reservation of that request, within the S4 seat's context capacity as seats.json declares it with its basis
839
+ (`gate.seat_capacity`), at the host version the dispatcher runs. No measured allowance is ALLOWANCE_UNMEASURED; no
840
+ declared capacity is FORM_CAPACITY_UNKNOWN. S3's window bound (`bound.INPUT_BOUND`) bounds a view window and is not
841
+ S4's. Returns `{capacity, capacity_basis, host_version, allowance, output_cap, bytes_per_token, density_basis,
842
+ retry_margin, margin_basis, retries, retries_basis}` - `retries` the host's retries the claim holds, the declared
843
+ `retry.count` else one (W r1, F4), each adding an answer at the output cap and the error share."""
844
+ from runlib import dispatch
845
+ path = gate.SEATS if seats_path is None else pathlib.Path(seats_path)
846
+ held = gate.seats(path)
847
+ host = seat.partition(":")[0]
848
+ entry = (held.get("hosts") or {}).get(host) or {}
849
+ slot = ((entry.get("host_allowance") or {}).get("hermetic")) or {}
850
+ if slot.get("measured") is not True or not isinstance(slot.get("allowance_tokens"), int):
851
+ raise Refused(f"ALLOWANCE_UNMEASURED S4: seats.json holds no measured hermetic allowance for {host}, so the "
852
+ "formation packet has no bound to be held to")
853
+ capacity, basis = gate.seat_capacity(seat, entry.get("version"), path=path)
854
+ if capacity is None:
855
+ raise Refused(f"FORM_CAPACITY_UNKNOWN S4: {basis}, so the formation call has no context capacity to be held to")
856
+ density = density or {"bytes_per_token": dispatch.DENSITY_FLOOR, "basis": f"floor: {dispatch.DENSITY_FLOOR}"}
857
+ retry = retry or {"margin": dispatch.RETRY_ERROR_TOKENS, "margin_basis": "constant: RETRY_ERROR_TOKENS"}
858
+ return {"capacity": capacity, "capacity_basis": basis, "host_version": entry.get("version"),
859
+ "allowance": slot["allowance_tokens"], "output_cap": OUTPUT_CAP, "bytes_per_token": density["bytes_per_token"],
860
+ "density_basis": density["basis"], "retry_margin": retry["margin"], "margin_basis": retry["margin_basis"],
861
+ "retries": retry.get("count", dispatch.RETRIES_CLAIMED),
862
+ "retries_basis": retry.get("count_basis", f"constant: RETRIES_CLAIMED {dispatch.RETRIES_CLAIMED}")}
863
+
864
+
865
+ def tokens_of(driver_bytes, limits):
866
+ """At most how many tokens `driver_bytes` take: the bytes over the fewest bytes per token measured, rounded up."""
867
+ return math.ceil(driver_bytes / limits["bytes_per_token"])
868
+
869
+
870
+ def input_at_most(driver_bytes, limits):
871
+ """`(first, at_most)` input tokens of the formation call that sends `driver_bytes` (`dispatch.input_at_most`)."""
872
+ from runlib import dispatch
873
+ return dispatch.input_at_most(driver_bytes, limits, limits["allowance"], limits["output_cap"], limits["retry_margin"],
874
+ limits.get("retries", dispatch.RETRIES_CLAIMED))
875
+
876
+
877
+ def bound_problems(driver_bytes, limits, form_bound=None, what="the formation packet"):
878
+ """FORM_OVER_BOUND, each by name, when what one request of the call takes at most (`input_at_most`: the bytes as
879
+ tokens, the host allowance, one answer at the output cap and the retry's error share) with the output reservation of
880
+ that request exceeds the seat's capacity, or when the bytes exceed what `form_bound` narrows the bound to."""
881
+ tokens = tokens_of(driver_bytes, limits)
882
+ _first, at_most = input_at_most(driver_bytes, limits)
883
+ need = at_most + limits["output_cap"]
884
+ out = []
885
+ if need > limits["capacity"]:
886
+ out.append(f"FORM_OVER_BOUND S4: {what} takes {driver_bytes} driver bytes, at most {tokens} tokens at "
887
+ f"{limits['bytes_per_token']} bytes each by the density {limits['density_basis']}; with the host allowance "
888
+ f"{limits['allowance']}, one retry's answer at the output cap and its error share {limits['retry_margin']}, "
889
+ f"and the output reservation {limits['output_cap']} that is {need}, over the S4 seat's context capacity "
890
+ f"{limits['capacity']}; formation is one call over the window and is not sharded, so a smaller window is read")
891
+ if form_bound is not None and driver_bytes > form_bound:
892
+ out.append(f"FORM_OVER_BOUND S4: {what} takes {driver_bytes} driver bytes, over the {form_bound} the run narrowed "
893
+ "its bound to")
894
+ return out
895
+
896
+
897
+ def packet_bytes(run_id, seat, text, schema_bytes):
898
+ """The driver bytes of the formation packet, measured as dispatch measures them, under its retry's call id: the
899
+ estimate S4 is admitted on. Each attempt is measured again once reserved, under the id it is given (`run`'s
900
+ packet_check; W review of WP-09 r2, F2)."""
901
+ call_id = f"{run_id}-{STAGE}-{ITEM}-a2"
902
+ return bound.driver_bytes(packet.build(call_id, STAGE, seat, text, schema_bytes), schema_bytes)[0]
903
+
904
+
905
+ def supervisor(run_dir, cells, plan=None):
906
+ """The supervisor a formation call goes through, its cells under `cells` (made mode 700). Live, the pinned runner,
907
+ whose token reaches claude-run only as CLAUDE_RUN_TOKEN_FILE in this process's environment - a path never read
908
+ here, refused by name before anything is reserved when it is not set (TOKEN_FILE_UNSET). With `plan`, a golden
909
+ host's plan (`[{match, answer}]`, dispatch.FAKE_HOST's), realization golden: the host answers from the plan and
910
+ starts no model, and the dispatcher refuses that runner under any other realization."""
911
+ from runlib import dispatch
912
+ if plan is None and not os.environ.get("CLAUDE_RUN_TOKEN_FILE"):
913
+ raise Refused("TOKEN_FILE_UNSET S4: a live formation call's token reaches claude-run only as "
914
+ "CLAUDE_RUN_TOKEN_FILE, and this environment does not set it")
915
+ cells = pathlib.Path(cells)
916
+ cells.mkdir(mode=0o700, parents=True, exist_ok=True)
917
+ if plan is None:
918
+ return dispatch.Supervisor(run_dir, cell_root=cells, realization="live")
919
+ fake, plan = cells / "fake_host.py", pathlib.Path(plan).resolve()
920
+ fake.write_text(dispatch.FAKE_HOST, encoding="utf-8")
921
+ sup = dispatch.Supervisor(run_dir, cell_root=cells, realization="golden")
922
+ sup.runner = lambda host, spec: [sys.executable, str(fake), host, "clean", json.dumps({**spec, "answers": str(plan)})]
923
+ return sup
924
+
925
+
926
+ def run(run_dir, supervisor=None, *, dry=False, index_rows=None, tranche="calibration", form_bound=None,
927
+ ledger_ref=None):
928
+ """S4 over S3's results: the barrier, what it forms from (`subject`), the lifecycle intake code derives
929
+ (lifecycle_intake.build, from the declaration S4 was admitted against), the formation packet held to its bound
930
+ (FORM_OVER_BOUND), then the one call through `supervisor`, its answer checked by the stage (`answer_problems`) and
931
+ read in its labels, and the population (`population`, `population_problems`). Writes `intake.json`,
932
+ `candidates.json`, `partition.jsonl`, `population.json` and `form.json`; a subject with no event makes no call.
933
+
934
+ `dry` stops before the call, with no supervisor: it writes `intake.json` and the packet with its measure
935
+ (`form/packet.md`, `form/dry.json`), and leaves S4's record `partial`, since nothing was formed. A call that ends
936
+ other than accepted leaves `form.json` with its outcome and the record `partial`. The call runs in a calibration
937
+ tranche: it is one call, so its class runs at concurrency one whether or not it was measured before. `form_bound`
938
+ narrows the packet's bound, never widens it: the self-test's way to make a small packet too large. `index_rows`
939
+ are the occasion index's rows (WP-21; golden until it lands)."""
940
+ from runlib import dispatch, stage_read
941
+ run_dir = pathlib.Path(run_dir)
942
+ if not dry and supervisor is None:
943
+ raise Refused("FORM_UNSUPERVISED S4: a formation call goes through a supervisor; without one, run it dry")
944
+ run_id = run_dir.resolve().name
945
+ with records.run_stage(run_dir, STAGE, INPUTS) as stage:
946
+ declaration = stage.declaration
947
+ # the stage's lock is held, so a reservation of S4 still open is a dead run's: closed before any reuse or
948
+ # reservation, its runner stopped when alive and named when it cannot be verified (W review of WP-09 r1, F4)
949
+ interrupted = [] if supervisor is None else supervisor.interrupted(STAGE)
950
+ problems = barrier(census.load(run_dir), records.read_json(run_dir / "read-results.json"))
951
+ if problems:
952
+ raise Refused("\n".join(problems))
953
+ subj = subject(run_dir)
954
+ intake = lifecycle_intake.build(run_dir, declaration, index_rows, ledger_ref=ledger_ref)
955
+ records.write_json(run_dir, run_dir / "intake.json", intake)
956
+ stage.output("intake.json")
957
+ clusters = [{"id": c["candidate_id"], "members": c["members"]} for c in intake["candidates"] if c["source"] == "g_cluster"]
958
+ labels = FormLabels(subj["events"], subj["claims"], clusters)
959
+ text, schema = payload(labels), form_schema()
960
+ schema_bytes = packet.schema_bytes(schema)
961
+ seat = declaration["seats"][STAGE]
962
+ host = seat.partition(":")[0]
963
+ # what the bytes take as tokens, from the run's own calls of the seat, and what a retry adds, from the host's
964
+ # (WP-08e; W r1, F3)
965
+ limits = form_budget(seat, None if supervisor is None else supervisor.seats_path,
966
+ dispatch.measured_density(run_dir, seat, STAGE, CASE, declaration.get("density")),
967
+ dispatch.retry_share(run_dir, host, declaration.get("retry")))
968
+ size = packet_bytes(run_id, seat, text, schema_bytes)
969
+ first, at_most = input_at_most(size, limits)
970
+ summary = {"stage": STAGE, "window": coverage.window_bounds(declaration["window"])[2],
971
+ "declaration_seq": declaration["declaration_seq"], "dry": dry,
972
+ "packet": {"driver_bytes": size, "bytes_per_token": limits["bytes_per_token"],
973
+ "density_basis": limits["density_basis"], "first_request_tokens": first,
974
+ "input_tokens_at_most": at_most, "retry_margin": limits["retry_margin"],
975
+ "margin_basis": limits["margin_basis"], "retries_claimed": limits["retries"],
976
+ "allowance_tokens": limits["allowance"], "output_cap": OUTPUT_CAP,
977
+ "capacity": limits["capacity"], "correction_room": stage_read.CORRECTION_ROOM,
978
+ "narrowed_to": form_bound,
979
+ "labels": {"events": len(labels.events), "claims": len(labels.claims), "quotes": len(labels.quotes),
980
+ "sessions": len(labels.sessions), "clusters": len(labels.clusters)}},
981
+ "subject": {"events": len(subj["events"]), "claims": len(subj["claims"]),
982
+ "carried_forward": len(subj["carried_forward"]), "units": dict(subj["units"]),
983
+ "not_formed": len(subj["not_formed"]),
984
+ "events_not_formed": sum(u["events"] for u in subj["not_formed"])},
985
+ "intake": dict(intake["counts"]), "interrupted": interrupted,
986
+ # what the run measured a token to cover, per seat and kind, in the shape a later declaration takes
987
+ # (WP-08e); taken again after the call
988
+ "density_table": dispatch.measured_table(run_dir)}
989
+ # admitted with room for its one retry's correction; every attempt is measured again as it is sent (W r1, F3)
990
+ problems = bound_problems(size + stage_read.CORRECTION_ROOM, limits, form_bound,
991
+ f"the formation packet ({len(labels.events)} events, {len(labels.claims)} claims, "
992
+ f"{len(labels.quotes)} quotes) with its retry's correction room")
993
+ if problems:
994
+ raise Refused("\n".join(problems))
995
+ if dry:
996
+ records.write_text(run_dir, run_dir / DRY_PACKET, text)
997
+ records.write_json(run_dir, run_dir / DRY_RECORD, summary)
998
+ stage.output(DRY_PACKET)
999
+ stage.output(DRY_RECORD)
1000
+ stage.record["status"] = "partial"
1001
+ return summary
1002
+ if labels.events or labels.clusters:
1003
+ episode = declaration["budget"]["per_episode"]
1004
+ out = supervisor.item(STAGE, ITEM, seat, text, schema, case_type=CASE,
1005
+ caps={"tokens": episode["tokens"], "compactions": episode["compactions"]},
1006
+ view_window=False, tranche=tranche, max_output_tokens=OUTPUT_CAP,
1007
+ stage_check=judge(labels, limits["capacity"]), resume=True,
1008
+ context_capacity=limits["capacity"],
1009
+ packet_check=lambda built: bound_problems(bound.driver_bytes(built, schema_bytes)[0],
1010
+ limits, form_bound, "this attempt's packet"))
1011
+ call = {"item": ITEM, "outcome": out["outcome"], "codes": out.get("codes", []),
1012
+ "attempts": stage_read.attempts_of(out), "reused": out.get("reused")}
1013
+ if out["outcome"] != "accepted":
1014
+ summary["call"] = call
1015
+ summary["density_table"] = dispatch.measured_table(run_dir)
1016
+ records.write_json(run_dir, run_dir / "form.json", summary)
1017
+ stage.output("form.json")
1018
+ stage.record["status"] = "partial"
1019
+ return summary
1020
+ call["call_id"] = stage_read.call_id_of(out["accepted"])
1021
+ rows = usage_rows(out["accepted"]) # read once, by name; the guard below judges these rows
1022
+ call["observed"] = observed(out["accepted"], limits, rows)
1023
+ if call["observed"]["within_claim"] is False:
1024
+ # W r1, F4: a call past its claim is not a completed stage. The dispatcher stops the run on it
1025
+ # (CLAIM_EXCEEDED) and the call fails before this; what reaches here is an attempt reused under a
1026
+ # declaration whose claim it now exceeds, or a call no claim was recorded for - so S4 stops the run on
1027
+ # it itself. The stop is offered whatever the ledger already holds: a record of an earlier stop that an
1028
+ # amendment lifted does not stand, and keeping by standing decides what does (W r2, F5). Its measured
1029
+ # values stay in its own records.
1030
+ o = call["observed"]
1031
+ supervisor.stop_on_claim(call["call_id"], rows, form_claim(o["driver_bytes"], limits))
1032
+ raise RunStopped(f"CLAIM_EXCEEDED {call['call_id']}: {'; '.join(o['breaches'])} - past the claim it is "
1033
+ "held to; S4 is not completed on it")
1034
+ answer = labels.resolve(gate.accepted(out["accepted"], judged=True))
1035
+ else:
1036
+ call = {"item": ITEM, "outcome": "not_called", "codes": [], "attempts": [], "reused": None,
1037
+ "why": "the subject holds no event and the intake no placed cluster, so nothing is formed and no call "
1038
+ "is made"}
1039
+ answer = {"candidates": [], "rejected_findings": [], "non_findings": []}
1040
+ summary["density_table"] = dispatch.measured_table(run_dir)
1041
+ pop = population(answer, subj, run_id, intake["candidates"])
1042
+ problems = population_problems(pop, subj, intake["candidates"])
1043
+ if problems:
1044
+ raise Refused("\n".join(problems))
1045
+ cited = origin_evidence(run_dir, answer, subj)
1046
+ session_of = {r["id"]: r["session"] for r in subj["events"]}
1047
+ formed = [{"candidate_id": sid("k", run_id, k["candidate_id"]), "label": k["candidate_id"], "source": "formed",
1048
+ **{f: k[f] for f in ("lesson", "type", "situation", "action", "exception", "admission", "tension")},
1049
+ "event_ids": list(k["event_ids"]), "sessions": sorted({session_of[e] for e in k["event_ids"]}),
1050
+ "evidence_bar": evidence_bar(k, subj) if k["type"] == "G" else None,
1051
+ "lifecycle": None} for k in answer["candidates"]]
1052
+ lifecycle = [{"candidate_id": c["candidate_id"], "source": c["source"], "event_ids": [], "sessions": [],
1053
+ "lifecycle": c} for c in intake["candidates"]]
1054
+ findings = [{"finding_id": sid("r", run_id, r["finding_id"]), "label": r["finding_id"],
1055
+ **{f: r[f] for f in ("finding", "event_ids", "failed", "reason")}} for r in answer["rejected_findings"]]
1056
+ records.write_json(run_dir, run_dir / "candidates.json", {"candidates": formed + lifecycle, "rejected_findings": findings,
1057
+ "origin_evidence": cited})
1058
+ records.write_text(run_dir, run_dir / "partition.jsonl",
1059
+ "".join(json.dumps(r, sort_keys=True, ensure_ascii=False) + "\n" for r in partition_rows(pop)))
1060
+ records.write_json(run_dir, run_dir / "population.json", pop)
1061
+ summary.update(call=call, population=pop["counts"])
1062
+ records.write_json(run_dir, run_dir / "form.json", summary)
1063
+ for name in OUTPUTS[1:]:
1064
+ stage.output(name)
1065
+ return summary
1066
+
1067
+
1068
+ def report_lines(summary):
1069
+ """What the driver prints of a run of S4: counts, bytes and codes, never a claim, a quote or a lesson."""
1070
+ p, s = summary["packet"], summary["subject"]
1071
+ lines = [f"S4 form{' (dry)' if summary['dry'] else ''}: window {summary['window']}, declaration_seq "
1072
+ f"{summary['declaration_seq']}",
1073
+ f"subject: {s['events']} events, {s['claims']} claims, {s['carried_forward']} carried forward; units {s['units']}; "
1074
+ f"not formed: {s['not_formed']} units, {s['events_not_formed']} events",
1075
+ "intake: " + ", ".join(f"{k} {v}" for k, v in summary["intake"].items()),
1076
+ f"packet: {p['driver_bytes']} driver bytes, density {p['density_basis']} at {p['bytes_per_token']} bytes each; "
1077
+ f"first request {p['first_request_tokens']} input tokens with the host allowance, at most {p['input_tokens_at_most']} "
1078
+ f"in one request with a retry's answer and error share {p['retry_margin']}; output cap {p['output_cap']}; seat "
1079
+ f"capacity {p['capacity']}; labels {p['labels']}"]
1080
+ if "call" in summary:
1081
+ c = summary["call"]
1082
+ lines.append(f"call: {c['outcome']}{' ' + ' '.join(c['codes']) if c['codes'] else ''}"
1083
+ f"{' (reused ' + c['reused'] + ')' if c.get('reused') else ''}")
1084
+ o = c.get("observed")
1085
+ if o:
1086
+ lines.append(f"observed: first request {o.get('input_tokens')} input tokens ({o.get('bytes_per_token')} bytes "
1087
+ f"each); {o.get('requests')} main requests, the largest {o.get('largest_input')}, within the claim "
1088
+ f"{o.get('within_claim')}")
1089
+ if "population" in summary:
1090
+ lines.append("population: " + json.dumps(summary["population"], sort_keys=True))
1091
+ for seat, kinds in sorted((summary.get("density_table") or {}).items()):
1092
+ for kind, entry in sorted(kinds.items()):
1093
+ lines.append(f"measured density: {seat} {kind}, {entry['samples']} calls, the fewest {entry['bytes_per_token']} "
1094
+ f"bytes each, in {entry['measured_in']}")
1095
+ return lines
1096
+
1097
+ # ---- self-test -----------------------------------------------------------------------------------
1098
+
1099
+ def fx_rows():
1100
+ """Three sessions' events, as the window's reading left them: a correction the person made in each of three sessions
1101
+ (the same tension resolved the same way), one command error and its fix, and a routine step. Every line is the
1102
+ fixture's own."""
1103
+ quotes = {
1104
+ "e-1": "user: stop and ask before you push; I said not to push",
1105
+ "e-2": "assistant: understood, I will not push without asking",
1106
+ "e-3": "user: don't push yet, ask me first",
1107
+ "e-4": "user: never push on your own, ask",
1108
+ "e-5": "bash: zsh: no matches found: --include=*.sh",
1109
+ "e-6": "assistant: quoting the glob fixed it: grep --include='*.sh'",
1110
+ "e-7": "bash: git status (clean)",
1111
+ }
1112
+ claim = lambda fact, *ev: {"fact": fact, "interpretation": "", "uncertainty": "",
1113
+ "quotes": [{"evidence_id": e, "record": f"{n}/message/content/0/text", "window_role": "in_window",
1114
+ "text": quotes[e]} for n, e in enumerate(ev, 3)]}
1115
+ claims = {"c-a1": claim("The person stopped a push and asked to be asked first.", "e-1"),
1116
+ "c-a2": claim("The agent agreed not to push without asking.", "e-2"),
1117
+ "c-b1": claim("The person asked again not to push before asking.", "e-3"),
1118
+ "c-c1": claim("The person said never to push without asking.", "e-4"),
1119
+ "c-c2": claim("A grep with an unquoted glob failed under zsh.", "e-5"),
1120
+ "c-c3": claim("Quoting the glob fixed the grep.", "e-6"),
1121
+ "c-c4": claim("The agent checked the status of the tree.", "e-7")}
1122
+ event = lambda ident, session, kind, own, out: {"id": ident, "session": session, "kind": kind,
1123
+ "description": f"a {kind} and what came of it", "claim_ids": own,
1124
+ "outcome_claim_ids": out}
1125
+ events = [event("v-a", "claude:aaaa", "correction", ["c-a1"], ["c-a2"]),
1126
+ event("v-b", "claude:bbbb", "correction", ["c-b1"], []),
1127
+ event("v-c", "codex:cccc", "correction", ["c-c1"], []),
1128
+ event("v-d", "codex:cccc", "error", ["c-c2"], ["c-c3"]),
1129
+ event("v-e", "codex:cccc", "check", ["c-c4"], [])]
1130
+ return events, claims
1131
+
1132
+
1133
+ def fx_answer():
1134
+ """A conforming answer to the fixture's packet, in its labels: v1-v3 one type G candidate, v4 a type B candidate,
1135
+ v5 a routine non-finding."""
1136
+ req = lambda claims=(), quotes=(): {"basis": "shown", "claim_ids": list(claims), "evidence_ids": list(quotes)}
1137
+ admission = lambda: {name: req(["c1"], ["q1"]) if name == "observed_event" else req() for name in ADMISSION}
1138
+ empty = {"sides": [], "ordering": "", "forbids": "", "instance_claim_ids": [], "instance_entry_ids": [], "cluster": ""}
1139
+ return {"candidates": [
1140
+ {"candidate_id": "k1", "lesson": "Ask before pushing", "type": "G", "situation": "a change is ready to push",
1141
+ "action": "ask the person first", "exception": "the person asked for the push in this turn",
1142
+ "admission": admission(), "event_ids": ["v1", "v2", "v3"],
1143
+ "tension": {"sides": ["speed of delivery", "the person's control of the remote"],
1144
+ "ordering": "control of the remote over speed", "forbids": "pushing without asking",
1145
+ "instance_claim_ids": ["c1", "c3", "c4"], "instance_entry_ids": [], "cluster": ""}},
1146
+ {"candidate_id": "k2", "lesson": "Quote globs under zsh", "type": "B", "situation": "a shell argument holds a glob",
1147
+ "action": "quote it", "exception": "the glob is meant to expand", "admission": admission(),
1148
+ "event_ids": ["v4"], "tension": dict(empty)}],
1149
+ "rejected_findings": [],
1150
+ "non_findings": [{"event_id": "v5", "reason": "routine_step", "duplicate_of": ""}]}
1151
+
1152
+
1153
+ # two placed clusters as the intake hands them on (lifecycle_intake.upward_clusters' members): what u1.1 ... and u2.1 ...
1154
+ # label in the packet
1155
+ FX_CLUSTERS = [
1156
+ {"id": "cluster-1", "members": [{"entry": f"S-{n}", "lesson": lesson, "evidence": evidence, "independent_lineages": lineages}
1157
+ for n, (lesson, evidence, lineages) in enumerate((
1158
+ ("Ask before acting on shared state", [{"session": "claude:s-1", "locator": "unavailable"}], "unavailable"),
1159
+ ("Ask before deleting a branch", [{"claim_id": "c-x1", "evidence_id": "e-x1"}], 1),
1160
+ ("Ask before force-pushing", [], "unavailable")), 1)]},
1161
+ {"id": "cluster-2", "members": [{"entry": f"T-{n}", "lesson": f"Quote the glob, case {n}", "evidence": [],
1162
+ "independent_lineages": "unavailable"} for n in (1, 2, 3)]}]
1163
+
1164
+
1165
+ FX_MARKERS = {"settled": "Settled in its window.", "joined": "Joined later.", "open": "Left open.",
1166
+ "child": "Settled in the child.", "codex": "Codex waits."}
1167
+
1168
+
1169
+ def fx_s3(root, density=None):
1170
+ """A golden S3 run over S2's golden corpus (views.golden: a Claude session with its child, and a Codex session),
1171
+ read through S3 itself with its golden host, no model called. The Claude unit is processed: an event its window
1172
+ resolves, one the stitch joins to a later claim, one no claim resolves (handed on), the event the previous window
1173
+ left pending (`pe-1`), resolved by the stitch, and one in the child. The Codex unit's stitch fails twice, so the
1174
+ unit ends `read_partial` with its one event still pending. The run's checkout pins `fx_ledger_s4` and S2's inventory
1175
+ part leaves `lifecycle_intake.FX_LIBRARY` (`fx_inventory`), so S4 can run over it. `density` is the declaration's
1176
+ density table (WP-08e). Returns `(run_dir, summary)`."""
1177
+ from runlib import stage_read as sr
1178
+
1179
+ def later_quote(doc):
1180
+ rec = doc["records"][-1]
1181
+ text, occurrence = sr.fx_quote(rec)
1182
+ return {"quote_id": "q2", "entry": views.eid(rec), "text": text, **({"occurrence": occurrence} if occurrence is not None else {})}
1183
+
1184
+ def answers(where, doc, rows, parts):
1185
+ first = doc["records"][0]
1186
+ view, n = where.split("/")[0], where.split("/")[-1]
1187
+
1188
+ def ev(outcome, marker):
1189
+ return {"event_id": f"v{len(made) + 1}", "kind": "request", "at_record": views.eid(first), "claim_ids": ["c1"],
1190
+ "outcome": outcome, "description": FX_MARKERS[marker]}
1191
+ made = []
1192
+ if "/x/" in where:
1193
+ return [((), sr.fx_answer(doc, rows, fact="The omitted middle holds the outcome."))]
1194
+ if view.endswith("0001") and n == "1":
1195
+ made.append(ev("resolved", "settled"))
1196
+ made.append(ev("pending", "joined"))
1197
+ elif view.endswith("0001") and n == "2":
1198
+ made.append(ev("pending", "open"))
1199
+ elif view.endswith("0001") and n == "3":
1200
+ return [((), sr.fx_answer(doc, rows, fact="OUTCOME: the change landed."))]
1201
+ elif view.endswith("0002"):
1202
+ made.append(ev("resolved", "child"))
1203
+ elif view.startswith("codex_"):
1204
+ made.append(ev("pending", "codex"))
1205
+ return [((), sr.fx_answer(doc, rows, events=made, extra_quotes=[later_quote(doc)]))]
1206
+ return [((), sr.fx_answer(doc, rows, events=made))]
1207
+
1208
+ def resolve(event, claims):
1209
+ if event.get("description", "").startswith(FX_MARKERS["joined"]) or "carried_from" in event:
1210
+ return sr.fx_joined(event, claims, "OUTCOME:")
1211
+ return None
1212
+ run_dir, sup, _made = sr.fx_reader(root / "s3", "s3", answers, expanding=lambda m: m["forced_by"] != "none",
1213
+ resolve=resolve, bad=lambda item: "codex" in item, ledger_doc=fx_ledger_s4(),
1214
+ **({"density": density} if density is not None else {}))
1215
+ summary = sr.run(run_dir, sup)
1216
+ fx_inventory(run_dir)
1217
+ return run_dir, summary
1218
+
1219
+
1220
+ def fx_two_windows(root):
1221
+ """Two scratch runs of S3 over consecutive windows (stage_read's done-when 4 corpus). Run N leaves the last request
1222
+ of its window pending (line 10) and leaves the event views.golden plants (`pe-1`, line 5) pending too; its results
1223
+ are folded into the coverage state run N+1 starts from. Run N+1, over the next window with one record appended,
1224
+ shows both at their first records: it joins the line-10 event to the outcome it reads, and leaves `pe-1`
1225
+ unresolved - an older event revisited and still pending (X round 1, F1). Returns `(run N+1, the ids run N left
1226
+ pending)`."""
1227
+ from runlib import stage_read as sr
1228
+
1229
+ def answers_n(where, doc, rows, parts):
1230
+ answer = sr.fx_answer(doc, rows)
1231
+ last = next((r for r in doc["records"] if r["line"] == 10), None)
1232
+ if last is not None and doc["overlap"]["next"]:
1233
+ after = doc["overlap"]["next"][0]
1234
+ a0, _b0 = after["segments"][0]["view"]
1235
+ answer["events"].append({"event_id": "v1", "kind": "request", "at_record": views.eid(last), "claim_ids": ["c1"],
1236
+ "outcome": "pending", "description": "The last request of the window; its answer comes after it."})
1237
+ answer["quotes"].append({"quote_id": "q2", "entry": after["entry"], "text": after["text"][a0:a0 + 24]})
1238
+ answer["claims"].append({"claim_id": "c2", "fact": "OUTCOME: the week after holds the answer.",
1239
+ "interpretation": "", "uncertainty": "", "evidence_ids": ["q2"], "call_id": "<CALL-ID>"})
1240
+ return [((), answer)]
1241
+
1242
+ def answers_n1(where, doc, rows, parts):
1243
+ if doc["records"][0]["line"] == 11 and doc["overlap"]["prev"]:
1244
+ answer = sr.fx_answer(doc, rows, fact="OUTCOME: the week after holds the answer.")
1245
+ answer["quotes"].append(sr.fx_overlap_quote(doc))
1246
+ answer["claims"][0]["evidence_ids"].append("q2")
1247
+ return [((), answer)]
1248
+ return [((), sr.fx_answer(doc, rows))]
1249
+ run_n, sup_n, _ = sr.fx_reader(root / "n", "n", answers_n, expanding=lambda m: m["forced_by"] != "none")
1250
+ sr.run(run_n, sup_n)
1251
+ handed = records.read_json(run_n / "read-results.json")
1252
+ state_n = census.reconcile(census.load(run_n), coverage.load(run_n / "coverage.json")[0], handed["results"], "periodic")[1]
1253
+ appended = lambda: views.fx_main_records() + [views.fx_assistant(views.fx_stamp(10, hour=1), "and one more the day after")] # noqa: E731
1254
+ run_n1, sup_n1, _ = sr.fx_reader(root / "n1", "n1", answers_n1, resolve=sr.fx_resolving({10: "OUTCOME:"}, beside=True),
1255
+ window=sr.FX_NEXT_WINDOW, state=state_n, owned=[[10, 13]], main_records=appended,
1256
+ prefix_ok=True)
1257
+ sr.run(run_n1, sup_n1)
1258
+ return run_n1, sorted(p["id"] for p in state_n["pending_events"])
1259
+
1260
+
1261
+ def codex_unit_of(results):
1262
+ """The Codex unit of the golden window's results."""
1263
+ return next((r["transcript"] for r in results["results"] if r["transcript"].startswith("codex:")), "codex:?")
1264
+
1265
+
1266
+ def fx_ledger_s4():
1267
+ """lifecycle_intake's ledger of every intake case, its due incubates expiring the day before views.FX_WINDOW opens:
1268
+ S3 shows no observation of them (it shows an expiry on or after the window's first day), and S4 takes them as due
1269
+ (an expiry on or before its last)."""
1270
+ return lifecycle_intake.fx_ledger("2026-09-30", due_expiry="2026-09-30")
1271
+
1272
+
1273
+ def fx_inventory(run_dir, units=None):
1274
+ """S2's inventory part as a golden run leaves it: `inventory/current.json` holding the library's units
1275
+ (`lifecycle_intake.FX_LIBRARY` by default), recorded as the part's output."""
1276
+ with records.run_stage(run_dir, "S2", [{"artifact": "census.json", "producer_stage": "S1"}], part="inventory") as stage:
1277
+ records.write_json(run_dir, pathlib.Path(run_dir) / "inventory" / "current.json",
1278
+ {"units": list(lifecycle_intake.FX_LIBRARY if units is None else units)})
1279
+ stage.output("inventory/current.json")
1280
+
1281
+
1282
+ def fx_partition(event_labels):
1283
+ """A conforming answer placing each of `event_labels` once: all but the last two one type C candidate, the second to
1284
+ last a rejected finding failing `bounded`, the last a routine non-finding."""
1285
+ req = {"basis": "shown", "claim_ids": [], "evidence_ids": []}
1286
+ empty = {"sides": [], "ordering": "", "forbids": "", "instance_claim_ids": [], "instance_entry_ids": [], "cluster": ""}
1287
+ return {"candidates": [{"candidate_id": "k1", "lesson": "Say when a change landed", "type": "C", "situation": "s",
1288
+ "action": "a", "exception": "e", "admission": {n: dict(req) for n in ADMISSION},
1289
+ "event_ids": list(event_labels[:-2]), "tension": dict(empty)}],
1290
+ "rejected_findings": [{"finding_id": "r1", "finding": "f", "event_ids": [event_labels[-2]], "failed": ["bounded"],
1291
+ "reason": "specific to the task"}],
1292
+ "non_findings": [{"event_id": event_labels[-1], "reason": "routine_step", "duplicate_of": ""}]}
1293
+
1294
+
1295
+ def fx_form_plan(run_dir, path):
1296
+ """The golden host's plan for S4 over a run `fx_s3` made: one row, matched by the packet's events as S4 lists them,
1297
+ answering `fx_partition` in the packet's labels, its type C candidate citing the origin quote of the carried event
1298
+ the stitch resolved, and beside it a type G candidate distilled from the intake's one placed cluster (u1, whose
1299
+ first three entries it cites), with no event. Read from S3's stores as S4 reads them (`subject`)."""
1300
+ got = subject(run_dir)
1301
+ labels = FormLabels(got["events"], got["claims"])
1302
+ answer = fx_partition(list(labels.events))
1303
+ answer["candidates"][0]["admission"]["observed_event"]["evidence_ids"] = [
1304
+ next(label for label, ident in labels.quotes.items() if ident.startswith("origin:"))]
1305
+ answer["candidates"].append({**copy.deepcopy(answer["candidates"][0]), "candidate_id": "k2", "type": "G", "event_ids": [],
1306
+ "admission": {n: {"basis": "shown", "claim_ids": [], "evidence_ids": []} for n in ADMISSION},
1307
+ "tension": {"sides": ["run the suite first", "answer fast"], "ordering": "the suite first",
1308
+ "forbids": "answering before the suite ran", "instance_claim_ids": [],
1309
+ "instance_entry_ids": ["u1.1", "u1.2", "u1.3"], "cluster": "u1"}})
1310
+ pathlib.Path(path).write_text(json.dumps([{"match": [labels.events_text()], "answer": answer}]), encoding="utf-8")
1311
+ return path
1312
+
1313
+ def self_test():
1314
+ failures, ran = [], []
1315
+
1316
+ def control(name, condition, detail=""):
1317
+ ran.append(name)
1318
+ if not condition:
1319
+ failures.append(f"{name}: {detail}")
1320
+
1321
+ def guarded(action, default):
1322
+ """What a control reads, or `default` when its subject raised: the control then fails by its own name."""
1323
+ try:
1324
+ return action()
1325
+ except Exception as exc: # noqa: BLE001 - reported by the control that reads the default
1326
+ return default if not callable(default) else default(exc)
1327
+
1328
+ def refusal(action):
1329
+ try:
1330
+ action()
1331
+ except Refused as exc:
1332
+ return str(exc)
1333
+ except Exception as exc: # noqa: BLE001 - a control whose subject raises anything else fails by its own name
1334
+ return f"RAISED {exc!r}"
1335
+ return ""
1336
+
1337
+ events, claims = fx_rows()
1338
+ labels = guarded(lambda: FormLabels(events, claims, FX_CLUSTERS),
1339
+ None)
1340
+ good = fx_answer()
1341
+
1342
+ def mutated(change):
1343
+ out = copy.deepcopy(good)
1344
+ change(out)
1345
+ return out
1346
+
1347
+ def problems(answer):
1348
+ return guarded(lambda: answer_problems(labels, answer), lambda exc: [f"RAISED {exc!r}"])
1349
+
1350
+ def schema_of(answer):
1351
+ return guarded(lambda: schema_problems(answer), lambda exc: [f"RAISED {exc!r}"])
1352
+
1353
+ # positive controls: the fixture's answer passes the schema and the stage's check, and resolves to stored ids
1354
+ control("a conforming answer passes the schema and the stage's check",
1355
+ labels is not None and schema_of(good) == [] and problems(good) == [],
1356
+ f"schema={schema_of(good)[:3]} check={problems(good)[:3]}")
1357
+ resolved = guarded(lambda: labels.resolve(good), None)
1358
+ control("an accepted answer resolves to the stored event, claim and quote ids",
1359
+ resolved is not None and resolved["candidates"][0]["event_ids"] == ["v-a", "v-b", "v-c"]
1360
+ and resolved["candidates"][0]["tension"]["instance_claim_ids"] == ["c-a1", "c-b1", "c-c1"]
1361
+ and resolved["candidates"][0]["admission"]["observed_event"]["evidence_ids"] == ["e-1"]
1362
+ and resolved["non_findings"][0]["event_id"] == "v-e", f"{resolved and resolved['candidates'][0]['event_ids']}")
1363
+
1364
+ # done-when 2: all eight admission fields, typed; a rejected finding names the requirement it fails
1365
+ seven = mutated(lambda a: a["candidates"][1]["admission"].pop("audience"))
1366
+ control("done-when 2: a candidate with seven admission fields is SCHEMA_INVALID",
1367
+ any(p.startswith("SCHEMA_INVALID") and "audience" in p for p in schema_of(seven)), f"{schema_of(seven)}")
1368
+ untyped = mutated(lambda a: a["candidates"][1]["admission"]["bounded"].update(basis=5))
1369
+ control("done-when 2: an admission field of the wrong type is SCHEMA_INVALID",
1370
+ any(p.startswith("SCHEMA_INVALID") for p in schema_of(untyped)), f"{schema_of(untyped)}")
1371
+ finding = {"finding_id": "r1", "finding": "always use this repo's script", "event_ids": ["v5"], "failed": ["bounded"],
1372
+ "reason": "specific to this task"}
1373
+ with_finding = mutated(lambda a: (a["rejected_findings"].append(finding), a["non_findings"].clear()))
1374
+ control("done-when 2: a rejected finding naming the requirement it fails passes",
1375
+ schema_of(with_finding) == [] and problems(with_finding) == [],
1376
+ f"{schema_of(with_finding)} {problems(with_finding)}")
1377
+ unnamed = mutated(lambda a: (a["rejected_findings"].append({**finding, "failed": []}), a["non_findings"].clear()))
1378
+ control("done-when 2: a rejected finding naming no failed requirement is SCHEMA_INVALID",
1379
+ any(p.startswith("SCHEMA_INVALID") and "failed" in p for p in schema_of(unnamed)), f"{schema_of(unnamed)}")
1380
+ other = mutated(lambda a: (a["rejected_findings"].append({**finding, "failed": ["clarity"]}), a["non_findings"].clear()))
1381
+ control("done-when 2: a rejected finding naming a requirement outside the eight is SCHEMA_INVALID",
1382
+ any(p.startswith("SCHEMA_INVALID") for p in schema_of(other)), f"{schema_of(other)}")
1383
+
1384
+ # done-when 1, the schema's half: a non-finding's reason is one of the fixed list
1385
+ off_list = mutated(lambda a: a["non_findings"][0].update(reason="not_interesting"))
1386
+ control("done-when 1: a non-finding reason outside the list is SCHEMA_INVALID",
1387
+ any(p.startswith("SCHEMA_INVALID") and "reason" in p for p in schema_of(off_list)), f"{schema_of(off_list)}")
1388
+ dup_none = mutated(lambda a: a["non_findings"][0].update(reason=DUPLICATE))
1389
+ dup_self = mutated(lambda a: a["non_findings"][0].update(reason=DUPLICATE, duplicate_of="v5"))
1390
+ dup_other = mutated(lambda a: a["non_findings"][0].update(duplicate_of="v4"))
1391
+ dup_good = mutated(lambda a: a["non_findings"][0].update(reason=DUPLICATE, duplicate_of="v4"))
1392
+ control("a duplicate naming no other event, or itself, is NON_FINDING_DUPLICATE",
1393
+ all(any(p.startswith("NON_FINDING_DUPLICATE") for p in problems(x)) for x in (dup_none, dup_self))
1394
+ and problems(dup_good) == [], f"{problems(dup_none)} {problems(dup_self)} {problems(dup_good)}")
1395
+ control("another reason naming an event is NON_FINDING_DUPLICATE",
1396
+ any(p.startswith("NON_FINDING_DUPLICATE") for p in problems(dup_other)), f"{problems(dup_other)}")
1397
+
1398
+ # done-when 4: the anti-abstraction guard, each part by name
1399
+ def g_with(**changes):
1400
+ return mutated(lambda a: a["candidates"][0]["tension"].update(changes))
1401
+ for what, answer, needle in (
1402
+ ("one side", g_with(sides=["speed of delivery"]), "/tension/sides"),
1403
+ ("two equal sides", g_with(sides=["speed", "speed"]), "/tension/sides"),
1404
+ ("no ordering", g_with(ordering=" "), "/tension/ordering"),
1405
+ ("nothing it forbids", g_with(forbids=""), "/tension/forbids"),
1406
+ ("two instances", g_with(instance_claim_ids=["c1", "c3"]), "/tension/instance_claim_ids")):
1407
+ found = problems(answer)
1408
+ control(f"done-when 4: a type G candidate with {what} is G_ANTI_ABSTRACTION",
1409
+ any(p.startswith("G_ANTI_ABSTRACTION") and needle in p for p in found), f"{found}")
1410
+ unknown_instance = g_with(instance_claim_ids=["c1", "c3", "c99"])
1411
+ control("done-when 4: an instance the packet does not show is UNKNOWN_LABEL and counts for nothing",
1412
+ any(p.startswith("UNKNOWN_LABEL 'c99'") for p in problems(unknown_instance))
1413
+ and any(p.startswith("G_ANTI_ABSTRACTION") for p in problems(unknown_instance)), f"{problems(unknown_instance)}")
1414
+ tension_b = mutated(lambda a: a["candidates"][1]["tension"].update(ordering="quoting over brevity"))
1415
+ control("a tension on a candidate of another type is TENSION_OUTSIDE_G",
1416
+ any(p.startswith("TENSION_OUTSIDE_G candidates/k2") for p in problems(tension_b)), f"{problems(tension_b)}")
1417
+ clustered = g_with(cluster="u1")
1418
+ control("a type G candidate may name the placed cluster the packet shows",
1419
+ problems(clustered) == [] and guarded(lambda: labels.resolve(clustered)["candidates"][0]["tension"]["cluster"],
1420
+ None) == "cluster-1", f"{problems(clustered)}")
1421
+
1422
+ # X round 1, F2 (lead decision): a principle distilled from a placed cluster alone cites that cluster's entries
1423
+ alone = guarded(lambda: FormLabels([], {}, FX_CLUSTERS), None)
1424
+ req0 = {"basis": "the placed entries show it", "claim_ids": [], "evidence_ids": []}
1425
+
1426
+ def cluster_g(entries, cluster="u1", kind="G", events=()):
1427
+ tension = ({"sides": ["asking first", "moving fast"], "ordering": "asking first over moving fast",
1428
+ "forbids": "acting on shared state unasked", "instance_claim_ids": [], "instance_entry_ids": list(entries),
1429
+ "cluster": cluster} if kind == "G" else
1430
+ {"sides": [], "ordering": "", "forbids": "", "instance_claim_ids": [], "instance_entry_ids": [], "cluster": ""})
1431
+ return {"candidates": [{"candidate_id": "k1", "lesson": "Ask before acting on shared state", "type": kind,
1432
+ "situation": "an action changes state others share", "action": "ask first",
1433
+ "exception": "the person asked for it in this turn", "admission": {n: dict(req0) for n in ADMISSION},
1434
+ "event_ids": list(events), "tension": tension}],
1435
+ "rejected_findings": [], "non_findings": []}
1436
+
1437
+ def alone_problems(answer):
1438
+ return guarded(lambda: answer_problems(alone, answer), lambda exc: [f"RAISED {exc!r}"])
1439
+ from_three = cluster_g(["u1.1", "u1.2", "u1.3"])
1440
+ control("F2: a type G candidate distilled from a placed cluster, with no event and no claim in the window, citing three "
1441
+ "of its entries, passes the schema and the check, and resolves to the entries' ids",
1442
+ alone is not None and schema_of(from_three) == [] and alone_problems(from_three) == []
1443
+ and guarded(lambda: alone.resolve(from_three)["candidates"][0]["tension"]["instance_entry_ids"], None) == ["S-1", "S-2", "S-3"],
1444
+ f"{schema_of(from_three)} {alone_problems(from_three)}")
1445
+ from_two = cluster_g(["u1.1", "u1.2"])
1446
+ control("F2: a cluster G candidate citing two of its entries is G_ANTI_ABSTRACTION",
1447
+ any(p.startswith("G_ANTI_ABSTRACTION candidates/k1/tension/instance_entry_ids") for p in alone_problems(from_two)),
1448
+ f"{alone_problems(from_two)}")
1449
+ foreign = cluster_g(["u2.1", "u2.2", "u2.3"], cluster="u1")
1450
+ control("F2: entries of another cluster are no instances of the one a candidate names (G_ANTI_ABSTRACTION)",
1451
+ any("are not entries of the cluster" in p for p in alone_problems(foreign)), f"{alone_problems(foreign)}")
1452
+ def entries_beside_claims(entries):
1453
+ """The fixture's type G candidate, its three claims kept, made a cluster G citing `entries` and resting on no
1454
+ event: its events become non-findings, so the partition holds (X round 2, F1)."""
1455
+ def change(a):
1456
+ k = a["candidates"][0]
1457
+ k["tension"].update(cluster="u1", instance_entry_ids=list(entries))
1458
+ a["non_findings"] += [{"event_id": v, "reason": "routine_step", "duplicate_of": ""} for v in k["event_ids"]]
1459
+ k["event_ids"] = []
1460
+ return mutated(change)
1461
+ for n, entries in ((1, ["u1.1"]), (2, ["u1.1", "u1.2"])):
1462
+ found = problems(entries_beside_claims(entries))
1463
+ control(f"X r2 F1: a cluster G citing {n} of its entries beside three claims is G_ANTI_ABSTRACTION, and resting on "
1464
+ "no event CANDIDATE_WITHOUT_EVENTS: the claims do not stand in for entries",
1465
+ schema_of(entries_beside_claims(entries)) == []
1466
+ and any(p.startswith("G_ANTI_ABSTRACTION candidates/k1/tension/instance_entry_ids") for p in found)
1467
+ and any(p.startswith("CANDIDATE_WITHOUT_EVENTS candidates/k1") for p in found), f"{found}")
1468
+ eventless = cluster_g([], kind="C")
1469
+ eventless_g = cluster_g([], cluster="")
1470
+ control("F2: a candidate that is not a cluster G and names no event is CANDIDATE_WITHOUT_EVENTS",
1471
+ any(p.startswith("CANDIDATE_WITHOUT_EVENTS candidates/k1/event_ids") for p in alone_problems(eventless))
1472
+ and any(p.startswith("CANDIDATE_WITHOUT_EVENTS") for p in alone_problems(eventless_g)),
1473
+ f"{alone_problems(eventless)} {alone_problems(eventless_g)}")
1474
+ unknown_entry = cluster_g(["u1.1", "u1.2", "u1.9"])
1475
+ control("F2: an entry label the packet does not show is UNKNOWN_LABEL in the check and where the answer is read, and "
1476
+ "counts for nothing",
1477
+ any(p.startswith("UNKNOWN_LABEL 'u1.9'") for p in alone_problems(unknown_entry))
1478
+ and any(p.startswith("G_ANTI_ABSTRACTION candidates/k1/tension/instance_entry_ids") for p in alone_problems(unknown_entry))
1479
+ and refusal(lambda: alone.resolve(unknown_entry)).startswith("UNKNOWN_LABEL 'u1.9'"), f"{alone_problems(unknown_entry)}")
1480
+ entries_on_b = mutated(lambda a: a["candidates"][1]["tension"].update(instance_entry_ids=["u1.1"]))
1481
+ control("F2: cluster entries on a candidate of another type are TENSION_OUTSIDE_G",
1482
+ any(p.startswith("TENSION_OUTSIDE_G candidates/k2") for p in problems(entries_on_b)), f"{problems(entries_on_b)}")
1483
+ template = guarded(lambda: (HERE / "packets" / f"{TEMPLATE}.md").read_text(encoding="utf-8"), "")
1484
+ tension_note = guarded(lambda: json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))["$defs"]["tension"]["$comment"], "")
1485
+ control("X r2 F3: the packet tells the model that three entries let it propose a principle and do not show three "
1486
+ "independent lines of evidence, the bar held, and the schema says the same",
1487
+ "they do not show three independent lines of evidence" in " ".join(template.split())
1488
+ and "the evidence bar stays held" in " ".join(template.split())
1489
+ and "do not establish three independent lineages" in tension_note, tension_note[-300:])
1490
+ shown_clusters = guarded(lambda: alone.clusters_text(), "")
1491
+ control("F2: the packet shows each cluster entry by its own label, with its lesson and where its stored evidence is",
1492
+ '"entry_id": "u1.1"' in shown_clusters and '"entry_id": "u2.3"' in shown_clusters
1493
+ and "Ask before deleting a branch" in shown_clusters and '"locator": "unavailable"' in shown_clusters
1494
+ and '"S-1"' not in shown_clusters, shown_clusters[:300])
1495
+ by_units = {"claims": {"c-a1": {"unit": "claude:aaaa"}, "c-b1": {"unit": "claude:bbbb"}, "c-c1": {"unit": "codex:cccc"},
1496
+ "c-c2": {"unit": "codex:cccc"}}}
1497
+ bar_claims = guarded(lambda: evidence_bar(labels.resolve(good)["candidates"][0], by_units), {})
1498
+ two_units = mutated(lambda a: a["candidates"][0]["tension"].update(instance_claim_ids=["c3", "c4", "c5"]))
1499
+ bar_two = guarded(lambda: evidence_bar(labels.resolve(two_units)["candidates"][0], by_units), {})
1500
+ bar_cluster = guarded(lambda: evidence_bar(alone.resolve(from_three)["candidates"][0], by_units), {})
1501
+ control("done-when 4: the evidence bar counts lineages through its interface: three units' claims are at the bar, two "
1502
+ "are held, and placed entries, whose shared lineages the ledger does not record, are held with that reason",
1503
+ bar_claims.get("status") == "at_bar" and bar_claims.get("lineages") == 3
1504
+ and bar_two.get("status") == "held" and bar_two.get("lineages") == 2
1505
+ and bar_cluster.get("status") == "held" and bar_cluster.get("lineages") is None
1506
+ and "not whether two entries share one" in bar_cluster.get("basis", ""), f"{bar_claims} {bar_two} {bar_cluster}")
1507
+
1508
+ # labels: a value the packet does not show is refused in the check and again where an answer is read
1509
+ for what, answer, needle in (
1510
+ ("event", mutated(lambda a: a["candidates"][1]["event_ids"].append("v9")), "'v9' at candidates/k2/event_ids"),
1511
+ ("claim", mutated(lambda a: a["candidates"][1]["admission"]["consequence"]["claim_ids"].append("c9")),
1512
+ "'c9' at candidates/k2/admission/consequence"),
1513
+ ("quote", mutated(lambda a: a["candidates"][1]["admission"]["consequence"]["evidence_ids"].append("q9")),
1514
+ "'q9' at candidates/k2/admission/consequence"),
1515
+ ("cluster", g_with(cluster="u9"), "'u9' at candidates/k1/tension/cluster"),
1516
+ ("non-finding event", mutated(lambda a: a["non_findings"][0].update(event_id="v9")), "'v9' at non_findings/v9"),
1517
+ ("rejected-finding event", mutated(lambda a: (a["rejected_findings"].append({**finding, "event_ids": ["v9"]}),
1518
+ a["non_findings"].clear())), "'v9' at rejected_findings/r1")):
1519
+ control(f"a label of an unshown {what} is UNKNOWN_LABEL in the check and where the answer is read",
1520
+ any(p.startswith(f"UNKNOWN_LABEL {needle}") for p in problems(answer))
1521
+ and refusal(lambda: labels.resolve(answer)).startswith("UNKNOWN_LABEL"),
1522
+ f"{problems(answer)} {refusal(lambda: labels.resolve(answer))}")
1523
+ twice = mutated(lambda a: a["candidates"][1].update(candidate_id="k1"))
1524
+ control("a candidate id given twice is RECORD_INTEGRITY",
1525
+ any(p.startswith("RECORD_INTEGRITY candidate ids repeat") for p in problems(twice)), f"{problems(twice)}")
1526
+ control("events naming a claim no row carries are refused as RECORD_INTEGRITY",
1527
+ refusal(lambda: FormLabels([{**events[0], "claim_ids": ["c-zz"]}], claims)).startswith("RECORD_INTEGRITY"),
1528
+ refusal(lambda: FormLabels([{**events[0], "claim_ids": ["c-zz"]}], claims)))
1529
+
1530
+ # the packet: its template takes the three fields S4 fills, the linter passes it, and it shows labels only
1531
+ text = guarded(lambda: payload(labels), "")
1532
+ control("the form template is one packet.TEMPLATES lists, so the packet linter's template checks cover it",
1533
+ TEMPLATE in packet.TEMPLATES, f"{packet.TEMPLATES}")
1534
+ control("the form template takes exactly the fields S4 fills",
1535
+ guarded(lambda: packet.template_fields(TEMPLATE), []) == ["claims", "clusters", "events"],
1536
+ f"{guarded(lambda: packet.template_fields(TEMPLATE), [])}")
1537
+ call = "r1-S4-form-a1"
1538
+ schema_bytes = guarded(lambda: packet.schema_bytes(form_schema()), b"")
1539
+ made = guarded(lambda: packet.build(call, STAGE, "claude:claude-opus-5-5/high", text, schema_bytes), b"")
1540
+ control("the form packet passes the linter", bool(made) and guarded(lambda: packet.check(made, call, schema_bytes), ["RAISED"]) == [],
1541
+ f"{guarded(lambda: packet.check(made, call, schema_bytes), ['RAISED'])}")
1542
+ stored = ("v-a", "c-a1", "e-1", "claude:aaaa", "cluster-1")
1543
+ control("the packet shows every event, claim, quote, session and cluster by its label, never by its stored id",
1544
+ all(f'"{x}"' in text for x in ("v5", "c7", "q7", "s3", "u1")) and not any(x in text for x in stored),
1545
+ f"stored ids shown: {[x for x in stored if x in text]}")
1546
+ control("an event's outcome claims are listed apart from its own",
1547
+ '"claims": ["c1"], "outcome_claims": ["c2"]' in text, text[:200])
1548
+
1549
+ # done-when 7: the closed lists equal the sections that own them, and the schema holds exactly them
1550
+ schema = guarded(form_schema, {})
1551
+ defs = schema.get("$defs", {})
1552
+ control("done-when 7: the non-finding reasons equal design §9's fixed list, in the schema and in code",
1553
+ NON_FINDING_REASONS == ("no_consequence", "routine_step", "duplicate_of_another_event")
1554
+ and defs.get("non_finding", {}).get("properties", {}).get("reason", {}).get("enum") == list(NON_FINDING_REASONS),
1555
+ f"§9 lines 921-924: {NON_FINDING_REASONS} vs schema {defs.get('non_finding', {}).get('properties', {}).get('reason')}")
1556
+ control("done-when 7: the partition classes equal design §9's three, and the answer has one list for each",
1557
+ PARTITION_CLASSES == ("candidate", "non_finding", "rejected_finding")
1558
+ and sorted(schema.get("required", [])) == ["candidates", "non_findings", "rejected_findings"],
1559
+ f"§9 lines 921-924: {PARTITION_CLASSES} vs {schema.get('required')}")
1560
+ control("done-when 7: the intake sources equal design §7.1's list as plan WP-09 names it",
1561
+ INTAKE_SOURCES == ("due_decision", "legacy", "obsolete_hint", "redundancy_hint", "g_cluster"),
1562
+ f"§7.1 lines 520-546: {INTAKE_SOURCES}")
1563
+ admission_def = defs.get("admission", {})
1564
+ control("done-when 7: the admission fields equal the purpose record's eight requirements, each required",
1565
+ ADMISSION == ("observed_event", "consequence", "causal_support", "recognizable_in_advance", "actionable",
1566
+ "bounded", "positioned", "audience")
1567
+ and admission_def.get("required") == list(ADMISSION) and list(admission_def.get("properties", {})) == list(ADMISSION)
1568
+ and defs.get("rejected_finding", {}).get("properties", {}).get("failed", {}).get("items", {}).get("enum") == list(ADMISSION),
1569
+ f"purpose record lines 47-66: {ADMISSION} vs {admission_def.get('required')}")
1570
+ control("done-when 7: the types equal PLACEMENT-FRAMEWORK.md's A-G",
1571
+ TYPES == tuple("ABCDEFG") and defs.get("candidate", {}).get("properties", {}).get("type", {}).get("enum") == list(TYPES),
1572
+ f"PLACEMENT-FRAMEWORK lines 32-45: {TYPES}")
1573
+ control("the schema passes the schema policy and is handed to a host whole",
1574
+ guarded(lambda: validate.lint(schema), ["RAISED"]) == [] and bool(schema_bytes)
1575
+ and guarded(lambda: packet.host_keywords(json.loads(schema_bytes)), ["RAISED"]) == [],
1576
+ f"{guarded(lambda: validate.lint(schema), ['RAISED'])}")
1577
+
1578
+
1579
+ # ---- commit 2: what S4 forms from, the partition, and the population (golden S3 run) ----
1580
+ with tempfile.TemporaryDirectory(prefix="s4-") as td:
1581
+ root = pathlib.Path(td)
1582
+ made = guarded(lambda: fx_s3(root), lambda exc: (None, {"problem": repr(exc)}))
1583
+ run_dir, s3 = made
1584
+ control("positive control: the golden S3 run processes the Claude unit and leaves the Codex unit read_partial",
1585
+ run_dir is not None and sorted(s3.get("units", {}).values()) == ["read_complete", "read_partial"],
1586
+ f"{s3.get('units') or s3}")
1587
+ got = guarded(lambda: subject(run_dir), lambda exc: {"problem": str(exc)})
1588
+ rows = got.get("events", [])
1589
+ by_text = {r["description"]: r for r in rows}
1590
+ control("D2: the subject is the resolved events of the processed unit, each once by its stored id: the one its "
1591
+ "window resolved, the one the stitch joined, the one in the child, and the carried pe-1 under its id",
1592
+ sorted(by_text) == sorted([FX_MARKERS["settled"], FX_MARKERS["joined"], FX_MARKERS["child"]]
1593
+ + [r["description"] for r in rows if r["id"] == "pe-1"])
1594
+ and any(r["id"] == "pe-1" for r in rows) and len({r["id"] for r in rows}) == len(rows) == 4,
1595
+ f"{got.get('problem') or [(r['id'][:10], r['description'][:24]) for r in rows]}")
1596
+ control("D2: an event the stitch joined, and the carried one, show their outcome claims apart from their own",
1597
+ by_text.get(FX_MARKERS["joined"], {}).get("outcome_claim_ids")
1598
+ and all(r["outcome_claim_ids"] for r in rows if r["id"] == "pe-1")
1599
+ and by_text.get(FX_MARKERS["settled"], {}).get("outcome_claim_ids") == [],
1600
+ f"{[(r['description'][:16], r['claim_ids'], r['outcome_claim_ids']) for r in rows]}")
1601
+ handed = got.get("carried_forward", [])
1602
+ from runlib import stage_read
1603
+ claude_files = guarded(lambda: [f["name"] for f in records.read_json(next((run_dir / "read").glob("claude_*.json")))["files"]], [])
1604
+ open_ids = [e["event_id"] for name in claude_files for e in guarded(lambda name=name: stage_read.current_events(run_dir, name), [])
1605
+ if e["description"] == FX_MARKERS["open"]]
1606
+ control("D2: the event the processed unit hands on is carried_forward and is no subject",
1607
+ len(handed) == 1 and [h["event_id"] for h in handed] == open_ids
1608
+ and FX_MARKERS["open"] not in by_text, f"{handed} {open_ids}")
1609
+ nf = got.get("not_formed", [])
1610
+ control("D1: the unit S3 left read_partial is listed with its status, its reasons and its one event, and none of "
1611
+ "its events is a subject",
1612
+ len(nf) == 1 and nf[0]["status"] == "read_partial" and nf[0]["unit"].startswith("codex:")
1613
+ and nf[0]["events"] == 1 and nf[0]["reasons"] and FX_MARKERS["codex"] not in by_text, f"{nf}")
1614
+ control("every claim the subject's events name is carried with its quotes, each where it stands",
1615
+ all(c in got.get("claims", {}) for r in rows for c in r["claim_ids"] + r["outcome_claim_ids"])
1616
+ and all(q["text"] and q["record"] for c in got.get("claims", {}).values() for q in c["quotes"]),
1617
+ f"{sorted(got.get('claims', {}))[:4]}")
1618
+
1619
+ def rerecord(where, artifact):
1620
+ """S3's record made to hold `artifact` as it now is: the bent file is one S3 itself would have written."""
1621
+ held = records.read_json(records.record_path(where, "S3"))
1622
+ for row in held["outputs"]:
1623
+ if row["artifact"] == artifact:
1624
+ row["sha256"] = records.sha256_file(pathlib.Path(where) / artifact)
1625
+ records.write_json(where, records.record_path(where, "S3"), held)
1626
+
1627
+ def bent(change):
1628
+ """subject() over a copy of the run whose read-results `change` edits, as S3 would have written them."""
1629
+ copy_dir = root / f"bent-{len(list(root.iterdir()))}"
1630
+ shutil.copytree(run_dir, copy_dir)
1631
+ doc = records.read_json(copy_dir / "read-results.json")
1632
+ change(doc)
1633
+ (copy_dir / "read-results.json").write_text(json.dumps(doc), encoding="utf-8")
1634
+ rerecord(copy_dir, "read-results.json")
1635
+ return refusal(lambda: subject(copy_dir))
1636
+
1637
+ def unhand(doc):
1638
+ next(r for r in doc["results"] if r["status"] == PROCESSED)["pending_events"] = []
1639
+ control("a processed unit holding open an event its result does not hand on is SET_MISMATCH",
1640
+ bent(unhand).startswith("SET_MISMATCH claude:"), bent(unhand))
1641
+
1642
+ def unresolve(doc):
1643
+ next(r for r in doc["results"] if r["status"] == PROCESSED)["resolved_events"] = []
1644
+ control("a processed unit whose resolved carried events are not its result's is SET_MISMATCH",
1645
+ bent(unresolve).startswith("SET_MISMATCH claude:"), bent(unresolve))
1646
+
1647
+ # W r1, F1: a processed unit's read record is held to S3's record of it, and the results that name it are too
1648
+ unbound = root / f"bent-{len(list(root.iterdir()))}"
1649
+ shutil.copytree(run_dir, unbound)
1650
+ guarded(lambda: (unbound / "read-results.json").write_text(
1651
+ json.dumps(records.read_json(unbound / "read-results.json")), encoding="utf-8"), None)
1652
+ control("W r1: results that are not the read-results.json S3's record holds are INPUT_INVALID, so no read record "
1653
+ "is held to a record of other results", refusal(lambda: subject(unbound)).startswith("INPUT_INVALID S3: read-results.json"),
1654
+ refusal(lambda: subject(unbound)))
1655
+ processed_unit = next((r["transcript"] for r in records.read_json(run_dir / "read-results.json")["results"]
1656
+ if r["status"] == PROCESSED), "claude:?")
1657
+
1658
+ def read_record_bent(change, record_again=False):
1659
+ """subject() over a copy of the run whose processed unit's read record `change` bends (and S3's record holds
1660
+ the bent record when `record_again`)."""
1661
+ copy_dir = root / f"bent-{len(list(root.iterdir()))}"
1662
+ shutil.copytree(run_dir, copy_dir)
1663
+ rel = f"read/{views.safe_name(processed_unit)}.json"
1664
+ change(copy_dir, copy_dir / rel)
1665
+ if record_again:
1666
+ rerecord(copy_dir, rel)
1667
+ return refusal(lambda: subject(copy_dir))
1668
+
1669
+ def write_back(path, doc):
1670
+ path.chmod(0o600)
1671
+ path.write_text(json.dumps(doc), encoding="utf-8")
1672
+ deleted = read_record_bent(lambda where, path: path.unlink())
1673
+ control("W r1: a processed unit whose read record is gone is refused by its name (RECORD_INTEGRITY), never formed "
1674
+ "from nothing", deleted.startswith(f"RECORD_INTEGRITY {processed_unit}: its read record") and "missing" in deleted,
1675
+ deleted)
1676
+ edited = read_record_bent(lambda where, path: write_back(path, {**records.read_json(path), "reasons": ["edited"]}))
1677
+ control("W r1: a processed unit whose read record is not the one S3 recorded is refused by its name",
1678
+ edited.startswith(f"RECORD_INTEGRITY {processed_unit}: its read record") and "not the one S3 recorded" in edited,
1679
+ edited)
1680
+ cut_files = read_record_bent(lambda where, path: write_back(path, {**records.read_json(path), "files": []}), True)
1681
+ control("W r1: a processed unit whose read record lists fewer files than its result read is refused by its name, "
1682
+ "even when S3's record holds that record", cut_files.startswith(f"SET_MISMATCH {processed_unit}: its read record lists"),
1683
+ cut_files)
1684
+
1685
+ def unrecord(where, path):
1686
+ held = records.read_json(records.record_path(where, "S3"))
1687
+ held["outputs"] = [o for o in held["outputs"] if o["artifact"] != str(path.relative_to(where))]
1688
+ records.write_json(where, records.record_path(where, "S3"), held)
1689
+ unrecorded = read_record_bent(unrecord)
1690
+ control("W r1: a processed unit whose read record S3's record does not hold is refused by its name",
1691
+ unrecorded.startswith(f"RECORD_INTEGRITY {processed_unit}: S3 processed it and recorded no read record"),
1692
+ unrecorded)
1693
+
1694
+ # the partition, in the packet's labels, over the golden subject
1695
+ flabels = guarded(lambda: FormLabels(rows, got["claims"]), None)
1696
+ part = fx_partition(["v1", "v2", "v3", "v4"])
1697
+ on = lambda answer: guarded(lambda: answer_problems(flabels, answer), lambda exc: [f"RAISED {exc!r}"]) # noqa: E731
1698
+ control("done-when 1: an answer placing every listed event exactly once passes",
1699
+ flabels is not None and len(flabels.events) == 4 and schema_of(part) == [] and on(part) == [],
1700
+ f"{schema_of(part)[:2]} {on(part)[:2]}")
1701
+ dropped = copy.deepcopy(part)
1702
+ dropped["non_findings"] = []
1703
+ control("done-when 1: an answer that drops one event is SET_MISMATCH, naming it",
1704
+ any(p.startswith("SET_MISMATCH events placed nowhere: ['v4']") for p in on(dropped)), f"{on(dropped)}")
1705
+ two_candidates = copy.deepcopy(part)
1706
+ two_candidates["candidates"].append({**copy.deepcopy(part["candidates"][0]), "candidate_id": "k2", "event_ids": ["v2"]})
1707
+ control("done-when 1: an event assigned to two candidates is SET_MISMATCH, naming it",
1708
+ any(p.startswith("SET_MISMATCH events placed more than once: {'v2': 2}") for p in on(two_candidates)),
1709
+ f"{on(two_candidates)}")
1710
+ and_non_finding = copy.deepcopy(part)
1711
+ and_non_finding["non_findings"].append({"event_id": "v3", "reason": "no_consequence", "duplicate_of": ""})
1712
+ control("done-when 1: an event both a rejected finding's and a non-finding is SET_MISMATCH",
1713
+ any(p.startswith("SET_MISMATCH events placed more than once: {'v3': 2}") for p in on(and_non_finding)),
1714
+ f"{on(and_non_finding)}")
1715
+
1716
+ # the population: one set, its membership, and the intake it must list
1717
+ resolved_part = guarded(lambda: flabels.resolve(part), None)
1718
+ intake = [{"candidate_id": "legacy:S3-03", "source": "legacy"}, {"candidate_id": "redundancy_hint:u-a|u-b",
1719
+ "source": "redundancy_hint"}]
1720
+ pop = guarded(lambda: population(resolved_part, got, "r9", intake), {})
1721
+ control("done-when 1 (N#12): the population lists every formed and lifecycle candidate, every rejected finding and "
1722
+ "non-finding, and a membership for every event of the subject; it holds as built",
1723
+ len(pop.get("candidate_ids", [])) == 3 and len(pop.get("rejected_finding_ids", [])) == 1
1724
+ and len(pop.get("non_finding_ids", [])) == 1 and len(pop.get("event_membership", {})) == 4
1725
+ and guarded(lambda: population_problems(pop, got, intake), ["RAISED"]) == []
1726
+ and pop.get("counts", {}).get("carried_forward") == 1 and pop.get("counts", {}).get("events_not_formed") == 1,
1727
+ f"{guarded(lambda: population_problems(pop, got, intake), ['RAISED'])} {pop.get('counts')}")
1728
+ without = copy.deepcopy(pop)
1729
+ without["candidates"] = [c for c in without.get("candidates", []) if c["candidate_id"] != "legacy:S3-03"]
1730
+ without["candidate_ids"] = [c for c in without.get("candidate_ids", []) if c != "legacy:S3-03"]
1731
+ control("done-when 1: a lifecycle candidate present in the intake and absent from the population is SET_MISMATCH "
1732
+ "naming it",
1733
+ any(p.startswith("SET_MISMATCH legacy:S3-03:") for p in guarded(lambda: population_problems(without, got, intake),
1734
+ [])), f"{guarded(lambda: population_problems(without, got, intake), [])}")
1735
+ stray = copy.deepcopy(pop)
1736
+ first_event = next(iter(stray.get("event_membership", {"x": None})))
1737
+ stray.setdefault("event_membership", {})[first_event] = "k-unlisted"
1738
+ control("done-when 1: an event whose membership names a candidate not in the list is SET_MISMATCH",
1739
+ any(p.startswith(f"SET_MISMATCH {first_event}: its membership names k-unlisted")
1740
+ for p in guarded(lambda: population_problems(stray, got, intake), [])),
1741
+ f"{guarded(lambda: population_problems(stray, got, intake), [])}")
1742
+ lost = copy.deepcopy(pop)
1743
+ lost["non_finding_ids"], lost["non_findings"] = [], []
1744
+ lost.get("event_membership", {}).pop(next((e for e, m in lost.get("event_membership", {}).items() if m == "non_finding"), None), None)
1745
+ control("done-when 1: a population that loses an event of the subject is SET_MISMATCH",
1746
+ any(p.startswith("SET_MISMATCH the population places") for p in guarded(lambda: population_problems(lost, got, intake), [])),
1747
+ f"{guarded(lambda: population_problems(lost, got, intake), [])}")
1748
+
1749
+ # X round 1, F4: every list is held to the rows it lists, each disagreement on its own
1750
+ def bent_pop(change):
1751
+ bent = copy.deepcopy(pop)
1752
+ guarded(lambda: change(bent), None)
1753
+ return guarded(lambda: population_problems(bent, got, intake), lambda exc: [f"RAISED {exc!r}"])
1754
+ formed_id = next((c["candidate_id"] for c in pop.get("candidates", []) if c["source"] == "formed"), "k-?")
1755
+ redirected = next((e for e, m in pop.get("event_membership", {}).items() if m == formed_id), "v-?")
1756
+ for what, change, needle in (
1757
+ ("a lifecycle row removed while its id is kept",
1758
+ lambda b: b["candidates"].remove(next(c for c in b["candidates"] if c["candidate_id"] == "legacy:S3-03")),
1759
+ "SET_MISMATCH candidate_ids are not the ids of the rows it lists"),
1760
+ ("a non-finding row removed while its id is kept", lambda b: b["non_findings"].clear(),
1761
+ "SET_MISMATCH non_finding_ids are not the ids of the rows it lists"),
1762
+ ("a rejected-finding row removed while its id is kept", lambda b: b["rejected_findings"].clear(),
1763
+ "SET_MISMATCH rejected_finding_ids are not the ids of the rows it lists"),
1764
+ ("an event's membership redirected to another listed candidate",
1765
+ lambda b: b["event_membership"].update({redirected: "legacy:S3-03"}),
1766
+ f"SET_MISMATCH {redirected}: its membership names legacy:S3-03, and the rows place it in {formed_id}"),
1767
+ ("carried_forward emptied", lambda b: b["carried_forward"].clear(), "SET_MISMATCH carried_forward"),
1768
+ ("not_formed emptied", lambda b: b["not_formed"].clear(), "SET_MISMATCH not_formed"),
1769
+ ("carried_forward deleted (X r2, F4)", lambda b: b.pop("carried_forward"), "SET_MISMATCH carried_forward: absent"),
1770
+ ("not_formed deleted (X r2, F4)", lambda b: b.pop("not_formed"), "SET_MISMATCH not_formed: absent"),
1771
+ ("a count edited by one", lambda b: b["counts"].update(events=b["counts"]["events"] + 1),
1772
+ "SET_MISMATCH counts ['events']"),
1773
+ ("a lifecycle row under another source",
1774
+ lambda b: next(c for c in b["candidates"] if c["candidate_id"] == "legacy:S3-03").update(source="g_cluster"),
1775
+ "SET_MISMATCH legacy:S3-03: its row's source"),
1776
+ ("a lifecycle row listed twice, its id with it",
1777
+ lambda b: (b["candidates"].append(dict(next(c for c in b["candidates"] if c["candidate_id"] == "legacy:S3-03"))),
1778
+ b["candidate_ids"].append("legacy:S3-03")),
1779
+ "SET_MISMATCH candidate ids listed more than once: ['legacy:S3-03']"),
1780
+ ("a lifecycle row the intake does not hold, its id with it",
1781
+ lambda b: (b["candidates"].append({"candidate_id": "legacy:X-9", "source": "legacy", "event_ids": []}),
1782
+ b["candidate_ids"].append("legacy:X-9")),
1783
+ "SET_MISMATCH legacy:X-9: a lifecycle row the intake does not hold")):
1784
+ found = bent_pop(change)
1785
+ control(f"F4: {what} is SET_MISMATCH by name", any(p.startswith(needle) for p in found), f"{found}")
1786
+ rows_p = guarded(lambda: partition_rows(pop), [])
1787
+ control("partition.jsonl has one row per event of the subject, each of one class and naming its candidate, finding "
1788
+ "or reason",
1789
+ len(rows_p) == 4 and sorted(collections.Counter(r["class"] for r in rows_p).items())
1790
+ == [("candidate", 2), ("non_finding", 1), ("rejected_finding", 1)]
1791
+ and all(("candidate_id" in r) + ("finding_id" in r) + ("reason" in r) == 1 for r in rows_p), f"{rows_p}")
1792
+
1793
+ # ---- X round 1, F1 and F3: the events earlier runs left pending, and where a resolved carried one began ----
1794
+ s3_results = guarded(lambda: records.read_json(run_dir / "read-results.json"), {"results": []})
1795
+ pe1 = next((r for r in rows if r["id"] == "pe-1"), {})
1796
+ pe1_origin = pe1.get("origin", [])
1797
+ flab = guarded(lambda: FormLabels(rows, got["claims"]), None)
1798
+ shown_pe1 = guarded(lambda: payload(flab), "")
1799
+
1800
+ def stitch_showed():
1801
+ """What S3's stitch packet showed of pe-1 when it resolved it: its first record's blocks, read from the call."""
1802
+ from runlib import stage_read as sr
1803
+ texts = []
1804
+ for call_dir in sorted((run_dir / "calls").glob("*-S3-claude_*-s*-a*")):
1805
+ events_listed, _claims = sr.fx_blocks((call_dir / "packet.md").read_text(encoding="utf-8"))
1806
+ texts += [s["text"] for e in events_listed if "carried_from" in e for s in e["shown"]]
1807
+ return texts
1808
+ stitched = guarded(stitch_showed, [])
1809
+ control("F3: a carried event resolved here shows where it began - its first record as S3's stitch was shown it when "
1810
+ "it resolved the event - in the formation packet, though its description holds none of it",
1811
+ bool(pe1_origin) and all(o.get("evidence_id", "").startswith("origin:") for o in pe1_origin)
1812
+ and bool(stitched) and all(json.dumps(s, ensure_ascii=False)[1:-1] in shown_pe1 for s in stitched)
1813
+ and "file 000 ok" in stitched[0] and "file 000" not in pe1.get("description", "")
1814
+ and [o.get("text") for o in pe1_origin] == stitched[:1] and pe1_origin[0].get("cut") is True
1815
+ and len(pe1_origin[0].get("text", "").encode()) <= QUOTE_BYTES, f"{pe1_origin[:1]} {stitched[:1]}")
1816
+ origin_label = next((lab for lab, ident in (flab.quotes.items() if flab else []) if ident.startswith("origin:")), None)
1817
+ citing = copy.deepcopy(part)
1818
+ if origin_label:
1819
+ citing["candidates"][0]["admission"]["observed_event"]["evidence_ids"] = [origin_label]
1820
+ resolved_origin = guarded(lambda: flab.resolve(citing), None)
1821
+ verified = guarded(lambda: origin_evidence(run_dir, resolved_origin, got), lambda exc: {"problem": str(exc)})
1822
+ control("F3: an origin quote is cited by its label like any quote, read back as origin:<view>#<record>, and verified "
1823
+ "against the immutable copy before candidates.json carries its evidence record",
1824
+ origin_label is not None and on(citing) == []
1825
+ and list(verified) == [o["evidence_id"] for o in pe1_origin[:1]]
1826
+ and all(v.get("char_span") and v.get("redacted_text") for v in verified.values() if isinstance(v, dict)),
1827
+ f"{origin_label} {verified}")
1828
+ tampered = root / "f3-tampered"
1829
+ shutil.copytree(run_dir.parent, tampered, ignore=shutil.ignore_patterns("c5-*", "bent-*", "f3-*"))
1830
+ tampered_run = tampered / run_dir.name
1831
+
1832
+ def tamper_projection():
1833
+ """The projection's text of pe-1's first record edited after S2 wrote it."""
1834
+ view = next(t for t in records.read_json(tampered_run / "views.json")["transcripts"] if t["name"] == pe1.get("file"))
1835
+ path = tampered_run / view["redacted"]
1836
+ lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
1837
+ edited = [line.replace("file 000 ok", "file 000 OK") if line.startswith('{"line":5,') else line for line in lines]
1838
+ path.write_text("".join(edited), encoding="utf-8")
1839
+ return edited != lines
1840
+ projection_edited = guarded(tamper_projection, False)
1841
+ control("F3: an origin whose projected text is not what the immutable copy projects is refused (RECORD_INTEGRITY)",
1842
+ projection_edited and refusal(lambda: subject(tampered_run)).startswith("RECORD_INTEGRITY pe-1"),
1843
+ f"edited {projection_edited}: {refusal(lambda: subject(tampered_run))}")
1844
+
1845
+ def sensitive(action):
1846
+ """`action` with every quote read as one that names a secret: evidence.make refuses each such quote
1847
+ (EVIDENCE_QUOTE_SENSITIVE), as it refuses a real one, and nothing else changes."""
1848
+ real = projection.evidence_quote_admissible
1849
+ projection.evidence_quote_admissible = lambda text: (False, "planted: read as naming a secret")
1850
+ try:
1851
+ return action()
1852
+ finally:
1853
+ projection.evidence_quote_admissible = real
1854
+ held_sensitive = sensitive(lambda: guarded(lambda: next(r for r in subject(run_dir)["events"] if r["id"] == "pe-1"), {}))
1855
+ shown_sensitive = sensitive(lambda: guarded(lambda: FormLabels([held_sensitive], {c: got["claims"][c] for c in
1856
+ held_sensitive["claim_ids"] + held_sensitive["outcome_claim_ids"]}).events_text(), ""))
1857
+ control("X r2 F2: an intact origin whose text names a secret is shown, cut as the stitch cut it, and cannot be cited",
1858
+ [o.get("withheld") for o in held_sensitive.get("origin", [])] == ["EVIDENCE_QUOTE_SENSITIVE"]
1859
+ and [o.get("text") for o in held_sensitive.get("origin", [])] == stitched[:1]
1860
+ and not any(o.get("evidence_id") for o in held_sensitive.get("origin", [])) and '"citable": false' in shown_sensitive,
1861
+ f"{[(o.get('withheld'), o.get('evidence_id')) for o in held_sensitive.get('origin', [])]}")
1862
+ altered_sensitive = sensitive(lambda: refusal(lambda: subject(tampered_run)))
1863
+ control("X r2 F2: an origin whose text names a secret and is not what the immutable copy projects is refused "
1864
+ "(RECORD_INTEGRITY), never shown", projection_edited and altered_sensitive.startswith("RECORD_INTEGRITY pe-1"),
1865
+ altered_sensitive)
1866
+
1867
+ def tamper_copy():
1868
+ """The immutable copy itself edited after S2 made it."""
1869
+ source = tampered_run / pe1_origin[0]["evidence"]["source_copy"]
1870
+ before = source.read_bytes()
1871
+ source.chmod(0o600) # the copy is written read-only; this control is the edit that mode does not stop
1872
+ source.write_bytes(before.replace(b"file 000 ok", b"file 000 not ok"))
1873
+ return source.read_bytes() != before
1874
+ copy_edited = guarded(tamper_copy, False)
1875
+ copy_changed = refusal(lambda: subject(tampered_run))
1876
+ control("X r2 F2: a carried event whose immutable copy changed is refused before its origin is read: the copy is "
1877
+ "held to the version it names first (RECORD_INTEGRITY, SOURCE_TAMPERED)",
1878
+ copy_edited and copy_changed.startswith("RECORD_INTEGRITY pe-1: its origin cannot be held to the immutable copy")
1879
+ and "SOURCE_TAMPERED" in copy_changed, copy_changed)
1880
+ control("F3: a cited origin quote whose copy changed after the subject was read is refused where its evidence is "
1881
+ "verified again (RECORD_INTEGRITY)",
1882
+ copy_edited and refusal(lambda: origin_evidence(tampered_run, resolved_origin, got)).startswith("RECORD_INTEGRITY origin:"),
1883
+ f"edited {copy_edited}: {refusal(lambda: origin_evidence(tampered_run, resolved_origin, got))}")
1884
+ dropped = root / "f3-dropped"
1885
+ shutil.copytree(run_dir.parent, dropped, ignore=shutil.ignore_patterns("c5-*", "bent-*", "f3-*"))
1886
+
1887
+ def drop_first_record():
1888
+ """pe-1's first record removed from the projection, so the projection holds no block of it."""
1889
+ view = next(t for t in records.read_json(dropped / run_dir.name / "views.json")["transcripts"] if t["name"] == pe1.get("file"))
1890
+ path = dropped / run_dir.name / view["redacted"]
1891
+ lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
1892
+ kept = [line for line in lines if not line.startswith('{"line":5,')]
1893
+ path.write_text("".join(kept), encoding="utf-8")
1894
+ return len(kept) == len(lines) - 1
1895
+ record_dropped = guarded(drop_first_record, False)
1896
+ control("F3: a carried event whose first record the projection does not hold is refused (RECORD_INTEGRITY), never "
1897
+ "shown without where it began",
1898
+ record_dropped and refusal(lambda: subject(dropped / run_dir.name)).startswith("RECORD_INTEGRITY pe-1: its first record"),
1899
+ f"dropped {record_dropped}: {refusal(lambda: subject(dropped / run_dir.name))}")
1900
+ cf = {c["event_id"]: c for c in got.get("carried_forward", [])}
1901
+ control("F1: the golden window's carried_forward holds the event the processed unit hands on (this run's) and not "
1902
+ "pe-1, which its stitch resolved",
1903
+ [c["origin"] for c in cf.values()] == ["this_run"] and "pe-1" not in cf, f"{list(cf.values())}")
1904
+
1905
+ def plant_pending(where, file_of_unit, ident):
1906
+ """A pending event an earlier run left on a file of `file_of_unit`'s unit, planted in a copy's coverage state."""
1907
+ state, sha = coverage.load(where / "coverage.json")
1908
+ key = next(k for k, u in unit_of_file(census.rows(census.load(where)), [r["transcript"] for r in s3_results["results"]]).items()
1909
+ if u == file_of_unit)
1910
+ state["pending_events"].append({"id": ident, "transcript": key, "version": 0, "window": "2026-09-24T00:00:00/2026-10-01T00:00:00@UTC",
1911
+ "first_record": 1})
1912
+ (where / "coverage.json").write_text(json.dumps(state), encoding="utf-8")
1913
+ claude_unit = next((r["transcript"] for r in s3_results["results"] if r["transcript"].startswith("claude:")), "claude:?")
1914
+ undecided = root / "f1-undecided"
1915
+ shutil.copytree(run_dir.parent, undecided, ignore=shutil.ignore_patterns("c5-*", "bent-*", "f3-*", "f1-*"))
1916
+ guarded(lambda: plant_pending(undecided / run_dir.name, claude_unit, "pe-planted"), None)
1917
+ control("F1: an earlier pending event on a processed unit's file that its stitch neither decided nor left unstitched "
1918
+ "is SET_MISMATCH naming the unit",
1919
+ refusal(lambda: subject(undecided / run_dir.name)).startswith(f"SET_MISMATCH {claude_unit}: earlier runs left"),
1920
+ refusal(lambda: subject(undecided / run_dir.name)))
1921
+ twice = root / "f1-twice"
1922
+ shutil.copytree(run_dir.parent, twice, ignore=shutil.ignore_patterns("c5-*", "bent-*", "f3-*", "f1-*"))
1923
+
1924
+ def decide_twice():
1925
+ """pe-1, which the Claude unit's stitch resolved, listed again among the events it left unstitched."""
1926
+ path = twice / run_dir.name / "read" / f"{views.safe_name(claude_unit)}.json"
1927
+ record = records.read_json(path)
1928
+ record["stitch"]["not_stitched"].append({"event_id": "pe-1", "file": pe1.get("file"), "reason": "planted"})
1929
+ path.chmod(0o600)
1930
+ path.write_text(json.dumps(record), encoding="utf-8")
1931
+ rerecord(twice / run_dir.name, f"read/{views.safe_name(claude_unit)}.json")
1932
+ return True
1933
+ planted_twice = guarded(decide_twice, False)
1934
+ control("F1: an earlier pending event a processed unit's stitch decided twice (resolved and left unstitched) is "
1935
+ "SET_MISMATCH naming the unit",
1936
+ planted_twice and refusal(lambda: subject(twice / run_dir.name)).startswith(f"SET_MISMATCH {claude_unit}: earlier runs left"),
1937
+ f"planted {planted_twice}: {refusal(lambda: subject(twice / run_dir.name))}")
1938
+ unformed = root / "f1-unformed"
1939
+ shutil.copytree(run_dir.parent, unformed, ignore=shutil.ignore_patterns("c5-*", "bent-*", "f3-*", "f1-*"))
1940
+ guarded(lambda: plant_pending(unformed / run_dir.name, codex_unit_of(s3_results), "pe-codex"), None)
1941
+ unformed_cf = guarded(lambda: {c["event_id"]: c for c in subject(unformed / run_dir.name)["carried_forward"]},
1942
+ lambda exc: {"problem": str(exc)})
1943
+ control("F1: an earlier pending event on a unit S3 did not process is carried forward, its unit not formed",
1944
+ unformed_cf.get("pe-codex", {}).get("why") == "unit_not_formed"
1945
+ and unformed_cf.get("pe-codex", {}).get("origin") == "earlier_run", f"{unformed_cf}")
1946
+ two = guarded(lambda: fx_two_windows(root / "two"), lambda exc: (None, [repr(exc)]))
1947
+ run_n1, left_by_n = two
1948
+ sub_n1 = guarded(lambda: subject(run_n1), lambda exc: {"problem": str(exc)})
1949
+ cf_n1 = {c["event_id"]: c for c in sub_n1.get("carried_forward", [])}
1950
+ joined_n1 = [r for r in sub_n1.get("events", []) if r.get("origin")]
1951
+ control("F1 (two windows): the event run N left pending that run N+1 revisits and leaves unresolved is carried "
1952
+ "forward from the earlier run, and the one run N+1 joins to its outcome is a subject with its origin",
1953
+ run_n1 is not None and "pe-1" in left_by_n and cf_n1.get("pe-1", {}).get("origin") == "earlier_run"
1954
+ and cf_n1.get("pe-1", {}).get("why") == "unresolved" and len(joined_n1) == 1
1955
+ and joined_n1[0]["id"] in left_by_n and joined_n1[0]["id"] not in cf_n1,
1956
+ f"{sub_n1.get('problem')} {left_by_n} {list(cf_n1.values())} {[r['id'] for r in joined_n1]}")
1957
+
1958
+ # ---- commit 5: the barrier, the bound, the call and what the stage leaves (golden S3 run, golden host) ----
1959
+ def copy_of(label):
1960
+ """A copy of the golden S3 run's tree (the run, its host and its checkout), for a stage run that writes."""
1961
+ where = root / f"c5-{label}"
1962
+ shutil.copytree(run_dir.parent, where, ignore=shutil.ignore_patterns("c5-*", "bent-*"))
1963
+ return where / run_dir.name
1964
+
1965
+ def record_of(where, stage_id=STAGE):
1966
+ return guarded(lambda: records.read_json(records.record_path(where, stage_id)), {})
1967
+
1968
+ document = guarded(lambda: census.load(run_dir), {})
1969
+ results = guarded(lambda: records.read_json(run_dir / "read-results.json"), {"results": []})
1970
+
1971
+ def barred(change):
1972
+ edited = copy.deepcopy(results)
1973
+ change(edited)
1974
+ return guarded(lambda: barrier(document, edited), lambda exc: [f"RAISED {exc!r}"])
1975
+ codex_unit = next((r["transcript"] for r in results["results"] if r["transcript"].startswith("codex:")), "codex:?")
1976
+ control("D1 barrier: the golden window, every eligible unit with one terminal result, passes",
1977
+ barred(lambda r: None) == [], f"{barred(lambda r: None)}")
1978
+ missing = barred(lambda r: r.update(results=[x for x in r["results"] if x["transcript"] != codex_unit]))
1979
+ control("D1 barrier: an eligible unit with no result is INPUT_PARTIAL naming it",
1980
+ any(p.startswith(f"INPUT_PARTIAL S3 {codex_unit}:") for p in missing), f"{missing}")
1981
+ running = barred(lambda r: next(x for x in r["results"] if x["transcript"] == codex_unit).update(status="running"))
1982
+ control("D1 barrier: a result whose status is not terminal is INPUT_PARTIAL naming its unit",
1983
+ any(p.startswith(f"INPUT_PARTIAL S3 {codex_unit}: its result is 'running'") for p in running), f"{running}")
1984
+ extra = barred(lambda r: r["results"].append({**r["results"][0], "transcript": "claude:not-eligible"}))
1985
+ twice = barred(lambda r: r["results"].append(copy.deepcopy(r["results"][0])))
1986
+ control("D1 barrier: a result for a unit the census did not make eligible, or a second one, is SET_MISMATCH",
1987
+ any(p.startswith("SET_MISMATCH read-results.json") and "claude:not-eligible" in p for p in extra)
1988
+ and any(p.startswith("SET_MISMATCH read-results.json") for p in twice), f"{extra} {twice}")
1989
+ partial_s3 = copy_of("s3-partial")
1990
+ held_s3 = record_of(partial_s3, "S3")
1991
+ if held_s3:
1992
+ records.write_json(partial_s3, records.record_path(partial_s3, "S3"), {**held_s3, "status": "partial"})
1993
+ control("D1: an S3 record that is partial stops S4 at admission (INPUT_PARTIAL S3), before any record of S4",
1994
+ refusal(lambda: run(partial_s3, dry=True)).startswith("INPUT_PARTIAL S3") and not record_of(partial_s3),
1995
+ refusal(lambda: run(partial_s3, dry=True)))
1996
+ rerun_s1 = copy_of("s1-again")
1997
+
1998
+ def census_again():
1999
+ """S1 run again at the same declaration sequence: its census in other bytes, recorded by S1's record, while
2000
+ S3's record still holds the census S3 read."""
2001
+ path = rerun_s1 / "census.json"
2002
+ path.chmod(0o600)
2003
+ path.write_text(path.read_text(encoding="utf-8") + "\n", encoding="utf-8")
2004
+ held = records.read_json(records.record_path(rerun_s1, "S1"))
2005
+ for row in held["outputs"]:
2006
+ if row["artifact"] == "census.json":
2007
+ row["sha256"] = records.sha256_file(path)
2008
+ records.write_json(rerun_s1, records.record_path(rerun_s1, "S1"), held)
2009
+ return True
2010
+ stale_census = guarded(census_again, False) and refusal(lambda: run(rerun_s1, dry=True))
2011
+ control("W r1 F2: S1 run again at the same sequence under S3's results stops S4 at admission (INPUT_STALE S3), "
2012
+ "before any record of S4", bool(stale_census) and "INPUT_STALE S3: it read census.json" in stale_census
2013
+ and not record_of(rerun_s1), f"{stale_census}")
2014
+ short = copy_of("short")
2015
+
2016
+ def drop_codex():
2017
+ """S3's results without the Codex unit's, recorded by S3's record as its own output: an S3 that left one."""
2018
+ doc = records.read_json(short / "read-results.json")
2019
+ doc["results"] = [x for x in doc["results"] if x["transcript"] != codex_unit]
2020
+ records.write_json(short, short / "read-results.json", doc)
2021
+ held = records.read_json(records.record_path(short, "S3"))
2022
+ for o in held["outputs"]:
2023
+ if o["artifact"] == "read-results.json":
2024
+ o["sha256"] = records.sha256_file(short / "read-results.json")
2025
+ records.write_json(short, records.record_path(short, "S3"), held)
2026
+ guarded(drop_codex, None)
2027
+ control("D1: S3 results holding no result for an eligible unit stop S4 by name, before anything is formed",
2028
+ refusal(lambda: run(short, dry=True)).startswith(f"INPUT_PARTIAL S3 {codex_unit}")
2029
+ and not (short / "intake.json").exists(), refusal(lambda: run(short, dry=True)))
2030
+ edited = copy_of("instances")
2031
+
2032
+ def add_instance():
2033
+ """A line added to S3's instances after S3 recorded them."""
2034
+ doc = records.read_json(edited / "observations" / "resolutions.json")
2035
+ with open(edited / doc["instances"], "a", encoding="utf-8") as handle:
2036
+ handle.write(json.dumps({"expected_id": "N-1@r1", "occasion_locator": "x#1", "exposure": "shown",
2037
+ "verdict": "met", "basis": "source", "evidence_ids": []}) + "\n")
2038
+ guarded(add_instance, None)
2039
+ control("S4 reads S3's follow-up through S3's own reader: an instance line added after S3 is INSTANCE_IMMUTABLE",
2040
+ refusal(lambda: run(edited, dry=True)).startswith("INSTANCE_IMMUTABLE"), refusal(lambda: run(edited, dry=True)))
2041
+
2042
+ # dry: the barrier, the intake and the packet's measure, no call, and a record that does not let S5 in
2043
+ dry_dir = copy_of("dry")
2044
+ dry = guarded(lambda: run(dry_dir, dry=True), lambda exc: {"problem": repr(exc)})
2045
+ dry_record = record_of(dry_dir)
2046
+ control("dry: S4 stops before its call, leaves its record partial with the intake and the packet's measure, and "
2047
+ "makes no call",
2048
+ dry_record.get("status") == "partial" and sorted(o["artifact"] for o in dry_record.get("outputs", []))
2049
+ == sorted(["intake.json", DRY_PACKET, DRY_RECORD]) and not list((dry_dir / "calls").glob(f"*-{STAGE}-*"))
2050
+ and dry.get("packet", {}).get("driver_bytes", 0) > 0,
2051
+ f"{dry.get('problem')} {dry_record.get('status')} {dry_record.get('outputs')}")
2052
+ from runlib import dispatch
2053
+ dp = dry.get("packet", {})
2054
+ first_dp = math.ceil(dp.get("driver_bytes", 0) / dispatch.DENSITY_FLOOR) + dp.get("allowance_tokens", 0)
2055
+ control("WP-08e: a run with no formation call of the host reads S4's packet at the floor of a byte a token, named "
2056
+ "as its basis, and claims at most the first request with one retry's answer at the output cap and the "
2057
+ "error share added once",
2058
+ dp.get("bytes_per_token") == dispatch.DENSITY_FLOOR and dp.get("density_basis") == "floor: 1.0"
2059
+ and dp.get("first_request_tokens") == first_dp
2060
+ and dp.get("retry_margin") == dispatch.RETRY_ERROR_TOKENS
2061
+ and dp.get("input_tokens_at_most") == first_dp + OUTPUT_CAP + dispatch.RETRY_ERROR_TOKENS,
2062
+ f"{ {k: dp.get(k) for k in ('bytes_per_token', 'density_basis', 'first_request_tokens', 'input_tokens_at_most', 'retry_margin')} }")
2063
+ control("dry: a stage reading S4's output refuses its partial record (INPUT_PARTIAL S4)",
2064
+ refusal(lambda: records.run_stage(dry_dir, "S5", [{"artifact": "intake.json", "producer_stage": "S4"}])
2065
+ .__enter__()).startswith("INPUT_PARTIAL S4"), "admitted")
2066
+ over_dir = copy_of("over")
2067
+ control("FORM_OVER_BOUND: a packet over the bound is refused by name, and S4's record is failed",
2068
+ refusal(lambda: run(over_dir, dry=True, form_bound=1000)).startswith("FORM_OVER_BOUND S4")
2069
+ and record_of(over_dir).get("status") == "failed", refusal(lambda: run(over_dir, dry=True, form_bound=1000)))
2070
+ # W r1, F5 (lead decision): S4's bound is its own seat's context capacity, never S3's window bound
2071
+ opus = "claude:claude-opus-5-5/high"
2072
+ own = guarded(lambda: form_budget(opus), {})
2073
+ held_seats = gate.seats()
2074
+ control("W r1 F5: S4's limits are its own seat's - the capacity seats.json declares for it with its basis, the "
2075
+ "host's measured allowance, the output cap S4 declares, and, with no density given, the floor (WP-08e)",
2076
+ own.get("capacity") == held_seats.get("seat_capacity", {}).get(opus, {}).get("context_capacity", "none")
2077
+ and own.get("capacity_basis")
2078
+ and own.get("host_version") == held_seats["hosts"]["claude"]["version"]
2079
+ and own.get("allowance") == held_seats["hosts"]["claude"]["host_allowance"]["hermetic"]["allowance_tokens"]
2080
+ and own.get("output_cap") == OUTPUT_CAP and own.get("bytes_per_token") == dispatch.DENSITY_FLOOR
2081
+ and own.get("density_basis") == "floor: 1.0" and own.get("retry_margin") == dispatch.RETRY_ERROR_TOKENS,
2082
+ f"{own}")
2083
+ no_opus = root / "seats-no-opus.json"
2084
+ no_opus.write_text(json.dumps({**held_seats, "seat_capacity": {k: v for k, v in held_seats["seat_capacity"].items()
2085
+ if k != opus}}), encoding="utf-8")
2086
+ no_allowance = root / "seats-no-allowance.json"
2087
+ no_allowance.write_text(json.dumps({**held_seats, "hosts": {}}), encoding="utf-8")
2088
+ control("W r1 F5: a seat with no declared context capacity is FORM_CAPACITY_UNKNOWN, and a host with no measured "
2089
+ "allowance ALLOWANCE_UNMEASURED",
2090
+ refusal(lambda: form_budget(opus, no_opus)).startswith("FORM_CAPACITY_UNKNOWN S4")
2091
+ and refusal(lambda: form_budget(opus, no_allowance)).startswith("ALLOWANCE_UNMEASURED S4"),
2092
+ f"{refusal(lambda: form_budget(opus, no_opus))} {refusal(lambda: form_budget(opus, no_allowance))}")
2093
+ fits = 6_000
2094
+ small = {**own, "capacity": input_at_most(fits, own)[1] + OUTPUT_CAP} if own else {}
2095
+ control("W r1 F5: a packet whose tokens, the host allowance, a retry's answer and error share and the output "
2096
+ "reservation exceed the seat's capacity is FORM_OVER_BOUND naming the capacity; one that fills it exactly "
2097
+ "passes, and S3's window bound does not apply", bool(own) and any(f"over the S4 seat's context capacity {small['capacity']}" in line
2098
+ for line in bound_problems(fits + 100, small))
2099
+ and bound_problems(fits, small) == [] and bound_problems(bound.INPUT_BOUND + 80_000, own) == [],
2100
+ f"{guarded(lambda: bound_problems(fits + 100, small), None)} {guarded(lambda: bound_problems(fits, small), None)}")
2101
+ # WP-08e: what the bytes take as tokens is read from the run's own calls of the seat and kind, each by its first
2102
+ # request; a retry is its own margin. Earlier formation attempts are planted in the run, counts only.
2103
+ from runlib import stage_read as s3_fx
2104
+ s4_seat = opus # the fixture's S4 seat: a density is read per class, its stage, seat and kind (W r1, F3)
2105
+ dense_dir = copy_of("dense")
2106
+ guarded(lambda: s3_fx.fx_planted_call(dense_dir, f"{dense_dir.name}-S4-form-a0", s4_seat, STAGE, CASE, 30_000,
2107
+ [(2, 500, 0, 19_998)]), None)
2108
+ guarded(lambda: s3_fx.fx_planted_call(dense_dir, f"{dense_dir.name}-S4-form-b0", s4_seat, STAGE, CASE, 40_000,
2109
+ [(2, 500, 0, 19_998)]), None)
2110
+ dense = guarded(lambda: run(dense_dir, dry=True), lambda exc: {"problem": repr(exc)}).get("packet", {})
2111
+ at_old = math.ceil(dense.get("driver_bytes", 0) / 1.94) + dense.get("allowance_tokens", 0) + OUTPUT_CAP \
2112
+ + dispatch.RETRY_ERROR_TOKENS
2113
+ control("WP-08e: of two formation calls the run measured at 1.5 and 2.0 bytes a token, the fewest - below the 1.94 "
2114
+ "S4 assumed - makes S4's claim the bytes at 1.5, named as measured, and higher than at 1.94",
2115
+ dense.get("bytes_per_token") == 1.5 and dense.get("density_basis") == f"measured: {s4_seat}/S4:form/2 samples"
2116
+ and dense.get("first_request_tokens") == math.ceil(dense.get("driver_bytes", 0) / 1.5) + dense.get("allowance_tokens", 0)
2117
+ and dense.get("input_tokens_at_most", 0) > at_old,
2118
+ f"{ {k: dense.get(k) for k in ('problem', 'bytes_per_token', 'density_basis', 'first_request_tokens', 'input_tokens_at_most')} } at 1.94: {at_old}")
2119
+ # C2's formation call, counts only: two main requests, the second the host's retry of a refused structured output
2120
+ c2_dir = copy_of("c2-shape")
2121
+ guarded(lambda: s3_fx.fx_planted_call(c2_dir, f"{c2_dir.name}-S4-form-a0", s4_seat, STAGE, CASE, 46_530,
2122
+ [(2, 5_719, 6_007, 14_482), (2, 4_435, 20_489, 6_303)]), None)
2123
+ c2_density = guarded(lambda: dispatch.measured_density(c2_dir, s4_seat, STAGE, CASE), {})
2124
+ c2_retry = guarded(lambda: dispatch.retry_share(c2_dir, "claude"), {})
2125
+ c2_seen = guarded(lambda: observed(c2_dir / "calls" / f"{c2_dir.name}-S4-form-a0", own), {})
2126
+ control("WP-08e: C2's two-request formation call reads 2.270 bytes a token by its first request - never 0.984 by "
2127
+ "the sum of its requests or 1.736 by the largest - and its retry is counted apart, its error share of 584 "
2128
+ "below the constant margin; S4's observation of the call keeps its first request and its largest apart",
2129
+ c2_density.get("bytes_per_token") == 2.27 and c2_retry.get("retried") == 1
2130
+ and c2_retry.get("margin") == dispatch.RETRY_ERROR_TOKENS and "constant" in c2_retry.get("margin_basis", "")
2131
+ and c2_seen.get("input_tokens") == 20_491 and c2_seen.get("bytes_per_token") == 2.271
2132
+ and c2_seen.get("requests") == 2 and c2_seen.get("largest_input") == 26_794
2133
+ and c2_seen.get("within_claim") is True,
2134
+ f"{c2_density} {c2_retry} {c2_seen}")
2135
+ wide_dir = copy_of("wide-retry")
2136
+ guarded(lambda: s3_fx.fx_planted_call(wide_dir, f"{wide_dir.name}-S4-form-a0", s4_seat, STAGE, CASE, 46_530,
2137
+ [(2, 5_719, 6_007, 14_482), (2, 4_435, 20_489, 6_303 + 2_416)]), None)
2138
+ wide = guarded(lambda: run(wide_dir, dry=True), lambda exc: {"problem": repr(exc)}).get("packet", {})
2139
+ control("WP-08e: a retry the run measured with a larger error share than the constant raises the margin S4 claims, "
2140
+ "named as measured",
2141
+ wide.get("retry_margin") == 3_000 and wide.get("margin_basis", "").startswith("measured: claude/1 retries")
2142
+ and wide.get("input_tokens_at_most") == wide.get("first_request_tokens", 0) + OUTPUT_CAP + 3_000,
2143
+ f"{ {k: wide.get(k) for k in ('problem', 'retry_margin', 'margin_basis', 'first_request_tokens', 'input_tokens_at_most')} }")
2144
+ # the margin once: a retry whose first answer filled the output cap and whose error took the whole margin stays
2145
+ # within the claim; a claim without the margin would not hold it, and one with it twice is not the claim
2146
+ if own:
2147
+ first_c, claim_c = input_at_most(40_000, own)
2148
+ filled = [{"role": "main", "state": "measured", "input": 2, "cache_read": 0, "cache_creation": first_c - 2,
2149
+ "output": OUTPUT_CAP},
2150
+ {"role": "main", "state": "measured", "input": 2, "cache_read": first_c - 2,
2151
+ "cache_creation": OUTPUT_CAP + own["retry_margin"], "output": 10}]
2152
+ control("WP-08e: S4 claims at most the first request plus one answer at the output cap plus the error share, "
2153
+ "the margin added once, and a retry that used all of it stays within the claim",
2154
+ claim_c == first_c + OUTPUT_CAP + own["retry_margin"]
2155
+ and within_claim(filled, form_claim(40_000, own)) is True
2156
+ and within_claim(filled, {**form_claim(40_000, own), "step": OUTPUT_CAP + own["retry_margin"] - 1})
2157
+ is False,
2158
+ f"first {first_c} claim {claim_c} largest {bound.observed_input(filled)[0]}")
2159
+ else:
2160
+ control("WP-08e: S4 claims at most the first request plus one answer at the output cap plus the error share, "
2161
+ "the margin added once, and a retry that used all of it stays within the claim", False, "no limits")
2162
+ # a declared density - an earlier run's measured table - is what S4's claim rests on where the run made no
2163
+ # formation call, and says so; the report ends with the run's own measured table
2164
+ declared_s4 = {opus: {f"{STAGE}:{CASE}": {"bytes_per_token": 2.27, "measured_in": "c2-20261110", "samples": 1,
2165
+ "at": "2026-11-10T23:22:00+09:00"}}}
2166
+ decl_run = guarded(lambda: fx_s3(root / "declared", density=declared_s4)[0], None)
2167
+ decl = guarded(lambda: run(decl_run, dry=True), lambda exc: {"problem": repr(exc)}) if decl_run else {}
2168
+ dp4 = decl.get("packet", {})
2169
+ said4 = guarded(lambda: report_lines(decl), [])
2170
+ own_table = decl.get("density_table") or {}
2171
+ own_kinds = [f"{seat_t} {kind}" for seat_t in sorted(own_table) for kind in sorted(own_table[seat_t])]
2172
+ control("WP-08e: with no formation call of its own, S4's claim rests on the declared density and names it "
2173
+ "(declared: <run>/<n>), and its report ends with the run's measured table, one line per seat and kind",
2174
+ dp4.get("bytes_per_token") == 2.27 and dp4.get("density_basis") == "declared: c2-20261110/1"
2175
+ and dp4.get("first_request_tokens") == math.ceil(dp4.get("driver_bytes", 0) / 2.27) + dp4.get("allowance_tokens", 0)
2176
+ and any(k.endswith(" S3:window") for k in own_kinds)
2177
+ and [line.split(",")[0] for line in said4[-len(own_kinds):]]
2178
+ == [f"measured density: {k}" for k in own_kinds] and len(said4) > len(own_kinds),
2179
+ f"{decl.get('problem')} { {k: dp4.get(k) for k in ('bytes_per_token', 'density_basis', 'first_request_tokens')} } "
2180
+ f"{own_kinds} {said4[-3:]}")
2181
+ control("a formation call is not dispatched without a supervisor (FORM_UNSUPERVISED)",
2182
+ refusal(lambda: run(copy_of("unsupervised"))).startswith("FORM_UNSUPERVISED"), "dispatched")
2183
+
2184
+ # golden: the one call through the golden host, its answer checked and read, and the population written
2185
+ gold_dir = copy_of("gold")
2186
+ plan = guarded(lambda: fx_form_plan(gold_dir, root / "c5-plan.json"), None)
2187
+ made = guarded(lambda: run(gold_dir, supervisor(gold_dir, root / "c5-cells", plan)), lambda exc: {"problem": repr(exc)})
2188
+ pop_doc = guarded(lambda: records.read_json(gold_dir / "population.json"), {})
2189
+ intake_doc = guarded(lambda: records.read_json(gold_dir / "intake.json"), {"candidates": []})
2190
+ control("golden: S4 makes its one call, accepts the answer, and completes with every output it wrote recorded",
2191
+ made.get("call", {}).get("outcome") == "accepted" and record_of(gold_dir).get("status") == "complete"
2192
+ and sorted(o["artifact"] for o in record_of(gold_dir).get("outputs", [])) == sorted(OUTPUTS),
2193
+ f"{made.get('problem') or made.get('call')} {record_of(gold_dir).get('status')}")
2194
+ control("golden: the intake is derived from the pinned ledger and the current library S2 left: two due decisions "
2195
+ "(one a pending intervention on a placed entry), two legacy entries, two redundancy hints (a near pair and "
2196
+ "a group of identical text), one G cluster",
2197
+ intake_doc.get("counts") == {"due_decision": 2, "legacy": 2, "obsolete_hint": 0, "redundancy_hint": 2,
2198
+ "g_cluster": 1}
2199
+ and any(c.get("pending_intervention") for c in intake_doc["candidates"] if c["source"] == "due_decision"),
2200
+ f"{intake_doc.get('counts')}")
2201
+ control("golden: the population lists the formed candidates and every lifecycle candidate of the intake, each once, "
2202
+ "and holds the subject's events exactly",
2203
+ set(c["candidate_id"] for c in intake_doc["candidates"]) <= set(pop_doc.get("candidate_ids", []))
2204
+ and len(pop_doc.get("candidate_ids", [])) == len(intake_doc["candidates"]) + 2
2205
+ and len(pop_doc.get("event_membership", {})) == 4 and pop_doc.get("counts", {}).get("carried_forward") == 1
2206
+ and [u["status"] for u in pop_doc.get("not_formed", [])] == ["read_partial"],
2207
+ f"{pop_doc.get('candidate_ids')} {pop_doc.get('counts')}")
2208
+ lines = guarded(lambda: [json.loads(x) for x in (gold_dir / "partition.jsonl").read_text(encoding="utf-8").splitlines()], [])
2209
+ cands = guarded(lambda: records.read_json(gold_dir / "candidates.json"), {"candidates": [], "rejected_findings": []})
2210
+ formed_rows = [c for c in cands["candidates"] if c["source"] == "formed"]
2211
+ control("golden: partition.jsonl places each event once, and candidates.json keeps the formed candidate with its "
2212
+ "events and sessions beside the lifecycle candidates and the rejected finding",
2213
+ len(lines) == 4 and len({r["event_id"] for r in lines}) == 4 and len(formed_rows) == 2
2214
+ and len(formed_rows[0]["event_ids"]) == 2 and formed_rows[0]["sessions"]
2215
+ and len(cands["candidates"]) == len(pop_doc.get("candidate_ids", [])) and len(cands["rejected_findings"]) == 1,
2216
+ f"{len(lines)} {formed_rows[:1]}")
2217
+ cluster_g = next((c for c in formed_rows if c["type"] == "G"), {})
2218
+ placed = next((c for c in intake_doc.get("candidates", []) if c["source"] == "g_cluster"), {})
2219
+ origin_cited = formed_rows[0]["admission"]["observed_event"]["evidence_ids"] if formed_rows else []
2220
+ control("golden (F2, F3): S4 shows the intake's placed cluster, so a type G candidate distilled from it with no event "
2221
+ "is formed with the entries it cites and an evidence bar held for lineages the ledger does not record; the "
2222
+ "origin quote a candidate cites reaches candidates.json as its verified evidence record",
2223
+ cluster_g.get("event_ids") == [] and cluster_g.get("tension", {}).get("cluster") == placed.get("candidate_id")
2224
+ and cluster_g.get("tension", {}).get("instance_entry_ids") == placed.get("entries", [None])[:3]
2225
+ and (cluster_g.get("evidence_bar") or {}).get("status") == "held"
2226
+ and (cluster_g.get("evidence_bar") or {}).get("lineages") is None
2227
+ and len(origin_cited) == 1 and origin_cited[0].startswith("origin:")
2228
+ and list(cands.get("origin_evidence", {})) == origin_cited
2229
+ and cands["origin_evidence"][origin_cited[0]].get("redacted_text"),
2230
+ f"{cluster_g.get('tension')} {cluster_g.get('evidence_bar')} {origin_cited} {list(cands.get('origin_evidence', {}))}")
2231
+ before = guarded(lambda: (gold_dir / "population.json").read_bytes(), b"")
2232
+ again = guarded(lambda: run(gold_dir, supervisor(gold_dir, root / "c5-cells", plan)), lambda exc: {"problem": repr(exc)})
2233
+ control("golden: S4 run again over its run reuses the accepted attempt and leaves the same population bytes",
2234
+ again.get("call", {}).get("reused") and guarded(lambda: (gold_dir / "population.json").read_bytes(), b"") == before
2235
+ and len(list((gold_dir / "calls").glob(f"*-{STAGE}-*"))) == 1,
2236
+ f"{again.get('problem') or again.get('call')}")
2237
+
2238
+ # W r1, F4 (lead decision): a formation call past its claim stops the run by name and S4 does not complete; an
2239
+ # attempt reused after the stop lifts is held to the claim as the declaration then stands
2240
+ def retried(directory, cells, plan_c, requests):
2241
+ sup_c = supervisor(directory, cells, plan_c)
2242
+ honest_runner = sup_c.runner
2243
+ sup_c.runner = lambda host, spec: [*honest_runner(host, spec)[:-1],
2244
+ json.dumps({**json.loads(honest_runner(host, spec)[-1]),
2245
+ "main_requests": requests, "request_step": 100})]
2246
+ return sup_c
2247
+ from runlib import declare
2248
+ claim_dir = copy_of("claim-three")
2249
+ claim_plan = guarded(lambda: fx_form_plan(claim_dir, root / "c5-plan-claim.json"), None)
2250
+ stopped_c = refusal(lambda: run(claim_dir, retried(claim_dir, root / "c5-cells-claim", claim_plan, 3)))
2251
+ control("W r1 F4: a formation call of three main requests, its claim holding one retry, stops the run by name and "
2252
+ "S4 does not complete",
2253
+ stopped_c.startswith(f"CLAIM_EXCEEDED {claim_dir.name}-S4-form-a") and "3 main requests" in stopped_c
2254
+ and record_of(claim_dir).get("status") != "complete"
2255
+ and "CLAIM_EXCEEDED" in (records.read_json(dispatch.run_ledger_path(claim_dir)).get("stops") or {}),
2256
+ f"{stopped_c} {record_of(claim_dir).get('status')}")
2257
+ guarded(lambda: declare.amend(claim_dir, [("retry", {"margin": 2_000})], "a wider margin, the count unchanged"),
2258
+ None)
2259
+ again_c = refusal(lambda: run(claim_dir, retried(claim_dir, root / "c5-cells-claim", claim_plan, 3)))
2260
+ control("W r1 F4: a margin amendment lifts the stop, and the next attempt of three main requests is stopped "
2261
+ "again: the claim still holds one retry",
2262
+ again_c.startswith(f"CLAIM_EXCEEDED {claim_dir.name}-S4-form-a") and again_c != stopped_c
2263
+ and record_of(claim_dir).get("status") != "complete", f"{again_c} {record_of(claim_dir).get('status')}")
2264
+ bare_dir = copy_of("claim-unrecorded")
2265
+ bare_plan = guarded(lambda: fx_form_plan(bare_dir, root / "c5-plan-claim-bare.json"), None)
2266
+
2267
+ def unclaimed(directory, cells, plan_c, requests):
2268
+ sup_c = retried(directory, cells, plan_c, requests)
2269
+ sup_c.claim_terms = lambda *args, **kwargs: None # a call the dispatcher records no claim for
2270
+ return sup_c
2271
+ bare_c = refusal(lambda: run(bare_dir, unclaimed(bare_dir, root / "c5-cells-claim-bare", bare_plan, 3)))
2272
+ control("W r1 F4: within_claim=false does not coexist with a completed stage - an accepted formation call no claim "
2273
+ "was recorded for, past S4's own claim, stops the run by name and S4 does not complete",
2274
+ bare_c.startswith(f"CLAIM_EXCEEDED {bare_dir.name}-S4-form-a") and "S4 is not completed on it" in bare_c
2275
+ and record_of(bare_dir).get("status") != "complete"
2276
+ and "CLAIM_EXCEEDED" in (records.read_json(dispatch.run_ledger_path(bare_dir)).get("stops") or {}),
2277
+ f"{bare_c} {record_of(bare_dir).get('status')}")
2278
+ # W r2, F5: the fallback stop is offered by standing, not by presence - a margin amendment lifts it, the accepted
2279
+ # attempt is reused and still breaches a claim of one retry, and the run stops again
2280
+ first_b = (records.read_json(dispatch.run_ledger_path(bare_dir)).get("stops") or {}).get("CLAIM_EXCEEDED") or {}
2281
+ guarded(lambda: declare.amend(bare_dir, [("retry", {"margin": 2_000})], "a wider margin, the count unchanged"),
2282
+ None)
2283
+ lifted_b = guarded(lambda: unclaimed(bare_dir, root / "c5-cells-claim-bare", bare_plan, 3)._blocked(), "unread")
2284
+ bare_again = refusal(lambda: run(bare_dir, unclaimed(bare_dir, root / "c5-cells-claim-bare", bare_plan, 3)))
2285
+ stood_b = (records.read_json(dispatch.run_ledger_path(bare_dir)).get("stops") or {}).get("CLAIM_EXCEEDED") or {}
2286
+ blocked_b = guarded(lambda: unclaimed(bare_dir, root / "c5-cells-claim-bare", bare_plan, 3)._blocked(), None)
2287
+ control("W r2 F5: after a margin amendment lifts S4's fallback stop, a reused attempt that still breaches the "
2288
+ "claim stops the run again - the new stop stands, stamped later than the lifted one",
2289
+ lifted_b is None and bare_again.startswith(f"CLAIM_EXCEEDED {bare_dir.name}-S4-form-a")
2290
+ and (blocked_b or "").startswith("RUN_STOPPED CLAIM_EXCEEDED")
2291
+ and isinstance(first_b.get("declaration_seq"), int)
2292
+ and stood_b.get("declaration_seq", 0) > first_b["declaration_seq"],
2293
+ f"lifted={lifted_b} again={bare_again} blocked={blocked_b} "
2294
+ f"seq {first_b.get('declaration_seq')} -> {stood_b.get('declaration_seq')}")
2295
+ # the lead's verification of commit 4, finding 4: S4's fallback persists its stop from the rows it judged, so a
2296
+ # usage record unreadable by then cannot take the stop down with it
2297
+ unread_dir = copy_of("claim-usage-unreadable")
2298
+ unread_plan = guarded(lambda: fx_form_plan(unread_dir, root / "c5-plan-claim-unread.json"), None)
2299
+ honest_observed = globals()["observed"]
2300
+
2301
+ def observed_then_lost(call_dir, limits=None, rows=None):
2302
+ seen = honest_observed(call_dir, limits, rows)
2303
+ (pathlib.Path(call_dir) / "usage.json").write_text(json.dumps({"call_id": "lost"}), encoding="utf-8")
2304
+ return seen
2305
+ globals()["observed"] = observed_then_lost
2306
+ try:
2307
+ unread_c = refusal(lambda: run(unread_dir, unclaimed(unread_dir, root / "c5-cells-claim-unread", unread_plan, 3)))
2308
+ finally:
2309
+ globals()["observed"] = honest_observed
2310
+ control("lead v4 4: S4's fallback stops the run from the rows it judged though the usage record is unreadable by "
2311
+ "then - the named stop, never a KeyError",
2312
+ unread_c.startswith(f"CLAIM_EXCEEDED {unread_dir.name}-S4-form-a") and "3 main requests, at most 2" in unread_c
2313
+ and "CLAIM_EXCEEDED" in (records.read_json(dispatch.run_ledger_path(unread_dir)).get("stops") or {}),
2314
+ f"{unread_c} {sorted((records.read_json(dispatch.run_ledger_path(unread_dir)).get('stops') or {}))}")
2315
+ control("lead v4 4: a usage record without request rows is refused by name (RECORD_UNREADABLE), not a KeyError",
2316
+ refusal(lambda: usage_rows(next(iter((unread_dir / "calls").glob(f"*-{STAGE}-*")), unread_dir)))
2317
+ .startswith("RECORD_UNREADABLE"), "read as rows")
2318
+
2319
+ # W r2, F7: S4's own claim holds the first request to its estimate too
2320
+ dense_dir = copy_of("claim-dense-first")
2321
+ dense_plan = guarded(lambda: fx_form_plan(dense_dir, root / "c5-plan-claim-dense.json"), None)
2322
+
2323
+ def denser(directory, cells, plan_c):
2324
+ sup_c = unclaimed(directory, cells, plan_c, 1)
2325
+ honest_c = sup_c.runner
2326
+ sup_c.runner = lambda host, spec: [*honest_c(host, spec)[:-1],
2327
+ json.dumps({**json.loads(honest_c(host, spec)[-1]),
2328
+ "request_base": first_dp + 1_000})]
2329
+ return sup_c
2330
+ dense_c = refusal(lambda: run(dense_dir, denser(dense_dir, root / "c5-cells-claim-dense", dense_plan)))
2331
+ control("W r2 F7: an accepted formation call no claim was recorded for, its one request denser than S4's estimate "
2332
+ "though within the retry's ceiling, stops the run by name and S4 does not complete",
2333
+ dense_c.startswith(f"CLAIM_EXCEEDED {dense_dir.name}-S4-form-a") and ": request 1 took" in dense_c
2334
+ and record_of(dense_dir).get("status") != "complete",
2335
+ f"{dense_c} {record_of(dense_dir).get('status')}")
2336
+ guarded(lambda: declare.amend(claim_dir, [("retry.count", 2)], "the host retried twice; the claim holds two"), None)
2337
+ held_c = guarded(lambda: run(claim_dir, retried(claim_dir, root / "c5-cells-claim", claim_plan, 3)),
2338
+ lambda exc: {"problem": repr(exc)})
2339
+ control("W r1 F4: ... and once the count is re-declared the same attempt is within its claim and S4 completes",
2340
+ (held_c.get("call", {}).get("observed") or {}).get("within_claim") is True
2341
+ and held_c["call"]["observed"].get("requests") == 3 and held_c["call"]["observed"].get("requests_at_most") == 3
2342
+ and record_of(claim_dir).get("status") == "complete",
2343
+ f"{held_c.get('problem') or held_c.get('call')} {record_of(claim_dir).get('status')}")
2344
+ two_dir = copy_of("claim-two")
2345
+ two_plan = guarded(lambda: fx_form_plan(two_dir, root / "c5-plan-claim-two.json"), None)
2346
+ two_c = guarded(lambda: run(two_dir, retried(two_dir, root / "c5-cells-claim-two", two_plan, 2)),
2347
+ lambda exc: {"problem": repr(exc)})
2348
+ control("control, W r1 F4: a formation call of two main requests within its claim completes S4",
2349
+ (two_c.get("call", {}).get("observed") or {}).get("within_claim") is True
2350
+ and two_c["call"]["observed"].get("requests") == 2 and record_of(two_dir).get("status") == "complete",
2351
+ f"{two_c.get('problem') or two_c.get('call')}")
2352
+
2353
+ # W r1, F3: every attempt is measured as it is sent, so a retry whose correction outgrows the room it was admitted
2354
+ # with is refused by name before it is reserved
2355
+ from runlib import stage_read as s3_read
2356
+ retry_dir = copy_of("retry-over")
2357
+ retry_plan = root / "c5-plan-retry-over.json"
2358
+
2359
+ def plant_unknown_claims():
2360
+ """The golden answer naming a hundred claim labels the packet does not show: its correction is long."""
2361
+ planned = json.loads(plan.read_text(encoding="utf-8"))
2362
+ planned[0]["answer"]["candidates"][0]["admission"]["consequence"]["claim_ids"] = [f"c{n}" for n in range(100, 200)]
2363
+ retry_plan.write_text(json.dumps(planned), encoding="utf-8")
2364
+ guarded(plant_unknown_claims, None)
2365
+ admitted_at = dry.get("packet", {}).get("driver_bytes", 0) + s3_read.CORRECTION_ROOM
2366
+ over_retry = refusal(lambda: run(retry_dir, supervisor(retry_dir, root / "c5-cells-retry-over", retry_plan),
2367
+ form_bound=admitted_at))
2368
+ control("W r1 F3: a packet admitted with its retry's correction room, whose correction outgrows that room, is "
2369
+ "refused by name before the retry is reserved, and S4's record is failed",
2370
+ over_retry.startswith("FORM_OVER_BOUND S4: this attempt's packet takes") and record_of(retry_dir).get("status") == "failed"
2371
+ and len(list((retry_dir / "calls").glob(f"*-{STAGE}-*"))) == 1, over_retry)
2372
+
2373
+ room_short = copy_of("room-short")
2374
+ short_by_one = refusal(lambda: run(room_short, dry=True, form_bound=admitted_at - 1))
2375
+ control("W r1 F3: S4 is admitted only with room for its retry's correction: a bound one byte short of the packet "
2376
+ "and that room is FORM_OVER_BOUND at admission", short_by_one.startswith("FORM_OVER_BOUND S4: the formation packet")
2377
+ and "with its retry's correction room" in short_by_one, short_by_one)
2378
+
2379
+ # W r1, F4: a run that died holding a reservation of S4 is closed, or refused beside, when S4 runs again
2380
+ s4_seat = gate.seats()["stage_seats"][STAGE][0]
2381
+
2382
+ def reserved_copy(label, plant=None):
2383
+ """A copy of the golden run whose S4 reservation a dead run left open, `plant` marking what it got to."""
2384
+ where = copy_of(label)
2385
+ sup = supervisor(where, root / f"c5-cells-{label}", plan)
2386
+ held = sup.reserve(STAGE, ITEM, s4_seat, CASE, tranche="calibration")
2387
+ if plant is not None:
2388
+ with sup._lock():
2389
+ ledger = sup.ledger()
2390
+ sup._stage(ledger, STAGE)["reservations"][held["call_id"]].update(plant(sup))
2391
+ sup._write(ledger)
2392
+ return where, held["call_id"]
2393
+
2394
+ def open_s4(where):
2395
+ sup = supervisor(where, root / "c5-cells-look", plan)
2396
+ return sorted(c for c, r in sup._stage(sup.ledger(), STAGE)["reservations"].items() if r["open"])
2397
+ crashed_dir, crashed_call = guarded(lambda: reserved_copy("reserved"), (None, None))
2398
+ resumed = guarded(lambda: run(crashed_dir, supervisor(crashed_dir, root / "c5-cells-reserved", plan)),
2399
+ lambda exc: {"problem": repr(exc)})
2400
+ control("W r1 F4: a run that died after reserving its call is closed when S4 runs again - the reservation released "
2401
+ "unspent - and the call is made",
2402
+ crashed_call is not None and resumed.get("call", {}).get("outcome") == "accepted"
2403
+ and [(r.get("call_id"), r.get("charged")) for r in resumed.get("interrupted", [])] == [(crashed_call, "unspent")]
2404
+ and guarded(lambda: open_s4(crashed_dir), ["?"]) == [],
2405
+ f"{resumed.get('problem') or resumed.get('call')} {resumed.get('interrupted')}")
2406
+ unverified_dir, unverified_call = guarded(
2407
+ lambda: reserved_copy("unverified", lambda sup: {"dispatched_at": sup.clock(), "spawning": sup.clock()}), (None, None))
2408
+ refused_unverified = refusal(lambda: run(unverified_dir, supervisor(unverified_dir, root / "c5-cells-unverified", plan)))
2409
+ control("W r1 F4: a run that died after starting a runner it never recorded is refused by name "
2410
+ "(RESUME_HOST_UNVERIFIED) before anything is reserved or sent, its reservation left open",
2411
+ unverified_call is not None and refused_unverified.startswith("RESUME_HOST_UNVERIFIED")
2412
+ and unverified_call in refused_unverified and record_of(unverified_dir).get("status") == "failed"
2413
+ and not list((unverified_dir / "calls").glob(f"*-{STAGE}-*"))
2414
+ and guarded(lambda: open_s4(unverified_dir), []) == [unverified_call], refused_unverified)
2415
+
2416
+ # W r2, F1: the capacity S4 was admitted against is in each attempt's record, where the gate holds the host's
2417
+ # reported window to it
2418
+ def reporting(where, label, plan_path, window):
2419
+ """S4's golden supervisor over `where`, its host reporting a context window of `window` in each result."""
2420
+ cells = root / f"c5-cells-{label}"
2421
+ sup = supervisor(where, cells, plan_path)
2422
+ fake, answers = cells / "fake_host.py", str(pathlib.Path(plan_path).resolve())
2423
+ sup.runner = lambda host, spec: [sys.executable, str(fake), host, "clean",
2424
+ json.dumps({**spec, "answers": answers, "context_window": window})]
2425
+ return sup
2426
+
2427
+ def s4_calls(where):
2428
+ return sorted((where / "calls").glob(f"*-{STAGE}-*"))
2429
+ same_dir = copy_of("cap-same")
2430
+ same = guarded(lambda: run(same_dir, reporting(same_dir, "cap-same", plan, own.get("capacity"))),
2431
+ lambda exc: {"problem": repr(exc)})
2432
+ seen = (same.get("call") or {}).get("observed") or {}
2433
+ same_record = guarded(lambda: records.read_json(s4_calls(same_dir)[0] / "call.json")["bound"], {})
2434
+ control("W r2 F1: an attempt's record carries the capacity S4 was admitted against, and a host reporting that "
2435
+ "window is accepted; form.json keeps what the call measured of the capacity and of the bytes a token covers",
2436
+ same.get("call", {}).get("outcome") == "accepted" and same_record.get("context_capacity") == own.get("capacity")
2437
+ and seen.get("admitted_capacity") == own.get("capacity")
2438
+ and list(seen.get("context_window", {}).values()) == [own.get("capacity")]
2439
+ and seen.get("driver_bytes") == same_record.get("driver_bytes") and (seen.get("input_tokens") or 0) > 0
2440
+ and seen.get("bytes_per_token") == round(same_record["driver_bytes"] / seen["input_tokens"], 3)
2441
+ and seen.get("requests") == 1 and seen.get("largest_input") == seen.get("input_tokens")
2442
+ and seen.get("within_claim") is True and isinstance(seen.get("input_tokens_at_most"), int),
2443
+ f"{same.get('problem') or same.get('call')} {same_record}")
2444
+ drift_dir = copy_of("cap-drift")
2445
+ drift = guarded(lambda: run(drift_dir, reporting(drift_dir, "cap-drift", plan, 200_000)),
2446
+ lambda exc: {"problem": repr(exc)})
2447
+ control("W r2 F1: a host reporting another context window than the capacity S4 was admitted against fails the "
2448
+ "gate (CAPACITY_DRIFT), and nothing is formed",
2449
+ drift.get("call", {}).get("outcome") == "failed" and "CAPACITY_DRIFT" in drift.get("call", {}).get("codes", [])
2450
+ and record_of(drift_dir).get("status") == "partial" and not (drift_dir / "population.json").exists(),
2451
+ f"{drift.get('problem') or drift.get('call')}")
2452
+ bare_dir = copy_of("cap-missing")
2453
+
2454
+ def unrecorded():
2455
+ """S4's supervisor, its calls made without the capacity S4 hands them: what a broken wire would leave."""
2456
+ sup = supervisor(bare_dir, root / "c5-cells-cap-missing", plan)
2457
+ real_call = sup.call
2458
+ sup.call = lambda *args, **kwargs: real_call(*args, **{**kwargs, "context_capacity": None})
2459
+ return sup
2460
+ bare = refusal(lambda: run(bare_dir, unrecorded()))
2461
+ control("W r2 F1: an attempt whose record lacks the capacity S4 was admitted against stops S4 by name "
2462
+ "(CAPACITY_UNRECORDED) before its answer is judged or retried",
2463
+ bare.startswith("CAPACITY_UNRECORDED") and len(guarded(lambda: s4_calls(bare_dir), [])) == 1
2464
+ and record_of(bare_dir).get("status") == "failed", bare)
2465
+
2466
+ invalid_dir = copy_of("cap-invalid")
2467
+
2468
+ def invalid_capacity():
2469
+ """One S4 call handed a capacity that is no number."""
2470
+ sup = supervisor(invalid_dir, root / "c5-cells-cap-invalid", plan)
2471
+ held = sup.reserve(STAGE, ITEM, s4_seat, CASE, tranche="calibration")
2472
+ sent_schema = packet.schema_bytes(form_schema())
2473
+ return sup, sup.call(STAGE, s4_seat, packet.build(held["call_id"], STAGE, s4_seat, "x\n", sent_schema), form_schema(),
2474
+ reservation=held, caps={"tokens": 1000, "compactions": 2}, view_window=False,
2475
+ max_output_tokens=OUTPUT_CAP, context_capacity="big")
2476
+ invalid = refusal(invalid_capacity)
2477
+ control("W r2 F1: a stage's capacity that is not a positive integer is refused by name (CAPACITY_INVALID), its "
2478
+ "reservation released and nothing sent", invalid.startswith("CAPACITY_INVALID")
2479
+ and not guarded(lambda: s4_calls(invalid_dir), ["?"]) and guarded(lambda: open_s4(invalid_dir), ["?"]) == [],
2480
+ invalid)
2481
+
2482
+ # W r2, F2: each attempt is measured under the call id it is given, a resumed run's two-digit ones included
2483
+ def closed_attempts(where, label):
2484
+ """Nine attempts of S4's item reserved and closed, as earlier runs leave them: the next is a10."""
2485
+ sup = supervisor(where, root / f"c5-cells-{label}", plan)
2486
+ for _ in range(9):
2487
+ held = sup.reserve(STAGE, ITEM, s4_seat, CASE, tranche="calibration")
2488
+ sup.release(STAGE, held["call_id"], "refused")
2489
+ events_shown = guarded(lambda: json.loads(plan.read_text(encoding="utf-8"))[0]["match"], [])
2490
+ resumed_plan = root / "c5-plan-two-digit.json"
2491
+ guarded(lambda: resumed_plan.write_text(json.dumps(
2492
+ [{"match": [*events_shown, "rejected by validation"], "answer": json.loads(plan.read_text(encoding="utf-8"))[0]["answer"]},
2493
+ {"match": events_shown, "answer": json.loads(retry_plan.read_text(encoding="utf-8"))[0]["answer"]}]),
2494
+ encoding="utf-8"), None)
2495
+ free_dir = copy_of("two-digit-free")
2496
+ guarded(lambda: closed_attempts(free_dir, "two-digit-free"), None)
2497
+ free = guarded(lambda: run(free_dir, supervisor(free_dir, root / "c5-cells-two-digit-free", resumed_plan)),
2498
+ lambda exc: {"problem": repr(exc)})
2499
+ free_calls = guarded(lambda: s4_calls(free_dir), [])
2500
+ sent = guarded(lambda: bound.driver_bytes((free_calls[1] / "packet.md").read_text(encoding="utf-8"),
2501
+ (free_calls[1] / "schema.json").read_bytes())[0], 0)
2502
+ tight_dir = copy_of("two-digit-tight")
2503
+ guarded(lambda: closed_attempts(tight_dir, "two-digit-tight"), None)
2504
+ tight = refusal(lambda: run(tight_dir, supervisor(tight_dir, root / "c5-cells-two-digit-tight", resumed_plan),
2505
+ form_bound=sent - 1))
2506
+ control("W r2 F2: after nine closed attempts S4's attempts are a10 and a11, and a bound one byte short of the a11 "
2507
+ "packet as sent refuses that retry, measured at exactly its bytes",
2508
+ free.get("call", {}).get("outcome") == "accepted" and [d.name[-4:] for d in free_calls] == ["-a10", "-a11"]
2509
+ and sent > 0 and tight.startswith(f"FORM_OVER_BOUND S4: this attempt's packet takes {sent} driver bytes")
2510
+ and [d.name[-4:] for d in guarded(lambda: s4_calls(tight_dir), [])] == ["-a10"]
2511
+ and guarded(lambda: open_s4(tight_dir), ["?"]) == [],
2512
+ f"{free.get('problem') or free.get('call')} {[d.name for d in free_calls]} sent={sent} {tight} "
2513
+ f"open={guarded(lambda: open_s4(tight_dir), ['?'])}")
2514
+
2515
+ # F2 at the stage: a window none of whose units resolved an event still forms from the intake's placed cluster
2516
+ quiet = copy_of("no-events")
2517
+ quiet_plan = root / "c5-plan-no-events.json"
2518
+ guarded(lambda: quiet_plan.write_text(json.dumps([{"match": ['"cluster_id": "u1"', '"entry_id": "u1.3"'], "answer": {
2519
+ "candidates": [{**json.loads(plan.read_text(encoding="utf-8"))[0]["answer"]["candidates"][1], "candidate_id": "k1"}],
2520
+ "rejected_findings": [], "non_findings": []}}]), encoding="utf-8"), None)
2521
+ real_subject = subject
2522
+
2523
+ def without_events(where):
2524
+ """The subject of a window none of whose processed units resolved an event: the golden one, its events gone."""
2525
+ return {**real_subject(where), "events": [], "claims": {}, "origins": {}}
2526
+ globals()["subject"] = without_events
2527
+ try:
2528
+ quiet_made = guarded(lambda: run(quiet, supervisor(quiet, root / "c5-cells-no-events", quiet_plan)),
2529
+ lambda exc: {"problem": repr(exc)})
2530
+ finally:
2531
+ globals()["subject"] = real_subject
2532
+ quiet_formed = [c for c in guarded(lambda: records.read_json(quiet / "candidates.json")["candidates"], []) if c["source"] == "formed"]
2533
+ control("F2: a window whose units resolved no event still makes the formation call when the intake holds a placed "
2534
+ "cluster, and forms the type G candidate distilled from it",
2535
+ quiet_made.get("call", {}).get("outcome") == "accepted" and len(quiet_formed) == 1
2536
+ and quiet_formed[0]["type"] == "G" and quiet_formed[0]["event_ids"] == []
2537
+ and quiet_formed[0]["tension"]["instance_entry_ids"] == placed.get("entries", [None])[:3],
2538
+ f"{quiet_made.get('problem') or quiet_made.get('call')} {quiet_formed[:1]}")
2539
+
2540
+ # the driver's own command, as a process runs it: dry, then golden, each over a copy (WP-09 commit 5)
2541
+ from runlib import ledger as ledger_records
2542
+
2543
+ def driver(where, *argv):
2544
+ # The child names the fixture checkout's ledger reference: a separate process does not
2545
+ # inherit the one the fixture builder declared (WP-24).
2546
+ done = subprocess.run([sys.executable, "-I", str(HERE / "distill.py"), "form", "--run-id", where.name,
2547
+ "--out", str(where.parent), "--checkout-ledger", ledger_records.STATE_LEDGER_REL,
2548
+ *argv], capture_output=True, text=True, timeout=600)
2549
+ return done.returncode, done.stdout + done.stderr
2550
+ cli_dry = copy_of("cli-dry")
2551
+ code, said = driver(cli_dry, "--dry")
2552
+ control("the driver's `form --dry` runs S4 up to its call as a process and prints counts",
2553
+ code == 0 and "S4 form (dry)" in said and record_of(cli_dry).get("status") == "partial", f"{code} {said[-600:]}")
2554
+ cli_gold = copy_of("cli-gold")
2555
+ cli_plan = guarded(lambda: fx_form_plan(cli_gold, root / "c5-cli-plan.json"), None)
2556
+ code, said = driver(cli_gold, "--cells", str(root / "c5-cli-cells"), "--golden-plan", str(cli_plan))
2557
+ control("the driver's `form` with a golden plan runs the stage through its call as a process, and the population "
2558
+ "it leaves holds the intake the stage derived from its admitted declaration",
2559
+ code == 0 and "call: accepted" in said and record_of(cli_gold).get("status") == "complete"
2560
+ and len(guarded(lambda: records.read_json(cli_gold / "population.json")["candidate_ids"], []))
2561
+ == len(guarded(lambda: records.read_json(cli_gold / "intake.json")["candidates"], [None] * 99)) + 2,
2562
+ f"{code} {said[-600:]}")
2563
+ control("the suite leaves no temporary tree", not root.exists(), str(root))
2564
+
2565
+ for failure in failures:
2566
+ print(f"stage_form --self-test [FAIL] {failure}")
2567
+ if failures:
2568
+ return 1
2569
+ print(f"stage_form --self-test: OK ({len(ran)} controls: " + "; ".join(ran) + ")")
2570
+ return 0
2571
+
2572
+
2573
+ if __name__ == "__main__":
2574
+ if "--self-test" not in sys.argv[1:]:
2575
+ sys.exit("usage: stage_form.py --self-test")
2576
+ sys.exit(self_test())