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,740 @@
1
+ #!/usr/bin/env python3
2
+ """The §7.5 total order over review rows (WP-12 commit 4), as a key computed from one table.
3
+
4
+ `tables/ranking.json` holds the seven keys in their order, each ordered vocabulary, and §9's six
5
+ groups. This module turns a row into a tuple and sorts by it; it decides nothing the table does not
6
+ say. The last key is the candidate's own id, which cannot tie, and that is what makes the order
7
+ total rather than merely stable.
8
+
9
+ Two things it refuses rather than guesses. A value outside an ordered vocabulary is named, because
10
+ sorting an unknown value to the end would place a row by its absence from a list. And a row whose
11
+ status, kind and disposition no §9 group names is named too: four of the six groups are statuses,
12
+ two are not, and six statuses of §7.2 appear in no group sentence at all - placing those by
13
+ resemblance would be this code inventing the report's shape.
14
+
15
+ ranking.py --self-test
16
+ """
17
+ import json
18
+ import pathlib
19
+ import sys
20
+
21
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
22
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
23
+ from runlib.records import Refused # noqa: E402
24
+
25
+ HERE = pathlib.Path(__file__).resolve().parents[1]
26
+ TABLE_PATH = HERE / "tables" / "ranking.json"
27
+ _TABLE = {}
28
+ # The design's own sentences, copied once and compared with the table's, so neither can be edited
29
+ # alone. §7.5 for the keys, §9 for the groups.
30
+ DESIGN_7_5 = (
31
+ "A total order over all review rows, computed by code and printed per row: status group (§9), "
32
+ "consequence class (irreversible, security, verification-corrupting, cost, quality, none), "
33
+ "affirmed independent lineages (descending), kind (misfire, gap, not delivered, obsolete, "
34
+ "confirmed, already resolved, unclassified), diagnosis (trigger problem, wrong or insufficient, "
35
+ "gap, redundant, covered, unknown), change before no-change, candidate id.")
36
+ DESIGN_9_GROUPS = (
37
+ "Rows appear in the single total order of §7.5, grouped by status: proposed and tested; disputed "
38
+ "(adjudicate); confirmed and keep; already resolved and unclassified; rejected; quarantined or "
39
+ "failed.")
40
+
41
+
42
+ # The amendment's sentence for the S7b key, held the same way: this one is NOT §7.5's, and saying so
43
+ # in code is the point - a reader who finds eight keys where the design names seven must be able to
44
+ # see which one rests on what.
45
+ DESIGN_AMENDMENT_S7B = (
46
+ "plan amendment 2026-11-11T0040 (release 1 ships distill without S8), the WP-20 row: \"the §7.5 "
47
+ "order falls back to the judges and S7b, and the header names the fallback\".")
48
+
49
+
50
+ def table():
51
+ """The ranking table, read once."""
52
+ if not _TABLE:
53
+ if not TABLE_PATH.is_file():
54
+ raise Refused(f"RANKING_TABLE_ABSENT {TABLE_PATH}: the order has no authority to read")
55
+ _TABLE.update(json.loads(TABLE_PATH.read_text(encoding="utf-8")))
56
+ for name in ("keys", "consequence_classes", "kind_order", "diagnosis_order", "change_order",
57
+ "groups", "unplaced_statuses"):
58
+ if name not in _TABLE:
59
+ raise Refused(f"RANKING_TABLE_INCOMPLETE {name}: the table does not say it")
60
+ return _TABLE
61
+
62
+
63
+ def group_of(row):
64
+ """`(group id, index)` for the §9 group this row belongs to, or `(None, None)`.
65
+
66
+ Two passes, and the order between them is the reading of §9 this module stands on. §9 says the
67
+ rows are "grouped by status", so a status a group names decides first. Two of the six groups are
68
+ named by no status - "confirmed and keep" names a kind and a disposition beside one, and "already
69
+ resolved and unclassified" names two kinds only - so a row whose status no group holds is placed
70
+ by its kind or its disposition instead. Without the second pass those two groups would be
71
+ unreachable for the rows they exist for: an approved keep carries a status §9 never mentions.
72
+ Within each pass the table's order is §9's sentence order, so the group a row lands in is the
73
+ group the report prints it under."""
74
+ groups = table()["groups"]
75
+ for fields in (("status",), ("kind", "disposition")):
76
+ for index, group in enumerate(groups):
77
+ for member in group["members"]:
78
+ if member["field"] in fields and row.get(member["field"]) == member["value"]:
79
+ return group["id"], index
80
+ return None, None
81
+
82
+
83
+ def changes_library(row):
84
+ """Whether this row's disposition changes the library: §7.5's "change before no-change".
85
+
86
+ Read from the row's own `changes_library` when it carries one, so the caller that knows §10.4's
87
+ ledger-only set stays its owner; absent that, from the disposition against the table."""
88
+ if "changes_library" in row:
89
+ return bool(row["changes_library"])
90
+ return row.get("disposition") not in ("keep", "incubate", "drop", "none", None)
91
+
92
+
93
+ def value_problems(rows):
94
+ """Values no ordered vocabulary of the table holds, and rows no §9 group names, each by name."""
95
+ held, problems = table(), []
96
+ vocabularies = {"consequence": held["consequence_classes"], "kind": held["kind_order"],
97
+ "diagnosis": held["diagnosis_order"]}
98
+ for row in rows:
99
+ where = row.get("candidate_id") or "<a row with no candidate id>"
100
+ if not row.get("candidate_id"):
101
+ problems.append(f"ROW_ID_ABSENT {where}: the last ranking key is the candidate's own id, "
102
+ f"and without it the order is not total")
103
+ for field, order in vocabularies.items():
104
+ value = row.get(field)
105
+ if value is None:
106
+ problems.append(f"ROW_VALUE_ABSENT {where}.{field}: a ranking key with no value")
107
+ elif value not in order:
108
+ problems.append(f"ROW_VALUE_UNKNOWN {where}.{field}={value!r}: not one of "
109
+ f"{', '.join(order)}")
110
+ lineages = row.get("lineages")
111
+ if not isinstance(lineages, int) or isinstance(lineages, bool):
112
+ problems.append(f"ROW_LINEAGES_NOT_A_COUNT {where}: affirmed independent lineages is the "
113
+ f"one numeric key, and {lineages!r} does not order")
114
+ name, _index = group_of(row)
115
+ if name is None:
116
+ problems.append(
117
+ f"ROW_GROUP_UNDECLARED {where}: no §9 group names its status {row.get('status')!r}, "
118
+ f"kind {row.get('kind')!r} or disposition {row.get('disposition')!r}"
119
+ + (f"; that status is one §9 places in no group ({', '.join(held['unplaced_statuses'])})"
120
+ if row.get("status") in held["unplaced_statuses"] else ""))
121
+ return problems
122
+
123
+
124
+ def row_label(row):
125
+ """What the report prints for this row's status: `proposed (untested: s8_deferred)`, or the status.
126
+
127
+ A label, not a placement. Release 1 defers S8, so no row is `tested`; the test state is a field of
128
+ the derivation, and the group a row lands in is decided by its status alone."""
129
+ held = table().get("test_state_label") or {}
130
+ status, state = row.get("status"), row.get("test_state")
131
+ if state and status in (held.get("applies_to_status") or ()):
132
+ return held.get("format", "{status} ({test_state})").format(status=status, test_state=state)
133
+ return str(status)
134
+
135
+
136
+ def rank_key(row):
137
+ """The row's position as a tuple, in the table's key order. Refuses a row with a bad value.
138
+
139
+ Refuses rather than sorts, because every key but the last is a position in a closed vocabulary:
140
+ a value outside one has no position, and giving it the end of the list would order a row by what
141
+ the list does not contain."""
142
+ problems = value_problems([row])
143
+ if problems:
144
+ raise Refused(f"RANK_UNDEFINED {'; '.join(problems)}")
145
+ held = table()
146
+ _name, group = group_of(row)
147
+ try:
148
+ return _position(held, row, group)
149
+ except (ValueError, TypeError, KeyError) as exc:
150
+ # Name the VALUE, not the exception: `list.index` says only "x not in list", so a refusal
151
+ # built from it told the reader nothing about which key or which value had no position.
152
+ culprit = [f"{field}={row.get(field)!r}" for field, order in
153
+ (("consequence", held["consequence_classes"]), ("kind", held["kind_order"]),
154
+ ("diagnosis", held["diagnosis_order"])) if row.get(field) not in order]
155
+ raise Refused(f"RANK_UNDEFINED {row.get('candidate_id')}: "
156
+ f"{', '.join(culprit) or f'{type(exc).__name__} {exc}'} has no position in its "
157
+ f"vocabulary") from exc
158
+
159
+
160
+ # What a row with no S7b answer takes: the same position as a reviewed row needing no owner, so the
161
+ # key cannot reorder a run that has no reviews.
162
+ NEUTRAL_POSITION = 1
163
+
164
+
165
+ def owner_resolves_position(row):
166
+ """The S7b key's position: a row the review leaves to the owner first, a row with no review neutral.
167
+
168
+ The amendment, not §7.5 — with S8 deferred the order falls back to the judges and S7b, and this
169
+ is S7b's part. A row carrying NO S7b record is neutral rather than last, so adding the key cannot
170
+ reorder a run that has no reviews: it takes the same position as a reviewed row that needs no
171
+ owner. The table holds the three positions (`keys[owner_resolves].values`) rather than this
172
+ function, so the direction is the table's statement and not a literal here.
173
+ """
174
+ key = next((key for key in table()["keys"] if key["id"] == "owner_resolves"), None)
175
+ if key is None or not key.get("values"):
176
+ # A key missing from the table is a TABLE defect, named by `fidelity_problems`, not a reason
177
+ # to make every report unorderable: the order degrades to §7.5's own keys, which is what it
178
+ # was before the amendment. Refusing here instead killed the whole suite at its first
179
+ # control, so the defect had no negative control at all.
180
+ return NEUTRAL_POSITION
181
+ values = key["values"]
182
+ held = row.get("owner_resolves")
183
+ if held is None:
184
+ return values["absent"]
185
+ if held:
186
+ return values["true"]
187
+ return values["false"]
188
+
189
+
190
+ # One reader per key id. The ORDER of the tuple and each key's DIRECTION come from the table, not
191
+ # from here: the tuple was written out in order with the descending sign hardcoded, so the table
192
+ # could declare a different key order, or turn `consequence` descending, and the ranking would not
193
+ # move and no control would fail (the WP-12 review). A key the table declares and nothing here can
194
+ # read is refused by name rather than ignored.
195
+ KEY_READERS = {
196
+ "status_group": lambda held, row, group: group,
197
+ "consequence": lambda held, row, group: held["consequence_classes"].index(row["consequence"]),
198
+ "lineages": lambda held, row, group: row["lineages"],
199
+ "owner_resolves": lambda held, row, group: owner_resolves_position(row),
200
+ "kind": lambda held, row, group: held["kind_order"].index(row["kind"]),
201
+ "diagnosis": lambda held, row, group: held["diagnosis_order"].index(row["diagnosis"]),
202
+ "change": lambda held, row, group: held["change_order"].index(
203
+ "change" if changes_library(row) else "no-change"),
204
+ "candidate_id": lambda held, row, group: str(row["candidate_id"]),
205
+ }
206
+
207
+
208
+ def _position(held, row, group):
209
+ """The tuple itself, built from the table's key order so neither surface can move alone.
210
+
211
+ Every lookup is in one place so a failed one cannot escape as a ValueError.
212
+ """
213
+ keys = held.get("keys") or []
214
+ if not keys:
215
+ raise Refused("RANK_KEYS_ABSENT: the table declares no key, so the order would be "
216
+ "whatever `sorted` does with equal rows")
217
+ held_tuple = []
218
+ for key in keys:
219
+ read = KEY_READERS.get(key.get("id"))
220
+ if read is None:
221
+ raise Refused(f"RANK_KEY_UNREADABLE {key.get('id')!r}: the table declares this key and "
222
+ f"nothing here reads it, so the order it asks for is not the order rows "
223
+ f"come out in")
224
+ value = read(held, row, group)
225
+ direction = key.get("direction", "ascending")
226
+ if direction == "descending":
227
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
228
+ raise Refused(f"RANK_KEY_DESCENDING_UNORDERABLE {key.get('id')}={value!r}: only a "
229
+ f"number can be reversed by negating it, so a descending order over "
230
+ f"this value cannot be expressed")
231
+ value = -value
232
+ elif direction != "ascending":
233
+ raise Refused(f"RANK_KEY_DIRECTION_UNKNOWN {key.get('id')}={direction!r}: the table "
234
+ f"declares ascending or descending")
235
+ held_tuple.append(value)
236
+ return tuple(held_tuple)
237
+
238
+
239
+ def ranked(rows):
240
+ """The rows in the §7.5 order, each carrying its `rank` (1-based) and its §9 group."""
241
+ ordered = sorted(rows, key=rank_key)
242
+ return [{**row, "rank": n, "status_group": group_of(row)[0], "status_label": row_label(row)}
243
+ for n, row in enumerate(ordered, start=1)]
244
+
245
+
246
+ def fidelity_problems():
247
+ """The table's sentences against the two copied here: neither can be edited alone."""
248
+ held, problems = table(), []
249
+ s7b_key = next((key for key in held.get("keys") or [] if key.get("id") == "owner_resolves"), {})
250
+ if not s7b_key.get("values"):
251
+ problems.append("RANK_KEY_ABSENT owner_resolves: the table carries no such key, so the order "
252
+ "has no position for the S7b fallback the amendment names and every row "
253
+ "takes the neutral one")
254
+ for name, mine, theirs in (("§7.5", DESIGN_7_5, held.get("design")),
255
+ ("§9", DESIGN_9_GROUPS, held.get("groups_design")),
256
+ ("the amendment", DESIGN_AMENDMENT_S7B, s7b_key.get("design"))):
257
+ if " ".join((theirs or "").split()) != " ".join(mine.split()):
258
+ problems.append(f"DESIGN_SENTENCE_DIVERGED {name}: the table's sentence is not the one this "
259
+ f"module holds")
260
+ # Every vocabulary the sentence enumerates must be the table's list, in the sentence's order: the
261
+ # sentence is the authority and the table is its transcription.
262
+ for field, phrase in (("consequence_classes", "consequence class ("),
263
+ ("kind_order", "kind ("), ("diagnosis_order", "diagnosis (")):
264
+ start = DESIGN_7_5.index(phrase) + len(phrase)
265
+ spelled = [v.strip() for v in DESIGN_7_5[start:DESIGN_7_5.index(")", start)].split(",")]
266
+ if spelled != held[field]:
267
+ problems.append(f"VOCABULARY_DIVERGED {field}: the sentence says {spelled} and the table "
268
+ f"says {held[field]}")
269
+ return problems
270
+
271
+
272
+ # ---- self-test -----------------------------------------------------------------------------------
273
+
274
+ def self_test():
275
+ """Positive control first, then one planted violation per rule, each named.
276
+
277
+ Done-when 9 is the last two controls: two rows differing only in candidate id order
278
+ deterministically, and the order is total over every row the fixtures hold.
279
+ The body is wrapped so a control that DIES still speaks: a traceback is not a control firing,
280
+ and a revert trial that reads any output counts one as if it were (the WP-12 review). The
281
+ wrapper prints a [FAIL] line naming the control that was in flight, so the evidence says which
282
+ rule stopped being enforced.
283
+ """
284
+ failures, ran = [], []
285
+ try:
286
+ return _self_test_body(failures, ran)
287
+ except BaseException as exc: # noqa: BLE001 - the suite must speak before it dies
288
+ held = ran[-1] if ran else "<no control ran>"
289
+ print(f"ranking --self-test [FAIL] the suite died after {held!r}: "
290
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
291
+ for name, detail in failures:
292
+ print(f"ranking --self-test [FAIL] {name}: {detail}", file=sys.stderr)
293
+ print(f"ranking --self-test: INCOMPLETE ({len(ran)} controls ran, {len(failures)} failed "
294
+ f"before the suite died)", file=sys.stderr)
295
+ raise
296
+
297
+
298
+ def _self_test_body(failures, ran):
299
+ reporting = []
300
+
301
+ def control(name, got, want):
302
+ if reporting:
303
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
304
+ if not isinstance(got, str):
305
+ raise TypeError(f"CONTROL_GOT_NOT_STR {name}: {type(got).__name__}")
306
+ ran.append(name)
307
+ if want not in got:
308
+ failures.append((name, f"expected {want!r} in {got!r}"))
309
+
310
+ def clean(name, problems):
311
+ if reporting:
312
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
313
+ if not isinstance(problems, list):
314
+ raise TypeError(f"CLEAN_PROBLEMS_NOT_LIST {name}: {type(problems).__name__}")
315
+ ran.append(name)
316
+ if problems:
317
+ failures.append((name, f"expected nothing, got {problems}"))
318
+
319
+ def refusal(call):
320
+ try:
321
+ call()
322
+ except Refused as exc:
323
+ return str(exc)
324
+ return ""
325
+
326
+ def row(**over):
327
+ held = {"candidate_id": "C-100", "status": "proposed", "kind": "gap", "diagnosis": "gap",
328
+ "disposition": "place", "consequence": "quality", "lineages": 2}
329
+ held.update(over)
330
+ return held
331
+
332
+ clean("the table carries the design's own sentences, and its vocabularies are those sentences' "
333
+ "lists in their order", fidelity_problems())
334
+ # Seven from §7.5 and one from the amendment: the count is stated as that sum, so a key added
335
+ # without a sentence to rest on fails here rather than quietly making the list longer.
336
+ control("the table holds §7.5's seven keys and the amendment's one",
337
+ f'{len([k for k in table()["keys"] if k["id"] != "owner_resolves"])}+'
338
+ f'{len([k for k in table()["keys"] if k["id"] == "owner_resolves"])}', "7+1")
339
+ control("and the last of them is the candidate id, which is what makes the order total",
340
+ table()["keys"][-1]["id"], "candidate_id")
341
+ clean("an ordinary row has every value a key needs", value_problems([row()]))
342
+
343
+ # The keys, one at a time: each control changes ONE field and asks for the order that field alone
344
+ # decides, so a key read from the wrong column cannot pass.
345
+ control("the status group orders before everything else: a rejected row follows a proposed one "
346
+ "that is worse by every other key",
347
+ ", ".join(r["candidate_id"] for r in ranked([
348
+ row(candidate_id="C-a", status="rejected", consequence="irreversible",
349
+ lineages=9, kind="misfire", diagnosis="trigger problem"),
350
+ row(candidate_id="C-b", consequence="none", lineages=0, kind="unclassified",
351
+ diagnosis="unknown")])),
352
+ "C-b, C-a")
353
+ control("consequence orders next, irreversible before quality",
354
+ ", ".join(r["candidate_id"] for r in ranked([row(candidate_id="C-a", consequence="quality"),
355
+ row(candidate_id="C-b", consequence="irreversible")])),
356
+ "C-b, C-a")
357
+ control("lineages order DESCENDING, which no other key does",
358
+ ", ".join(r["candidate_id"] for r in ranked([row(candidate_id="C-few", lineages=1),
359
+ row(candidate_id="C-many", lineages=7)])),
360
+ "C-many, C-few")
361
+ control("kind orders by §7.5's list, misfire before unclassified",
362
+ ", ".join(r["candidate_id"] for r in ranked([row(candidate_id="C-a", kind="unclassified",
363
+ diagnosis="unknown"),
364
+ row(candidate_id="C-b", kind="misfire",
365
+ diagnosis="unknown")])),
366
+ "C-b, C-a")
367
+ control("diagnosis orders by §7.5's list, trigger problem before covered",
368
+ ", ".join(r["candidate_id"] for r in ranked([row(candidate_id="C-c", diagnosis="covered"),
369
+ row(candidate_id="C-t", diagnosis="trigger problem")])),
370
+ "C-t, C-c")
371
+ control("and change comes before no-change, a place before a keep of the same group",
372
+ ", ".join(r["candidate_id"] for r in ranked([
373
+ row(candidate_id="C-keep", disposition="keep", changes_library=False),
374
+ row(candidate_id="C-place", disposition="place")])),
375
+ "C-place, C-keep")
376
+ control("a row's own changes_library is read even where the disposition would say otherwise: a "
377
+ "place marked as changing nothing sorts after a keep that does",
378
+ ", ".join(r["candidate_id"] for r in ranked([
379
+ row(candidate_id="C-a", disposition="place", changes_library=False),
380
+ row(candidate_id="C-b", disposition="keep", changes_library=True)])),
381
+ "C-b, C-a")
382
+ clean("§10.4's ledger-only dispositions are the no-change side, read from the disposition when "
383
+ "the row does not say",
384
+ [d for d in ("keep", "incubate", "drop", "none") if changes_library(row(disposition=d))]
385
+ + ([] if changes_library(row(disposition="place")) else ["place read as no-change"]))
386
+
387
+ # Done-when 9: determinism, and a total order.
388
+ pair = [row(candidate_id="C-002"), row(candidate_id="C-001")]
389
+ control("two rows differing only in candidate id order deterministically",
390
+ ", ".join(r["candidate_id"] for r in ranked(pair)), "C-001, C-002")
391
+ control("and the same two in the other arrival order give the same answer",
392
+ ", ".join(r["candidate_id"] for r in ranked(list(reversed(pair)))), "C-001, C-002")
393
+ many = [row(candidate_id=f"C-{n:03d}", consequence=table()["consequence_classes"][n % 6],
394
+ kind=table()["kind_order"][n % 7], diagnosis=table()["diagnosis_order"][n % 6],
395
+ lineages=n % 4) for n in range(40)]
396
+ keys = [rank_key(r) for r in many]
397
+ clean("the key is a total order over forty rows: no two share one",
398
+ [f"{len(keys) - len(set(keys))} rows share a key"] if len(set(keys)) != len(keys) else [])
399
+ control("and every row carries its rank and its §9 group",
400
+ str(sorted({(r["rank"] is not None) and bool(r["status_group"]) for r in ranked(many)})),
401
+ "[True]")
402
+ control("the ranks run 1..n with no gap",
403
+ str([r["rank"] for r in ranked(many)] == list(range(1, len(many) + 1))), "True")
404
+
405
+ # §9's groups, including the two the sentence does not name by status.
406
+ control("a row is placed in the first group any of its fields names",
407
+ str(group_of(row(status="proposed"))[0]), "proposed_and_tested")
408
+ control("a status a group names decides before the row's kind does, because §9 groups by status: "
409
+ "a tested row whose kind is confirmed is printed under proposed and tested",
410
+ group_of(row(status="tested", kind="confirmed", diagnosis="covered"))[0], "proposed_and_tested")
411
+ control("a status decides even when the row's kind names an earlier group: a rejected row whose "
412
+ "kind is confirmed is printed under rejected, which one pass over all three fields got wrong",
413
+ str(group_of(row(status="rejected", kind="confirmed", diagnosis="covered"))[0]), "rejected")
414
+ control("while a row whose status §9 never mentions is placed by its KIND of confirmed",
415
+ str(group_of(row(status="approved", kind="confirmed", diagnosis="covered"))[0]),
416
+ "confirmed_and_keep")
417
+ control("or by its keep disposition, which is how an approved keep reaches that group at all",
418
+ str(group_of(row(status="applied", kind="gap", disposition="keep"))[0]), "confirmed_and_keep")
419
+ control("an unclassified KIND goes to the group §9 names by kind alone",
420
+ # `approved` on purpose: a status no group holds, so the kind pass is what answers. Was
421
+ # `untested`, which release 1 placed in the first group - the control then measured the
422
+ # status pass twice and said nothing about the kind pass.
423
+ str(group_of(row(status="approved", kind="unclassified", diagnosis="unknown"))[0]),
424
+ "already_resolved_and_unclassified")
425
+ # WP-20's rows, each built here rather than borrowed. Lane E found two of them in the wrong
426
+ # place: a returned proposal fell into the resolved/unclassified group by its KIND, and a
427
+ # returned row whose kind is gap was refused outright, so K2 and K3 could not be committed.
428
+ control("a returned proposal is in the quarantined-or-failed group, not in the group its kind "
429
+ "would have chosen", str(group_of(row(status="returned"))[0]), "quarantined_or_failed")
430
+ clean("and that holds for every kind, including the gap row that was refused outright",
431
+ [k for k in table()["kind_order"]
432
+ if group_of(row(status="returned", kind=k,
433
+ diagnosis="unknown"))[0] != "quarantined_or_failed"])
434
+ clean("a returned row of each kind can be ranked at all, which the refusal prevented",
435
+ [k for k in table()["kind_order"]
436
+ if value_problems([row(status="returned", kind=k, diagnosis="unknown")])])
437
+ control("a failed item is in the same group, because §9's population sentence says \"quarantined "
438
+ "or failed\"", str(group_of(row(status="failed"))[0]), "quarantined_or_failed")
439
+ clean("and a failed row of every kind ranks and groups the same way",
440
+ [k for k in table()["kind_order"]
441
+ if group_of(row(status="failed", kind=k, diagnosis="unknown"))[0] != "quarantined_or_failed"
442
+ or value_problems([row(status="failed", kind=k, diagnosis="unknown")])])
443
+ clean("neither status is counted as one §9 places nowhere any more",
444
+ [s for s in table()["unplaced_statuses"] if s in ("returned", "failed")])
445
+ control("an untested row is in the first group, as release 1's deferral of S8 puts it there",
446
+ str(group_of(row(status="untested"))[0]), "proposed_and_tested")
447
+ control("and the report prints it with its test state",
448
+ row_label(row(status="untested", test_state="untested: s8_deferred")),
449
+ "untested (untested: s8_deferred)")
450
+ control("a proposed row carries the same label, which is what a release-1 report shows",
451
+ row_label(row(test_state="untested: s8_deferred")), "proposed (untested: s8_deferred)")
452
+ labelled = ranked([row(test_state="untested: s8_deferred")])[0]
453
+ clean("the ranked row's own status is unchanged by its label, so nothing is ranked by it",
454
+ [] if labelled["status"] == "proposed" else [f'status is {labelled["status"]!r}'])
455
+ control("while its label carries the state", str(labelled.get("status_label")),
456
+ "proposed (untested: s8_deferred)")
457
+ clean("and every ranked row carries a label",
458
+ [r["candidate_id"] for r in ranked([row(), row(candidate_id="C-2")])
459
+ if not r.get("status_label")])
460
+ held_label = row_label(row(status="rejected", test_state="untested: s8_deferred"))
461
+ clean("a test state on a status the label does not apply to is the status itself, not the status "
462
+ "with the state appended",
463
+ [] if held_label == "rejected" else [f"the label is {held_label!r}"])
464
+
465
+ control("a row no group names by status, kind or disposition is refused by name",
466
+ "; ".join(value_problems([row(status="approved", kind="gap", disposition="place")])),
467
+ "ROW_GROUP_UNDECLARED")
468
+ control("and the refusal says that status is one of the unplaced ones, rather than leaving the "
469
+ "reader to infer it",
470
+ "; ".join(value_problems([row(status="approved", kind="gap", disposition="place")])),
471
+ "that status is one §9 places in no group")
472
+ control("the unplaced list is exactly §7.2's statuses no group holds",
473
+ ", ".join(sorted(table()["unplaced_statuses"])),
474
+ "admitted, applied, approved, delivery_verified")
475
+
476
+ # Values with no position, and rows that cannot be ranked at all.
477
+ control("a consequence outside the vocabulary is named rather than sorted to the end",
478
+ "; ".join(value_problems([row(consequence="mild")])), "ROW_VALUE_UNKNOWN")
479
+ control("a kind outside it too", "; ".join(value_problems([row(kind="regression")])),
480
+ "ROW_VALUE_UNKNOWN")
481
+ control("a missing diagnosis is named as absent, not as unknown",
482
+ "; ".join(value_problems([{**row(), "diagnosis": None}])), "ROW_VALUE_ABSENT")
483
+ control("a row with no candidate id is named, because the last key is what makes the order total",
484
+ "; ".join(value_problems([{k: v for k, v in row().items() if k != "candidate_id"}])),
485
+ "ROW_ID_ABSENT")
486
+ control("lineages that are not a count are named",
487
+ "; ".join(value_problems([row(lineages="several")])), "ROW_LINEAGES_NOT_A_COUNT")
488
+ control("a boolean is not a count either, though Python would happily order it",
489
+ "; ".join(value_problems([row(lineages=True)])), "ROW_LINEAGES_NOT_A_COUNT")
490
+ control("and ranking such a row refuses instead of returning a position",
491
+ refusal(lambda: rank_key(row(consequence="mild"))), "RANK_UNDEFINED")
492
+ control("the refusal carries the value it could not place",
493
+ refusal(lambda: rank_key(row(consequence="mild"))), "'mild'")
494
+ # What the pre-check alone can say: the tuple's own lookups would raise a KeyError here, and a
495
+ # refusal reading "KeyError 'candidate_id'" names Python's problem rather than the row's.
496
+ control("a row with no candidate id refuses by the rule's name, not by the exception the tuple "
497
+ "would have raised",
498
+ refusal(lambda: rank_key({k: v for k, v in row().items() if k != "candidate_id"})),
499
+ "ROW_ID_ABSENT")
500
+
501
+ # The loader's two refusals, with their cases PLANTED: a guard whose case never occurs in a run
502
+ # is a guard no control can fire. No temp file is made - `runlib/dispatch.py` admits `tempfile`
503
+ # only in the two files it declares - so the planted paths are a name that is not there and a
504
+ # table of this tree that is real JSON without the keys this one needs.
505
+ def with_table_path(path):
506
+ held_path, held_table = globals()["TABLE_PATH"], dict(_TABLE)
507
+ globals()["TABLE_PATH"] = path
508
+ _TABLE.clear()
509
+ try:
510
+ return refusal(table)
511
+ finally:
512
+ globals()["TABLE_PATH"] = held_path
513
+ _TABLE.clear()
514
+ _TABLE.update(held_table)
515
+
516
+ control("a table that is not there is refused by name rather than read as empty",
517
+ with_table_path(HERE / "tables" / "no-such-ranking.json"), "RANKING_TABLE_ABSENT")
518
+ control("and the refusal names the path it looked at",
519
+ with_table_path(HERE / "tables" / "no-such-ranking.json"), "no-such-ranking.json")
520
+ control("a table that is real JSON but says none of these keys is refused by the key it lacks",
521
+ with_table_path(HERE / "tables" / "structural_rules.json"), "RANKING_TABLE_INCOMPLETE")
522
+ clean("and the real table is back after both plants, so the controls below judge it and not a "
523
+ "leftover", fidelity_problems())
524
+
525
+ # The S7b key the amendment adds. Its rows are built here, and every id is deliberately ordered
526
+ # AGAINST the answer: a key control whose expected order coincides with the id order passes under
527
+ # revert, which this branch has already paid for once.
528
+ control("a row the S7b review leaves to the owner sorts first, ahead of one with no review and "
529
+ "one that needs no owner",
530
+ ",".join(r["candidate_id"] for r in ranked(
531
+ [row(candidate_id="a-no-review"),
532
+ row(candidate_id="z-owner", owner_resolves=True),
533
+ row(candidate_id="m-agreed", owner_resolves=False)])),
534
+ "z-owner,a-no-review,m-agreed")
535
+ # The ids put the ABSENT row first, so ranking absent LAST reverses this answer. With the
536
+ # absent row named `z-none` the expectation was `a-agreed,z-none` — which is also the id order
537
+ # and also the result when absent moves from position 1 to 2, so the control passed either way
538
+ # (the WP-21 review). This is the second time a key control here coincided with the id order.
539
+ control("a row with no S7b record is NEUTRAL: it ranks where S7's own keys put it, so the key "
540
+ "cannot reorder a run that has no reviews",
541
+ ",".join(r["candidate_id"] for r in ranked(
542
+ [row(candidate_id="a-none"), row(candidate_id="z-agreed", owner_resolves=False)])),
543
+ "a-none,z-agreed")
544
+ control("and ranking an absent record LAST would reverse that, which is what makes the "
545
+ "expectation above a test rather than a restatement of the id order",
546
+ ",".join(sorted(["a-none", "z-agreed"],
547
+ key=lambda held: (2 if held == "a-none" else 1, held))),
548
+ "z-agreed,a-none")
549
+ def with_key_removed(call):
550
+ """Run `call` with the S7b key gone from the table, restoring it however the call ends."""
551
+ held = table()
552
+ kept = [key for key in held["keys"] if key["id"] == "owner_resolves"]
553
+ held["keys"] = [key for key in held["keys"] if key["id"] != "owner_resolves"]
554
+ try:
555
+ return call()
556
+ finally:
557
+ at = [i for i, key in enumerate(held["keys"]) if key["id"] == "lineages"][0] + 1
558
+ held["keys"][at:at] = kept
559
+
560
+ def with_key_design(sentence, call):
561
+ """Run `call` with the key's design sentence replaced; a renamed key leaves it alone."""
562
+ key = next((key for key in table()["keys"] if key["id"] == "owner_resolves"), None)
563
+ if key is None:
564
+ return call()
565
+ kept = key["design"]
566
+ key["design"] = sentence
567
+ try:
568
+ return call()
569
+ finally:
570
+ key["design"] = kept
571
+
572
+ # The FUNCTION's own source, not the file's: a scan of the whole file is satisfied by the
573
+ # control text below it, which is how a planted mutation passed here once already.
574
+ import inspect
575
+ key_src = inspect.getsource(owner_resolves_position)
576
+
577
+ def src_line(fragment, text=None):
578
+ """The one line carrying `fragment`, or a placeholder naming its absence.
579
+
580
+ A `next()` over the lines raises StopIteration when the line is gone, which killed the suite
581
+ instead of failing the control it belongs to.
582
+ """
583
+ for line in (text if text is not None else key_src).splitlines():
584
+ if fragment in line:
585
+ return line.strip()
586
+ return f"<no line carrying {fragment!r}>"
587
+
588
+ control("the positions are read from the table rather than written here",
589
+ src_line("key = next("), 'table()["keys"]')
590
+ clean("and each of the three is looked up by its own name, so an absent record cannot be read "
591
+ "as a false one while they happen to share a position",
592
+ [name for name in ("absent", "true", "false") if f'values["{name}"]' not in key_src])
593
+ control("an absent record takes the table's `absent` position by that name",
594
+ src_line('values["absent"]'), 'return values["absent"]')
595
+ control("a table with no such key is a named TABLE defect, not a report nobody can order",
596
+ "; ".join(with_key_removed(fidelity_problems)), "RANK_KEY_ABSENT owner_resolves")
597
+ clean("and with the key gone the order degrades to §7.5's own keys rather than refusing",
598
+ with_key_removed(lambda: [] if [r["candidate_id"] for r in ranked(
599
+ [row(candidate_id="z-owner", owner_resolves=True), row(candidate_id="a-none")])]
600
+ == ["a-none", "z-owner"] else ["the order was not §7.5's own"]))
601
+ control("and the three positions come from the table, not from this module",
602
+ f'{owner_resolves_position(row())},'
603
+ f'{owner_resolves_position(row(owner_resolves=True))},'
604
+ f'{owner_resolves_position(row(owner_resolves=False))}',
605
+ "1,0,1")
606
+ control("the key sits after the judges' and before the structural ones, which is where the "
607
+ "amendment's fallback puts it",
608
+ ",".join(key["id"] for key in table()["keys"]),
609
+ "lineages,owner_resolves,kind")
610
+ control("a higher-ranking key still decides over it: more affirmed lineages comes first even "
611
+ "when the other row is the owner's to resolve",
612
+ ",".join(r["candidate_id"] for r in ranked(
613
+ [row(candidate_id="a-owner", lineages=1, owner_resolves=True),
614
+ row(candidate_id="z-many", lineages=4)])),
615
+ "z-many,a-owner")
616
+ control("and a lower-ranking one does not: the owner's row comes first whatever its kind",
617
+ ",".join(r["candidate_id"] for r in ranked(
618
+ [row(candidate_id="a-gap", kind="gap", diagnosis="gap"),
619
+ row(candidate_id="z-owner", kind="unclassified", diagnosis="unknown",
620
+ owner_resolves=True)])),
621
+ "z-owner,a-gap")
622
+ # ---- the table's key order and directions DECIDE, rather than being described ---------------
623
+ #
624
+ # `_position` wrote the tuple out in order with the descending sign hardcoded: the table could
625
+ # declare `consequence` before `status_group`, or turn `consequence` descending, and no row
626
+ # would move and no control would fail (the WP-12 review).
627
+ def with_keys(mutate, call):
628
+ """Run `call` with the table's keys mutated, restoring them however the call ends."""
629
+ held = table()
630
+ kept = list(held["keys"])
631
+ held["keys"] = mutate([dict(key) for key in kept])
632
+ try:
633
+ return call()
634
+ finally:
635
+ held["keys"] = kept
636
+
637
+ def order_of(rows):
638
+ return ",".join(held_row["candidate_id"] for held_row in ranked(rows))
639
+
640
+ # The ids are ordered AGAINST the answer: `a-cost` is the graver consequence and sorts first,
641
+ # so a mutation that stops the consequence key deciding reverses the pair.
642
+ pair = [row(candidate_id="z-quality", consequence="quality", lineages=1),
643
+ row(candidate_id="a-cost", consequence="cost", lineages=1)]
644
+ control("the keys as declared put the graver consequence first",
645
+ order_of(pair), "a-cost,z-quality")
646
+ control("and turning that key DESCENDING in the table reverses them, so the direction is read "
647
+ "rather than written here",
648
+ with_keys(lambda keys: [{**key, "direction": "descending"}
649
+ if key["id"] == "consequence" else key for key in keys],
650
+ lambda: order_of(pair)),
651
+ "z-quality,a-cost")
652
+ # And the key ORDER: with `candidate_id` ahead of every other key, the id decides. Here that
653
+ # happens to agree with the declared answer, so the DESCENDING id is what distinguishes it.
654
+ control("moving a key ahead of another in the table changes which one decides",
655
+ with_keys(lambda keys: ([key for key in keys if key["id"] == "candidate_id"]
656
+ + [{**key, "id": key["id"]}
657
+ for key in keys if key["id"] != "candidate_id"]),
658
+ lambda: order_of([row(candidate_id="z-cost", consequence="cost", lineages=1),
659
+ row(candidate_id="a-quality", consequence="quality",
660
+ lineages=1)])),
661
+ "a-quality,z-cost")
662
+ control("a key the table declares and nothing here reads is refused by name, since the order it "
663
+ "asks for is not the order rows come out in",
664
+ refusal(lambda: with_keys(lambda keys: keys + [{"id": "invented",
665
+ "direction": "ascending"}],
666
+ lambda: order_of(pair))),
667
+ "RANK_KEY_UNREADABLE 'invented'")
668
+ control("a direction that is neither is refused too",
669
+ refusal(lambda: with_keys(lambda keys: [{**key, "direction": "sideways"}
670
+ if key["id"] == "kind" else key
671
+ for key in keys],
672
+ lambda: order_of(pair))),
673
+ "RANK_KEY_DIRECTION_UNKNOWN kind='sideways'")
674
+ control("and a descending order over a value that is not a number, since negating it is the "
675
+ "only way a tuple expresses descending",
676
+ refusal(lambda: with_keys(lambda keys: [{**key, "direction": "descending"}
677
+ if key["id"] == "candidate_id" else key
678
+ for key in keys],
679
+ lambda: order_of(pair))),
680
+ "RANK_KEY_DESCENDING_UNORDERABLE candidate_id")
681
+ control("and the same pair without the mutation still orders by the consequence, so the "
682
+ "mutations above are what the controls are reading",
683
+ order_of(pair), "a-cost,z-quality")
684
+ control("a table with NO keys is refused rather than left to sorted() over equal rows",
685
+ refusal(lambda: with_keys(lambda keys: [], lambda: order_of(pair))),
686
+ "RANK_KEYS_ABSENT")
687
+ control("every key the table declares has a reader, and every reader a key: one set, named in "
688
+ "both places",
689
+ json.dumps(sorted(KEY_READERS)),
690
+ json.dumps(sorted(key["id"] for key in table()["keys"])))
691
+
692
+ def s7b_key_field(name):
693
+ key = next((key for key in table()["keys"] if key["id"] == "owner_resolves"), None)
694
+ return f"<no owner_resolves key>" if key is None else str(key.get(name))
695
+
696
+ control("the table's own sentence for this key names the amendment rather than §7.5, so a "
697
+ "reader finding eight keys where the design names seven can see which is which",
698
+ s7b_key_field("design"), "plan amendment 2026-11-11T0040")
699
+ clean("and that sentence is held against the one this module carries, like the other two",
700
+ [p for p in fidelity_problems() if "the amendment" in p])
701
+ control("a hand edit of the key's sentence is named as a divergence, so the comparison is real "
702
+ "and not merely present",
703
+ "; ".join(with_key_design("§7.5, the eighth key.", fidelity_problems)),
704
+ "DESIGN_SENTENCE_DIVERGED the amendment")
705
+
706
+ # The wrapper that makes a dying control speak. Asserted from the source, because a suite that
707
+ # ends in a traceback prints no control name at all and a revert trial then reads the traceback
708
+ # as the control firing (the WP-12 review).
709
+ # The WRAPPER's own source, not the file's. A scan of the whole file is satisfied by this
710
+ # control's own text — the phrase it looks for appears in the line that looks for it — which is
711
+ # how a planted mutation passed here before. The wrapper lives in `self_test` and this control
712
+ # lives in `_self_test_body`, so asking `self_test` for its source excludes the control.
713
+ wrapper_text = inspect.getsource(self_test)
714
+ control("a control that dies names itself, since a traceback is not a control firing",
715
+ next((line.strip() for line in wrapper_text.splitlines()
716
+ if "died after" in line and "print(" in line), "<no such line>"),
717
+ "self-test [FAIL] the suite died after")
718
+ control("and the wrapper is what the entry point runs, so the body cannot be called around it",
719
+ next((line.strip() for line in wrapper_text.splitlines()
720
+ if "_self_test_body(" in line), "<no such line>"),
721
+ "return _self_test_body(failures, ran)")
722
+
723
+ reporting.append(True)
724
+ if failures:
725
+ for name, detail in failures:
726
+ print(f"ranking --self-test [FAIL] {name}: {detail}", file=sys.stderr)
727
+ print(f"ranking --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
728
+ return 1
729
+ print(f"ranking --self-test: OK ({len(ran)} controls: §7.5's seven keys and the amendment's "
730
+ f"S7b key each ordering one field "
731
+ f"against the table, lineages descending, change before no-change, determinism and "
732
+ f"totality over forty rows, §9's two groups that are not named by a status, and the six "
733
+ f"statuses no group places refused by name)")
734
+ return 0
735
+
736
+
737
+ if __name__ == "__main__":
738
+ if sys.argv[1:2] == ["--self-test"]:
739
+ sys.exit(self_test())
740
+ sys.exit("usage: ranking.py --self-test")