agent-bios 0.19.4 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/DEPENDENCIES.md +20 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +8 -7
  6. package/claude/guides/gpt-prompting.md +319 -144
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/agents/frontier.toml +1 -1
  10. package/codex/agents/reviewer.toml +1 -1
  11. package/codex/agents/workhorse.toml +1 -1
  12. package/codex/guides/claude-prompting.md +475 -234
  13. package/codex/guides/cli-multi-model-workflow.md +8 -7
  14. package/codex/guides/gpt-prompting.md +319 -144
  15. package/codex/guides/session-distill-workflow.md +93 -43
  16. package/codex/guides/tooling-gotchas.md +3 -1
  17. package/compose/assemble.py +4 -1
  18. package/compose/canary.sh +8 -6
  19. package/compose/host_platform.py +158 -15
  20. package/compose/instructions-state.py +183 -41
  21. package/compose/instructions_install.py +222 -27
  22. package/compose/instructions_session.py +250 -75
  23. package/compose/instructions_setup_cli.py +2 -36
  24. package/compose/instructions_store.py +160 -3
  25. package/compose/instructions_transaction.py +29 -5
  26. package/docs/advanced-launch.md +5 -1
  27. package/docs/releases/0.20.0.md +102 -0
  28. package/docs/releases/0.20.1.md +76 -0
  29. package/install.sh +42 -14
  30. package/launch/agent-launch.py +152 -18
  31. package/launch/agent-launch.toml +28 -16
  32. package/launch/agent-launch.zsh +104 -13
  33. package/launch/claude_subcommands.py +179 -0
  34. package/launch/shell_integration.py +7 -1
  35. package/learn/collect-learning.py +60 -9
  36. package/learn/migrate-learnings.py +70 -4
  37. package/learn/redact.py +2 -1
  38. package/package.json +36 -3
  39. package/provenance.json +1 -1
  40. package/session-cost.py +80 -9
  41. package/session-distill/coverage.json +6 -0
  42. package/session-distill/distill.py +2575 -0
  43. package/session-distill/grammar/__init__.py +0 -0
  44. package/session-distill/grammar/owner_lines.py +874 -0
  45. package/session-distill/originators.json +9 -0
  46. package/session-distill/packets/cross_review.md +31 -0
  47. package/session-distill/packets/form.md +86 -0
  48. package/session-distill/packets/judge.md +81 -0
  49. package/session-distill/packets/placement_contract.md +90 -0
  50. package/session-distill/packets/propose.md +124 -0
  51. package/session-distill/packets/read.md +57 -0
  52. package/session-distill/packets/reconsider.md +53 -0
  53. package/session-distill/packets/s7b.md +65 -0
  54. package/session-distill/packets/s9b.md +39 -0
  55. package/session-distill/packets/stitch.md +35 -0
  56. package/session-distill/packets/sweep.md +33 -0
  57. package/session-distill/runlib/__init__.py +0 -0
  58. package/session-distill/runlib/bound.py +1102 -0
  59. package/session-distill/runlib/breaker.py +467 -0
  60. package/session-distill/runlib/census.py +2347 -0
  61. package/session-distill/runlib/claims.py +420 -0
  62. package/session-distill/runlib/controls.py +902 -0
  63. package/session-distill/runlib/coverage.py +881 -0
  64. package/session-distill/runlib/declare.py +888 -0
  65. package/session-distill/runlib/delivery_evidence.py +1145 -0
  66. package/session-distill/runlib/derive.py +812 -0
  67. package/session-distill/runlib/destinations.py +3072 -0
  68. package/session-distill/runlib/dispatch.py +7940 -0
  69. package/session-distill/runlib/drift.py +1077 -0
  70. package/session-distill/runlib/entry.py +401 -0
  71. package/session-distill/runlib/evidence.py +890 -0
  72. package/session-distill/runlib/exposure.py +1162 -0
  73. package/session-distill/runlib/gate.py +2727 -0
  74. package/session-distill/runlib/gitread.py +79 -0
  75. package/session-distill/runlib/inventory.py +19624 -0
  76. package/session-distill/runlib/journal.py +1919 -0
  77. package/session-distill/runlib/ledger.py +3210 -0
  78. package/session-distill/runlib/ledger_compat.py +101 -0
  79. package/session-distill/runlib/ledger_migration.py +190 -0
  80. package/session-distill/runlib/lifecycle_intake.py +693 -0
  81. package/session-distill/runlib/lineage.py +454 -0
  82. package/session-distill/runlib/measures.py +249 -0
  83. package/session-distill/runlib/monitor.py +1180 -0
  84. package/session-distill/runlib/operations.py +522 -0
  85. package/session-distill/runlib/packet.py +838 -0
  86. package/session-distill/runlib/placement.py +1769 -0
  87. package/session-distill/runlib/projection.py +4090 -0
  88. package/session-distill/runlib/ranking.py +740 -0
  89. package/session-distill/runlib/receipts.py +200 -0
  90. package/session-distill/runlib/records.py +1965 -0
  91. package/session-distill/runlib/search.py +249 -0
  92. package/session-distill/runlib/sequencing.py +829 -0
  93. package/session-distill/runlib/sources.py +641 -0
  94. package/session-distill/runlib/stage_adjudicate.py +845 -0
  95. package/session-distill/runlib/stage_apply.py +1378 -0
  96. package/session-distill/runlib/stage_approvals.py +758 -0
  97. package/session-distill/runlib/stage_close.py +1220 -0
  98. package/session-distill/runlib/stage_confirm.py +929 -0
  99. package/session-distill/runlib/stage_delivery.py +3080 -0
  100. package/session-distill/runlib/stage_form.py +2576 -0
  101. package/session-distill/runlib/stage_judge.py +4248 -0
  102. package/session-distill/runlib/stage_propose.py +3307 -0
  103. package/session-distill/runlib/stage_read.py +5179 -0
  104. package/session-distill/runlib/stage_render.py +2739 -0
  105. package/session-distill/runlib/stage_retrieve.py +924 -0
  106. package/session-distill/runlib/stage_review_korean.py +1002 -0
  107. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  108. package/session-distill/runlib/stagelock.py +412 -0
  109. package/session-distill/runlib/stop.py +1061 -0
  110. package/session-distill/runlib/targets.py +809 -0
  111. package/session-distill/runlib/usage.py +280 -0
  112. package/session-distill/runlib/validate.py +319 -0
  113. package/session-distill/runlib/views.py +4327 -0
  114. package/session-distill/schemas/adjudication.schema.json +35 -0
  115. package/session-distill/schemas/approval.schema.json +35 -0
  116. package/session-distill/schemas/census.schema.json +128 -0
  117. package/session-distill/schemas/checks.schema.json +207 -0
  118. package/session-distill/schemas/claim.schema.json +16 -0
  119. package/session-distill/schemas/confirmation.schema.json +24 -0
  120. package/session-distill/schemas/coverage.schema.json +66 -0
  121. package/session-distill/schemas/cross_review.schema.json +24 -0
  122. package/session-distill/schemas/event.schema.json +20 -0
  123. package/session-distill/schemas/evidence.schema.json +20 -0
  124. package/session-distill/schemas/expected_observation.schema.json +18 -0
  125. package/session-distill/schemas/form.schema.json +103 -0
  126. package/session-distill/schemas/intake.schema.json +71 -0
  127. package/session-distill/schemas/inventory.schema.json +872 -0
  128. package/session-distill/schemas/judge.schema.json +77 -0
  129. package/session-distill/schemas/ledger.schema.json +313 -0
  130. package/session-distill/schemas/observation.schema.json +16 -0
  131. package/session-distill/schemas/propose.schema.json +555 -0
  132. package/session-distill/schemas/read.schema.json +76 -0
  133. package/session-distill/schemas/reconsider.schema.json +122 -0
  134. package/session-distill/schemas/run.schema.json +150 -0
  135. package/session-distill/schemas/s7b.schema.json +200 -0
  136. package/session-distill/schemas/s9b.schema.json +28 -0
  137. package/session-distill/schemas/stitch.schema.json +25 -0
  138. package/session-distill/schemas/sweep.schema.json +25 -0
  139. package/session-distill/seats.json +149 -0
  140. package/session-distill/tables/allowed_pairs.json +257 -0
  141. package/session-distill/tables/controls.json +30 -0
  142. package/session-distill/tables/delivery_evidence.json +36 -0
  143. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  144. package/session-distill/tables/destinations.json +684 -0
  145. package/session-distill/tables/drift_layers.json +68 -0
  146. package/session-distill/tables/exposure_rules.json +192 -0
  147. package/session-distill/tables/placement_rules.json +148 -0
  148. package/session-distill/tables/propose_fixtures.json +154 -0
  149. package/session-distill/tables/ranking.json +194 -0
  150. package/session-distill/tables/redundancy.json +10 -0
  151. package/session-distill/tables/structural_rules.json +44 -0
  152. package/session-distill/tables/transition_fixtures.json +398 -0
  153. package/session-distill/tables/transitions.json +69 -0
  154. package/session-distill/tables/unit_outcome.json +67 -0
  155. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  156. package/wrappers/claude-run.sh +481 -33
  157. package/wrappers/claude_hermetic_evidence.py +1423 -0
  158. package/wrappers/codex-helm.sh +46 -15
  159. package/wrappers/codex-run.sh +183 -20
  160. package/wrappers/codex_frame_filter.py +1199 -0
  161. package/wrappers/codex_protocol.py +737 -0
  162. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,812 @@
1
+ #!/usr/bin/env python3
2
+ """The derivations of design §6.4 (WP-10): two judges' judgments and the delivery states in; each unit's diagnosis,
3
+ the candidate's diagnosis per reference point, the unit outcomes, the kind, the admission and the promotion
4
+ eligibility out.
5
+
6
+ Every rule is read from `tables/unit_outcome.json`, the one source this code and its fixture generator both read:
7
+ the table's rows decide, and this module only says how a row is matched. A row the code never reaches is visible by
8
+ name, because the generator wrote one frozen fixture per row (`--generate-fixtures`, once) and the self-test runs
9
+ every fixture through these functions and compares three sets - the table's rows, the frozen fixtures and the cases
10
+ the run executed (WP-10 done-when 1, the pattern of `ledger.py`'s transition fixtures).
11
+
12
+ Two judges answer every judged field (§6.2). Where they agree, the field takes their value; where they differ it is
13
+ `disputed`, shown with both values, and the owner's adjudication (§10.1 `판정`, §10.2) supplies the value the
14
+ derivation is computed again with. A disputed following or contribution is matched as the table's `unknown`; a
15
+ disputed situation or action leaves the unit's diagnosis `disputed`, which only a row accepting every diagnosis
16
+ matches, and the outcome is `unknown` otherwise; a disputed unit that could outrank the candidate's best agreed
17
+ diagnosis leaves the candidate's diagnosis `unknown`.
18
+
19
+ A candidate's units are judged at two reference points: `release` (the session's time) and `current`. Unit outcomes
20
+ are read at `release`, one per unit and session, because delivery is a fact about a session; `current` answers
21
+ only whether a gap has since been covered (`already resolved`). An absence - the diagnosis `gap` - holds only at a
22
+ complete reference point (§6.4); which completeness is read is the table's `absence_completeness` policy, and every
23
+ absence answer names the layers it read.
24
+
25
+ Release 1 runs no S8 (D-20261111-818391): every derivation takes a named test state, `untested: s8_deferred`, never a
26
+ blank; no row of §6.4 needs a test result, and each row says so in its own `test` column.
27
+
28
+ derive.py --self-test
29
+ derive.py --generate-fixtures [PATH]
30
+ """
31
+ import copy
32
+ import itertools
33
+ import json
34
+ import pathlib
35
+ import sys
36
+ import tempfile
37
+
38
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
39
+ from runlib.records import Refused # noqa: E402
40
+
41
+ HERE = pathlib.Path(__file__).resolve().parents[1]
42
+ TABLE_PATH = HERE / "tables" / "unit_outcome.json"
43
+ FIXTURES_PATH = HERE / "tables" / "unit_outcome_fixtures.json"
44
+ SECTIONS = ("unit_diagnosis", "unit_outcome", "candidate_diagnosis", "kind", "admission", "promotion")
45
+ DISPUTED = "disputed"
46
+ WILD = ("any", "—")
47
+ JUDGED = ("situation", "action", "following", "contribution")
48
+ POINTS = ("release", "current")
49
+
50
+ _TABLES = {}
51
+
52
+
53
+ def table():
54
+ """The §6.4 table, read once per process; a control may hold a scratch copy in `_TABLES["t"]`."""
55
+ if "t" not in _TABLES:
56
+ _TABLES["t"] = json.loads(TABLE_PATH.read_text(encoding="utf-8"))
57
+ return _TABLES["t"]
58
+
59
+
60
+ def row_ids(held=None):
61
+ held = held or table()
62
+ return [f"{section}/{row['id']}" for section in SECTIONS for row in held[section]]
63
+
64
+
65
+ def accepted(column, domain):
66
+ """The values a column of the unit-outcome table accepts: its domain for `any` or `—`, else its list."""
67
+ return list(domain) if column in WILD else list(column)
68
+
69
+
70
+ # ---- the judged fields --------------------------------------------------------------------------
71
+
72
+ def agreed(a, b):
73
+ """One judged field from the two judges: their value when they agree, `disputed` when they differ."""
74
+ return a if a == b else DISPUTED
75
+
76
+
77
+ def unit_diagnosis(situation, action):
78
+ """§6.4's unit diagnosis from a situation and an action match, each `yes` or `no` - or `disputed`."""
79
+ if DISPUTED in (situation, action):
80
+ return DISPUTED
81
+ for row in table()["unit_diagnosis"]:
82
+ if (row["situation"], row["action"]) == (situation, action):
83
+ return row["diagnosis"]
84
+ raise Refused(f"JUDGMENT_INVALID situation {situation!r}, action {action!r}: a match is one of "
85
+ f"{table()['domains']['judged']}")
86
+
87
+
88
+ def outcome_row(diagnosis, delivery, following, contribution):
89
+ """`(row id, outcome)` of the unit-outcome row these values select. A disputed following or contribution is
90
+ matched as `unknown`; a disputed diagnosis only by a row accepting every diagnosis, and `("disputed", "unknown")`
91
+ when none does. Exactly one row matches any other combination (`table_problems` holds the table total)."""
92
+ domains = table()["domains"]
93
+ following = "unknown" if following == DISPUTED else following
94
+ contribution = "unknown" if contribution == DISPUTED else contribution
95
+ for name, value in (("delivery", delivery), ("following", following), ("contribution", contribution)):
96
+ if value not in domains[name]:
97
+ raise Refused(f"JUDGMENT_INVALID {name} {value!r}: one of {domains[name]}")
98
+ hits = [row for row in table()["unit_outcome"]
99
+ if (row["diagnosis"] in WILD or diagnosis in row["diagnosis"])
100
+ and delivery in accepted(row["delivery"], domains["delivery"])
101
+ and following in accepted(row["following"], domains["following"])
102
+ and contribution in accepted(row["contribution"], domains["contribution"])]
103
+ if len(hits) > 1:
104
+ raise Refused(f"TABLE_AMBIGUOUS {[row['id'] for row in hits]}: rows overlap at ({diagnosis}, {delivery}, "
105
+ f"{following}, {contribution})")
106
+ if not hits:
107
+ if diagnosis == DISPUTED:
108
+ return DISPUTED, "unknown"
109
+ raise Refused(f"TABLE_NOT_TOTAL ({diagnosis}, {delivery}, {following}, {contribution}): no row selects it")
110
+ return hits[0]["id"], hits[0]["outcome"]
111
+
112
+
113
+ def candidate_diagnosis(units, complete, lifecycle=None):
114
+ """`(diagnosis, row id)` over a reference point's unit diagnoses: `units` maps a unit id to its diagnosis, or to
115
+ `(disputed, [A's, B's])`. A redundancy candidate with enough covering units is `redundant`; otherwise the first
116
+ precedence row an agreed unit reaches; `gap` only at a complete reference point; `unknown` when a disputed unit
117
+ could reach a row before the agreed one."""
118
+ rows = table()["candidate_diagnosis"]
119
+ agreed_diagnoses = [d for d in units.values() if not isinstance(d, tuple)]
120
+ possible = [p for d in units.values() if isinstance(d, tuple) for p in d[1]]
121
+ for row in rows:
122
+ if row.get("lifecycle") and lifecycle == row["lifecycle"] \
123
+ and agreed_diagnoses.count("covers") >= row["covering_units_at_least"]:
124
+ return row["diagnosis"], row["id"]
125
+ ladder = [row for row in rows if not row.get("lifecycle")]
126
+ for rank, row in enumerate(ladder):
127
+ if row["if_any_unit"] is None or row["if_any_unit"] in agreed_diagnoses:
128
+ if any(earlier["if_any_unit"] in possible for earlier in ladder[:rank]):
129
+ return "unknown", DISPUTED
130
+ if row["if_any_unit"] is None and not complete:
131
+ return row["incomplete"], row["id"]
132
+ return row["diagnosis"], row["id"]
133
+ raise Refused("TABLE_NOT_TOTAL candidate diagnosis: no precedence row is reached")
134
+
135
+
136
+ def absence(point):
137
+ """`(complete, read)` for an absence at one reference point under the table's policy: `literal` reads the point's
138
+ own flag (§6.1), `scoped` the statuses of the layers it lists. `read` names what was read."""
139
+ policy = table()["absence_completeness"]
140
+ layers = point.get("layers") or {}
141
+ if policy["policy"] == "literal":
142
+ return point.get("complete") is True, {"policy": "literal", "flag": point.get("complete"),
143
+ "unknown_layers": sorted(k for k, v in layers.items() if v != "complete")}
144
+ if policy["policy"] == "scoped":
145
+ wanted = policy["layers"]
146
+ unknown = sorted(name for name in wanted if layers.get(name) != "complete")
147
+ return not unknown, {"policy": "scoped", "layers_read": list(wanted), "unknown_layers": unknown}
148
+ raise Refused(f"TABLE_INVALID absence_completeness {policy['policy']!r}: literal or scoped")
149
+
150
+
151
+ def kind_of(outcomes, release, current, no_longer_arises=False):
152
+ """`(kind, row id)`: the first kind row, in the table's order, that holds. Outcome rows hold when a unit outcome is
153
+ among theirs; the no-matching-unit rows only when no unit matched, by the pair of candidate diagnoses at
154
+ `release` and `current`; the lifecycle row when both judges find the situation no longer arises."""
155
+ for row in table()["kind"]:
156
+ if row.get("lifecycle_no_longer_arises"):
157
+ if no_longer_arises:
158
+ return row["kind"], row["id"]
159
+ elif "if_any_outcome" in row:
160
+ if outcomes and set(outcomes) & set(row["if_any_outcome"]):
161
+ return row["kind"], row["id"]
162
+ elif not outcomes:
163
+ if row["no_matching_unit"] == "otherwise" or row["no_matching_unit"] == {"release": release,
164
+ "current": current}:
165
+ return row["kind"], row["id"]
166
+ raise Refused(f"TABLE_NOT_TOTAL kind over {sorted(set(outcomes))}: no row holds")
167
+
168
+
169
+ def admission(a, b, checks_pass):
170
+ """`(admission, row id)` from both judges' marks on every requirement and the deterministic checks."""
171
+ names = table()["requirements"]
172
+ for who, marks in (("A", a), ("B", b)):
173
+ bad = [n for n in names if marks.get(n) not in table()["domains"]["requirement"]]
174
+ if bad:
175
+ raise Refused(f"JUDGMENT_INVALID judge {who}: requirement {bad[0]} is {marks.get(bad[0])!r}, one of "
176
+ f"{table()['domains']['requirement']}")
177
+ rows = {row["id"]: row for row in table()["admission"]}
178
+ if checks_pass is True and all(a[n] == b[n] == "met" for n in names):
179
+ return rows["admitted"]["admission"], "admitted"
180
+ if any(a[n] == b[n] == "unmet" for n in names):
181
+ return rows["rejected"]["admission"], "rejected"
182
+ return rows["disputed"]["admission"], "disputed"
183
+
184
+
185
+ def eligible(kind, lineages, class_a, class_b, arc_confirmed=False):
186
+ """`(eligible, row id, allowed dispositions)` for a candidate of type `kind` with `lineages` affirmed independent
187
+ lineages and each judge's consequence class."""
188
+ rows = {row["id"]: row for row in table()["promotion"]}
189
+ if isinstance(lineages, bool) or not isinstance(lineages, int) or lineages < 0:
190
+ raise Refused(f"JUDGMENT_INVALID lineages {lineages!r}: a count")
191
+
192
+ def verdict(row_id): # the row's own `eligible` (Codex WP-10 r1 #5: written here as True and False)
193
+ allowed = rows[row_id].get("allowed_dispositions")
194
+ return rows[row_id]["eligible"], row_id, list(allowed) if allowed is not None else None
195
+ if kind in rows["type_g"]["types"]:
196
+ g = rows["type_g"]
197
+ if lineages >= g["independent_lineages_at_least"] or (g["or_arc_confirmed"] and arc_confirmed is True):
198
+ return verdict("type_g")
199
+ else:
200
+ if lineages >= rows["lineages"]["independent_lineages_at_least"]:
201
+ return verdict("lineages")
202
+ classes = rows["consequence"]["both_judges_class_one_of"]
203
+ if class_a in classes and class_b in classes:
204
+ return verdict("consequence")
205
+ return verdict("below_bar")
206
+
207
+
208
+ # ---- the whole derivation -----------------------------------------------------------------------
209
+
210
+ def unit_outcome(judgment, delivery, test_state):
211
+ """The derivations of §6.4 for one candidate (the interface of WP-10):
212
+ `{unit_diagnosis, candidate_diagnosis, unit_outcomes[], kind, admission, eligible, test}`.
213
+
214
+ `judgment`: `candidate {candidate_id, type, lifecycle}`; `judges {A, B}`, each `{requirements {name: mark},
215
+ consequence_class, no_longer_arises}`; `points {release, current}`, each `{complete, layers {layer: status},
216
+ units {unit_id: {A: {situation, action, following, contribution}, B: {...}}}}`; optional `adjudicated
217
+ {point: {unit_id: {field: value}}}`; `checks_pass`; `lineages`; optional `arc_confirmed`.
218
+ `delivery`: `{unit_id: [{session, state}]}` at `release`; a unit with no entry is `unknown` in no session."""
219
+ if test_state not in table()["domains"]["test"]:
220
+ raise Refused(f"TEST_STATE_UNNAMED {test_state!r}: a derivation names its test state, one of "
221
+ f"{table()['domains']['test']}, never a blank")
222
+ candidate, judges = judgment["candidate"], judgment["judges"]
223
+ adjudicated = judgment.get("adjudicated") or {}
224
+ diagnoses, per_point, fields = {}, {}, {}
225
+ for point in POINTS:
226
+ held = judgment["points"].get(point)
227
+ if held is None:
228
+ per_point[point] = {"diagnosis": "unknown", "row": "absent", "absence": None}
229
+ continue
230
+ units = {}
231
+ for unit_id, pair in held["units"].items():
232
+ settled = adjudicated.get(point, {}).get(unit_id, {})
233
+ values = {f: settled.get(f, agreed(pair["A"].get(f), pair["B"].get(f))) for f in JUDGED}
234
+ diagnosis = unit_diagnosis(values["situation"], values["action"])
235
+ if diagnosis == DISPUTED:
236
+ both = [unit_diagnosis(pair[who]["situation"], pair[who]["action"]) for who in ("A", "B")]
237
+ units[unit_id] = (DISPUTED, both)
238
+ else:
239
+ units[unit_id] = diagnosis
240
+ fields[(point, unit_id)] = values
241
+ complete, read = absence(held)
242
+ diagnosis, row = candidate_diagnosis(units, complete, candidate.get("lifecycle"))
243
+ per_point[point] = {"diagnosis": diagnosis, "row": row, "absence": read}
244
+ diagnoses[point] = {u: (d[0] if isinstance(d, tuple) else d) for u, d in units.items()}
245
+ outcomes = []
246
+ for unit_id, diagnosis in sorted((diagnoses.get("release") or {}).items()):
247
+ if diagnosis == "no match":
248
+ continue
249
+ values = fields[("release", unit_id)]
250
+ disputed = [f for f in JUDGED if values[f] == DISPUTED]
251
+ for held in delivery.get(unit_id) or [{"session": None, "state": "unknown"}]:
252
+ row, outcome = outcome_row(diagnosis, held["state"], values["following"], values["contribution"])
253
+ outcomes.append({"unit_id": unit_id, "session": held["session"], "diagnosis": diagnosis,
254
+ "delivery": held["state"], "following": values["following"],
255
+ "contribution": values["contribution"], "outcome": outcome, "row": row,
256
+ "disputed": disputed})
257
+ no_longer = all(judges[who].get("no_longer_arises") is True for who in ("A", "B")) \
258
+ and bool(candidate.get("lifecycle"))
259
+ kind, kind_row = kind_of([o["outcome"] for o in outcomes], per_point["release"]["diagnosis"],
260
+ per_point["current"]["diagnosis"], no_longer)
261
+ admitted, admission_row = admission(judges["A"]["requirements"], judges["B"]["requirements"],
262
+ judgment.get("checks_pass"))
263
+ ok, eligible_row, allowed = eligible(candidate["type"], judgment.get("lineages", 0),
264
+ judges["A"].get("consequence_class"), judges["B"].get("consequence_class"),
265
+ judgment.get("arc_confirmed", False))
266
+ return {"candidate_id": candidate["candidate_id"], "unit_diagnosis": diagnoses, "candidate_diagnosis": per_point,
267
+ "unit_outcomes": outcomes, "kind": {"kind": kind, "row": kind_row},
268
+ "admission": {"admission": admitted, "row": admission_row},
269
+ "eligible": {"eligible": ok, "row": eligible_row, "allowed_dispositions": allowed}, "test": test_state}
270
+
271
+
272
+ # ---- the table's own checks ---------------------------------------------------------------------
273
+
274
+ def table_problems(held=None):
275
+ """What makes the table unusable as a total function: an unknown value, a combination no row or two rows select,
276
+ an outcome no kind row reads, a row id twice, a test column that is neither `—` nor a named state."""
277
+ held = held or table()
278
+ domains, problems = held["domains"], []
279
+ for section in SECTIONS:
280
+ seen = [row["id"] for row in held[section]]
281
+ problems += [f"TABLE_INVALID {section}/{i}: the id appears twice" for i in sorted({i for i in seen if seen.count(i) > 1})]
282
+ for row in held["unit_outcome"]:
283
+ for name in ("delivery", "following", "contribution"):
284
+ if row[name] not in WILD and not set(row[name]) <= set(domains[name]):
285
+ problems.append(f"TABLE_INVALID unit_outcome/{row['id']}: {name} {row[name]} outside {domains[name]}")
286
+ if row["diagnosis"] not in WILD and not set(row["diagnosis"]) <= set(domains["diagnosis"]):
287
+ problems.append(f"TABLE_INVALID unit_outcome/{row['id']}: diagnosis {row['diagnosis']}")
288
+ if row["test"] != "—" and row["test"] not in domains["test"]:
289
+ problems.append(f"TABLE_INVALID unit_outcome/{row['id']}: test {row['test']!r} names no test state")
290
+ matching = [d for d in domains["diagnosis"] if d != "no match"]
291
+ for combo in itertools.product(matching, domains["delivery"], domains["following"], domains["contribution"]):
292
+ hits = [row["id"] for row in held["unit_outcome"]
293
+ if (row["diagnosis"] in WILD or combo[0] in row["diagnosis"])
294
+ and combo[1] in accepted(row["delivery"], domains["delivery"])
295
+ and combo[2] in accepted(row["following"], domains["following"])
296
+ and combo[3] in accepted(row["contribution"], domains["contribution"])]
297
+ if len(hits) != 1:
298
+ problems.append(f"{'TABLE_NOT_TOTAL' if not hits else 'TABLE_AMBIGUOUS'} {combo}: rows {hits}")
299
+ read = {o for row in held["kind"] for o in row.get("if_any_outcome", [])}
300
+ problems += [f"TABLE_INVALID kind: outcome {o!r} reaches no kind row"
301
+ for o in sorted({row["outcome"] for row in held["unit_outcome"]} - read)]
302
+ # a class no judge can return would make its row unreachable without a word (D-20261111-f3d39c)
303
+ declared = consequence_classes()
304
+ problems += [f"CLASS_UNDECLARED promotion/{row['id']}: {c!r} is not a consequence class the judgment schema "
305
+ f"declares ({list(declared)})"
306
+ for row in held["promotion"] for c in row.get("both_judges_class_one_of") or [] if c not in declared]
307
+ return problems
308
+
309
+
310
+ # ---- the frozen fixtures ------------------------------------------------------------------------
311
+
312
+ def _cases(section, row, held):
313
+ """The cases one row's fixture holds, built from the row's own fields; the expectation is the row's, never this
314
+ code's answer."""
315
+ domains = held["domains"]
316
+ if section == "unit_diagnosis":
317
+ return [{"situation": row["situation"], "action": row["action"], "expected": row["diagnosis"]}]
318
+ if section == "unit_outcome":
319
+ diagnoses = [d for d in domains["diagnosis"] if d != "no match"] if row["diagnosis"] in WILD else row["diagnosis"]
320
+ return [{"diagnosis": d, "delivery": v, "following": f, "contribution": c,
321
+ "expected": {"row": row["id"], "outcome": row["outcome"]}}
322
+ for d, v, f, c in itertools.product(diagnoses, accepted(row["delivery"], domains["delivery"]),
323
+ accepted(row["following"], domains["following"]),
324
+ accepted(row["contribution"], domains["contribution"]))]
325
+ if section == "candidate_diagnosis":
326
+ ladder = [r for r in held[section] if not r.get("lifecycle")]
327
+ if row.get("lifecycle"):
328
+ units = {f"u{n}": "covers" for n in range(row["covering_units_at_least"])}
329
+ return [{"units": units, "complete": True, "lifecycle": row["lifecycle"],
330
+ "expected": {"diagnosis": row["diagnosis"], "row": row["id"]}}]
331
+ below = [r["if_any_unit"] for r in ladder[ladder.index(row) + 1:] if r["if_any_unit"]]
332
+ units = {f"u{n}": d for n, d in enumerate(([row["if_any_unit"]] if row["if_any_unit"] else []) + below + ["no match"])}
333
+ cases = [{"units": units, "complete": True, "lifecycle": None,
334
+ "expected": {"diagnosis": row["diagnosis"], "row": row["id"]}}]
335
+ if "incomplete" in row:
336
+ cases.append({"units": units, "complete": False, "lifecycle": None,
337
+ "expected": {"diagnosis": row["incomplete"], "row": row["id"]}})
338
+ return cases
339
+ if section == "kind":
340
+ rows = held[section]
341
+ if row.get("lifecycle_no_longer_arises"):
342
+ return [{"outcomes": ["misfire"], "release": "covered", "current": "covered", "no_longer_arises": True,
343
+ "expected": {"kind": row["kind"], "row": row["id"]}}]
344
+ if "if_any_outcome" in row:
345
+ later = [o for r in rows[rows.index(row) + 1:] for o in r.get("if_any_outcome", [])]
346
+ return [{"outcomes": [o] + later, "release": "covered", "current": "covered", "no_longer_arises": False,
347
+ "expected": {"kind": row["kind"], "row": row["id"]}} for o in row["if_any_outcome"]]
348
+ pair = row["no_matching_unit"] if row["no_matching_unit"] != "otherwise" else {"release": "unknown",
349
+ "current": "gap"}
350
+ return [{"outcomes": [], **pair, "no_longer_arises": False, "expected": {"kind": row["kind"], "row": row["id"]}}]
351
+ if section == "admission":
352
+ met = {n: "met" for n in held["requirements"]}
353
+ first = held["requirements"][0]
354
+ inputs = {"admitted": (met, met, True), "rejected": ({**met, first: "unmet"}, {**met, first: "unmet"}, True),
355
+ "disputed": ({**met, first: "uncertain"}, met, True)}[row["id"]]
356
+ cases = [{"a": inputs[0], "b": inputs[1], "checks_pass": inputs[2], "expected": {"admission": row["admission"],
357
+ "row": row["id"]}}]
358
+ if row["id"] == "disputed":
359
+ cases.append({"a": met, "b": met, "checks_pass": False, "expected": {"admission": row["admission"],
360
+ "row": row["id"]}})
361
+ return cases
362
+ if section == "promotion":
363
+ inputs = {"lineages": ("A", row.get("independent_lineages_at_least"), None, None, False),
364
+ "consequence": ("B", 0) + (tuple(row.get("both_judges_class_one_of", [None])[:1]) * 2) + (False,),
365
+ "type_g": ("G", row.get("independent_lineages_at_least"), None, None, False),
366
+ "below_bar": ("A", 1, "irreversible", "reversible", False)}[row["id"]]
367
+ cases = [{"type": inputs[0], "lineages": inputs[1], "class_a": inputs[2], "class_b": inputs[3],
368
+ "arc_confirmed": inputs[4], "expected": {"eligible": row["eligible"], "row": row["id"]}}]
369
+ if row["id"] == "type_g":
370
+ cases.append({"type": "G", "lineages": 0, "class_a": None, "class_b": None, "arc_confirmed": True,
371
+ "expected": {"eligible": row["eligible"], "row": row["id"]}})
372
+ return cases
373
+ raise Refused(f"TABLE_INVALID section {section!r}")
374
+
375
+
376
+ def generate_fixtures(path=FIXTURES_PATH):
377
+ """Write one fixture per row of the table, once. The fixtures are committed and a second call refuses: a fixture
378
+ regenerated from the table it is meant to hold would hold nothing."""
379
+ path = pathlib.Path(path)
380
+ if path.exists():
381
+ raise Refused(f"FIXTURES_FROZEN {path}: generated once and committed; delete it by hand to regenerate")
382
+ held = table()
383
+ fixtures = [{"id": f"{section}/{row['id']}", "cases": _cases(section, row, held)}
384
+ for section in SECTIONS for row in held[section]]
385
+ doc = {"$comment": "design §6.4: one frozen fixture per row of tables/unit_outcome.json, written once by "
386
+ "`runlib/derive.py --generate-fixtures`; the self-test never regenerates them.",
387
+ "fixtures": fixtures}
388
+ path.write_text(json.dumps(doc, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
389
+ return len(fixtures)
390
+
391
+
392
+ def run_fixture(fixture):
393
+ """Every case of one frozen fixture through the production functions: the problems, `[]` when all hold."""
394
+ section = fixture["id"].split("/", 1)[0]
395
+ problems = []
396
+ for n, case in enumerate(fixture["cases"]):
397
+ try:
398
+ if section == "unit_diagnosis":
399
+ got = unit_diagnosis(case["situation"], case["action"])
400
+ elif section == "unit_outcome":
401
+ row, outcome = outcome_row(case["diagnosis"], case["delivery"], case["following"], case["contribution"])
402
+ got = {"row": row, "outcome": outcome}
403
+ elif section == "candidate_diagnosis":
404
+ diagnosis, row = candidate_diagnosis(case["units"], case["complete"], case["lifecycle"])
405
+ got = {"diagnosis": diagnosis, "row": row}
406
+ elif section == "kind":
407
+ kind, row = kind_of(case["outcomes"], case["release"], case["current"], case["no_longer_arises"])
408
+ got = {"kind": kind, "row": row}
409
+ elif section == "admission":
410
+ result, row = admission(case["a"], case["b"], case["checks_pass"])
411
+ got = {"admission": result, "row": row}
412
+ else:
413
+ ok, row, _allowed = eligible(case["type"], case["lineages"], case["class_a"], case["class_b"],
414
+ case["arc_confirmed"])
415
+ got = {"eligible": ok, "row": row}
416
+ except Refused as exc:
417
+ got = f"refused {str(exc).split()[0]}"
418
+ if got != case["expected"]:
419
+ problems.append(f"FIXTURE_FAILED {fixture['id']} case {n}: expected {case['expected']}, got {got}")
420
+ return problems
421
+
422
+
423
+ def coverage_problems(rows, frozen, executed):
424
+ """The three sets of done-when 1 by id: the table's rows, the frozen fixtures, the cases the run executed."""
425
+ rows, frozen, executed = set(rows), set(frozen), set(executed)
426
+ return ([f"ROW_UNFIXTURED {i}: a row of the table with no frozen fixture" for i in sorted(rows - frozen)]
427
+ + [f"FIXTURE_ORPHAN {i}: a frozen fixture for no row of the table" for i in sorted(frozen - rows)]
428
+ + [f"CASE_NOT_EXECUTED {i}: a frozen fixture the run never executed" for i in sorted(frozen - executed)]
429
+ + [f"CASE_UNFROZEN {i}: a case the run executed with no frozen fixture" for i in sorted(executed - frozen)]
430
+ + (["ROWS_NONE: the table has no rows, so a bijection over it says nothing"] if not rows else []))
431
+
432
+
433
+ # ---- the self-test ------------------------------------------------------------------------------
434
+
435
+ # The design's §6.4, copied here once (WP-10 done-when 5); the review compares it with the design text. Each
436
+ # outcome row is (unit diagnosis, delivery, following, contribution, unit outcome) in the design's words.
437
+ DESIGN_6_4_OUTCOME = (
438
+ ("any", "unknown", "—", "—", "unknown"),
439
+ ("any", "selected_unavailable or not_delivered", "—", "—", "not delivered"),
440
+ ("covers", "exposed_not_read", "—", "—", "misfire (trigger)"),
441
+ ("covers", "delivered", "not_followed", "—", "misfire"),
442
+ ("covers", "delivered", "followed", "harmed", "misfire"),
443
+ ("covers", "delivered", "followed", "helped", "confirmed"),
444
+ ("covers", "delivered", "followed", "neutral", "neutral (followed, no effect)"),
445
+ ("covers", "delivered", "followed", "unknown", "unknown"),
446
+ ("covers", "delivered", "unknown", "—", "unknown"),
447
+ ("trigger problem, wrong or insufficient", "delivered or exposed_not_read", "—", "—", "misfire"),
448
+ )
449
+ # "situation yes / action yes → covers; situation yes / action no → wrong or insufficient; situation no / action
450
+ # yes → trigger problem; neither → no match"
451
+ DESIGN_6_4_DIAGNOSIS = (("yes", "yes", "covers"), ("yes", "no", "wrong or insufficient"),
452
+ ("no", "yes", "trigger problem"), ("no", "no", "no match"))
453
+ # "covered (list every covering unit) > wrong or insufficient > trigger problem > gap"
454
+ DESIGN_6_4_CANDIDATE = ("covered", "wrong or insufficient", "trigger problem", "gap")
455
+ # "any misfire → misfire; else any not delivered → not delivered; else any unknown → unclassified; else any
456
+ # confirmed → confirmed; else (all neutral) → unclassified"
457
+ DESIGN_6_4_KIND = (("misfire", "misfire"), ("not delivered", "not delivered"), ("unknown", "unclassified"),
458
+ ("confirmed", "confirmed"), ("neutral (followed, no effect)", "unclassified"))
459
+ # "gap at release and current → gap; gap at release, covered at current → already resolved (no proposal)"
460
+ DESIGN_6_4_ABSENT = ((("gap", "gap"), "gap"), (("gap", "covered"), "already resolved"))
461
+ # "affirmed independent lineages ≥ 2, or a consequence both judges classed irreversible, security-relevant, or
462
+ # verification-corrupting"; §7.4, type G: "at least three independent lineages ... or an arc retrospective the owner
463
+ # confirms"; "Below the bar, the allowed dispositions are incubate, keep, and drop."
464
+ DESIGN_6_4_PROMOTION = (2, ("irreversible", "security-relevant", "verification-corrupting"), 3,
465
+ ("incubate", "keep", "drop"))
466
+ # D-20261112-644ff3: the table's below-bar list adds `none` to the sentence above. §7.2 allows an unclassified candidate
467
+ # only `none`, so as written the two lists were disjoint: a below-bar unclassified candidate had no acceptable answer,
468
+ # and the owner's legacy default `none` (D-20261111-e53a01) was refused below the bar. `none` promotes nothing. The
469
+ # copy keeps the design's words and the fidelity check reads the table through this addition, so the difference is
470
+ # declared here rather than written over.
471
+ DESIGN_BELOW_BAR_ADDED = ("none",)
472
+ # D-20261111-f3d39c (WP-11 D11): §6.4 says "security-relevant" and §7.5 "security" for one class. The judgment
473
+ # schema's enum is the classes' one owner and spells them as §7.5 does; the copy above keeps §6.4's word, and the
474
+ # fidelity check reads it through this rename, so the difference is declared here rather than written over.
475
+ DESIGN_CLASS_RENAMES = {"security-relevant": "security"}
476
+ CLASSES_SCHEMA = HERE / "schemas" / "judge.schema.json"
477
+
478
+
479
+ def consequence_classes(path=CLASSES_SCHEMA):
480
+ """The consequence classes a judge can return: the judgment schema's enum, their one owner (D-20261111-f3d39c)."""
481
+ return tuple(json.loads(pathlib.Path(path).read_text(encoding="utf-8"))["$defs"]["consequence_class"]["enum"])
482
+
483
+
484
+ def render_outcome(row):
485
+ def column(value, joiner):
486
+ return value if value in WILD else joiner.join(value)
487
+ return (column(row["diagnosis"], ", "), column(row["delivery"], " or "), column(row["following"], " or "),
488
+ column(row["contribution"], " or "), row["outcome"])
489
+
490
+
491
+ def fidelity_problems(held=None):
492
+ """The table against the design's own rows (WP-10 done-when 5)."""
493
+ held = held or table()
494
+ problems = []
495
+ rendered = tuple(render_outcome(row) for row in held["unit_outcome"])
496
+ if rendered != DESIGN_6_4_OUTCOME:
497
+ problems += [f"CONTRACT_DRIFT unit_outcome row {n + 1}: the table says {have}, §6.4 says {want}"
498
+ for n, (have, want) in enumerate(itertools.zip_longest(rendered, DESIGN_6_4_OUTCOME)) if have != want]
499
+ diagnosis = tuple((r["situation"], r["action"], r["diagnosis"]) for r in held["unit_diagnosis"])
500
+ if diagnosis != DESIGN_6_4_DIAGNOSIS:
501
+ problems.append(f"CONTRACT_DRIFT unit_diagnosis: {diagnosis}")
502
+ ladder = tuple(r["diagnosis"] for r in held["candidate_diagnosis"] if not r.get("lifecycle"))
503
+ if ladder != DESIGN_6_4_CANDIDATE:
504
+ problems.append(f"CONTRACT_DRIFT candidate_diagnosis precedence: {ladder}")
505
+ kinds = tuple((o, r["kind"]) for r in held["kind"] for o in r.get("if_any_outcome", [])[:1])
506
+ if kinds != DESIGN_6_4_KIND:
507
+ problems.append(f"CONTRACT_DRIFT kind precedence: {kinds}")
508
+ absent = tuple(((r["no_matching_unit"]["release"], r["no_matching_unit"]["current"]), r["kind"])
509
+ for r in held["kind"] if isinstance(r.get("no_matching_unit"), dict))
510
+ if absent != DESIGN_6_4_ABSENT:
511
+ problems.append(f"CONTRACT_DRIFT kind with no matching unit: {absent}")
512
+ rows = {r["id"]: r for r in held["promotion"]}
513
+ promotion = (rows["lineages"]["independent_lineages_at_least"], tuple(rows["consequence"]["both_judges_class_one_of"]),
514
+ rows["type_g"]["independent_lineages_at_least"], tuple(rows["below_bar"]["allowed_dispositions"]))
515
+ design = (DESIGN_6_4_PROMOTION[0], tuple(DESIGN_CLASS_RENAMES.get(c, c) for c in DESIGN_6_4_PROMOTION[1]),
516
+ DESIGN_6_4_PROMOTION[2], DESIGN_6_4_PROMOTION[3] + DESIGN_BELOW_BAR_ADDED)
517
+ if promotion != design:
518
+ problems.append(f"CONTRACT_DRIFT promotion: {promotion}")
519
+ if len(held["requirements"]) != 8:
520
+ problems.append(f"CONTRACT_DRIFT admission: {len(held['requirements'])} requirements, §6.4 names eight")
521
+ return problems
522
+
523
+
524
+ def self_test():
525
+ failures, ran = [], []
526
+
527
+ def expect(label, got, want):
528
+ ran.append(label)
529
+ if got != want:
530
+ failures.append(f"{label}: expected {want!r}, got {got!r}")
531
+
532
+ def named(label, lines, needle):
533
+ ran.append(label)
534
+ if not any(needle in line for line in lines):
535
+ failures.append(f"{label}: expected {needle!r} in {lines}")
536
+
537
+ def refused(label, action, code):
538
+ ran.append(label)
539
+ try:
540
+ action()
541
+ except Refused as exc:
542
+ if not str(exc).startswith(code):
543
+ failures.append(f"{label}: refused {str(exc)[:160]!r}, expected {code}")
544
+ return
545
+ except Exception as exc: # noqa: BLE001 - anything else fails this control by name, never the suite
546
+ failures.append(f"{label}: raised {type(exc).__name__}: {exc}, expected {code}")
547
+ return
548
+ failures.append(f"{label}: not refused, expected {code}")
549
+
550
+ held = table()
551
+ expect("the table is total, unambiguous and closed over its domains", table_problems(), [])
552
+ expect("the table holds §6.4's rows, words and orders", fidelity_problems(), [])
553
+
554
+ # done-when 5's controls: a changed row is named against the design's
555
+ drifted = copy.deepcopy(held)
556
+ drifted["unit_outcome"][5]["outcome"] = "neutral (followed, no effect)"
557
+ named("control: a unit-outcome row that no longer says what §6.4 says", fidelity_problems(drifted),
558
+ "CONTRACT_DRIFT unit_outcome row 6")
559
+ swapped = copy.deepcopy(held)
560
+ swapped["kind"][1], swapped["kind"][2] = swapped["kind"][2], swapped["kind"][1]
561
+ named("control: the kind precedence reordered", fidelity_problems(swapped), "CONTRACT_DRIFT kind precedence")
562
+ # the table's own totality, with its controls
563
+ gone = copy.deepcopy(held)
564
+ gone["unit_outcome"] = [row for row in gone["unit_outcome"] if row["id"] != "o9"]
565
+ named("control: a row removed leaves its combinations unselected", table_problems(gone), "TABLE_NOT_TOTAL")
566
+ overlap = copy.deepcopy(held)
567
+ overlap["unit_outcome"][3]["following"] = "—"
568
+ named("control: a row widened over another is ambiguous", table_problems(overlap), "TABLE_AMBIGUOUS")
569
+ blank = copy.deepcopy(held)
570
+ blank["unit_outcome"][0]["test"] = ""
571
+ named("control: a test column that names nothing", table_problems(blank), "names no test state")
572
+ respelled = copy.deepcopy(held)
573
+ next(r for r in respelled["promotion"] if r["id"] == "consequence")["both_judges_class_one_of"][1] = "security-relevant"
574
+ named("control: a promotion row naming a class outside the judgment schema's enum (D-20261111-f3d39c)",
575
+ table_problems(respelled), "CLASS_UNDECLARED promotion/consequence")
576
+
577
+ # done-when 1: the frozen fixtures, the table's rows, and the cases this run executed
578
+ fixtures = json.loads(FIXTURES_PATH.read_text(encoding="utf-8"))["fixtures"]
579
+ executed = set()
580
+ for fixture in fixtures:
581
+ failures.extend(run_fixture(fixture))
582
+ executed.add(fixture["id"]) # recorded after its cases ran through the production functions
583
+ frozen = {f["id"] for f in fixtures}
584
+ expect("table rows, frozen fixtures and executed cases are one set", coverage_problems(row_ids(), frozen, executed), [])
585
+ added = copy.deepcopy(held)
586
+ added["unit_outcome"].append({**added["unit_outcome"][0], "id": "o11"})
587
+ named("control: a row added to a scratch copy, the frozen fixtures unchanged",
588
+ coverage_problems(row_ids(added), frozen, executed), "ROW_UNFIXTURED unit_outcome/o11")
589
+ named("control: a frozen fixture deleted", coverage_problems(row_ids(), frozen - {"kind/gap"}, executed - {"kind/gap"}),
590
+ "ROW_UNFIXTURED kind/gap")
591
+ named("control: an executed case removed from the run's record",
592
+ coverage_problems(row_ids(), frozen, executed - {"unit_outcome/o4"}), "CASE_NOT_EXECUTED unit_outcome/o4")
593
+ named("control: a case executed with no frozen fixture",
594
+ coverage_problems(row_ids(), frozen, executed | {"unit_outcome/o0"}), "CASE_UNFROZEN unit_outcome/o0")
595
+ named("control: a bijection over no rows", coverage_problems([], set(), set()), "ROWS_NONE")
596
+ by_id = {f["id"]: f for f in fixtures}
597
+ _TABLES["t"] = drifted
598
+ try:
599
+ named("control: a frozen fixture against a table whose row changed", run_fixture(by_id["unit_outcome/o6"]),
600
+ "FIXTURE_FAILED unit_outcome/o6")
601
+ finally:
602
+ _TABLES["t"] = held
603
+ with tempfile.TemporaryDirectory() as td:
604
+ target = pathlib.Path(td) / "fixtures.json"
605
+ expect("the generator writes one fixture per row", generate_fixtures(target), len(row_ids()))
606
+ expect("the generator's fixtures are the frozen ones",
607
+ json.loads(target.read_text(encoding="utf-8"))["fixtures"], fixtures)
608
+ refused("a second generation", lambda: generate_fixtures(target), "FIXTURES_FROZEN")
609
+
610
+ # done-when 2 (the derivation side): O3 verdicts, each with the control that flips its expectation
611
+ met = {n: "met" for n in held["requirements"]}
612
+
613
+ def unit(situation="yes", action="yes", following="followed", contribution="helped", b=None):
614
+ one = {"situation": situation, "action": action, "following": following, "contribution": contribution}
615
+ return {"A": one, "B": {**one, **(b or {})}}
616
+
617
+ def judged(units, delivery, release=None, current=None, lifecycle=None, kind_type="A", test="untested: s8_deferred",
618
+ **extra):
619
+ point = {"complete": True, "layers": {}, "units": units}
620
+ return unit_outcome({"candidate": {"candidate_id": "k1", "type": kind_type, "lifecycle": lifecycle},
621
+ "judges": {"A": {"requirements": met, "consequence_class": None},
622
+ "B": {"requirements": met, "consequence_class": None}},
623
+ "points": {"release": release or point, "current": current or point},
624
+ "checks_pass": True, "lineages": 2, **extra},
625
+ delivery, test)
626
+
627
+ def kind(result):
628
+ return result["kind"]["kind"]
629
+ pinned = {"session": "claude:s1", "state": "delivered"}
630
+ expect("O3: a pinned session violating a delivered rule is a misfire",
631
+ kind(judged({"u1": unit(following="not_followed", contribution="harmed")}, {"u1": [pinned]})), "misfire")
632
+ expect("O3 control: the same rule followed, helping, is confirmed",
633
+ kind(judged({"u1": unit()}, {"u1": [pinned]})), "confirmed")
634
+ exposed = {"session": "claude:s1", "state": "exposed_not_read"}
635
+ expect("O3: a guide pointer exposed and never read is a misfire (trigger)",
636
+ judged({"u1": unit(following="not_followed")}, {"u1": [exposed]})["unit_outcomes"][0]["outcome"],
637
+ "misfire (trigger)")
638
+ expect("O3 control: the same guide read is a misfire, not a trigger misfire",
639
+ judged({"u1": unit(following="not_followed")}, {"u1": [pinned]})["unit_outcomes"][0]["outcome"], "misfire")
640
+ unavailable = {"session": "claude:s1", "state": "selected_unavailable"}
641
+ expect("O3: selected_unavailable is not delivered", kind(judged({"u1": unit()}, {"u1": [unavailable]})),
642
+ "not delivered")
643
+ expect("O3 control: the same unit delivered is confirmed", kind(judged({"u1": unit()}, {"u1": [pinned]})), "confirmed")
644
+ unpinned = {"session": "claude:s2", "state": "unknown"}
645
+ expect("O3: an unpinned session is unclassified", kind(judged({"u1": unit()}, {"u1": [unpinned]})), "unclassified")
646
+ expect("O3 control: with no delivery entry at all the unit is unknown in no session, unclassified",
647
+ (kind(judged({"u1": unit()}, {})), judged({"u1": unit()}, {})["unit_outcomes"][0]["session"]),
648
+ ("unclassified", None))
649
+ mixed = judged({"u1": unit(), "u2": unit(following="not_followed")}, {"u1": [pinned], "u2": [pinned]})
650
+ expect("O3: one helpful and one violated covering unit is a misfire, both shown",
651
+ (kind(mixed), sorted(o["outcome"] for o in mixed["unit_outcomes"])), ("misfire", ["confirmed", "misfire"]))
652
+ expect("O3 control: the violated unit removed, confirmed",
653
+ kind(judged({"u1": unit()}, {"u1": [pinned]})), "confirmed")
654
+ unknown_c = judged({"u1": unit(), "u2": unit(contribution="unknown")}, {"u1": [pinned], "u2": [pinned]})
655
+ expect("O3: helpful and unknown-contribution is unclassified, both shown",
656
+ (kind(unknown_c), sorted(o["outcome"] for o in unknown_c["unit_outcomes"])), ("unclassified", ["confirmed", "unknown"]))
657
+ unknown_f = judged({"u1": unit(), "u2": unit(following="unknown")}, {"u1": [pinned], "u2": [pinned]})
658
+ expect("O3: helpful and unknown-following is unclassified", kind(unknown_f), "unclassified")
659
+ expect("O3 control: both helpful is confirmed",
660
+ kind(judged({"u1": unit(), "u2": unit()}, {"u1": [pinned], "u2": [pinned]})), "confirmed")
661
+ # the kind precedence on one mixed candidate (misfire > not delivered > unclassified > confirmed > all neutral)
662
+ ladder = {"u1": (unit(), [pinned]), "u2": (unit(contribution="unknown"), [pinned]), "u3": (unit(), [unavailable]),
663
+ "u4": (unit(following="not_followed"), [pinned]), "u5": (unit(contribution="neutral"), [pinned])}
664
+ seen = []
665
+ for drop in (None, "u4", "u3", "u2", "u1"):
666
+ ladder.pop(drop, None)
667
+ seen.append(kind(judged({u: v[0] for u, v in ladder.items()}, {u: v[1] for u, v in ladder.items()})))
668
+ expect("the kind precedence over a mixed fixture, removing the strongest outcome each time", seen,
669
+ ["misfire", "not delivered", "unclassified", "confirmed", "unclassified"])
670
+
671
+ # two judges: agreement, dispute, adjudication
672
+ split = judged({"u1": unit(b={"following": "not_followed"})}, {"u1": [pinned]})
673
+ expect("a following the judges disagree on is disputed and read as unknown",
674
+ (split["unit_outcomes"][0]["outcome"], split["unit_outcomes"][0]["disputed"], kind(split)),
675
+ ("unknown", ["following"], "unclassified"))
676
+ settled = judged({"u1": unit(b={"following": "not_followed"})}, {"u1": [pinned]},
677
+ adjudicated={"release": {"u1": {"following": "not_followed"}}})
678
+ expect("control: the owner's adjudication of that following recomputes a misfire", kind(settled), "misfire")
679
+ torn = judged({"u1": unit(b={"action": "no"})}, {"u1": [pinned]})
680
+ expect("a situation or action the judges disagree on leaves the unit disputed and its outcome unknown",
681
+ (torn["unit_diagnosis"]["release"]["u1"], torn["unit_outcomes"][0]["row"], kind(torn)),
682
+ ("disputed", "disputed", "unclassified"))
683
+ expect("a disputed unit that could cover leaves the candidate's diagnosis unknown",
684
+ judged({"u1": unit(b={"action": "no"}), "u2": unit(situation="no")}, {})["candidate_diagnosis"]["release"]["row"],
685
+ "disputed")
686
+ expect("control: a disputed unit below an agreed cover leaves the cover",
687
+ judged({"u1": unit(), "u2": unit(situation="no", b={"action": "no"})}, {"u1": [pinned]})
688
+ ["candidate_diagnosis"]["release"]["diagnosis"], "covered")
689
+
690
+ # absences: the completeness policy, by the layers it read
691
+ nothing = {"u1": unit(situation="no", action="no")}
692
+ gap_point = {"complete": True, "layers": {"catalog": "complete"}, "units": nothing}
693
+ open_point = {"complete": False, "layers": {"catalog": "complete", "native_settings": "unknown"}, "units": nothing}
694
+ expect("no matching unit at a complete release and current is a gap",
695
+ kind(judged(nothing, {}, release=gap_point, current=gap_point)), "gap")
696
+ covered_now = {"complete": True, "layers": {}, "units": {"u9": unit()}}
697
+ expect("a gap at release, covered at current, is already resolved",
698
+ kind(judged(nothing, {}, release=gap_point, current=covered_now)), "already resolved")
699
+ literal = judged(nothing, {}, release=open_point, current=gap_point)
700
+ expect("under the literal policy an incomplete release turns the gap unknown and the kind unclassified, naming the "
701
+ "unknown layer", (literal["candidate_diagnosis"]["release"]["diagnosis"], kind(literal),
702
+ literal["candidate_diagnosis"]["release"]["absence"]["unknown_layers"]),
703
+ ("unknown", "unclassified", ["native_settings"]))
704
+ _TABLES["t"] = {**held, "absence_completeness": {"policy": "scoped", "layers": ["catalog"]}}
705
+ try:
706
+ scoped = judged(nothing, {}, release=open_point, current=gap_point)
707
+ expect("control: the scoped policy over the catalog alone reads the same point as a gap, naming what it read",
708
+ (kind(scoped), scoped["candidate_diagnosis"]["release"]["absence"]),
709
+ ("gap", {"policy": "scoped", "layers_read": ["catalog"], "unknown_layers": []}))
710
+ finally:
711
+ _TABLES["t"] = held
712
+ _TABLES["t"] = {**held, "absence_completeness": {"policy": "guessed"}}
713
+ try:
714
+ refused("an absence policy the table does not define", lambda: judged(nothing, {}), "TABLE_INVALID")
715
+ finally:
716
+ _TABLES["t"] = held
717
+
718
+ # lifecycle: redundant and obsolete
719
+ pair = {"u1": unit(), "u2": unit()}
720
+ redundant = judged(pair, {"u1": [pinned], "u2": [pinned]}, lifecycle="redundancy_hint")
721
+ expect("a redundancy candidate with two covering units is redundant and keeps the kind its units yield",
722
+ (redundant["candidate_diagnosis"]["release"]["diagnosis"], kind(redundant)), ("redundant", "confirmed"))
723
+ expect("control: the same units on a formed candidate are covered",
724
+ judged(pair, {"u1": [pinned], "u2": [pinned]})["candidate_diagnosis"]["release"]["diagnosis"], "covered")
725
+ gone_now = {"u1": unit(following="not_followed")}
726
+ no_longer = unit_outcome({"candidate": {"candidate_id": "obsolete_hint:x", "type": "A", "lifecycle": "obsolete_hint"},
727
+ "judges": {"A": {"requirements": met, "no_longer_arises": True},
728
+ "B": {"requirements": met, "no_longer_arises": True}},
729
+ "points": {"release": {"complete": True, "layers": {}, "units": gone_now},
730
+ "current": {"complete": True, "layers": {}, "units": gone_now}},
731
+ "checks_pass": True, "lineages": 0}, {"u1": [pinned]}, "untested: s8_deferred")
732
+ expect("a lifecycle candidate both judges find no longer arising is obsolete", kind(no_longer), "obsolete")
733
+ expect("control: one judge alone does not make it obsolete",
734
+ unit_outcome({**{"candidate": {"candidate_id": "obsolete_hint:x", "type": "A", "lifecycle": "obsolete_hint"},
735
+ "judges": {"A": {"requirements": met, "no_longer_arises": True},
736
+ "B": {"requirements": met, "no_longer_arises": False}},
737
+ "points": {"release": {"complete": True, "layers": {}, "units": gone_now},
738
+ "current": {"complete": True, "layers": {}, "units": gone_now}},
739
+ "checks_pass": True, "lineages": 0}}, {"u1": [pinned]}, "untested: s8_deferred")["kind"]["kind"],
740
+ "misfire")
741
+
742
+ # admission, eligibility, the test state
743
+ result = judged({"u1": unit()}, {"u1": [pinned]})
744
+ expect("both judges met on all eight with the checks passing is admitted, and two lineages are eligible",
745
+ (result["admission"]["admission"], result["eligible"]["eligible"], result["test"]),
746
+ ("admitted", True, "untested: s8_deferred"))
747
+ expect("control: a failing deterministic check leaves it disputed",
748
+ judged({"u1": unit()}, {"u1": [pinned]}, checks_pass=False)["admission"]["admission"], "disputed")
749
+ flipped = copy.deepcopy(held)
750
+ for r in flipped["promotion"]:
751
+ if r["id"] == "lineages":
752
+ r["eligible"] = False
753
+ _TABLES["t"] = flipped
754
+ try:
755
+ moved = eligible("D", 2, None, None)
756
+ finally:
757
+ _TABLES["t"] = held
758
+ expect("Codex WP-10 r1 #5: two lineages are eligible as the lineages row says, and not once a scratch table says "
759
+ "that row is not", (eligible("D", 2, None, None)[:2], moved[:2]), ((True, "lineages"), (False, "lineages")))
760
+ expect("one lineage, no grave consequence: below the bar, with the dispositions it allows",
761
+ judged({"u1": unit()}, {"u1": [pinned]}, lineages=1)["eligible"],
762
+ {"eligible": False, "row": "below_bar", "allowed_dispositions": ["incubate", "keep", "drop", "none"]})
763
+ # D-20261112-644ff3, through lane L's own reader: a candidate in the shape release 1 derives (the current point
764
+ # only, incomplete, no unit matched, one lineage) is below the bar and unclassified, and `none` is the one answer
765
+ # both §7.2's row and the bar accept - for a new candidate and for a legacy entry the owner's default answers
766
+ from runlib import placement, stage_propose
767
+ names = table()["requirements"]
768
+ for label, lifecycle, legacy in (("a new candidate", None, False), ("a legacy entry", "legacy", True)):
769
+ given = {"candidate": {"candidate_id": "k-bar", "type": "D", "lifecycle": lifecycle},
770
+ "judges": {who: {"requirements": {n: "met" for n in names}, "consequence_class": "quality",
771
+ "no_longer_arises": False} for who in ("A", "B")},
772
+ "points": {"current": {"complete": False, "layers": {"native_settings": "unknown"}, "units": {}}},
773
+ "checks_pass": True, "lineages": 1, "arc_confirmed": False}
774
+ outcome = unit_outcome(given, {}, "untested: s8_deferred")
775
+ row = {"outcome": outcome, "requirements": {}, "lineages": 1}
776
+ said = {disposition: placement.problems(stage_propose.proposal_of(stage_propose._answered(
777
+ disposition=disposition, operations=[], destination={"layer": "incubator", "carrier": None}),
778
+ {"candidate_id": "k-bar", "type": "D"}, row, legacy), {}) for disposition in ("none", "place")}
779
+ expect(f"{label} below the bar, as release 1 derives it, may be proposed `none` and still not `place`",
780
+ (outcome["kind"]["kind"], outcome["eligible"]["row"], said["none"],
781
+ any(line.startswith("PAIR_DISALLOWED") for line in said["place"])),
782
+ ("unclassified", "below_bar", [], True))
783
+ expect("a type G candidate needs three lineages", judged({"u1": unit()}, {"u1": [pinned]}, kind_type="G")["eligible"]["row"],
784
+ "below_bar")
785
+ refused("a derivation with no test state", lambda: judged({"u1": unit()}, {"u1": [pinned]}, test=""),
786
+ "TEST_STATE_UNNAMED")
787
+ refused("a derivation with a test state the table does not name",
788
+ lambda: judged({"u1": unit()}, {"u1": [pinned]}, test="tested: maybe"), "TEST_STATE_UNNAMED")
789
+ refused("a judged match outside the domain", lambda: unit_diagnosis("maybe", "yes"), "JUDGMENT_INVALID")
790
+ refused("a requirement mark outside the domain", lambda: admission({**met, "bounded": "probably"}, met, True),
791
+ "JUDGMENT_INVALID judge A")
792
+
793
+ for failure in failures:
794
+ print(f"derive --self-test [FAIL] {failure}")
795
+ if failures:
796
+ return 1
797
+ print(f"derive --self-test: OK ({len(ran)} controls, {len(fixtures)} frozen fixtures over the table's "
798
+ f"{len(row_ids())} rows: the §6.4 table total and as the design states it, the three-set bijection with its "
799
+ "four failures, the O3 verdicts each with its flipped control, the kind precedence over a mixed fixture, two "
800
+ "judges' disputes and the adjudication that settles one, both absence policies, lifecycle redundant and "
801
+ "obsolete, admission and promotion, the named test state)")
802
+ return 0
803
+
804
+
805
+ if __name__ == "__main__":
806
+ if sys.argv[1:2] == ["--generate-fixtures"]:
807
+ target = pathlib.Path(sys.argv[2]) if len(sys.argv) > 2 else FIXTURES_PATH
808
+ print(f"wrote {generate_fixtures(target)} fixtures to {target}")
809
+ sys.exit(0)
810
+ if "--self-test" not in sys.argv[1:]:
811
+ sys.exit("usage: derive.py --self-test | --generate-fixtures [PATH]")
812
+ sys.exit(self_test())