agent-bios 0.19.3 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,1769 @@
1
+ #!/usr/bin/env python3
2
+ """The proposal contract as code over its tables (WP-12 commit 1): §7.2's allowed pairs and §7.3's
3
+ structural rules.
4
+
5
+ Two tables and no judgement. `tables/allowed_pairs.json` holds the four closed vocabularies and the
6
+ dispositions each (kind, diagnosis) pair allows; `tables/structural_rules.json` holds §7.3's rules in
7
+ the order they are applied, each with the code it refuses by and the design sentence it comes from.
8
+ This module reads them and returns problems; it decides nothing a table does not state, because the
9
+ alternative is two authorities for one contract and the plan's own main risk for this package.
10
+
11
+ What it does NOT do: the §7.4 placement rules (`tables/placement_rules.json`, the next commit), the
12
+ semantic bars (`packets/placement_contract.md`, judged by S7b), and the ranking (§7.5). Those are
13
+ separate authorities on purpose.
14
+
15
+ placement.py --self-test
16
+ """
17
+ import contextlib
18
+ import hashlib
19
+ import itertools
20
+ import json
21
+ import pathlib
22
+ import sys
23
+
24
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
25
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
26
+ from runlib import operations, targets # noqa: E402
27
+ from runlib.records import Refused # noqa: E402
28
+
29
+ HERE = pathlib.Path(__file__).resolve().parents[1]
30
+ PAIRS_PATH = HERE / "tables" / "allowed_pairs.json"
31
+ RULES_PATH = HERE / "tables" / "structural_rules.json"
32
+ PLACEMENT_PATH = HERE / "tables" / "placement_rules.json"
33
+ # The semantic bars' one canonical text. It is carried into the S7 and S7b packets with its digest,
34
+ # because a bar the packet paraphrases is a second authority and S7b would be judging that one.
35
+ CONTRACT_PATH = HERE / "packets" / "placement_contract.md"
36
+ _TABLES = {}
37
+
38
+ # A disposition that writes nothing into the library: §10.4's ledger-only set, named once.
39
+ LEDGER_ONLY = ("keep", "incubate", "drop")
40
+ # What a candidate below the promotion bar may still be proposed as (the §6.4 table's `below_bar`
41
+ # row, whose `allowed_dispositions` this list must equal — asserted in the suite rather than copied
42
+ # by hand).
43
+ BELOW_BAR = ("incubate", "keep", "drop", "none")
44
+
45
+
46
+ # ---- release 1's scope -----------------------------------------------------------------------------
47
+ #
48
+ # Release 1 changes no library file (D-20261116-7853bc). A disposition that would - any of §7.2's vocabulary outside
49
+ # the ledger-only set and `none` - and any operation are refused where an answer is accepted (S7, and S7b's
50
+ # alternative), where the final set is built (S10b) and where S11 takes its items, so nothing approved can reach a
51
+ # write. The contract as designed stays in the tables and in the code that reads them, and its controls run it
52
+ # under the scope `all`: the redesign that reopens these dispositions starts from a path its controls still hold.
53
+ # `scoped` is the scope's only writer, and the suite holds that only a self-test calls it.
54
+ RELEASE_SCOPES = ("release_1", "all")
55
+ _SCOPE = ["release_1"]
56
+ NO_CHANGE = ("none",)
57
+ # The functions a suite runs in. `scoped` refuses to run unless one of them is on the calling thread's stack, and
58
+ # placement's suite refuses a reference to it anywhere else (Codex release-1 review F4).
59
+ SELF_TEST_FUNCTIONS = ("self_test", "_self_test_all", "_self_test_body")
60
+
61
+
62
+ def self_test_on_stack(names):
63
+ """Whether a stack of function names, innermost first, runs inside a suite."""
64
+ return any(name in SELF_TEST_FUNCTIONS for name in names)
65
+
66
+
67
+ def _stack_names():
68
+ frame, names = sys._getframe(1), []
69
+ while frame is not None:
70
+ names.append(frame.f_code.co_name)
71
+ frame = frame.f_back
72
+ return names
73
+
74
+
75
+ def release_scope():
76
+ return _SCOPE[0]
77
+
78
+
79
+ @contextlib.contextmanager
80
+ def scoped(scope):
81
+ """The release scope for the code inside, for a self-test: `all` runs the contract as designed.
82
+
83
+ What holds it: no shipped code refers to it, to `_SCOPE` or to placement's dict outside a suite function (the
84
+ suite's AST walk), and it runs only with a suite function on the calling thread's stack. What does not: Python
85
+ run in the same process at will - `exec`, a thread started under a suite's name, a module that defines its own
86
+ `self_test` to call it - can change any module state, this one included. No command of the driver runs such code;
87
+ the property is release 1's commands, not an interpreter boundary (release 1's confirmation review, round 2 F4)."""
88
+ if scope not in RELEASE_SCOPES:
89
+ raise Refused(f"RELEASE_SCOPE_UNKNOWN {scope!r}: the scopes are {', '.join(RELEASE_SCOPES)}")
90
+ if not self_test_on_stack(_stack_names()):
91
+ raise Refused("RELEASE_SCOPE_OUTSIDE_SELF_TEST: the release scope is changed only inside a suite; release 1 "
92
+ "changes no library file")
93
+ held = _SCOPE[0]
94
+ _SCOPE[0] = scope
95
+ try:
96
+ yield
97
+ finally:
98
+ _SCOPE[0] = held
99
+
100
+
101
+ def library_changing():
102
+ """The dispositions that change a library file: §7.2's vocabulary less the ledger-only set and `none`, derived
103
+ so that a disposition added to the vocabulary is refused in release 1 until someone decides otherwise."""
104
+ return tuple(d for d in vocabularies()["disposition"] if d not in LEDGER_ONLY + NO_CHANGE)
105
+
106
+
107
+ def release_accepts():
108
+ """The dispositions this release accepts, in the vocabulary's order."""
109
+ changing = library_changing() if release_scope() == "release_1" else ()
110
+ return tuple(d for d in vocabularies()["disposition"] if d not in changing)
111
+
112
+
113
+ def release_problems(disposition, operations_held=(), where=""):
114
+ """Release 1's refusal of one proposal, alternative or approved item: a disposition that changes a library
115
+ file, or an operation under any disposition. Empty under the scope `all`."""
116
+ if release_scope() != "release_1":
117
+ return []
118
+ if disposition in library_changing():
119
+ return [f"RELEASE_1_NO_LIBRARY_CHANGE {where}{disposition}: release 1 changes no library file, so it "
120
+ f"accepts only {', '.join(release_accepts())}"]
121
+ if operations_held:
122
+ return [f"RELEASE_1_NO_LIBRARY_CHANGE {where}{len(operations_held)} operation(s) under {disposition!r}: "
123
+ f"release 1 changes no library file"]
124
+ return []
125
+
126
+
127
+ def release_packet_text(role="propose"):
128
+ """What a proposer (`propose`) or a reviewer of proposals (`review`) is told of the release scope: empty under
129
+ `all`."""
130
+ if release_scope() != "release_1":
131
+ return ""
132
+ head = ("## This release changes no library file\n\n"
133
+ f"Code refuses the dispositions {', '.join(library_changing())} and any operation in this release "
134
+ f"(`RELEASE_1_NO_LIBRARY_CHANGE`), whatever the contract above would allow. ")
135
+ if role == "review":
136
+ return head + (f"An alternative you name is held to the same refusal: choose it among "
137
+ f"{', '.join(release_accepts())}, as the contract's row for the pair allows them. A "
138
+ "`drop` alternative carries its reason into the ledger; a `keep` alternative names no units to keep "
139
+ "and an `incubate` alternative carries no observation, so a person who adopts either sends the "
140
+ "item back for a complete proposal. Where you "
141
+ "judge that a change to a library file is what the evidence supports, say so in your reason; "
142
+ "it is shown to the person, and a later release can carry it out.\n")
143
+ return head + (f"Choose among {', '.join(release_accepts())}, as the contract's row for this pair allows them and "
144
+ "with what each requires, and carry no operations. Where the evidence supports a change to a "
145
+ "library file, choose `incubate` if the row allows it (with its observation and expiry) and "
146
+ "otherwise `none` or `drop` with its reason, and name the change the evidence supports in the "
147
+ "Korean `proposal` reason, so the person sees it and a later release can carry it out.\n")
148
+
149
+
150
+ def table(which):
151
+ """One of the two tables, read once per process. A control may seed `_TABLES` with a scratch copy."""
152
+ if which not in _TABLES:
153
+ path = {"pairs": PAIRS_PATH, "rules": RULES_PATH, "placement": PLACEMENT_PATH}[which]
154
+ try:
155
+ _TABLES[which] = json.loads(path.read_text(encoding="utf-8"))
156
+ except (OSError, ValueError) as exc:
157
+ raise Refused(f"TABLE_UNREADABLE {path.name}: {exc}") from exc
158
+ return _TABLES[which]
159
+
160
+
161
+ def vocabularies():
162
+ return table("pairs")["vocabularies"]
163
+
164
+
165
+ def matches(row, kind, diagnosis, legacy_incubating=False):
166
+ """Whether one row of the pairs table answers for this (kind, diagnosis).
167
+
168
+ `any` is a wildcard in either column, and the legacy row answers ONLY for a legacy incubating
169
+ entry — it holds for every kind including unclassified, so without that flag it would swallow
170
+ every other row's pair and make the table unreadable."""
171
+ if bool(row.get("legacy_incubating")) != bool(legacy_incubating):
172
+ return False
173
+ return ((row["kind"] == "any" or row["kind"] == kind)
174
+ and (row["diagnosis"] == "any" or row["diagnosis"] == diagnosis))
175
+
176
+
177
+ def rows_for(kind, diagnosis, legacy_incubating=False):
178
+ return [row for row in table("pairs")["rows"] if matches(row, kind, diagnosis, legacy_incubating)]
179
+
180
+
181
+ def allowed_for(kind, diagnosis, legacy_incubating=False):
182
+ """`{disposition: the condition it requires, or None}` over every row that answers.
183
+
184
+ Several rows can answer one pair — `redundant` holds for any kind — and the union is what §7.2
185
+ means by "allowed": a disposition any answering row allows is allowed. Where two rows allow the
186
+ same disposition, the one with no condition wins, because a row that allows it outright is the
187
+ weaker bar and the table would otherwise read as forbidding what it allows."""
188
+ out = {}
189
+ for row in rows_for(kind, diagnosis, legacy_incubating):
190
+ for entry in row["allowed"]:
191
+ name, condition = entry["disposition"], entry.get("requires")
192
+ if name not in out or out[name] is not None:
193
+ out[name] = condition
194
+ return out
195
+
196
+
197
+ def unknown_values(proposal):
198
+ """The proposal's fields that are outside §7.2's closed vocabularies, by field name."""
199
+ held = vocabularies()
200
+ problems = []
201
+ for field, vocabulary in (("kind", "kind"), ("diagnosis", "diagnosis"), ("disposition", "disposition")):
202
+ value = proposal.get(field)
203
+ if value not in held[vocabulary]:
204
+ problems.append(f"VALUE_UNKNOWN {field} {value!r}: §7.2's vocabulary is "
205
+ f"{', '.join(held[vocabulary])}")
206
+ return problems
207
+
208
+
209
+ # ---- the conditions §7.2's rows name -------------------------------------------------------------
210
+ #
211
+ # One reader per condition, each asking the proposal and nothing else. A condition whose reader is
212
+ # missing is a refusal rather than a pass: a row that names a condition nobody checks allows the
213
+ # disposition unconditionally, which is the quiet failure this table exists to prevent.
214
+
215
+ def _reason(proposal):
216
+ reason = proposal.get("reason")
217
+ return isinstance(reason, str) and reason.strip() != ""
218
+
219
+
220
+ def _operations(proposal, types=None):
221
+ rows = [op for op in proposal.get("operations") or [] if isinstance(op, dict)]
222
+ return [op for op in rows if types is None or op.get("type") in types]
223
+
224
+
225
+ CONDITIONS = {
226
+ "drop_reason_acceptable_miss": _reason,
227
+ "reduce_when_harmful": lambda p: p.get("harmful") is True,
228
+ "reduce_by_merge": lambda p: bool(_operations(p, {"merge"})),
229
+ "keep_with_reason": _reason,
230
+ "incubate_owner_approved": lambda p: bool((p.get("expected_observation") or {}).get("expiry"))
231
+ and bool(p.get("expected_observation")),
232
+ "drop_retire_with_reason": _reason,
233
+ "none_stays_in_intake": lambda p: not _operations(p),
234
+ "place_admitted_and_eligible": lambda p: p.get("admitted") is True and p.get("promotion_eligible") is True,
235
+ }
236
+
237
+
238
+ def condition_problems():
239
+ """A condition the pairs table names and this module cannot check, or the reverse."""
240
+ named = set(table("pairs")["conditions"]) - {"$comment"}
241
+ held = set(CONDITIONS)
242
+ return ([f"CONDITION_UNCHECKED {name}: the pairs table names it and no reader asks it"
243
+ for name in sorted(named - held)]
244
+ + [f"CONDITION_UNNAMED {name}: a reader for a condition no row names"
245
+ for name in sorted(held - named)])
246
+
247
+
248
+ def pair_problems(proposal):
249
+ """§7.2 for one proposal: the pair, and the condition the allowing row names."""
250
+ problems = unknown_values(proposal)
251
+ if problems:
252
+ return problems
253
+ kind, diagnosis = proposal["kind"], proposal["diagnosis"]
254
+ legacy = bool(proposal.get("legacy_incubating"))
255
+ allowed = allowed_for(kind, diagnosis, legacy)
256
+ disposition = proposal["disposition"]
257
+ if disposition not in allowed:
258
+ return [f"PAIR_DISALLOWED {kind} / {diagnosis} / {disposition}: §7.2 allows "
259
+ f"{', '.join(sorted(allowed)) or 'nothing'}"
260
+ + (" under the legacy-maintenance row" if legacy else "")]
261
+ condition = allowed[disposition]
262
+ if condition is not None and not CONDITIONS[condition](proposal):
263
+ return [f"PAIR_DISALLOWED {kind} / {diagnosis} / {disposition}: §7.2 allows it only where "
264
+ f"{table('pairs')['conditions'][condition]}"]
265
+ return []
266
+
267
+
268
+ # ---- §7.3's structural rules ---------------------------------------------------------------------
269
+
270
+ def global_files():
271
+ return tuple(table("rules")["operations"].get("global_files") or ())
272
+
273
+
274
+ def _global_ops(proposal):
275
+ """The operations that touch the always-loaded global file, by IDENTITY and not by spelling.
276
+
277
+ Literal membership read `./claude/CLAUDE.md` as a different file from `claude/CLAUDE.md`, so an
278
+ edit on the global file passed the rule that allows only deletion and merge there (the WP-12
279
+ review). `targets.identity` is the one owner of "which file is this", so the question is asked
280
+ of it rather than answered again here.
281
+ """
282
+ return [op for op in _operations(proposal) if is_global(op.get("target"))]
283
+
284
+
285
+ def is_global(name):
286
+ """Whether a target or a carrier names the always-loaded global file: by the identity of the FILE it names, so
287
+ a section of it (`claude/CLAUDE.md#Heading`) is the file too (Codex WP-12 r2 F7: naming a heading passed both
288
+ global rules, which compared the whole string)."""
289
+ held = {targets.identity(g) or g for g in global_files()}
290
+ if not isinstance(name, str) or not name:
291
+ return False
292
+ return (targets.identity(targets.file_of(name)) or targets.file_of(name)) in held
293
+
294
+
295
+ def _library_ops(proposal):
296
+ return _operations(proposal, set(table("rules")["operations"]["library"]))
297
+
298
+
299
+ def touches(proposal, path):
300
+ """Whether one of the proposal's operations may reach a unit that lives in the file at `path`: an operation's
301
+ target, or a merge's unit, names that file, whatever section it names. The file is read as S11 reads it
302
+ (`operations.split_target`), so a spelling S11 resolves to the same file is the same file.
303
+
304
+ The FILE, not the section (Codex WP-12 r3 F1). The inventory's `heading` is the chain of titles open above a
305
+ unit, and that is not a lossless picture of the sections S11 resolves: a title holding ` > ` splits into two, a
306
+ title that begins with marks loses them, and an indented or tab-separated heading the inventory leaves unnamed is
307
+ a section S11 still finds and deletes. No comparison of those strings can show that a section operation misses a
308
+ kept unit, so a guard that must err towards refusing treats every operation on the unit's file as reaching it.
309
+ A keep a proposal reaches only by this rule is released by the owner's `keep 해제`, or named by the proposal.
310
+ A unit with no known place is reached by every operation (`keep_places`)."""
311
+ if not path:
312
+ return True
313
+ own = operations.split_target(path)[0]
314
+ for op in _operations(proposal):
315
+ names = [op.get("target")] + [u for u in (op.get("units") if isinstance(op.get("units"), list) else [])]
316
+ for name in names:
317
+ if isinstance(name, str) and name and operations.split_target(name)[0] == own:
318
+ return True
319
+ return False
320
+
321
+
322
+ def keep_places(held):
323
+ """The places a keep record's unit lives in, or None for a bare record id (guarded whatever is touched). A unit
324
+ id the inventory gives more than once is every one of its places (Codex WP-12 r3 F2: a map by id kept the last),
325
+ and an empty list is a unit the inventory does not place, which every touching operation reaches."""
326
+ if not isinstance(held, dict):
327
+ return None
328
+ if "places" in held:
329
+ return [p for p in held.get("places") or [] if isinstance(p, dict)]
330
+ return [{"path": held.get("path"), "heading": held.get("heading")}]
331
+
332
+
333
+ def keep_reached(proposal, held):
334
+ """Whether the proposal's operations reach the unit a keep record stands over: a bare id and a unit with no place
335
+ are reached by any touching proposal; otherwise any of its places in the file an operation names."""
336
+ places = keep_places(held)
337
+ return places is None or not places or any(touches(proposal, place.get("path")) for place in places)
338
+
339
+
340
+ def structural_problems(proposal, active_keep=None):
341
+ """§7.3's rules in the table's order, each refused by the table's own code.
342
+
343
+ `active_keep` maps a unit id to the keep record standing over it (§10.1): `{record, path, heading}`, the unit's
344
+ place in the current inventory, so the rule guards only the units the proposal's operations reach (Codex WP-12
345
+ r2 F5: every keep in the ledger was guarded, whatever was merged). A bare record id says nothing of where its unit
346
+ lives and is guarded whatever the proposal touches. It is the caller's to supply from the ledger, because this
347
+ module reads no ledger: a module that read one would answer about whatever file it found.
348
+ """
349
+ active_keep = dict(active_keep or {})
350
+ problems = []
351
+ for rule in table("rules")["rules"]:
352
+ code, rid = rule["code"], rule["id"]
353
+ if rid == "global_op":
354
+ allowed = set(table("rules")["operations"]["global_allowed"])
355
+ for op in _global_ops(proposal):
356
+ if op.get("type") not in allowed:
357
+ problems.append(f"{code} {op.get('type')} on {op.get('target')}: §7.3 allows only "
358
+ f"{', '.join(sorted(allowed))} on the always-loaded global file")
359
+ elif rid == "incubate_expiry":
360
+ if proposal.get("disposition") == "incubate" and not CONDITIONS["incubate_owner_approved"](proposal):
361
+ problems.append(f"{code} {proposal.get('item_id')}: an incubate carries an expected "
362
+ f"observation and an expiry")
363
+ elif rid == "keep_reason":
364
+ if proposal.get("disposition") in ("keep", "drop") and not _reason(proposal):
365
+ problems.append(f"{code} {proposal.get('disposition')} {proposal.get('item_id')}: "
366
+ f"§7.3 refuses a keep or a drop with no reason")
367
+ elif rid == "pair":
368
+ problems += pair_problems(proposal)
369
+ elif rid == "promotion":
370
+ if proposal.get("promotion_eligible") is False and proposal.get("disposition") not in BELOW_BAR:
371
+ problems.append(f"{code} {proposal.get('disposition')} {proposal.get('item_id')}: a candidate "
372
+ f"below the promotion bar may be proposed only as "
373
+ f"{', '.join(BELOW_BAR)}")
374
+ elif rid == "keep_record":
375
+ touching = (["reduce"] if proposal.get("disposition") == "reduce" else []) + \
376
+ [op.get("type") for op in _operations(proposal, {"merge"})]
377
+ if touching:
378
+ named = set(proposal.get("keep_records_named") or ())
379
+ guarded = sorted({unit: (held["record"] if isinstance(held, dict) else held)
380
+ for unit, held in active_keep.items()
381
+ if (held["record"] if isinstance(held, dict) else held) not in named
382
+ and keep_reached(proposal, held)}.items())
383
+ problems += [f"{code} {unit}: an active keep record ({record}) stands over it, and the "
384
+ f"proposal does not name it; the owner's `keep 해제` comes first"
385
+ for unit, record in guarded]
386
+ elif rid == "ledger_only":
387
+ if proposal.get("disposition") in LEDGER_ONLY:
388
+ if _library_ops(proposal):
389
+ problems.append(f"{code} {proposal.get('disposition')} {proposal.get('item_id')}: a "
390
+ f"ledger-only disposition carries no library operation, and this one "
391
+ f"carries {len(_library_ops(proposal))}")
392
+ if proposal.get("requires_test") is not False:
393
+ problems.append(f"{code} {proposal.get('disposition')} {proposal.get('item_id')}: a "
394
+ f"ledger-only disposition sets requires_test false, not "
395
+ f"{proposal.get('requires_test')!r}")
396
+ else:
397
+ problems.append(f"RULE_UNIMPLEMENTED {rid}: the table names a rule this module does not apply")
398
+ return problems
399
+
400
+
401
+ # ---- §7.4's decidable restrictions ---------------------------------------------------------------
402
+
403
+ def contract_text():
404
+ """The semantic bars' canonical text, read from the packet."""
405
+ try:
406
+ return CONTRACT_PATH.read_text(encoding="utf-8")
407
+ except OSError as exc:
408
+ raise Refused(f"CONTRACT_UNREADABLE {CONTRACT_PATH.name}: {exc}") from exc
409
+
410
+
411
+ def contract_digest():
412
+ """The sha256 of that text. The packet carries it so a reader can bind the bars it was judged by."""
413
+ return hashlib.sha256(contract_text().encode("utf-8")).hexdigest()
414
+
415
+
416
+ def contract_bars():
417
+ """The bars the canonical text states, by their heading lines in `## The bars` and `## Type G`.
418
+
419
+ Read out of the text rather than listed here: the text is the authority, and a list beside it
420
+ would be the second one this contract exists to avoid. A bar is a bolded lead-in of a paragraph
421
+ under those sections, which is the shape the text is written in."""
422
+ bars, section = [], None
423
+ for line in contract_text().splitlines():
424
+ if line.startswith("## "):
425
+ section = line[3:].strip()
426
+ continue
427
+ if section and section.startswith(("The bars", "Type G")) and line.startswith("**"):
428
+ bars.append(line[2:].split("**", 1)[0].strip().rstrip("."))
429
+ return tuple(bars)
430
+
431
+
432
+ # A bar whose text names a COUNT of conditions must enumerate that many. `The enforcement bar` once
433
+ # said only "All four of its conditions hold" with the four nowhere in the table or either packet, so
434
+ # a proposal was reviewed against a bar nobody could read while the contract check, which asked only
435
+ # for the heading, passed (the WP-12 review). `contract_problems` now refuses that shape by name.
436
+ _COUNT_WORDS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6}
437
+
438
+
439
+ def bar_condition_problems(text=None):
440
+ """Each bar that names a count of conditions without enumerating them, by name.
441
+
442
+ An enumeration is a numbered or bulleted list, or sentences separated by semicolons, inside the
443
+ bar's own paragraph — anything a reader can count. The check is deliberately generous about the
444
+ shape and strict about the count.
445
+ """
446
+ problems, section, held, heading = [], None, [], None
447
+
448
+ def close():
449
+ if heading is None:
450
+ return
451
+ text = " ".join(held)
452
+ for word, wanted in _COUNT_WORDS.items():
453
+ if f"{word} of its conditions" not in text and f"{word} conditions" not in text:
454
+ continue
455
+ counted = max(text.count(";") + 1 if ";" in text else 0,
456
+ sum(1 for piece in held if piece.strip().startswith(("-", "*"))),
457
+ sum(1 for n in range(1, wanted + 1) if f"{n}." in text or f"({n})" in text))
458
+ if counted < wanted:
459
+ problems.append(f"BAR_CONDITIONS_UNSTATED {heading}: the text says {word} "
460
+ f"condition(s) and enumerates {counted}, so a proposal is reviewed "
461
+ f"against a bar nobody can read")
462
+
463
+ for line in (contract_text() if text is None else text).splitlines():
464
+ if line.startswith("## "):
465
+ close()
466
+ heading, held = None, []
467
+ section = line[3:].strip()
468
+ continue
469
+ if not (section and section.startswith(("The bars", "Type G"))):
470
+ continue
471
+ if line.startswith("**"):
472
+ close()
473
+ heading = line[2:].split("**", 1)[0].strip().rstrip(".")
474
+ held = [line]
475
+ elif heading is not None:
476
+ held.append(line)
477
+ close()
478
+ return problems
479
+
480
+
481
+ def _layer(proposal):
482
+ return (proposal.get("destination") or {}).get("layer")
483
+
484
+
485
+ def _carrier(proposal):
486
+ return (proposal.get("destination") or {}).get("carrier")
487
+
488
+
489
+ # When each §7.4 rule applies: one reader per declared scope, named by the table. A scope the table
490
+ # names and this module does not is refused (SCOPE_UNCHECKED), in both directions, like CONDITIONS.
491
+ SCOPES = {
492
+ "always": lambda p: True,
493
+ "placing_a_guide": lambda p: _layer(p) == "guides" and p.get("disposition") == "place",
494
+ "carries_an_instruction": lambda p: bool(_operations(p)),
495
+ "placing_a_gate": lambda p: _layer(p) == "gates",
496
+ "placing_a_hook": lambda p: _layer(p) == "hooks",
497
+ "a_c_principle": lambda p: bool(_operations(p)),
498
+ }
499
+
500
+
501
+ def scope_problems():
502
+ """Scopes the table names with no reader here, and readers the table never names. Both directions."""
503
+ named = {rule.get("scope") for rule in table("placement")["rules"]}
504
+ problems = [f"SCOPE_UNCHECKED {name!r}: the placement table names this scope and no reader here "
505
+ f"decides it" for name in sorted(named - set(SCOPES)) if name]
506
+ problems += [f"SCOPE_UNNAMED {name!r}: this module reads a scope the placement table does not name"
507
+ for name in sorted(set(SCOPES) - named)]
508
+ return problems
509
+
510
+
511
+ def _holds_when(proposal, cond):
512
+ """Whether a `requires_when` condition holds: `layer` is the destination's layer, any other key the proposal's
513
+ own field, each equal to the value named."""
514
+ return all((_layer(proposal) if key == "layer" else proposal.get(key)) == value
515
+ for key, value in cond.items() if key != "fields")
516
+
517
+
518
+ def input_problems(proposal):
519
+ """Inputs a rule needs, for every rule whose scope this proposal is in, missing by name.
520
+
521
+ This is the guard against a rule that passes over a field nobody filled. It was not hypothetical:
522
+ the flat proposal S7 handed this module carried none of §7.4's inputs, so five of the six rules
523
+ read None and found nothing, while their own controls - built from hand-written dicts - passed."""
524
+ problems = []
525
+ for rule in table("placement")["rules"]:
526
+ scope = rule.get("scope")
527
+ if scope not in SCOPES:
528
+ problems.append(f"SCOPE_UNCHECKED {scope!r} for {rule['id']}: no reader decides it")
529
+ continue
530
+ if not SCOPES[scope](proposal):
531
+ continue
532
+ wanted = list(rule.get("requires") or [])
533
+ wanted += [f for cond in rule.get("requires_when") or [] if _holds_when(proposal, cond)
534
+ for f in cond.get("fields") or []]
535
+ for field in wanted:
536
+ if proposal.get(field) is None:
537
+ problems.append(f"PLACEMENT_INPUT_ABSENT {rule['code']} {proposal.get('item_id')}."
538
+ f"{field}: this proposal is in the rule's scope ({scope}) and carries "
539
+ f"no {field}, so the rule would pass over a field nobody filled")
540
+ return problems
541
+
542
+
543
+ def placement_problems(proposal):
544
+ """§7.4's decidable rules, from `tables/placement_rules.json`, in its order.
545
+
546
+ Every rule here is decidable from the proposal's own fields. The section's judgements —
547
+ leftward reformulation, retirement reasons, facts kept verbatim — are not decided here at all:
548
+ they are in the canonical text and are S7b's to judge, which is why this function never reads
549
+ that text."""
550
+ held = table("placement")
551
+ problems = []
552
+ for rule in held["rules"]:
553
+ code, rid = rule["code"], rule["id"]
554
+ if rid == "guide_premature":
555
+ if _layer(proposal) == "guides" and proposal.get("disposition") == "place":
556
+ sharing = proposal.get("situation_promoted_items")
557
+ covered = proposal.get("situation_covered_by_guide")
558
+ if covered is False and (not isinstance(sharing, int) or sharing < rule["threshold"]):
559
+ problems.append(f"{code} {proposal.get('item_id')}: §7.4 asks for at least "
560
+ f"{rule['threshold']} promoted items sharing a situation no guide "
561
+ f"covers, and this one has {sharing!r}")
562
+ elif rid == "consumer_mismatch":
563
+ reads = held["consumers"]["reads"].get(proposal.get("consumer"))
564
+ if reads is None and proposal.get("consumer") is not None and SCOPES[rule["scope"]](proposal):
565
+ # a consumer the table does not name is not one this rule can judge, so it is refused rather than
566
+ # passed (Codex WP-12 r2 F6: an invented consumer made the lookup None and the rule skipped)
567
+ problems.append(f"{code} {proposal.get('item_id')}: the consumer {proposal.get('consumer')!r} is not "
568
+ f"one the table names ({', '.join(sorted(held['consumers']['reads']))})")
569
+ if reads is not None and proposal.get("artifact_form") == "instruction" and "instruction" not in reads:
570
+ problems.append(f"{code} {proposal.get('item_id')}: an instruction cannot reach a "
571
+ f"{proposal.get('consumer')}, which reads {', '.join(reads)}")
572
+ elif rid == "gate_on_judgment":
573
+ if _layer(proposal) == "gates" and proposal.get("blocking") is True \
574
+ and proposal.get("criterion") == "semantic":
575
+ problems.append(f"{code} {proposal.get('item_id')}: a semantic check discloses and never "
576
+ f"blocks, so a blocking gate is not its destination")
577
+ elif rid == "global_addition":
578
+ if is_global(_carrier(proposal)) and proposal.get("disposition") in ("place", "correct", "re-deliver"):
579
+ problems.append(f"{code} {proposal.get('item_id')}: the always-loaded global file receives "
580
+ f"deletions and merges only, so it is no home for a new learning")
581
+ elif rid == "c_route":
582
+ # the rule's declared scope decides whether it applies, as `input_problems` reads it: a C
583
+ # principle that carries no operation is routed nowhere, so there is no route to judge
584
+ if proposal.get("typology") == "C" and SCOPES[rule["scope"]](proposal):
585
+ layer = _layer(proposal)
586
+ if layer not in rule["allowed_layers"]:
587
+ problems.append(f"{code} {proposal.get('item_id')}: a recognition principle goes to the "
588
+ f"router trigger of the guide whose situation it names, or to "
589
+ f"session-level injection, not to {layer!r}")
590
+ elif layer == "guides" and proposal.get("names_situation_of_guide") is not True:
591
+ problems.append(f"{code} {proposal.get('item_id')}: a recognition principle placed in a "
592
+ f"guide goes to the router trigger of the guide whose situation it "
593
+ f"names, and this one names none")
594
+ elif layer == "session_injection" and proposal.get("owner_only") is not True:
595
+ problems.append(f"{code} {proposal.get('item_id')}: session-level injection is for a "
596
+ f"principle that concerns only the owner")
597
+ elif rid == "hook_charter":
598
+ if _layer(proposal) == "hooks" and (proposal.get("blocking") is True or proposal.get("judges") is True):
599
+ problems.append(f"{code} {proposal.get('item_id')}: a hook does pattern-matched injection of "
600
+ f"canonical text; it does not block and it does not judge")
601
+ else:
602
+ problems.append(f"RULE_UNIMPLEMENTED {rid}: the placement table names a rule this module "
603
+ f"does not apply")
604
+ return problems
605
+
606
+
607
+ # A destination is model output that reaches the owner's review page, so it is held to the layer
608
+ # vocabulary and to path rules at the SOURCE as well as escaped on render. A carrier carrying a
609
+ # newline followed by a decision-shaped line could otherwise forge an owner's line in the rendered
610
+ # review; a `..` segment or an absolute path names a file outside anything the run declared.
611
+ #
612
+ # One function for both callers: S7's own destination and S7b's alternative destination. The
613
+ # alternative IS a proposal - it is what the owner may take instead - so it is held to the same rules,
614
+ # and a second copy of them would be a second authority.
615
+ CARRIER_RULES = (
616
+ ("DESTINATION_CARRIER_CONTROL", "a control character (a newline, tab or other C0/C1 code), which "
617
+ "could forge a line in the rendered review"),
618
+ ("DESTINATION_CARRIER_TRAVERSAL", "a `..` segment, which names a path outside the tree it starts in"),
619
+ ("DESTINATION_CARRIER_ABSOLUTE", "an absolute path, which names a file outside anything the run declared"),
620
+ )
621
+
622
+
623
+ def _carrier_problem(carrier):
624
+ """Which carrier rule a carrier breaks, by code, or None.
625
+
626
+ The control character is this module's own rule, because it is about the RENDERED review a
627
+ carrier reaches, not about a path's identity. Everything else about the spelling — absolute,
628
+ traversal, non-canonical, `./x` and `a//b` — is `runlib/targets`', and is asked of it rather
629
+ than implemented again: this function used to accept `./claude/CLAUDE.md` and
630
+ `claude//CLAUDE.md`, which the identity contract refuses, so one spelling was approved here and
631
+ refused there (the round-3 review).
632
+ """
633
+ if any(ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F for ch in carrier):
634
+ return CARRIER_RULES[0]
635
+ for held in targets.lexical_problems(carrier):
636
+ code = held.split(" ", 1)[0]
637
+ if code == "TARGET_ABSENT":
638
+ continue # an empty carrier is the shape rule's, not the path's
639
+ return (f"DESTINATION_CARRIER_{code[len('TARGET_'):]}", held.partition(": ")[2])
640
+ return None
641
+
642
+
643
+ # The operation types whose text has to END UP in a named file. A delete removes and a merge is
644
+ # executed as deletes plus one edit into a target the operation itself names, so neither needs the
645
+ # destination to say where the item lands.
646
+ CARRIER_REQUIRING_TYPES = ("create", "edit")
647
+
648
+
649
+ def carrier_problems(proposal):
650
+ """A proposal that CHANGES the library must name the file that carries the change.
651
+
652
+ `carrier` is nullable on purpose — a disposition with no operation carries nothing — but a
653
+ proposal with library operations and no carrier names no file at all, and the review found it
654
+ accepted (the WP-12 review). The rule is the pairing, not the field.
655
+ """
656
+ writing = _operations(proposal, CARRIER_REQUIRING_TYPES)
657
+ if not writing:
658
+ # A removal names its own target and adds no text, so nothing has to say where the item
659
+ # lands; `merge` is executed as deletes plus one edit into a target the operation already
660
+ # names. The rule is about text that must END UP somewhere.
661
+ return []
662
+ held = (proposal.get("destination") or {}).get("carrier")
663
+ if held:
664
+ return []
665
+ return [f"CARRIER_ABSENT destination.carrier: the proposal writes "
666
+ f"{len(writing)} operation(s) of type "
667
+ f"{', '.join(sorted({str(op.get('type')) for op in writing}))} and names no carrier, so "
668
+ f"nothing says which file would hold the text"]
669
+
670
+
671
+ def destination_problems(destination, where="destination", item=""):
672
+ """A destination's problems, by name: its layer against §7.4's order, its carrier against the rules.
673
+
674
+ `where` names the field so one message serves both the proposal's destination and the
675
+ alternative's, and the reader can tell which one it was.
676
+ """
677
+ problems = []
678
+ if destination is None:
679
+ return problems
680
+ if not isinstance(destination, dict):
681
+ return [f"DESTINATION_SHAPE {where}: not an object"]
682
+ held = table("placement")["destinations"]
683
+ layers = tuple(held["order"])
684
+ layer = destination.get("layer")
685
+ if layer not in layers:
686
+ problems.append(f"LAYER_UNKNOWN {item}{where}.layer={layer!r}: §7.4's destinations are "
687
+ f"{', '.join(layers)}")
688
+ carrier = destination.get("carrier")
689
+ if isinstance(carrier, str):
690
+ broken = _carrier_problem(carrier)
691
+ if broken:
692
+ code, why = broken
693
+ problems.append(f"{code} {item}{where}.carrier={carrier!r}: {why}")
694
+ elif carrier is not None:
695
+ problems.append(f"DESTINATION_CARRIER_SHAPE {item}{where}.carrier: not a string or null")
696
+ return problems
697
+
698
+
699
+ def fx_proposal(kind, diagnosis, disposition, promotion_eligible=True, legacy=False):
700
+ """A minimally complete proposal of one (kind, diagnosis, disposition), for the enumeration.
701
+
702
+ Built here rather than in the suite because `combination_problems` is the library's own answer to
703
+ "can this candidate be answered at all", and a caller asking that question must not have to
704
+ reconstruct a valid proposal to ask it.
705
+ """
706
+ ledger = disposition in LEDGER_ONLY + ("none",)
707
+ return {"item_id": "enum", "candidate_id": "enum", "kind": kind, "diagnosis": diagnosis,
708
+ "disposition": disposition, "consequence": "cost", "consumer": "session", "typology": "D",
709
+ "admitted": True, "promotion_eligible": promotion_eligible, "legacy_incubating": legacy,
710
+ "names_situation_of_guide": False, "situation_covered_by_guide": False,
711
+ "situation_promoted_items": 0, "blocking": False, "owner_only": False,
712
+ "requires_test": not ledger, "artifact_set": ["x"], "artifact_form": "guide",
713
+ "behavior_contract": "c", "criterion": "c", "keep_records_named": [], "reason": "이유",
714
+ "operations": [] if ledger else [{"type": "create", "target": "claude/guides/g.md"}],
715
+ "destination": ({"layer": "incubator", "carrier": None} if ledger
716
+ else {"layer": "guides", "carrier": "claude/guides/g.md"}),
717
+ "expected_observation": ({"occasion": "o", "exposure_rule": "e",
718
+ "expected_behavior": "b", "retrieval_terms": ["t"],
719
+ "expiry": "2026-12-01"} if disposition == "incubate" else None)}
720
+
721
+
722
+ def acceptable_dispositions(kind, diagnosis, promotion_eligible=True, legacy=False):
723
+ """Every disposition the WHOLE contract accepts for this combination, not just §7.2's table.
724
+
725
+ §7.2 says which dispositions the pair allows; §7.3's structural rules and §6.4's promotion row
726
+ then refuse some of those. The question a candidate's existence poses is the intersection, and
727
+ only the intersection.
728
+ """
729
+ held = []
730
+ for disposition in table("pairs")["vocabularies"]["disposition"]:
731
+ if not problems(fx_proposal(kind, diagnosis, disposition, promotion_eligible, legacy)):
732
+ held.append(disposition)
733
+ return tuple(held)
734
+
735
+
736
+ # The refusals that depend on NOTHING but (kind, diagnosis, disposition, bar): §7.2's pair table and
737
+ # §6.4's promotion row, which share one code. A combination refused only by these cannot be answered
738
+ # whatever the rest of the proposal says; one refused by a structural rule might be answerable with
739
+ # other field values, and reporting that as a contract defect would be a false alarm off a fixture.
740
+ FIELD_INDEPENDENT = ("PAIR_DISALLOWED",)
741
+
742
+
743
+ def _refusal_codes(kind, diagnosis, promotion_eligible, legacy):
744
+ """The refusal codes of the dispositions §7.2 ALLOWS for this pair.
745
+
746
+ Only those are candidates for an answer, so only their refusals decide whether the emptiness is
747
+ the contract's. Collecting across every disposition instead swept in a `place` attempt's
748
+ GUIDE_PREMATURE and made every emptiness look field-dependent — a check that cannot fire.
749
+ """
750
+ codes = set()
751
+ for disposition in sorted(allowed_for(kind, diagnosis, legacy)):
752
+ for problem in problems(fx_proposal(kind, diagnosis, disposition, promotion_eligible, legacy)):
753
+ codes.add(problem.split()[0])
754
+ return codes
755
+
756
+
757
+ def combination_problems():
758
+ """Every (kind, diagnosis, bar) S6 can produce that the contract cannot answer at all, by name.
759
+
760
+ A candidate with no acceptable disposition is a contract defect whatever else is true: the stage
761
+ has to answer for it and every answer is refused. The combinations known open are declared in
762
+ `tables/allowed_pairs.json` `pending_empty` with their reason; this reports an UNDECLARED empty
763
+ one, and also a declared one that is no longer empty — a declaration that has stopped being true
764
+ is a stale declaration, the bar this repository applies to every other allowlist.
765
+ """
766
+ pairs = table("pairs")
767
+ declared = {(row["kind"], row["diagnosis"], row["promotion_eligible"])
768
+ for row in (pairs.get("pending_empty") or {}).get("combinations") or ()}
769
+ problems, found = [], set()
770
+ for kind in pairs["vocabularies"]["kind"]:
771
+ for diagnosis in pairs["vocabularies"]["diagnosis"]:
772
+ if not allowed_for(kind, diagnosis, False):
773
+ continue # §7.2 allows nothing: not a combination S6 produces
774
+ for bar in (True, False):
775
+ if acceptable_dispositions(kind, diagnosis, bar):
776
+ continue
777
+ codes = _refusal_codes(kind, diagnosis, bar, False)
778
+ if not codes <= set(FIELD_INDEPENDENT):
779
+ # Refused by a rule that reads other fields: this enumeration's proposal fixes
780
+ # them, so the emptiness may be the fixture's and not the contract's. Disclosed
781
+ # in the document rather than failed here.
782
+ continue
783
+ found.add((kind, diagnosis, bar))
784
+ if (kind, diagnosis, bar) not in declared:
785
+ problems.append(f"COMBINATION_UNANSWERABLE {kind}/{diagnosis}/"
786
+ f"{'above' if bar else 'below'} bar: §7.2 allows "
787
+ f"{', '.join(sorted(allowed_for(kind, diagnosis, False)))} and "
788
+ f"every one of those is refused by {', '.join(sorted(codes))} "
789
+ f"alone, which reads no other field, so this candidate has no "
790
+ f"answer whatever else it carries")
791
+ for row in sorted(declared - found):
792
+ problems.append(f"PENDING_EMPTY_STALE {row[0]}/{row[1]}/{'above' if row[2] else 'below'} "
793
+ f"bar: declared as having no acceptable disposition and it now has one, so "
794
+ f"the declaration is stale")
795
+ return problems
796
+
797
+
798
+ def problems(proposal, active_keep=None):
799
+ """Every problem of one proposal: §7.2's, §7.3's and §7.4's decidable rules, in the tables' order.
800
+
801
+ The inputs §7.4's rules need come first: a rule that cannot see its own field has not judged, and
802
+ reporting the rules' silence as agreement is what this ordering refuses."""
803
+ return (pair_problems(proposal) + structural_problems(proposal, active_keep)
804
+ + destination_problems(proposal.get("destination"),
805
+ item=f"{proposal.get('item_id') or proposal.get('candidate_id')}: ")
806
+ + carrier_problems(proposal)
807
+ + input_problems(proposal) + placement_problems(proposal))
808
+
809
+
810
+ # ---- the tables against the design ---------------------------------------------------------------
811
+ #
812
+ # §7.2's table, copied from `design/session-distill/2026-10-20T1942--9684f05--mechanism-design.md`
813
+ # (### 7.2 Fields) and cited here, as (kind, diagnosis, the allowed dispositions in the design's
814
+ # order). The design writes the conditions in prose inside the cells; they are rendered here as the
815
+ # table's own condition ids so one comparison covers both.
816
+ DESIGN_7_2 = (
817
+ ("gap", "any", "place, incubate, drop"),
818
+ ("misfire", "trigger problem", "re-deliver, correct, incubate, drop (drop_reason_acceptable_miss)"),
819
+ ("misfire", "wrong or insufficient", "correct, incubate, drop (drop_reason_acceptable_miss)"),
820
+ ("misfire", "covered", "correct, re-deliver, reduce (reduce_when_harmful), incubate, "
821
+ "drop (drop_reason_acceptable_miss)"),
822
+ ("not delivered", "any", "re-deliver, incubate, drop"),
823
+ ("confirmed", "any", "keep, none"),
824
+ ("any", "redundant", "reduce (reduce_by_merge), keep (keep_with_reason), none"),
825
+ ("obsolete", "any", "reduce, keep (keep_with_reason), none"),
826
+ ("any", "any", "incubate (incubate_owner_approved), drop (drop_retire_with_reason), "
827
+ "none (none_stays_in_intake), place (place_admitted_and_eligible)"),
828
+ ("already resolved", "any", "none"),
829
+ ("unclassified", "any", "none"),
830
+ )
831
+ # §7.3's structural sentences, copied from the same file (### 7.3 Proposal content (S7), the
832
+ # "Structural rules (code)" paragraph) and §10.4's ledger-only sentence from the plan's done-when 6.
833
+ DESIGN_7_3 = (
834
+ "Global-file operations other than delete and merge are rejected",
835
+ "an incubate without observation and expiry",
836
+ "keep or drop without reason",
837
+ "a disposition the promotion eligibility or §7.2 does not allow",
838
+ "a disposition the promotion eligibility or §7.2 does not allow",
839
+ "a `reduce` or `merge` touching a unit with an active `keep` record unless the proposal names the record",
840
+ "Keep/incubate/drop proposals carry no library operations and `requires_test == false`",
841
+ )
842
+
843
+
844
+ # §7.4's own list, copied from `design/session-distill/2026-10-20T1942--9684f05--mechanism-design.md`
845
+ # (### 7.4 Placement contract (operative)) and cited here, each item with the owner that carries it:
846
+ # `table:<rule id or block>` for a decidable restriction, `text:<heading or bar>` for a bar a person
847
+ # judges. An item may have both owners — the gate bar's decidable half is a rule and its judgement is
848
+ # a bar. The pair of authorities is complete exactly when every item has an owner that exists and
849
+ # every rule and bar is some item's owner, which is what `fidelity_problems` asks.
850
+ DESIGN_7_4 = (
851
+ ("the layers as destinations, cheapest that still fires on time", ("table:destinations",)),
852
+ ("the A-G typology as the second axis", ("table:c_route", "text:Type G, the recognition principles")),
853
+ ("leftward reformulation when the target layer's bar passes", ("text:Leftward reformulation",)),
854
+ ("consumer escalation: who executes when the learning is needed", ("table:consumer_mismatch",
855
+ "text:Where a learning goes")),
856
+ ("the enforcement bar, all four conditions", ("text:The enforcement bar",)),
857
+ ("the gate bar; semantic checks disclose and never block", ("table:gate_on_judgment", "text:The gate bar")),
858
+ ("the hook charter: pattern-matched injection, no blocking, no semantic judging",
859
+ ("table:hook_charter", "text:The hook charter")),
860
+ ("one canonical home per learning, with accelerators and mirrors derived from it",
861
+ ("text:Where a learning goes",)),
862
+ ("the new-guide criterion: at least five promoted items sharing a situation no guide covers",
863
+ ("table:guide_premature",)),
864
+ ("retirement for refutation or harm, an expired version-bound fact, or mechanization - never for "
865
+ "low frequency", ("text:Retirement",)),
866
+ ("concrete facts kept verbatim rather than abstracted away", ("text:Facts stay verbatim",)),
867
+ ("the always-loaded global file receives deletions and merges only", ("table:global_addition",)),
868
+ ("a recognition principle (C) to the router trigger of the guide whose situation it names, or to "
869
+ "session-level injection", ("table:c_route",)),
870
+ ("hooks are a destination on both hosts, and the skills tree is shared", ("text:Where a learning goes",)),
871
+ ("type G: the sources, the evidence bar, the four carries, and the routes by gap kind",
872
+ ("text:Type G, the recognition principles",)),
873
+ ("the exclusions, each with its reason and revisit condition", ("text:What this contract excludes, and why",)),
874
+ )
875
+
876
+
877
+ def contract_headings():
878
+ """The canonical text's own section headings."""
879
+ return tuple(line[3:].strip() for line in contract_text().splitlines() if line.startswith("## "))
880
+
881
+
882
+ def contract_problems(text=None):
883
+ """§7.4's list against its two authorities: the table's rules and the text's bars and sections.
884
+ `text` stands in for the canonical text in the count check only, so a control can plant a bar.
885
+
886
+ Both directions. An item whose owner does not exist is a bar nobody carries; a rule or bar that
887
+ is nobody's owner is an authority the design does not ask for. Either way the contract has drifted
888
+ from the section it claims to be."""
889
+ rules = {f"table:{rule['id']}" for rule in table("placement")["rules"]}
890
+ blocks = {f"table:{name}" for name in table("placement") if not name.startswith("$")} - {"table:rules"}
891
+ bars = {f"text:{bar}" for bar in contract_bars()}
892
+ headings = {f"text:{heading}" for heading in contract_headings()}
893
+ held = rules | blocks | bars | headings
894
+ problems = [f"CONTRACT_OWNER_ABSENT {owner}: §7.4's item {item!r} names an owner that does not exist"
895
+ for item, owners in DESIGN_7_4 for owner in owners if owner not in held]
896
+ claimed = {owner for _item, owners in DESIGN_7_4 for owner in owners}
897
+ problems += [f"CONTRACT_ITEM_UNCLAIMED {name}: a rule of the placement table that no §7.4 item owns"
898
+ for name in sorted(rules - claimed)]
899
+ problems += [f"CONTRACT_ITEM_UNCLAIMED {name}: a bar of the canonical text that no §7.4 item owns"
900
+ for name in sorted(bars - claimed)]
901
+ if not DESIGN_7_4:
902
+ problems.append("CONTRACT_EMPTY: a bijection over no items says nothing")
903
+ if not bars:
904
+ problems.append("CONTRACT_NO_BARS: the canonical text states no bar, so S7b would judge nothing")
905
+ return problems + bar_condition_problems(text)
906
+
907
+
908
+ def render_pair_row(row):
909
+ def one(entry):
910
+ return entry["disposition"] + (f" ({entry['requires']})" if entry.get("requires") else "")
911
+ return (row["kind"], row["diagnosis"], ", ".join(one(entry) for entry in row["allowed"]))
912
+
913
+
914
+ def fidelity_problems():
915
+ """The two tables against the design's own rows and sentences, and the conditions against their readers."""
916
+ problems = list(condition_problems())
917
+ rendered = tuple(render_pair_row(row) for row in table("pairs")["rows"])
918
+ if rendered != DESIGN_7_2:
919
+ problems += [f"CONTRACT_DRIFT allowed_pairs row {n + 1}: the table says {have}, §7.2 says {want}"
920
+ for n, (have, want) in enumerate(itertools.zip_longest(rendered, DESIGN_7_2))
921
+ if have != want]
922
+ sentences = tuple(rule["design"] for rule in table("rules")["rules"])
923
+ if sentences != DESIGN_7_3:
924
+ problems += [f"CONTRACT_DRIFT structural_rules row {n + 1}: the table says {have!r}, §7.3 says {want!r}"
925
+ for n, (have, want) in enumerate(itertools.zip_longest(sentences, DESIGN_7_3))
926
+ if have != want]
927
+ # The vocabularies are the design's four, and nothing reads a fifth.
928
+ held = vocabularies()
929
+ if set(held) != {"kind", "diagnosis", "disposition", "status"}:
930
+ problems.append(f"CONTRACT_DRIFT vocabularies: {sorted(held)}")
931
+ if not table("pairs")["rows"]:
932
+ problems.append("TABLE_EMPTY allowed_pairs: a table with no rows allows nothing and refuses nothing")
933
+ if not table("rules")["rules"]:
934
+ problems.append("TABLE_EMPTY structural_rules: a table with no rules judges nothing")
935
+ if not table("placement")["rules"]:
936
+ problems.append("TABLE_EMPTY placement_rules: a table with no rules restricts nothing")
937
+ problems += contract_problems()
938
+ return problems
939
+
940
+
941
+ # ---- self-test -----------------------------------------------------------------------------------
942
+
943
+ def self_test():
944
+ """Positive control first, then one planted violation per rule, each refused BY NAME.
945
+
946
+ The body is wrapped so a control that DIES still speaks. A planted mutation of the pair rule
947
+ (`if disposition not in allowed` -> `if False`) made `allowed[disposition]` raise
948
+ KeyError('correct') and the suite ended on a traceback with no [FAIL] line at all — and a
949
+ revert trial that accepts any output counted the KeyError as the control firing (the WP-12
950
+ review). A traceback is not a control firing: the wrapper prints a [FAIL] line naming the
951
+ control that was in flight, so the evidence says which rule stopped being enforced.
952
+ """
953
+ failures, ran = [], []
954
+ try:
955
+ return _self_test_body(failures, ran)
956
+ except BaseException as exc: # noqa: BLE001 - the suite must speak before it dies
957
+ held = ran[-1] if ran else "<no control ran>"
958
+ print(f"placement --self-test [FAIL] the suite died after {held!r}: "
959
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
960
+ for name, detail in failures:
961
+ print(f"placement --self-test [FAIL] {name}: {detail}", file=sys.stderr)
962
+ print(f"placement --self-test: INCOMPLETE ({len(ran)} controls ran, {len(failures)} "
963
+ f"failed before the suite died)", file=sys.stderr)
964
+ raise
965
+
966
+
967
+ def _self_test_body(failures, ran):
968
+ reporting = []
969
+
970
+ def control(name, got, want):
971
+ if reporting:
972
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}: this suite has begun publishing its report")
973
+ if not isinstance(got, str):
974
+ raise TypeError(f"CONTROL_GOT_NOT_STR {name}: this helper judges a string, not "
975
+ f"{type(got).__name__}; a list is truthy whatever it holds")
976
+ ran.append(name)
977
+ if want not in got:
978
+ failures.append((name, f"expected {want!r} in {got!r}"))
979
+
980
+ def equals(name, got, want):
981
+ """A control whose expectation is the WHOLE answer, not a fragment of it.
982
+
983
+ `control` asks `want in str(got)`, which is right for a refusal's name inside a longer
984
+ message and wrong for a value (the WP-12 review asked for equality where exact values and
985
+ counts are meant)."""
986
+ ran.append(name)
987
+ if str(got) != str(want):
988
+ failures.append((name, f"expected exactly {want!r}, got {str(got)[:400]!r}"))
989
+
990
+ def clean(name, problems):
991
+ if reporting:
992
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
993
+ if not isinstance(problems, list):
994
+ raise TypeError(f"CLEAN_PROBLEMS_NOT_LIST {name}: {type(problems).__name__}")
995
+ ran.append(name)
996
+ if problems:
997
+ failures.append((name, f"expected nothing, got {problems}"))
998
+
999
+ def said(proposal, active_keep=None):
1000
+ # the subject is computed here, so a rule that dies under its mutation fails the control asking about it
1001
+ # by name instead of ending the suite after the one before (Codex WP-12 r2 F13)
1002
+ try:
1003
+ return "; ".join(problems(proposal, active_keep))
1004
+ except Exception as exc: # noqa: BLE001 - reported as this control's subject, never swallowed
1005
+ return f"RAISED {type(exc).__name__}: {exc}"
1006
+
1007
+ # The tables are the design's, and every condition they name has a reader.
1008
+ clean("the two tables carry §7.2's rows and §7.3's sentences, and every condition has a reader",
1009
+ fidelity_problems())
1010
+ # The below-bar dispositions are the §6.4 table's, not a second list: one owner for one value.
1011
+ from runlib import derive
1012
+ below = next((row.get("allowed_dispositions") for row in derive.table()["promotion"]
1013
+ if row["id"] == "below_bar"), None)
1014
+ clean("the below-bar dispositions are the ones the §6.4 table allows, not a copy",
1015
+ [] if below is not None and tuple(below) == BELOW_BAR
1016
+ else [f"§6.4 says {below}, this module says {list(BELOW_BAR)}"])
1017
+
1018
+ # ---- a proposal that passes, per disposition kind. Every control below plants ONE violation
1019
+ # into one of these, so a refusal is attributable to the mutation and not to the fixture.
1020
+ place = {"item_id": "i-1", "candidate_id": "k-1", "kind": "gap", "diagnosis": "gap",
1021
+ "disposition": "place", "admitted": True, "promotion_eligible": True,
1022
+ "requires_test": True, "reason": "the window shows the gap three times",
1023
+ "operations": [{"type": "create", "target": "claude/guides/g.md", "before_sha256": None}],
1024
+ "destination": {"layer": "guides", "carrier": "claude/guides/g.md"},
1025
+ "expected_observation": {"occasion": "a run of the gate", "expiry": "2027-01-01"}}
1026
+ keep = {"item_id": "i-2", "candidate_id": "k-2", "kind": "confirmed", "diagnosis": "covered",
1027
+ "disposition": "keep", "promotion_eligible": True, "requires_test": False,
1028
+ "reason": "the unit is followed and helps", "operations": []}
1029
+ incubate = {"item_id": "i-3", "candidate_id": "k-3", "kind": "misfire", "diagnosis": "trigger problem",
1030
+ "disposition": "incubate", "promotion_eligible": False, "requires_test": False,
1031
+ "operations": [], "reason": "below the bar, watched instead",
1032
+ "expected_observation": {"occasion": "the same situation recurs", "expiry": "2027-02-01"}}
1033
+ merge = {"item_id": "i-4", "candidate_id": "k-4", "kind": "misfire", "diagnosis": "redundant",
1034
+ "disposition": "reduce", "promotion_eligible": True, "requires_test": True,
1035
+ "reason": "two units say the same thing",
1036
+ "keep_records_named": ["kr-1"],
1037
+ "operations": [{"type": "merge", "target": "claude/guides/g.md", "before_sha256": "a" * 64}]}
1038
+ legacy = {"item_id": "i-5", "candidate_id": "S3-03", "kind": "unclassified", "diagnosis": "unknown",
1039
+ "disposition": "incubate", "legacy_incubating": True, "promotion_eligible": False,
1040
+ "requires_test": False, "operations": [], "reason": "the entry's history is unavailable",
1041
+ "expected_observation": {"occasion": "the situation recurs in a later window",
1042
+ "expiry": "2027-03-01"}}
1043
+ # Every clean pair carries §7.4's inputs for the scopes its own destination puts it in. Before
1044
+ # `input_problems` these dicts carried none, and five of §7.4's six rules read None here while
1045
+ # the suite reported them clean - the same silence S7's flat proposal had in production.
1046
+ claims = {"consumer": "session", "artifact_form": "instruction", "blocking": None,
1047
+ "criterion": None, "judges": None, "situation_promoted_items": 7,
1048
+ "situation_covered_by_guide": False, "names_situation_of_guide": None,
1049
+ "owner_only": None, "typology": "D"}
1050
+ place, keep, incubate = {**place, **claims}, {**keep, **claims}, {**incubate, **claims}
1051
+ merge, legacy = {**merge, **claims}, {**legacy, **claims}
1052
+ for label, proposal in (("a place", place), ("a keep", keep), ("an incubate", incubate),
1053
+ ("a reduce by merge", merge), ("a legacy incubate", legacy)):
1054
+ clean(f"{label} proposal that satisfies §7.2 and §7.3 has no problem", problems(proposal))
1055
+ clean("and §7.4's inputs are present for every scope each of those proposals is in, which is why "
1056
+ "its rules can judge them at all",
1057
+ [p for proposal in (place, keep, incubate, merge, legacy)
1058
+ for p in input_problems(proposal)])
1059
+ control("while the same place proposal with its situation claims removed is refused by the rule "
1060
+ "whose input it dropped",
1061
+ "; ".join(input_problems({**place, "situation_promoted_items": None})),
1062
+ "PLACEMENT_INPUT_ABSENT GUIDE_PREMATURE")
1063
+ clean("the scopes the table names and the readers here are the same set, both ways",
1064
+ scope_problems())
1065
+ control("and `problems` itself carries the input guard, so a caller that asks the one question "
1066
+ "gets it: a place proposal missing a claim its scope needs is named",
1067
+ "; ".join(problems({**place, "situation_promoted_items": None})),
1068
+ "PLACEMENT_INPUT_ABSENT")
1069
+ control("`problems` carries §7.2's pair check too, so one call is the whole contract",
1070
+ said({**place, "disposition": "correct"}), "PAIR_DISALLOWED")
1071
+ clean("and the reduce passes while its keep record is named",
1072
+ problems(merge, {"u-1": "kr-1"}))
1073
+ # The union's precedence rule, over a PLANTED table: no pair in the real table has an
1074
+ # unconditional row after a conditioned one for the same disposition, so the rule has no live
1075
+ # case and would otherwise sit here untested. A table that grows will have one.
1076
+ held_for_union = json.loads(PAIRS_PATH.read_text(encoding="utf-8"))
1077
+ try:
1078
+ _TABLES["pairs"] = {**held_for_union,
1079
+ "rows": [{"id": "conditioned", "kind": "gap", "diagnosis": "any",
1080
+ "allowed": [{"disposition": "place", "requires": "keep_with_reason"}]},
1081
+ {"id": "outright", "kind": "any", "diagnosis": "any",
1082
+ "allowed": [{"disposition": "place"}]}]}
1083
+ clean("where two rows allow one disposition and only one of them conditions it, the "
1084
+ "unconditional row is the bar",
1085
+ [] if allowed_for("gap", "gap") == {"place": None}
1086
+ else [f"the union says {allowed_for('gap', 'gap')}"])
1087
+ _TABLES["pairs"] = {**held_for_union,
1088
+ "rows": [{"id": "outright", "kind": "any", "diagnosis": "any",
1089
+ "allowed": [{"disposition": "place"}]},
1090
+ {"id": "conditioned", "kind": "gap", "diagnosis": "any",
1091
+ "allowed": [{"disposition": "place", "requires": "keep_with_reason"}]}]}
1092
+ clean("and the order of the two rows does not change that",
1093
+ [] if allowed_for("gap", "gap") == {"place": None}
1094
+ else [f"the union says {allowed_for('gap', 'gap')}"])
1095
+ finally:
1096
+ _TABLES["pairs"] = held_for_union
1097
+
1098
+ # ---- one planted violation per rule (O5's fixtures F-O5-05, -06, -07, -14, and §7.3's rest)
1099
+ control("F-O5-07: a disposition §7.2 does not allow for the pair is refused by name",
1100
+ said({**place, "disposition": "keep"}), "PAIR_DISALLOWED")
1101
+ # The whole sorted list, not one word of it: "place" alone appears in half this suite's messages.
1102
+ control("and the refusal names what §7.2 does allow there",
1103
+ said({**place, "disposition": "keep"}), "§7.2 allows drop, incubate, place")
1104
+ control("a disposition §7.2 allows only under a condition is refused when the condition fails",
1105
+ said({**merge, "operations": [{"type": "edit", "target": "claude/guides/g.md",
1106
+ "before_sha256": "a" * 64}]}),
1107
+ "only where the reduce is a merge")
1108
+ control("F-O5-06: an incubate with no expiry is refused by name",
1109
+ said({**incubate, "expected_observation": {"occasion": "x"}}), "EXPIRY_REQUIRED")
1110
+ control("and one with no expected observation at all, the same",
1111
+ said({**incubate, "expected_observation": None}), "EXPIRY_REQUIRED")
1112
+ control("a keep with no reason is refused by name", said({**keep, "reason": ""}), "REASON_REQUIRED")
1113
+ control("a drop with no reason, the same",
1114
+ said({**place, "disposition": "drop", "reason": None, "operations": [],
1115
+ "requires_test": False}), "REASON_REQUIRED")
1116
+ control("F-O5-05: a reduce over a unit with an active keep record the proposal does not name is "
1117
+ "refused by name",
1118
+ said({**merge, "keep_records_named": []}, {"u-1": "kr-1"}), "KEEP_GUARDED")
1119
+ control("and the refusal names the record, so the owner knows what to release",
1120
+ said({**merge, "keep_records_named": []}, {"u-1": "kr-1"}), "kr-1")
1121
+ reached = {"u-1": {"record": "kr-1", "path": "claude/guides/g.md", "heading": "One"},
1122
+ "u-3": {"record": "kr-3", "path": "claude/guides/other.md", "heading": "Three"}}
1123
+ section_merge = {**merge, "keep_records_named": [],
1124
+ "operations": [{"type": "merge", "target": "claude/guides/g.md#One", "before_sha256": "a" * 64,
1125
+ "units": ["claude/guides/g.md#One", "claude/guides/g.md#Two"]}]}
1126
+ control("Codex WP-12 r2 F5: a keep over a unit the merge reaches is guarded",
1127
+ said(section_merge, reached), "KEEP_GUARDED u-1")
1128
+ clean("and a keep over a unit in a file the merge does not reach is not",
1129
+ [x for x in said(section_merge, reached).split("; ") if x.startswith("KEEP_GUARDED u-3")])
1130
+ nested = {"u-5": {"record": "kr-5", "path": "claude/guides/g.md", "heading": "Parent > One"}}
1131
+ control("a keep under a nested heading is reached by a merge of a section in its chain (review of 7a7752e8)",
1132
+ said(section_merge, nested), "KEEP_GUARDED u-5")
1133
+ control("and by a spelling S11 resolves to the same section: marks and spaces",
1134
+ said({**section_merge, "operations": [{"type": "merge", "target": "claude/guides/g.md# ## One ",
1135
+ "before_sha256": "a" * 64}]}, nested), "KEEP_GUARDED u-5")
1136
+ control("and by an edit of the parent section, whose span holds it",
1137
+ said({**section_merge, "operations": [{"type": "merge", "target": "claude/guides/g.md#Parent",
1138
+ "before_sha256": "a" * 64}]}, nested), "KEEP_GUARDED u-5")
1139
+ control("a keep the inventory cannot place is guarded, not skipped",
1140
+ said(section_merge, {"u-6": {"record": "kr-6", "path": None, "heading": None}}), "KEEP_GUARDED u-6")
1141
+ # Codex WP-12 r3 F1: a section of the kept unit's file reaches it, whatever the headings say, because the
1142
+ # inventory's heading chain cannot show that S11's section misses the unit
1143
+ control("a keep over another section of the merged file is guarded too: the file is what decides",
1144
+ said(section_merge, {"u-4": {"record": "kr-4", "path": "claude/guides/g.md", "heading": "Four"}}),
1145
+ "KEEP_GUARDED u-4")
1146
+ for label, title in (("a title holding the chain's separator", "A > B"), ("a title beginning with marks", "# B"),
1147
+ ("a heading the inventory left unnamed", "")):
1148
+ control(f"and so is one under {label}, which no heading comparison can place (Codex WP-12 r3 F1)",
1149
+ said({**section_merge, "operations": [{"type": "delete", "target": f"claude/guides/g.md#{title or 'X'}",
1150
+ "before_sha256": "a" * 64}]},
1151
+ {"u-7": {"record": "kr-7", "path": "claude/guides/g.md", "heading": title}}), "KEEP_GUARDED u-7")
1152
+ # Codex WP-12 r3 F2: a unit id the inventory gives twice keeps both places
1153
+ twice = {"u-8": {"record": "kr-8", "places": [{"path": "claude/guides/other.md", "heading": "B"},
1154
+ {"path": "claude/guides/g.md", "heading": "A"}]}}
1155
+ control("a unit id given at two places is reached through either of them",
1156
+ said(section_merge, twice), "KEEP_GUARDED u-8")
1157
+ clean("and one whose places all lie in files the proposal does not touch is not",
1158
+ [x for x in said(section_merge, {"u-9": {"record": "kr-9", "places": [
1159
+ {"path": "claude/guides/other.md", "heading": "B"}]}}).split("; ") if x.startswith("KEEP_GUARDED")])
1160
+ control("a unit the inventory gives no place at all is guarded",
1161
+ said(section_merge, {"u-10": {"record": "kr-10", "places": []}}), "KEEP_GUARDED u-10")
1162
+ control("a merge of the whole file reaches every section of it",
1163
+ said({**section_merge, "operations": [{"type": "merge", "target": "claude/guides/g.md",
1164
+ "before_sha256": "a" * 64}]},
1165
+ {"u-4": {"record": "kr-4", "path": "./claude/guides/g.md", "heading": "Four"}}), "KEEP_GUARDED u-4")
1166
+ control("a merge operation under another disposition is guarded the same way",
1167
+ said({**place, "operations": [{"type": "merge", "target": "claude/guides/g.md",
1168
+ "before_sha256": "a" * 64}]}, {"u-2": "kr-9"}),
1169
+ "KEEP_GUARDED")
1170
+ control("a global-file operation that is not a delete or a merge is refused by name",
1171
+ said({**place, "operations": [{"type": "edit", "target": "claude/CLAUDE.md",
1172
+ "before_sha256": "a" * 64}]}),
1173
+ "GLOBAL_OP_DISALLOWED")
1174
+ control("the Korean global file is the same surface",
1175
+ said({**place, "operations": [{"type": "create", "target": "ko/claude/CLAUDE.md",
1176
+ "before_sha256": None}]}),
1177
+ "GLOBAL_OP_DISALLOWED")
1178
+ # The global file by IDENTITY, not by spelling: literal membership read `./claude/CLAUDE.md` as
1179
+ # another file and let an edit through the rule that allows only deletion and merge there.
1180
+ for spelling in ("./claude/CLAUDE.md", "claude/./CLAUDE.md", "claude/guides/../CLAUDE.md"):
1181
+ control(f"an equivalent spelling of the global file is the same file ({spelling})",
1182
+ said({**place, "operations": [{"type": "edit", "target": spelling,
1183
+ "before_sha256": "a" * 64}]}),
1184
+ "GLOBAL_OP_DISALLOWED")
1185
+ control("Codex WP-12 r2 F7: a section of the global file is the global file",
1186
+ said({**place, "operations": [{"type": "edit", "target": "claude/CLAUDE.md#Header",
1187
+ "before_sha256": "a" * 64}]}), "GLOBAL_OP_DISALLOWED")
1188
+ clean("while a file whose name merely starts with the global file's is not it",
1189
+ [p for p in problems({**place, "operations": [
1190
+ {"type": "edit", "target": "claude/CLAUDE.md.bak", "before_sha256": "a" * 64}]})
1191
+ if "GLOBAL_OP_DISALLOWED" in p])
1192
+ equals("and the identity question has one owner, so this rule cannot answer it differently from "
1193
+ "the target contract",
1194
+ json.dumps([targets.identity("./claude/CLAUDE.md") == targets.identity("claude/CLAUDE.md"),
1195
+ targets.identity("claude/CLAUDE.md.bak")
1196
+ == targets.identity("claude/CLAUDE.md")]),
1197
+ "[true, false]")
1198
+
1199
+ # A proposal that CHANGES the library must name the file that carries the change. `carrier` is
1200
+ # nullable for a disposition that carries nothing, which is why the rule is the pairing.
1201
+ control("a proposal with library operations and no carrier is refused by name",
1202
+ said({**place, "destination": {**place["destination"], "carrier": None}}),
1203
+ "CARRIER_ABSENT")
1204
+ control("and the refusal names the operation types whose text would have had nowhere to land",
1205
+ said({**place, "destination": {**place["destination"], "carrier": None}}),
1206
+ "operation(s) of type create and names no carrier")
1207
+ clean("while a disposition that carries no operation needs no carrier, which is what makes the "
1208
+ "field nullable", carrier_problems({"operations": [],
1209
+ "destination": {"carrier": None}}))
1210
+ clean("and neither does a pure removal, which names its own target and adds no text",
1211
+ carrier_problems({"operations": [{"type": "delete", "target": "claude/guides/g.md"}],
1212
+ "destination": {"carrier": None}}))
1213
+ clean("nor a merge, which is executed as deletes plus one edit into a target the operation "
1214
+ "itself names", carrier_problems({"operations": [{"type": "merge",
1215
+ "target": "claude/guides/g.md"}],
1216
+ "destination": {"carrier": None}}))
1217
+ clean("and a proposal that names one is clean", carrier_problems(place))
1218
+ clean("while a delete on the global file is allowed",
1219
+ problems({**place, "disposition": "reduce", "kind": "obsolete", "diagnosis": "unknown",
1220
+ "operations": [{"type": "delete", "target": "claude/CLAUDE.md",
1221
+ "before_sha256": "a" * 64}]}))
1222
+ control("a candidate below the promotion bar proposed as a place is refused by name",
1223
+ said({**place, "promotion_eligible": False}), "PAIR_DISALLOWED")
1224
+ control("and the refusal says it was the promotion bar, not the pair",
1225
+ said({**place, "promotion_eligible": False}), "below the promotion bar")
1226
+ control("F-O5-14: a ledger-only disposition carrying a library operation is refused by name",
1227
+ said({**keep, "operations": [{"type": "edit", "target": "claude/guides/g.md",
1228
+ "before_sha256": "a" * 64}]}),
1229
+ "LEDGER_ONLY_VIOLATED")
1230
+ control("and one whose requires_test is not false, the same",
1231
+ said({**keep, "requires_test": True}), "LEDGER_ONLY_VIOLATED")
1232
+ control("a value outside §7.2's vocabulary is named as that, not read as a pair",
1233
+ said({**place, "kind": "regression"}), "VALUE_UNKNOWN kind")
1234
+ control("and the refusal prints the vocabulary it is outside of",
1235
+ said({**place, "diagnosis": "hunch"}), "§7.2's vocabulary is")
1236
+
1237
+ # ---- the legacy row answers for a legacy entry only, which is what keeps it from swallowing
1238
+ # every other row: it holds for any kind, unclassified included.
1239
+ control("a legacy entry proposed as a correct, which its row does not allow, is refused by name",
1240
+ said({**legacy, "disposition": "correct"}), "under the legacy-maintenance row")
1241
+ control("an unclassified candidate that is NOT a legacy entry can only be none",
1242
+ said({**legacy, "legacy_incubating": False}), "PAIR_DISALLOWED")
1243
+ clean("and the same candidate as a legacy entry may be incubated", problems(legacy))
1244
+ control("a legacy place without admission and eligibility is refused by name",
1245
+ said({**legacy, "disposition": "place", "admitted": False}),
1246
+ "only where the entry is admitted")
1247
+
1248
+ # ---- §7.4's six decidable rules, each with its clean counterpart (F-O5-17 x6). Every fixture
1249
+ # below is a proposal §7.2 and §7.3 already pass, so a refusal here is the placement rule's.
1250
+ guide = {**place, "destination": {"layer": "guides", "carrier": "claude/guides/g.md"},
1251
+ "situation_promoted_items": 5, "situation_covered_by_guide": False,
1252
+ "consumer": "session", "artifact_form": "instruction", "typology": "A"}
1253
+ clean("a guide proposed where five promoted items share an uncovered situation passes",
1254
+ problems(guide))
1255
+ control("F-O5-17: a guide proposed below the five-item criterion is refused by name",
1256
+ said({**guide, "situation_promoted_items": 4}), "GUIDE_PREMATURE")
1257
+ control("and the refusal says how many §7.4 asks for and how many there are",
1258
+ said({**guide, "situation_promoted_items": 4}), "at least 5 promoted items")
1259
+ clean("while a guide over a situation a guide already covers is not this rule's business",
1260
+ problems({**guide, "situation_promoted_items": 2, "situation_covered_by_guide": True}))
1261
+ control("F-O5-17: an instruction aimed at a consumer that reads only code is refused by name",
1262
+ said({**guide, "consumer": "script"}), "CONSUMER_MISMATCH")
1263
+ control("and a hermetic dispatch, which reads only its packet, the same",
1264
+ said({**guide, "consumer": "hermetic_dispatch"}), "CONSUMER_MISMATCH")
1265
+ clean("while code aimed at a script is not a mismatch",
1266
+ problems({**guide, "consumer": "script", "artifact_form": "code"}))
1267
+ control("Codex WP-12 r2 F6: a consumer the table does not name is refused, not skipped",
1268
+ said({**guide, "consumer": "invented-consumer"}), "the consumer 'invented-consumer' is not one the table names")
1269
+ clean("while a proposal that carries no instruction is outside the rule's scope, whatever consumer it names (RR-1: "
1270
+ "a `none` named one in its own words)",
1271
+ [x for x in said({**fx_proposal("unclassified", "covered", "none"), "consumer": "claude main session"})
1272
+ .split("; ") if x.startswith("CONSUMER_MISMATCH")])
1273
+ # The carrier is a NAME, not a path: a fixture spelling a real author-side module is read by the
1274
+ # payload gate as this shipped file naming one, which it refuses (and rightly: it cannot tell a
1275
+ # proposal's data from a code reference).
1276
+ gate = {**guide, "destination": {"layer": "gates", "carrier": "the gate this item changes"},
1277
+ "blocking": True, "criterion": "deterministic"}
1278
+ clean("a blocking gate on a deterministic criterion passes", problems(gate))
1279
+ control("F-O5-17: a blocking gate proposed for a semantic criterion is refused by name",
1280
+ said({**gate, "criterion": "semantic"}), "GATE_ON_JUDGMENT")
1281
+ clean("while a semantic check that discloses rather than blocks passes",
1282
+ problems({**gate, "criterion": "semantic", "blocking": False}))
1283
+ control("F-O5-17: an addition to the global file is refused by name",
1284
+ said({**guide, "destination": {"layer": "guides", "carrier": "claude/CLAUDE.md"}}),
1285
+ "GLOBAL_ADDITION")
1286
+ control("Codex WP-12 r2 F7: and so is one whose carrier names a section of it",
1287
+ said({**guide, "destination": {"layer": "guides", "carrier": "claude/CLAUDE.md#Header"}}),
1288
+ "GLOBAL_ADDITION")
1289
+ clean("while a reduce whose carrier is the global file is not an addition",
1290
+ problems({**guide, "kind": "obsolete", "diagnosis": "unknown", "disposition": "reduce",
1291
+ "destination": {"layer": "guides", "carrier": "claude/CLAUDE.md"},
1292
+ "operations": [{"type": "delete", "target": "claude/CLAUDE.md",
1293
+ "before_sha256": "a" * 64}]}))
1294
+ c_rule = {**guide, "typology": "C", "names_situation_of_guide": True}
1295
+ clean("a C principle at the router trigger of the guide whose situation it names passes",
1296
+ problems(c_rule))
1297
+ clean("and one in session-level injection, where it concerns only the owner",
1298
+ problems({**c_rule, "destination": {"layer": "session_injection", "carrier": "session"},
1299
+ "names_situation_of_guide": None, "owner_only": True}))
1300
+ clean("a C principle whose proposal carries no operation is routed nowhere, so the route rule does not judge "
1301
+ "the layer it happens to name (the first live S7: a complete `none` refused for it)",
1302
+ [p for p in problems({**fx_proposal("unclassified", "covered", "none"), "typology": "C",
1303
+ "destination": {"layer": "incubator", "carrier": None}}) if p.startswith("C_ROUTE")])
1304
+ control("F-O5-17: a C principle routed anywhere else is refused by name",
1305
+ said({**c_rule, "destination": {"layer": "skills", "carrier": "claude/skills/s"}}),
1306
+ "C_ROUTE")
1307
+ control("one placed in a guide whose situation it does not name, the same",
1308
+ said({**c_rule, "names_situation_of_guide": False}), "names none")
1309
+ control("and one injected at session level without concerning only the owner, the same",
1310
+ said({**c_rule, "destination": {"layer": "session_injection", "carrier": "session"},
1311
+ "owner_only": False}), "concerns only the owner")
1312
+ control("Codex WP-12 r2 F6: a C principle in a guide that does not say whether it names the guide's situation is "
1313
+ "a missing input, by name",
1314
+ said({**c_rule, "names_situation_of_guide": None}),
1315
+ "PLACEMENT_INPUT_ABSENT C_ROUTE i-1.names_situation_of_guide")
1316
+ control("and one injected at session level that does not say whether it concerns only the owner, the same",
1317
+ said({**c_rule, "destination": {"layer": "session_injection", "carrier": "session"},
1318
+ "names_situation_of_guide": None, "owner_only": None}),
1319
+ "PLACEMENT_INPUT_ABSENT C_ROUTE i-1.owner_only")
1320
+ hook = {**guide, "destination": {"layer": "hooks", "carrier": "hooks/x"}, "blocking": False,
1321
+ "judges": False}
1322
+ clean("a hook that injects canonical text passes", problems(hook))
1323
+ control("F-O5-17: a hook that blocks is refused by name", said({**hook, "blocking": True}),
1324
+ "HOOK_CHARTER")
1325
+ control("and one that judges, the same", said({**hook, "judges": True}), "HOOK_CHARTER")
1326
+
1327
+ # ---- the two authorities of §7.4, and the packet that carries one of them
1328
+ clean("§7.4's list is owned, item by item, by a rule of the table or a bar of the canonical text",
1329
+ contract_problems())
1330
+ control("the canonical text states the bars S7b judges", "; ".join(contract_bars()),
1331
+ "Leftward reformulation")
1332
+ control("and the retirement bar among them", "; ".join(contract_bars()), "Retirement")
1333
+
1334
+ # ---- a bar that names a count of conditions must enumerate them ------------------------------
1335
+ #
1336
+ # `The enforcement bar` once said only "All four of its conditions hold", and neither the
1337
+ # placement table nor either rendered packet supplied those four: an enforcement proposal was
1338
+ # reviewed against a bar nobody could read, and the contract check passed because it only asked
1339
+ # whether the heading was there (the WP-12 review). The four are the placement framework's, which
1340
+ # the design says it retains; the owner confirmed them on 2026-11-13, and an unenumerated count is
1341
+ # now one of `contract_problems`' refusals. The rows below build their own text, so they keep
1342
+ # testing now that the live contract is clean.
1343
+ clean("the live contract enumerates every count of conditions a bar names", bar_condition_problems())
1344
+ control("and a contract whose bar names a count without the list is refused by the contract check",
1345
+ "; ".join(contract_problems(
1346
+ "## The bars\n\n**The enforcement bar.** All four of its conditions hold.\n")),
1347
+ "BAR_CONDITIONS_UNSTATED The enforcement bar")
1348
+ enumerated = ("## The bars\n\n"
1349
+ "**The enforcement bar.** All four of its conditions hold, or the learning does "
1350
+ "not go to enforcement: the violation is deterministically detectable; the check "
1351
+ "has a natural run point; a false positive is cheaper than the violation; and the "
1352
+ "rule is stated once.\n")
1353
+ clean("a bar that enumerates its four conditions passes, so the check can be satisfied rather "
1354
+ "than merely fired",
1355
+ bar_condition_problems(enumerated))
1356
+ control("a bar naming two conditions and giving one is caught too, which is what makes this a "
1357
+ "rule about counts and not about the word four",
1358
+ "; ".join(bar_condition_problems(
1359
+ "## The bars\n\n**The gate bar.** Both two conditions hold: it is "
1360
+ "deterministic.\n")),
1361
+ "BAR_CONDITIONS_UNSTATED The gate bar")
1362
+ clean("and a bar that names no count is not asked for an enumeration",
1363
+ bar_condition_problems("## The bars\n\n**The hook charter.** A hook injects text.\n"))
1364
+ control("the check reads the bar's own paragraph, so a later bar's conditions cannot satisfy an "
1365
+ "earlier bar's count",
1366
+ "; ".join(bar_condition_problems(
1367
+ "## The bars\n\n**The enforcement bar.** All four of its conditions hold.\n\n"
1368
+ "**The gate bar.** one; two; three; four\n")),
1369
+ "BAR_CONDITIONS_UNSTATED The enforcement bar")
1370
+ clean("the digest is the text's own, so a packet can bind the bars it was judged by",
1371
+ [] if contract_digest() == hashlib.sha256(contract_text().encode("utf-8")).hexdigest()
1372
+ else ["the digest is not of this text"])
1373
+ held_contract = contract_text()
1374
+ try:
1375
+ # A planted text with one bar removed: the item that owns it is then unowned by name.
1376
+ CONTRACT_PATH.write_text(held_contract.replace("**Retirement.**", "Retirement."), encoding="utf-8")
1377
+ control("a bar the canonical text drops leaves its §7.4 item with no owner",
1378
+ "; ".join(contract_problems()), "CONTRACT_OWNER_ABSENT text:Retirement")
1379
+ # Planted INSIDE the bars section, which is the only place a bar is read from: appended at
1380
+ # the end of the file it would not be a bar at all, and the control passed over nothing.
1381
+ CONTRACT_PATH.write_text(
1382
+ held_contract.replace("**Retirement.**",
1383
+ "**An invented bar.** Nothing in §7.4 says this.\n\n**Retirement.**"),
1384
+ encoding="utf-8")
1385
+ control("and a bar it invents is named as owned by no item",
1386
+ "; ".join(contract_problems()), "CONTRACT_ITEM_UNCLAIMED text:An invented bar")
1387
+ finally:
1388
+ CONTRACT_PATH.write_text(held_contract, encoding="utf-8")
1389
+ clean("and the canonical text is back as it is on disk", contract_problems())
1390
+ held_placement = json.loads(PLACEMENT_PATH.read_text(encoding="utf-8"))
1391
+ try:
1392
+ _TABLES["placement"] = {**held_placement,
1393
+ "rules": held_placement["rules"] + [{"id": "invented", "code": "X",
1394
+ "design": "y", "reads": []}]}
1395
+ control("a placement rule this module does not apply is named",
1396
+ said(guide), "RULE_UNIMPLEMENTED invented")
1397
+ control("and a rule no §7.4 item owns is named too",
1398
+ "; ".join(contract_problems()), "CONTRACT_ITEM_UNCLAIMED table:invented")
1399
+ _TABLES["placement"] = {**held_placement, "rules": []}
1400
+ control("an emptied placement table is named rather than restricting nothing",
1401
+ "; ".join(fidelity_problems()), "TABLE_EMPTY placement_rules")
1402
+ finally:
1403
+ _TABLES["placement"] = held_placement
1404
+
1405
+ # ---- the tables themselves: a planted drift and an emptied table are named
1406
+ held_pairs = json.loads(PAIRS_PATH.read_text(encoding="utf-8"))
1407
+ held_rules = json.loads(RULES_PATH.read_text(encoding="utf-8"))
1408
+ try:
1409
+ _TABLES["pairs"] = {**held_pairs, "rows": [{**held_pairs["rows"][0],
1410
+ "allowed": [{"disposition": "correct"}]}]
1411
+ + held_pairs["rows"][1:]}
1412
+ control("a pairs table that drifts from §7.2 is named by row",
1413
+ "; ".join(fidelity_problems()), "CONTRACT_DRIFT allowed_pairs row 1")
1414
+ _TABLES["pairs"] = {**held_pairs, "rows": []}
1415
+ control("and an emptied pairs table is named rather than passing over nothing",
1416
+ "; ".join(fidelity_problems()), "TABLE_EMPTY allowed_pairs")
1417
+ _TABLES["pairs"] = held_pairs
1418
+ _TABLES["rules"] = {**held_rules, "rules": [{**held_rules["rules"][0], "design": "anything"}]
1419
+ + held_rules["rules"][1:]}
1420
+ control("a structural table that drifts from §7.3 is named by row",
1421
+ "; ".join(fidelity_problems()), "CONTRACT_DRIFT structural_rules row 1")
1422
+ _TABLES["rules"] = {**held_rules,
1423
+ "rules": held_rules["rules"] + [{"id": "invented", "code": "X", "design": "y",
1424
+ "applies_to": "", "requires": ""}]}
1425
+ control("a rule the table names and this module does not apply is named",
1426
+ said(place), "RULE_UNIMPLEMENTED invented")
1427
+ _TABLES["pairs"] = {**held_pairs,
1428
+ "conditions": {**held_pairs["conditions"], "never_checked": "a condition nobody asks"}}
1429
+ _TABLES["rules"] = held_rules
1430
+ control("a condition the table names with no reader is named",
1431
+ "; ".join(fidelity_problems()), "CONDITION_UNCHECKED never_checked")
1432
+ finally:
1433
+ _TABLES["pairs"], _TABLES["rules"] = held_pairs, held_rules
1434
+ clean("and the tables are back as they are on disk", fidelity_problems())
1435
+
1436
+ def with_table(which, mutate, call):
1437
+ """Run `call` with one table mutated, restoring it however the call ends."""
1438
+ held = json.loads(json.dumps(table(which)))
1439
+ try:
1440
+ mutate(_TABLES[which])
1441
+ return call()
1442
+ finally:
1443
+ _TABLES[which] = held
1444
+
1445
+ # Every (kind, diagnosis, bar) S6 can produce must have at least ONE acceptable disposition. A
1446
+ # candidate the stage must answer for and whose every answer is refused is a contract defect
1447
+ # whatever else is true, which is why this is enumerated rather than reasoned about.
1448
+ def raised(call):
1449
+ """`call()`, or the exception it raised as its one problem: the enumeration below calls the pair rule
1450
+ directly, and a rule that dies under its mutation fails these controls by name (Codex WP-12 r2 F13)."""
1451
+ try:
1452
+ return call()
1453
+ except Exception as exc: # noqa: BLE001 - reported as the subject, never swallowed
1454
+ return [f"RAISED {type(exc).__name__}: {exc}"]
1455
+
1456
+ clean("every combination S6 can produce has an acceptable disposition, or is declared open with "
1457
+ "its reason", raised(combination_problems))
1458
+ control("the enumeration really judges the whole vocabulary, not a sample",
1459
+ f'{len(table("pairs")["vocabularies"]["kind"])}x'
1460
+ f'{len(table("pairs")["vocabularies"]["diagnosis"])}',
1461
+ "7x6")
1462
+ clean("and it finds at least one answer for a combination that has one",
1463
+ (lambda held: held if isinstance(held, list) and held and str(held[0]).startswith("RAISED ")
1464
+ else [] if held else ["misfire/wrong or insufficient above the bar has no answer"])(
1465
+ raised(lambda: acceptable_dispositions("misfire", "wrong or insufficient", True))))
1466
+ # The ten combinations this enumeration found open on 2026-11-12 are CLOSED: lane E's
1467
+ # `BELOW_BAR` is the §6.4 table's own below-bar row and now admits `none`, which is the one
1468
+ # disposition §7.2 allowed for both kinds. The declaration that named them went stale the moment
1469
+ # that landed and said so by failing, which is what it was for. Nothing declares an open
1470
+ # combination now, so these controls build their own rows: a control that indexes a live list
1471
+ # stops testing when the list empties, silently.
1472
+ control("no combination is declared open any more, so the clean row above is a real answer and "
1473
+ "not a declaration standing in for one",
1474
+ str("pending_empty" in table("pairs")), "False")
1475
+ held_plant = with_table(
1476
+ # The row's own shape, read from the table rather than guessed: `allowed` is a list of
1477
+ # `{disposition, requires?}`. Restricted to `correct` alone, the combination has nothing
1478
+ # left BELOW the bar — the §6.4 below-bar row does not admit `correct`, and that refusal is
1479
+ # PAIR_DISALLOWED, which reads no field but the bar. `place` would not do: it is refused
1480
+ # below the bar by a rule that also reads the destination, and this enumeration skips such
1481
+ # a combination on purpose, because then the emptiness could be the fixture's.
1482
+ "pairs", lambda t: [row.__setitem__("allowed", [{"disposition": "correct"}])
1483
+ for row in t["rows"]
1484
+ if row.get("kind") == "misfire"
1485
+ and row.get("diagnosis") == "wrong or insufficient"],
1486
+ lambda: raised(combination_problems))
1487
+ control("a combination with no acceptable disposition is reported by name, with the code that "
1488
+ "refuses every one §7.2 allows",
1489
+ "; ".join(held_plant),
1490
+ "COMBINATION_UNANSWERABLE misfire/wrong or insufficient/below bar")
1491
+ control("and the report says the refusal reads no other field, so the emptiness is the "
1492
+ "contract's and not this enumeration's fixture",
1493
+ "; ".join(held_plant), "which reads no other field")
1494
+ clean("while the same combination ABOVE the bar still has its answer, so the plant is the bar's "
1495
+ "own rule and not a broken table",
1496
+ [p for p in held_plant if "misfire/wrong or insufficient/above bar" in p])
1497
+ control("a declaration that has stopped being true is reported as stale, like every other "
1498
+ "allowlist here",
1499
+ "; ".join(with_table("pairs", lambda t: t.__setitem__("pending_empty", {
1500
+ "decided": None,
1501
+ "combinations": [{"kind": "misfire", "diagnosis": "redundant",
1502
+ "promotion_eligible": True}]}), lambda: raised(combination_problems))),
1503
+ "PENDING_EMPTY_STALE misfire/redundant/above bar")
1504
+ clean("an emptiness a structural rule causes is NOT reported as a contract defect: this "
1505
+ "enumeration fixes the other fields, so that one may be the fixture's",
1506
+ [p for p in raised(combination_problems) if "gap/gap" in p or p.startswith("RAISED ")])
1507
+
1508
+ # An adjudicated admission is an admission for §7.2 (§10.2: "a candidate that becomes admitted
1509
+ # goes through S7, S7b"), which `stage_propose` now reads; the legacy row's `place` condition is
1510
+ # where it mattered, so the pair is exercised from here as well.
1511
+ held_place = {**fx_proposal("unclassified", "unknown", "place", True, True),
1512
+ # Into the incubator, not a guide: §7.4's guide bar is a separate question and
1513
+ # would answer this control instead of the pair and the admission doing it.
1514
+ "destination": {"layer": "incubator", "carrier": "design/session-distill/ledger.json"},
1515
+ "names_situation_of_guide": False}
1516
+ control("the legacy row's place condition accepts an item admitted by adjudication, since the "
1517
+ "owner resolved the dispute",
1518
+ "; ".join(raised(lambda: problems(held_place)) or ["ACCEPTED"]), "ACCEPTED")
1519
+ control("while the same item NOT admitted is refused, so the condition is really being read",
1520
+ "; ".join(raised(lambda: problems({**held_place, "admitted": False})) or ["ACCEPTED"]),
1521
+ "PAIR_DISALLOWED")
1522
+
1523
+ # A destination is model output that reaches the owner's review page. The layer vocabulary and
1524
+ # the carrier rules were unchecked here until now: §7.4's rules read the layer, but no rule asked
1525
+ # whether it was a layer at all, so `nowhere` passed and a carrier carrying a newline and a
1526
+ # decision-shaped line could forge an owner's line in the rendered review.
1527
+ def dest_problems(destination, **over):
1528
+ """`destination_problems` with any exception returned as text.
1529
+
1530
+ A revert that removed the shape guard made `destination.get` raise on a string and killed the
1531
+ suite where it needed a named failure: a control that dies is not a control.
1532
+ """
1533
+ try:
1534
+ return destination_problems(destination, **over)
1535
+ except Exception as exc: # noqa: BLE001 - the exception IS the answer here
1536
+ return [f"RAISED {type(exc).__name__}: {exc}"]
1537
+
1538
+ def dest_src_line(fragment):
1539
+ """The line carrying `fragment`, or a placeholder naming its absence (never StopIteration)."""
1540
+ for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines():
1541
+ if fragment in line:
1542
+ return line.strip()
1543
+ return f"<no line carrying {fragment!r}>"
1544
+
1545
+ def dest(**over):
1546
+ held = {"layer": "guides", "carrier": "claude/guides/g.md"}
1547
+ held.update(over)
1548
+ return held
1549
+
1550
+ clean("a destination naming a §7.4 layer and a relative carrier is clean",
1551
+ destination_problems(dest()))
1552
+ clean("and so is every layer in §7.4's order, so the check cannot be passing by accident",
1553
+ [layer for layer in table("placement")["destinations"]["order"]
1554
+ if destination_problems(dest(layer=layer))])
1555
+ control("a layer outside §7.4's order is refused by name, with the order",
1556
+ "; ".join(destination_problems(dest(layer="nowhere"))), "LAYER_UNKNOWN")
1557
+ control("and the refusal lists the layers rather than saying only that it is wrong",
1558
+ "; ".join(destination_problems(dest(layer="nowhere"))), "enforcement, gates, hooks")
1559
+ control("a carrier carrying a newline is refused: a decision-shaped line after it could forge "
1560
+ "an owner's line in the rendered review",
1561
+ "; ".join(destination_problems(dest(carrier="g.md\nowner approved: yes"))),
1562
+ "DESTINATION_CARRIER_CONTROL")
1563
+ clean("and so is every other control character, not only the newline",
1564
+ [hex(code) for code in list(range(0x00, 0x20)) + list(range(0x7F, 0xA0))
1565
+ if not destination_problems(dest(carrier=f"g{chr(code)}md"))])
1566
+ control("a carrier with a `..` segment is refused",
1567
+ "; ".join(destination_problems(dest(carrier="../../etc/x"))),
1568
+ "DESTINATION_CARRIER_TRAVERSAL")
1569
+ clean("a carrier whose NAME merely contains two dots is not a traversal, since the rule is about "
1570
+ "a path segment", destination_problems(dest(carrier="claude/guides/a..b.md")))
1571
+ control("an absolute carrier is refused", "; ".join(destination_problems(dest(carrier="/etc/passwd"))),
1572
+ "DESTINATION_CARRIER_ABSOLUTE")
1573
+ control("and so is one starting at a home directory",
1574
+ "; ".join(destination_problems(dest(carrier="~/.claude/CLAUDE.md"))),
1575
+ "DESTINATION_CARRIER_ABSOLUTE")
1576
+ clean("a null carrier is clean: a ledger-only disposition carries none",
1577
+ destination_problems(dest(carrier=None)))
1578
+ control("a carrier that is not a string or null is refused by shape",
1579
+ "; ".join(destination_problems(dest(carrier=["g.md"]))), "DESTINATION_CARRIER_SHAPE")
1580
+ control("a destination that is not an object is refused by shape, rather than raising",
1581
+ "; ".join(dest_problems("guides")), "DESTINATION_SHAPE")
1582
+ clean("an absent destination is not a destination problem: whether one is required is §7.3's "
1583
+ "question, answered by its own rule", destination_problems(None))
1584
+ control("the refusal names the item and the field, so a reader can tell the proposal's "
1585
+ "destination from an alternative's",
1586
+ "; ".join(destination_problems(dest(layer="nowhere"), where="alternative.destination",
1587
+ item="k1: ")),
1588
+ "LAYER_UNKNOWN k1: alternative.destination.layer")
1589
+ control("and a proposal's own destination is held by `problems`, not only by this function",
1590
+ "; ".join(problems({**place, "destination": dest(layer="nowhere")})), "LAYER_UNKNOWN")
1591
+ control("the layers come from the table, so this module holds no second list",
1592
+ dest_src_line('held = table("placement")["destinations"]'),
1593
+ 'table("placement")["destinations"]')
1594
+
1595
+ # The wrapper that makes a dying control speak. Asserted from the source, because a suite that
1596
+ # ends in a traceback prints no control name at all and a revert trial then reads the traceback
1597
+ # as the control firing (the WP-12 review).
1598
+ # The WRAPPER's own source, not the file's. A scan of the whole file is satisfied by this
1599
+ # control's own text — the phrase it looks for appears in the line that looks for it — which is
1600
+ # how a planted mutation passed here before. The wrapper lives in `self_test` and this control
1601
+ # lives in `_self_test_body`, so asking `self_test` for its source excludes the control.
1602
+ # ---- release 1's scope (D-20261116-7853bc): no library file changes --------------------------------
1603
+ import ast
1604
+ vocab = vocabularies()["disposition"]
1605
+ equals("release 1 is the scope the module ships with", release_scope(), "release_1")
1606
+ equals("the dispositions that change a library file are §7.2's vocabulary less the ledger-only set and none",
1607
+ json.dumps(list(library_changing())), json.dumps(["place", "correct", "re-deliver", "reduce"]))
1608
+ equals("release 1 refuses each of them by name and accepts each of the rest",
1609
+ json.dumps({d: [p.split(":")[0] for p in release_problems(d)] for d in vocab}, sort_keys=True),
1610
+ json.dumps({"place": ["RELEASE_1_NO_LIBRARY_CHANGE place"], "correct": ["RELEASE_1_NO_LIBRARY_CHANGE correct"],
1611
+ "re-deliver": ["RELEASE_1_NO_LIBRARY_CHANGE re-deliver"],
1612
+ "reduce": ["RELEASE_1_NO_LIBRARY_CHANGE reduce"], "keep": [], "incubate": [], "drop": [],
1613
+ "none": []}, sort_keys=True))
1614
+ control("and an operation is refused under a disposition that changes nothing, too",
1615
+ "; ".join(release_problems("none", [{"type": "edit", "target": "g.md"}], where="k: ")),
1616
+ "RELEASE_1_NO_LIBRARY_CHANGE k: 1 operation(s) under 'none'")
1617
+ for role in ("propose", "review"):
1618
+ text = release_packet_text(role)
1619
+ equals(f"the {role} packet's release section names every refused disposition, the code and what is accepted",
1620
+ json.dumps([text.startswith("## This release changes no library file"),
1621
+ "place, correct, re-deliver, reduce" in text, "RELEASE_1_NO_LIBRARY_CHANGE" in text,
1622
+ "keep, incubate, drop, none" in text]), json.dumps([True, True, True, True]))
1623
+ with scoped("all"):
1624
+ under_all = ([release_problems(d, [{"type": "edit"}]) for d in vocab], release_packet_text(),
1625
+ release_packet_text("review"), list(release_accepts()))
1626
+ equals("under the design's scope nothing is refused, the packets say nothing and every disposition is accepted",
1627
+ json.dumps(under_all), json.dumps([[[] for _d in vocab], "", "", list(vocab)]))
1628
+ try:
1629
+ with scoped("all"):
1630
+ raise LookupError("planted")
1631
+ except LookupError:
1632
+ pass
1633
+ equals("and the scope is release 1 again after the block, an exception included", release_scope(), "release_1")
1634
+ control("an unknown scope is refused by name", "; ".join(raised(lambda: scoped("release_2").__enter__())),
1635
+ "RELEASE_SCOPE_UNKNOWN 'release_2'")
1636
+
1637
+ def answerable_in_release_1():
1638
+ """Every combination the contract answers, answered by a disposition release 1 accepts."""
1639
+ out = []
1640
+ for kind in vocabularies()["kind"]:
1641
+ for diagnosis in vocabularies()["diagnosis"]:
1642
+ for bar in (True, False):
1643
+ held = acceptable_dispositions(kind, diagnosis, bar)
1644
+ if held and not set(held) & set(release_accepts()):
1645
+ out.append(f"{kind}/{diagnosis}/{'above' if bar else 'below'}: only {sorted(held)}")
1646
+ return out
1647
+ clean("every combination the contract answers has an answer release 1 accepts, so refusing the four leaves no "
1648
+ "candidate unanswerable", answerable_in_release_1())
1649
+ with_table("pairs", lambda t: [row.__setitem__("allowed", [{"disposition": "re-deliver"}]) for row in t["rows"]
1650
+ if row["id"] == "not_delivered"],
1651
+ lambda: control("and a row left with only a disposition that changes a file is named",
1652
+ "; ".join(answerable_in_release_1()), "not delivered/covered/above: only ['re-deliver']"))
1653
+
1654
+ def scope_writers(sources):
1655
+ """Every REFERENCE to `scoped` outside a function SELF_TEST_FUNCTIONS names, as `file:line`: a call, an
1656
+ attribute read, a name, an imported alias, or the string a `getattr` would take. A reference is how a call
1657
+ through another name begins, so none stands outside a suite (Codex release-1 review F4)."""
1658
+ out = []
1659
+ for name, text in sorted(sources.items()):
1660
+ tree = ast.parse(text)
1661
+ # the names this file binds to placement itself: `placement`, and any alias it imports it under
1662
+ aliases = {"placement"} | {a.asname or a.name.split(".")[-1] for node in ast.walk(tree)
1663
+ if isinstance(node, (ast.Import, ast.ImportFrom))
1664
+ for a in node.names if a.name.split(".")[-1] == "placement"}
1665
+ own = name.endswith("placement.py")
1666
+
1667
+ def refers(child):
1668
+ # placement's own state and dict count as the switch: writing them is changing the scope
1669
+ if isinstance(child, ast.Attribute) and child.attr in ("_SCOPE", "__dict__") and not own:
1670
+ return (isinstance(child.value, ast.Name) and child.value.id in aliases) or \
1671
+ (not isinstance(child.value, ast.Name) and "placement" in ast.unparse(child.value))
1672
+ if isinstance(child, ast.Call) and getattr(child.func, "id", None) == "vars":
1673
+ return any(isinstance(arg, ast.Name) and arg.id in aliases for arg in child.args)
1674
+ if isinstance(child, ast.Call) and getattr(child.func, "attr", getattr(child.func, "id", None)) \
1675
+ == "import_module":
1676
+ return any(isinstance(arg, ast.Constant) and str(arg.value).endswith("placement")
1677
+ for arg in child.args)
1678
+ if isinstance(child, ast.Attribute) and child.attr == "scoped":
1679
+ return (isinstance(child.value, ast.Name) and child.value.id in aliases) or \
1680
+ (not isinstance(child.value, ast.Name) and "placement" in ast.unparse(child.value))
1681
+ if isinstance(child, ast.ImportFrom):
1682
+ return (child.module or "").split(".")[-1] == "placement" and any(
1683
+ a.name in ("scoped", "*") for a in child.names)
1684
+ if isinstance(child, ast.Call) and getattr(child.func, "id", None) == "getattr":
1685
+ return any(isinstance(arg, ast.Constant) and arg.value == "scoped" for arg in child.args[1:2])
1686
+ return own and isinstance(child, ast.Name) and child.id == "scoped"
1687
+
1688
+ def walk(node, inside):
1689
+ for child in ast.iter_child_nodes(node):
1690
+ now = inside or (isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef))
1691
+ and child.name in SELF_TEST_FUNCTIONS)
1692
+ if refers(child) and not now:
1693
+ out.append(f"{name}:{child.lineno}")
1694
+ walk(child, now)
1695
+ walk(tree, False)
1696
+ return out
1697
+ # every Python file the driver ships beside it, its grammar package among them (release 1's third confirmation
1698
+ # review: the walk had covered runlib/ and the driver only)
1699
+ shipped = {str(p.relative_to(HERE)): p.read_text(encoding="utf-8")
1700
+ for p in sorted(list((HERE / "runlib").glob("*.py")) + list((HERE / "grammar").glob("*.py"))
1701
+ + [HERE / "distill.py"])}
1702
+ equals("the walk reads the driver and its grammar package beside runlib",
1703
+ json.dumps([sorted(n for n in shipped if n.startswith("grammar/")), "distill.py" in shipped,
1704
+ "runlib/placement.py" in shipped]),
1705
+ json.dumps([["grammar/__init__.py", "grammar/owner_lines.py"], True, True]))
1706
+ inside = [n for n, t in shipped.items() if ".scoped(" in t]
1707
+ equals("the suites that run the design's scope call it, eight of them, and this one", len(inside), 9)
1708
+ clean("no shipped code calls `scoped` outside a self-test", scope_writers(shipped))
1709
+ equals("and a call outside a self-test is named, through an alias, a captured callable, getattr or a helper "
1710
+ "whose name merely holds self_test", json.dumps(scope_writers({
1711
+ "a.py": "def run():\n with placement.scoped('all'):\n pass\n",
1712
+ "b.py": "from runlib.placement import scoped as switch\n",
1713
+ "c.py": "switch = placement.scoped\n",
1714
+ "d.py": "def run():\n getattr(placement, 'scoped')('all')\n",
1715
+ "e.py": "def run_self_test_helper():\n placement.scoped('all')\n",
1716
+ "f.py": "from runlib import placement as p\ndef run():\n p.scoped('all')\n",
1717
+ "g.py": "def run(scoped, x):\n return scoped + x.scoped\n",
1718
+ "h.py": "def run():\n placement._SCOPE[0] = 'all'\n vars(placement)['_SCOPE'][0] = 'all'\n",
1719
+ "i.py": "def run():\n importlib.import_module('runlib.placement')\n placement.__dict__.clear()\n"})),
1720
+ json.dumps(["a.py:2", "b.py:1", "c.py:1", "d.py:2", "e.py:2", "f.py:3", "h.py:2", "h.py:3", "i.py:2",
1721
+ "i.py:3"]))
1722
+ equals("a stack is a suite's only with one of its functions on it",
1723
+ json.dumps([self_test_on_stack(["run", "main", "<module>"]), self_test_on_stack(["run_self_test_x"]),
1724
+ self_test_on_stack(["helper", "_self_test_body", "<module>"])]), json.dumps([False, False, True]))
1725
+ import threading
1726
+ outside = []
1727
+
1728
+ def from_another_stack():
1729
+ try:
1730
+ scoped("all").__enter__()
1731
+ outside.append("entered")
1732
+ except Refused as exc:
1733
+ outside.append(str(exc).split(":")[0])
1734
+ worker = threading.Thread(target=from_another_stack)
1735
+ worker.start()
1736
+ worker.join()
1737
+ _SCOPE[0] = "release_1" # had the guard let it in, the scope is restored here before anything else runs
1738
+ equals("and `scoped` called from a stack with no suite on it is refused by name", json.dumps(outside),
1739
+ json.dumps(["RELEASE_SCOPE_OUTSIDE_SELF_TEST"]))
1740
+
1741
+ import inspect
1742
+ wrapper_text = inspect.getsource(self_test)
1743
+ control("a control that dies names itself, since a traceback is not a control firing",
1744
+ next((line.strip() for line in wrapper_text.splitlines()
1745
+ if "died after" in line and "print(" in line), "<no such line>"),
1746
+ "self-test [FAIL] the suite died after")
1747
+ control("and the wrapper is what the entry point runs, so the body cannot be called around it",
1748
+ next((line.strip() for line in wrapper_text.splitlines()
1749
+ if "_self_test_body(" in line), "<no such line>"),
1750
+ "return _self_test_body(failures, ran)")
1751
+
1752
+ reporting.append(True)
1753
+ if failures:
1754
+ for name, detail in failures:
1755
+ print(f"placement --self-test [FAIL] {name}: {detail}", file=sys.stderr)
1756
+ print(f"placement --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
1757
+ return 1
1758
+ print(f"placement --self-test: OK ({len(ran)} controls: §7.2's pairs and their conditions, §7.3's "
1759
+ f"structural rules and §10.4's ledger-only rule, §7.4's six decidable restrictions each with "
1760
+ f"its clean counterpart, and the two authorities of §7.4 held against the section's own list "
1761
+ f"item by item in both directions - every rule and bar from its table or the canonical text, "
1762
+ f"and each planted violation refused by name)")
1763
+ return 0
1764
+
1765
+
1766
+ if __name__ == "__main__":
1767
+ if sys.argv[1:2] == ["--self-test"]:
1768
+ sys.exit(self_test())
1769
+ sys.exit("usage: placement.py --self-test")