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,1162 @@
1
+ #!/usr/bin/env python3
2
+ """§11's exposure predicate, one branch per table row (WP-21 commit 7).
3
+
4
+ Design §11: an occasion's exposure to the applied item "must be shown BEFORE the decision or action
5
+ the occasion concerns, not before the session began", and what counts as shown depends on what was
6
+ applied — a created unit's delivered version, a deleted unit's absence from the pin, a route's entry,
7
+ an executable's invocation path and hash, the installer's receipt digests, a deleted executable's
8
+ effective resolution, a personal layer's identity and loading record.
9
+
10
+ `tables/exposure_rules.json` holds those branches as data with the design clause each comes from;
11
+ this module picks the one row that applies and answers. It decides nothing a row does not state,
12
+ which is why the predicate's branch set can be held against §11's (done-when 12) instead of trusted.
13
+
14
+ **Three verdicts, and the reason is in the table's own `$comment_verdicts`.** §11's sentence names
15
+ two — `eligible`, `exposure_unknown` — while the plan's O9 fixtures distinguish an occasion shown NOT
16
+ exposed (an installer change with the old installer on the receipt) from one that cannot be shown (no
17
+ resolution recorded). `not_exposed` is the third, and `runlib/measures.py`, which admits only two,
18
+ receives those occasions as a COUNT rather than as instances: calling them eligible would count an
19
+ occasion the item could not reach, and calling them unknown would hold the window pending forever on
20
+ a question that has been answered.
21
+
22
+ **The ordering rule is the occasion's, not this module's.** §11 says exposure must be shown before
23
+ the decision the occasion concerns. An occasion record carries `at_record`, and every fact offered
24
+ as exposure carries the record it was observed at; a fact observed AFTER the decision is not
25
+ exposure, and this module refuses it by name rather than reading it.
26
+
27
+ exposure.py --self-test
28
+ """
29
+ import ast
30
+ import json
31
+ import pathlib
32
+ import sys
33
+
34
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
35
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
36
+ from runlib import measures # noqa: E402
37
+ from runlib.records import Refused # noqa: E402
38
+
39
+ HERE = pathlib.Path(__file__).resolve().parents[1]
40
+ TABLE_PATH = HERE / "tables" / "exposure_rules.json"
41
+ # §11's own two, which `measures` admits, and the third the O9 fixtures distinguish.
42
+ ELIGIBLE, NOT_EXPOSED, UNKNOWN = "eligible", "not_exposed", "exposure_unknown"
43
+ VERDICTS = (ELIGIBLE, NOT_EXPOSED, UNKNOWN)
44
+ _TABLE = {}
45
+
46
+
47
+ def table():
48
+ if not _TABLE:
49
+ _TABLE.update(json.loads(TABLE_PATH.read_text(encoding="utf-8")))
50
+ return _TABLE
51
+
52
+
53
+ def rules():
54
+ return tuple(table()["rules"])
55
+
56
+
57
+ def branches():
58
+ return tuple(row["id"] for row in rules())
59
+
60
+
61
+ def table_problems():
62
+ """What is wrong with the rule table itself, by name."""
63
+ problems, rows = [], rules()
64
+ if not rows:
65
+ problems.append("RULE_SET_EMPTY: a predicate over no rule answers nothing")
66
+ return problems
67
+ seen, verdicts = set(), table().get("verdicts") or {}
68
+ if sorted(verdicts) != sorted(VERDICTS):
69
+ problems.append(f"VERDICT_SET: the table names {', '.join(sorted(verdicts))}, the code "
70
+ f"{', '.join(sorted(VERDICTS))}")
71
+ for row in rows:
72
+ name = row.get("id")
73
+ if not name:
74
+ problems.append("RULE_UNNAMED: a row with no id")
75
+ continue
76
+ if name in seen:
77
+ problems.append(f"RULE_REPEATED {name}: two rows claiming one branch")
78
+ seen.add(name)
79
+ for field in ("applies_to", "requires", "shown_when", "design", "$comment"):
80
+ if not row.get(field):
81
+ problems.append(f"RULE_INCOMPLETE {name}: no {field}")
82
+ if row.get("unknown_when"):
83
+ try:
84
+ _unknown(row, {"facts": {}})
85
+ except Refused as exc:
86
+ problems.append(f"RULE_UNKNOWN_UNREAD {name}: {exc}")
87
+ # Every fact a predicate READS must be declared, as required or as optional. Undeclared, an
88
+ # absent fact compares equal to None and the branch answers from nothing: `pin_units: []`
89
+ # alone was certified eligible because `removed_unit` and `merged_unit` were neither
90
+ # required nor declared optional.
91
+ declared = set(row.get("requires") or ())
92
+ for held_names in (row.get("requires_by_operation") or {}).values():
93
+ declared |= set(held_names)
94
+ declared |= set(row.get("optional_facts") or ())
95
+ for field in ("shown_when", "unknown_when"):
96
+ if not row.get(field):
97
+ continue
98
+ try:
99
+ _eval(row[field], {}, f"{name}.{field}")
100
+ except Refused as exc:
101
+ problems.append(f"RULE_PREDICATE_UNREADABLE {name}: {exc}")
102
+ continue
103
+ undeclared = sorted(predicate_names(row[field]) - declared)
104
+ if undeclared:
105
+ problems.append(f"RULE_FACT_UNDECLARED {name}.{field}: reads "
106
+ f"{', '.join(undeclared)}, which the row declares neither in "
107
+ f"requires/requires_by_operation nor in optional_facts — an "
108
+ f"undeclared fact answers from its own absence")
109
+ for operation in (row.get("requires_by_operation") or {}):
110
+ if operation not in ((row.get("applies_to") or {}).get("operation") or ()):
111
+ problems.append(f"RULE_OPERATION_UNCLAIMED {name}: requires_by_operation names "
112
+ f"{operation}, which this row does not apply to")
113
+ if not (row.get("applies_to") or {}).get("operation") and not (row.get("applies_to") or {}).get("role"):
114
+ problems.append(f"RULE_APPLIES_TO_NOTHING {name}: a row answering for no operation and "
115
+ f"no role is never picked")
116
+ for key in (row.get("applies_to") or {}):
117
+ if key not in precedence():
118
+ problems.append(f"RULE_KEY_UNRANKED {name}: applies_to names {key}, which the "
119
+ f"table's precedence does not rank, so two rows matching on it "
120
+ f"could not be separated")
121
+ if not precedence():
122
+ problems.append("PRECEDENCE_UNSTATED: with no key order, a row matching one key and a row "
123
+ "matching another are separated by their position in the file")
124
+ return problems
125
+
126
+
127
+ def precedence():
128
+ """The applies_to keys, most specific first, as the table declares them."""
129
+ return tuple(table().get("precedence") or ())
130
+
131
+
132
+ def rule_for(occasion):
133
+ """The one row that answers for this occasion, or None. Refuses an ambiguous match.
134
+
135
+ A role is more specific than an operation: a DELETED executable is answered by
136
+ `executable_deleted`, not by `delete_or_merge`, because §11 writes that branch separately.
137
+
138
+ Counting MATCHED KEYS was not enough, and round 2 found what that let through: an occasion of
139
+ operation `edit` and role `installer` matches `create_or_edit` on its one key and
140
+ `executable_installer` on its one key, and the loop kept whichever came FIRST in the file —
141
+ `create_or_edit`, so an installer's exposure was judged by a library unit's rule. The weights
142
+ come from the table's `precedence` now, and a genuine tie is REFUSED rather than broken by
143
+ position: two rows claiming one occasion is a table defect, not something to answer by guessing.
144
+ """
145
+ operation, role = occasion.get("operation"), occasion.get("role")
146
+ order = precedence()
147
+ asked = {"operation": operation, "role": role}
148
+ matched = []
149
+ for row in rules():
150
+ applies = row.get("applies_to") or {}
151
+ wants = {key: applies.get(key) for key in order}
152
+ if not any(wants.values()):
153
+ continue
154
+ if any(value and asked.get(key) not in value for key, value in wants.items()):
155
+ continue
156
+ # Most specific first: more matched keys outranks fewer, and among equal counts a row
157
+ # matched on an EARLIER key in the declared precedence outranks one matched on a later key.
158
+ weight = tuple(1 if wants.get(key) else 0 for key in order)
159
+ matched.append((weight, row))
160
+ if not matched:
161
+ return None
162
+ rank = lambda held: (sum(held), held) # noqa: E731
163
+ best = max(matched, key=lambda held: rank(held[0]))
164
+ tied = sorted(row["id"] for weight, row in matched if rank(weight) == rank(best[0]))
165
+ if len(tied) > 1:
166
+ raise Refused(f"EXPOSURE_RULE_AMBIGUOUS {occasion.get('locator')}: {', '.join(tied)} claim "
167
+ f"one occasion (operation={operation!r} role={role!r}) at the same "
168
+ f"specificity, and the table's precedence {list(order)} does not separate "
169
+ f"them")
170
+ return best[1]
171
+
172
+
173
+ def _is_position(value):
174
+ """A record ordinal: an integer, and not a boolean wearing one's type."""
175
+ return isinstance(value, int) and not isinstance(value, bool)
176
+
177
+
178
+ def ordering_problems(occasion, required=()):
179
+ """Facts offered as exposure that were observed at or after the decision, by name.
180
+
181
+ §11: exposure must be shown BEFORE the decision or action the occasion concerns. A fact observed
182
+ after it is not exposure, and reading it would answer the question with evidence from the wrong
183
+ side of the decision.
184
+ """
185
+ at = occasion.get("at_record")
186
+ if at is None:
187
+ return [f"OCCASION_UNPOSITIONED {occasion.get('locator')}: the occasion records no position, "
188
+ f"so 'before the decision' has nothing to be before"]
189
+ if not _is_position(at):
190
+ return [f"OCCASION_POSITION_INVALID {occasion.get('locator')}: its position {at!r} is not a "
191
+ f"record ordinal (an integer), so nothing can be shown to precede it"]
192
+ problems = []
193
+ for name, held in sorted((occasion.get("facts") or {}).items()):
194
+ if isinstance(held, dict) and "at_record" in held:
195
+ # A positioned fact is an envelope `{value, at_record}`, and both halves are the claim.
196
+ # One with no `value` was read as its own dictionary — two envelopes holding nothing
197
+ # compared equal and certified `eligible` — and a position that is text orders by
198
+ # spelling, so '11' preceded '2' (the round-5 review). Either is a fact nobody can read.
199
+ if "value" not in held:
200
+ problems.append(f"FACT_VALUE_ABSENT {occasion.get('locator')} {name}: the fact "
201
+ f"records a position and no value, so there is nothing the "
202
+ f"predicate could compare")
203
+ continue
204
+ if not _is_position(held["at_record"]):
205
+ problems.append(f"FACT_POSITION_INVALID {occasion.get('locator')} {name}: its "
206
+ f"position {held['at_record']!r} is not a record ordinal (an "
207
+ f"integer), so whether it precedes the decision cannot be shown")
208
+ continue
209
+ if not isinstance(held, dict) or "at_record" not in held:
210
+ # A fact the ANSWER rests on must say where it was observed. An unpositioned one used to
211
+ # be skipped, so an occasion could be certified eligible with no evidence at all that
212
+ # its facts precede the decision — the ordering rule simply had nothing to read (the
213
+ # round-3 review). A fact the rule does not require is not part of the answer, and is
214
+ # not held to it.
215
+ if name in (required or ()):
216
+ problems.append(f"FACT_UNPOSITIONED {occasion.get('locator')} {name}: the answer "
217
+ f"rests on this fact and it records no position, so whether it was "
218
+ f"observed before the decision cannot be shown")
219
+ continue
220
+ if held["at_record"] >= at:
221
+ problems.append(f"FACT_AFTER_DECISION {occasion.get('locator')} {name}: observed at "
222
+ f"record {held['at_record']} and the decision is at {at}, so it is not "
223
+ f"exposure to it")
224
+ return problems
225
+
226
+
227
+ # ─── The predicate itself ────────────────────────────────────────────────────────────────────────
228
+ # `shown_when` and `unknown_when` are EXECUTED, over a grammar small enough to read in one sitting.
229
+ # They used to be prose beside a branch that dispatched on the row's id, and round 2 showed what
230
+ # that costs: replacing `create_or_edit.shown_when` with `False` left every answer unchanged, so
231
+ # the table described the predicate without being it. The only way a declaration cannot drift from
232
+ # the code is for the code to have no second copy to drift from.
233
+ #
234
+ # What the grammar admits: names (facts), the constants None/True/False and literal strings and
235
+ # numbers, `and`/`or`/`not`, the comparisons `== != is is not in not in`, and tuple and list
236
+ # literals. No calls, no attributes, no subscripts, no arithmetic — a predicate that needed one
237
+ # would be a branch in code again, and the table would have stopped being the authority.
238
+ _EVAL_COMPARISONS = {ast.Eq: lambda a, b: a == b, ast.NotEq: lambda a, b: a != b,
239
+ ast.Is: lambda a, b: a is b, ast.IsNot: lambda a, b: a is not b,
240
+ ast.In: lambda a, b: a in (b if b is not None else ()),
241
+ ast.NotIn: lambda a, b: a not in (b if b is not None else ())}
242
+
243
+
244
+ def _eval(expression, facts, where):
245
+ """The expression's truth over `facts`, or Refused if it is outside the grammar."""
246
+ def refuse(node):
247
+ return Refused(f"EXPOSURE_PREDICATE_UNREADABLE {where}: {expression!r} uses "
248
+ f"{type(node).__name__}, which this module does not execute; a predicate "
249
+ f"outside the grammar would have to be a branch in code, and then the table "
250
+ f"would no longer be the authority")
251
+
252
+ def value(node):
253
+ if isinstance(node, ast.BoolOp):
254
+ held = [value(part) for part in node.values]
255
+ return all(held) if isinstance(node.op, ast.And) else any(held)
256
+ if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
257
+ return not value(node.operand)
258
+ if isinstance(node, ast.Compare):
259
+ left = value(node.left)
260
+ for operator, right in zip(node.ops, node.comparators):
261
+ held = _EVAL_COMPARISONS.get(type(operator))
262
+ if held is None:
263
+ raise refuse(operator)
264
+ right_value = value(right)
265
+ if not held(left, right_value):
266
+ return False
267
+ left = right_value
268
+ return True
269
+ if isinstance(node, ast.Constant):
270
+ return node.value
271
+ if isinstance(node, (ast.Tuple, ast.List)):
272
+ return tuple(value(part) for part in node.elts)
273
+ if isinstance(node, ast.Name):
274
+ return facts.get(node.id)
275
+ raise refuse(node)
276
+
277
+ try:
278
+ tree = ast.parse(expression, mode="eval")
279
+ except SyntaxError as exc:
280
+ raise Refused(f"EXPOSURE_PREDICATE_UNPARSED {where}: {expression!r} ({exc})") from exc
281
+ return bool(value(tree.body))
282
+
283
+
284
+ def predicate_names(expression):
285
+ """Every fact name an expression reads. Derived, so a declaration cannot omit one silently."""
286
+ try:
287
+ tree = ast.parse(expression, mode="eval")
288
+ except SyntaxError:
289
+ return set()
290
+ return {node.id for node in ast.walk(tree) if isinstance(node, ast.Name)}
291
+
292
+
293
+ def predicate_reads(row):
294
+ """Every fact name the row's own predicates READ, taken from their source.
295
+
296
+ Derived rather than listed: `requires` is the floor the answer cannot be given without, and the
297
+ predicate reads more than that. An OPTIONAL fact the predicate reads decides the answer when it
298
+ is supplied — `required_replacement` turned `exposure_unknown` into `eligible` — so giving it
299
+ without a position was a way past the before-the-decision rule (the round-4 review).
300
+ """
301
+ held = set()
302
+ for expression in (row.get("shown_when"), row.get("unknown_when")):
303
+ if expression:
304
+ # The names come from the one reader that already parses these expressions, so this
305
+ # cannot disagree with what the predicate actually reads.
306
+ held |= set(predicate_names(str(expression)))
307
+ return held
308
+
309
+
310
+ def positioned_facts(row, occasion):
311
+ """The facts this answer must have a position for: what the predicate reads and the occasion gave.
312
+
313
+ Optionality says whether a fact must EXIST. It says nothing about the timing of one that was
314
+ supplied and is read, which is what the ordering rule is for.
315
+ """
316
+ held = set(required_facts(row, occasion))
317
+ supplied = set((occasion.get("facts") or {}))
318
+ return sorted(held | (predicate_reads(row) & supplied))
319
+
320
+
321
+ def required_facts(row, occasion):
322
+ """The facts this row's predicate cannot be shown without, for THIS occasion's operation.
323
+
324
+ `requires` is the row's floor; `requires_by_operation` adds what a particular operation needs.
325
+ A merge needs the unit it merged into, a plain delete does not — and with neither required, an
326
+ occasion carrying only `pin_units: []` was certified eligible because every absent fact
327
+ compared equal to None. An absent fact is 'cannot be shown', which is `exposure_unknown`.
328
+ """
329
+ held = list(row.get("requires") or ())
330
+ by_operation = row.get("requires_by_operation") or {}
331
+ for name in by_operation.get(occasion.get("operation"), ()):
332
+ if name not in held:
333
+ held.append(name)
334
+ return held
335
+
336
+
337
+ def _facts_of(occasion):
338
+ """Every fact the occasion carries, by name, with positioned facts unwrapped."""
339
+ return {name: _value(occasion, name) for name in (occasion.get("facts") or {})}
340
+
341
+
342
+ def _value(occasion, name):
343
+ """One fact's value, whether it is a bare value or a positioned `{value, at_record}`."""
344
+ held = (occasion.get("facts") or {}).get(name)
345
+ if isinstance(held, dict) and "value" in held:
346
+ return held["value"]
347
+ return held
348
+
349
+
350
+ def verdict(occasion):
351
+ """`{verdict, rule, why}` for one occasion. Refuses an occasion no rule answers for.
352
+
353
+ The rule's `requires` decides answerability: a required fact absent means the question cannot be
354
+ shown either way, which is `exposure_unknown` — never `not_exposed`. That is the distinction the
355
+ O9 fixtures turn on, and reading an absent fact as a negative answer is the mistake §11's
356
+ 'cannot be shown' clause exists to prevent.
357
+ """
358
+ row = rule_for(occasion)
359
+ if row is None:
360
+ raise Refused(f"EXPOSURE_RULE_ABSENT {occasion.get('locator')}: no §11 branch answers for "
361
+ f"operation={occasion.get('operation')!r} role={occasion.get('role')!r}")
362
+ held = ordering_problems(occasion, positioned_facts(row, occasion))
363
+ if held:
364
+ return {"verdict": UNKNOWN, "rule": row["id"], "why": "; ".join(held)}
365
+ facts = _facts_of(occasion)
366
+ missing = [name for name in required_facts(row, occasion) if facts.get(name) is None]
367
+ if missing:
368
+ return {"verdict": UNKNOWN, "rule": row["id"],
369
+ "why": f"EXPOSURE_FACT_ABSENT {', '.join(missing)}: the branch cannot be shown "
370
+ f"either way, so the occasion is carried rather than answered"}
371
+ # A row's `unknown_when` is read BEFORE its `shown_when`: §11 writes the unknown case into two
372
+ # of its branches itself ("a transaction begun or finished by another installer version, or an
373
+ # unbound one, is exposure_unknown"), and a condition like that answered as `not_exposed` would
374
+ # say the item could not have fired where the design says nobody knows. The field had no reader
375
+ # for one commit, which is the label-nobody-reads trap in its own right.
376
+ #
377
+ # Both conditions are the TABLE's expressions, executed. `_unknown` and `_shown` are consulted
378
+ # for the sentence a reader needs and for nothing else: they no longer decide, so a row whose
379
+ # condition is edited changes the answer.
380
+ if row.get("unknown_when"):
381
+ if _eval(row["unknown_when"], facts, f"{row['id']}.unknown_when"):
382
+ return {"verdict": UNKNOWN, "rule": row["id"], "why": _unknown(row, occasion)[1]}
383
+ shown = _eval(row["shown_when"], facts, f"{row['id']}.shown_when")
384
+ return {"verdict": ELIGIBLE if shown else NOT_EXPOSED, "rule": row["id"],
385
+ "why": _shown(row, occasion)[1]}
386
+
387
+
388
+ def _unknown(row, occasion):
389
+ """The sentence for this row's unknown condition, when it holds.
390
+
391
+ The table's `unknown_when` decides; this says it in words. The boolean it returns is the
392
+ SENTENCE's subject, read by `table_problems` to show the two agree — never by `verdict`, which
393
+ executes the expression. One decider, one explainer.
394
+ """
395
+ get = lambda name: _value(occasion, name) # noqa: E731
396
+ name = row["id"]
397
+ if name == "executable_installer":
398
+ begun = get("begun_by_installer_digest")
399
+ if begun is not None and begun != get("applied_sha256"):
400
+ return True, (f"the receipt says the transaction was begun by {str(begun)[:12]}… and "
401
+ f"finished by another version, so §11 shows nobody which version the "
402
+ f"session was exposed to")
403
+ return False, ""
404
+ if name == "executable_deleted":
405
+ if get("resolved_path") is None and get("resolved_sha256") is None:
406
+ return True, "the occasion recorded no resolution, so §11's exposure cannot be shown"
407
+ return False, ""
408
+ if name == "personal":
409
+ if get("loading_record") is None:
410
+ return True, "the host recorded no loading, so whether the layer was loaded is unknown"
411
+ return False, ""
412
+ raise Refused(f"EXPOSURE_UNKNOWN_UNIMPLEMENTED {name}: the table declares an unknown condition "
413
+ f"this module does not read, so the field would have no reader")
414
+
415
+
416
+ def _shown(row, occasion):
417
+ """The sentence a reader needs for this row, and the subject of that sentence.
418
+
419
+ As with `_unknown`: the table's `shown_when` is what `verdict` executes. This function explains
420
+ the answer in the words of the facts, and `table_problems` holds its boolean against the
421
+ executed expression for every generated fixture, so an explanation that says the opposite of
422
+ the answer is a named failure rather than a surprise in a report.
423
+ """
424
+ get = lambda name: _value(occasion, name) # noqa: E731
425
+ name = row["id"]
426
+ if name == "create_or_edit":
427
+ held = get("delivered_version") == get("applied_version")
428
+ return held, (f"the delivered version {str(get('delivered_version'))[:12]}… "
429
+ f"{'is' if held else 'is not'} the applied one")
430
+ if name == "delete_or_merge":
431
+ units = get("pin_units") or []
432
+ removed_absent = get("removed_unit") not in units
433
+ merged = get("merged_unit")
434
+ merged_present = merged is None or merged in units
435
+ held = removed_absent and merged_present
436
+ return held, (f"the pin {'does not hold' if removed_absent else 'still holds'} the removed "
437
+ f"unit and {'holds' if merged_present else 'does not hold'} the merged one")
438
+ if name == "route":
439
+ held = get("route_entry") in (get("pin_routes") or []) and \
440
+ get("routed_unit") in (get("pin_units") or [])
441
+ return held, ("the pin shows the route entry and the unit it reaches" if held
442
+ else "the pin shows no route entry reaching the unit")
443
+ if name == "executable_invoked":
444
+ held = (get("invocation_path") == get("applied_path")
445
+ and get("invocation_sha256") == get("applied_sha256"))
446
+ return held, (f"the invocation names {str(get('invocation_path'))} at "
447
+ f"{str(get('invocation_sha256'))[:12]}…, "
448
+ f"{'the applied artifact' if held else 'not the applied artifact'}")
449
+ if name == "executable_compiler":
450
+ held = get("compiler_digest") == get("applied_sha256")
451
+ return held, (f"the snapshot records compiler digest {str(get('compiler_digest'))[:12]}…, "
452
+ f"{'the applied version' if held else 'another version'}")
453
+ if name == "executable_installer":
454
+ begun = get("begun_by_installer_digest")
455
+ held = (get("installer_digest") == get("applied_sha256")
456
+ and begun in (None, get("applied_sha256")))
457
+ return held, (f"the receipt names installer {str(get('installer_digest'))[:12]}… and "
458
+ f"{'no other beginner' if begun is None else 'beginner ' + str(begun)[:12] + '…'}")
459
+ if name == "executable_deleted":
460
+ resolved = get("resolved_sha256")
461
+ replacement = get("required_replacement")
462
+ held = (resolved != get("removed_sha256") and resolved != get("fallback_sha256")
463
+ and (replacement is None or resolved == replacement))
464
+ return held, (f"the effective resolution is {str(resolved)[:12]}…, "
465
+ f"{'neither the removed artifact nor an older carrier' if held else 'the removed artifact or an older carrier'}")
466
+ if name == "personal":
467
+ held = get("layer_sha256") == get("applied_sha256") and get("loading_record") is True
468
+ return held, (f"the layer's identity {'matches' if get('layer_sha256') == get('applied_sha256') else 'does not match'} "
469
+ f"and the host's record says {'loaded' if get('loading_record') is True else 'not loaded'}")
470
+ raise Refused(f"EXPOSURE_BRANCH_UNIMPLEMENTED {name}: the table names a branch this module does "
471
+ f"not answer, so the predicate is narrower than its own table")
472
+
473
+
474
+ def instances_for(expected_id, occasions, basis):
475
+ """`{instances, not_exposed, verdicts}` — what `measures.derive_resolution` may be handed.
476
+
477
+ The `not_exposed` occasions are COUNTED and listed, never passed on as instances: `measures`
478
+ admits two exposure values, and either choice for a not-exposed occasion is wrong in a different
479
+ direction. The count is what makes the exclusion visible in the run record.
480
+ """
481
+ instances, excluded, held = [], [], {}
482
+ for occasion in occasions or ():
483
+ answer = verdict(occasion)
484
+ held[occasion.get("locator")] = answer
485
+ if answer["verdict"] == NOT_EXPOSED:
486
+ excluded.append({"locator": occasion.get("locator"), "rule": answer["rule"],
487
+ "why": answer["why"]})
488
+ continue
489
+ instances.append({"expected_id": expected_id,
490
+ "occasion_locator": occasion.get("locator"),
491
+ "exposure": answer["verdict"],
492
+ "verdict": occasion.get("judged") or "not_observed",
493
+ "basis": basis,
494
+ "evidence_ids": occasion.get("evidence_ids") or []})
495
+ return {"instances": instances, "not_exposed": excluded, "verdicts": held}
496
+
497
+
498
+ def resolution_for(expected_id, occasions, basis):
499
+ """The window resolution, through `measures.derive_resolution`, with the exclusions beside it.
500
+
501
+ The resolution half is WP-08's and stays there: this module decides exposure and hands it over.
502
+ """
503
+ built = instances_for(expected_id, occasions, basis)
504
+ held = measures.derive_resolution(built["instances"], basis)
505
+ return {**held, "not_exposed": built["not_exposed"],
506
+ "counts": {**held["counts"], "not_exposed": len(built["not_exposed"])}}
507
+
508
+
509
+ def fixture_cases():
510
+ """Three cases per rule, generated FROM the rule: shown, shown absent, unanswerable.
511
+
512
+ Done-when 7 asks for a generated fixture per rule. Generated rather than written out, so a branch
513
+ added to the table without its cases cannot go untested — `fixture_problems` fails on a rule
514
+ whose generated cases do not come back with the verdicts their construction implies.
515
+ """
516
+ cases = []
517
+ for row in rules():
518
+ name = row["id"]
519
+ shown, absent, unknown = _fixture_facts(name)
520
+ applies = row.get("applies_to") or {}
521
+ operation = (applies.get("operation") or [None])[0]
522
+ role = (applies.get("role") or [None])[0]
523
+ # The 'absent' case is NOT_EXPOSED only where the rule HAS such an answer. The installer
524
+ # branch does not: §11 says a transaction whose receipt names another version is unknown, so
525
+ # for that rule every state is eligible or unknown, and a generator that assumed three
526
+ # verdicts was asserting an answer the design does not have (the round-3 review). Read from
527
+ # the row's own unknown condition over the case's own facts.
528
+ held_absent = (UNKNOWN if row.get("unknown_when")
529
+ and _eval(row["unknown_when"], absent, f"{name}.unknown_when")
530
+ else NOT_EXPOSED)
531
+ for label, facts, want in (("shown", shown, ELIGIBLE), ("absent", absent, held_absent),
532
+ ("unanswerable", unknown, UNKNOWN)):
533
+ # Every fact is POSITIONED before the decision, because that is what the answer now
534
+ # requires: a fact the rule rests on says where it was observed, and a generated
535
+ # fixture that left it bare would be asking for an answer §11 does not allow.
536
+ cases.append({"id": f"F-EXP-{name}-{label}", "rule": name, "expect": want,
537
+ "occasion": {"locator": f"{name}/{label}", "operation": operation,
538
+ "role": role, "at_record": 10,
539
+ "facts": {held: {"value": value, "at_record": 5}
540
+ for held, value in facts.items()}}})
541
+ return cases
542
+
543
+
544
+ APPLIED, OTHER = "ap" + "p" * 62, "ot" + "h" * 62
545
+
546
+
547
+ def _fixture_facts(name):
548
+ """The three fact sets for one rule: shown, shown absent, and one a required fact is missing from."""
549
+ if name == "create_or_edit":
550
+ return ({"delivered_version": APPLIED, "applied_version": APPLIED},
551
+ {"delivered_version": OTHER, "applied_version": APPLIED},
552
+ {"applied_version": APPLIED})
553
+ if name == "delete_or_merge":
554
+ return ({"pin_units": ["u-kept", "u-merged"], "removed_unit": "u-gone",
555
+ "merged_unit": "u-merged"},
556
+ {"pin_units": ["u-gone", "u-merged"], "removed_unit": "u-gone",
557
+ "merged_unit": "u-merged"},
558
+ {"removed_unit": "u-gone", "merged_unit": "u-merged"})
559
+ if name == "route":
560
+ return ({"pin_routes": ["r-1"], "pin_units": ["u-1"], "route_entry": "r-1",
561
+ "routed_unit": "u-1"},
562
+ {"pin_routes": ["r-1"], "pin_units": [], "route_entry": "r-1",
563
+ "routed_unit": "u-1"},
564
+ {"route_entry": "r-1", "routed_unit": "u-1"})
565
+ if name == "executable_invoked":
566
+ return ({"invocation_path": "bin/w", "invocation_sha256": APPLIED, "applied_path": "bin/w",
567
+ "applied_sha256": APPLIED},
568
+ {"invocation_path": "bin/w", "invocation_sha256": OTHER, "applied_path": "bin/w",
569
+ "applied_sha256": APPLIED},
570
+ {"applied_path": "bin/w", "applied_sha256": APPLIED})
571
+ if name == "executable_compiler":
572
+ return ({"compiler_digest": APPLIED, "applied_sha256": APPLIED},
573
+ {"compiler_digest": OTHER, "applied_sha256": APPLIED},
574
+ {"applied_sha256": APPLIED})
575
+ if name == "executable_installer":
576
+ return ({"installer_digest": APPLIED, "applied_sha256": APPLIED,
577
+ "begun_by_installer_digest": None},
578
+ {"installer_digest": OTHER, "applied_sha256": APPLIED,
579
+ "begun_by_installer_digest": None},
580
+ {"applied_sha256": APPLIED})
581
+ if name == "executable_deleted":
582
+ return ({"resolved_path": "bin/new", "resolved_sha256": APPLIED, "removed_sha256": OTHER,
583
+ "fallback_sha256": "fa" + "l" * 62, "required_replacement": APPLIED},
584
+ {"resolved_path": "bin/old", "resolved_sha256": "fa" + "l" * 62,
585
+ "removed_sha256": OTHER, "fallback_sha256": "fa" + "l" * 62,
586
+ "required_replacement": APPLIED},
587
+ {"removed_sha256": OTHER, "fallback_sha256": "fa" + "l" * 62})
588
+ if name == "personal":
589
+ return ({"layer_sha256": APPLIED, "applied_sha256": APPLIED, "loading_record": True},
590
+ {"layer_sha256": OTHER, "applied_sha256": APPLIED, "loading_record": True},
591
+ {"layer_sha256": APPLIED, "applied_sha256": APPLIED})
592
+ raise Refused(f"FIXTURE_UNGENERATED {name}: the table names a branch this generator has no cases "
593
+ f"for, so adding a rule without its fixtures would leave it untested")
594
+
595
+
596
+ def fixture_problems():
597
+ """Every generated case whose verdict is not the one its construction implies, by name."""
598
+ problems = []
599
+ for case in fixture_cases():
600
+ try:
601
+ answer = verdict(case["occasion"])
602
+ except Refused as exc:
603
+ problems.append(f"FIXTURE_REFUSED {case['id']}: {exc}")
604
+ continue
605
+ if answer["verdict"] != case["expect"]:
606
+ problems.append(f"FIXTURE_CHANGED {case['id']}: {answer['verdict']} where the case is "
607
+ f"built to be {case['expect']} ({answer['why']})")
608
+ if answer["rule"] != case["rule"]:
609
+ problems.append(f"FIXTURE_RULE {case['id']}: answered by {answer['rule']}")
610
+ return problems
611
+
612
+
613
+ def document():
614
+ """The predicate, for a reader checking it against §11."""
615
+ return {"branches": list(branches()), "verdicts": list(VERDICTS),
616
+ "design": {row["id"]: row["design"] for row in rules()},
617
+ "cases": len(fixture_cases())}
618
+
619
+
620
+ # ---- self-test ---------------------------------------------------------------------------------
621
+
622
+
623
+ def self_test():
624
+ """Every §11 branch, each table defect planted, and the three verdicts.
625
+
626
+ The body is wrapped so a control that DIES still speaks: a traceback is not a control firing,
627
+ and a revert trial that reads any output counts one as if it were. Found here by a revert trial
628
+ of this unit's own round-2 fixes — the precedence row made `rule_for` refuse, a control read its
629
+ answer without guarding, and the suite ended in a traceback with no [FAIL] line at all.
630
+ """
631
+ failures, ran = [], []
632
+ try:
633
+ return _self_test_body(failures, ran)
634
+ except BaseException as exc: # noqa: BLE001 - the suite must speak before it dies
635
+ held = ran[-1] if ran else "<no control ran>"
636
+ print(f"exposure --self-test [FAIL] the suite died after {held!r}: "
637
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
638
+ for name, detail in failures:
639
+ print(f"exposure --self-test [FAIL] {name}: {detail}", file=sys.stderr)
640
+ print(f"exposure --self-test: INCOMPLETE ({len(ran)} controls ran, {len(failures)} failed "
641
+ f"before the suite died)", file=sys.stderr)
642
+ raise
643
+
644
+
645
+ def _self_test_body(failures, ran):
646
+ def control(name, got, want):
647
+ ran.append(name)
648
+ if want not in str(got):
649
+ failures.append((name, f"expected {want!r} in {str(got)[:400]!r}"))
650
+
651
+ def equals(name, got, want):
652
+ """A control whose expectation is the WHOLE answer, not a fragment of it."""
653
+ ran.append(name)
654
+ if str(got) != str(want):
655
+ failures.append((name, f"expected exactly {want!r}, got {str(got)[:400]!r}"))
656
+
657
+ def clean(name, held):
658
+ ran.append(name)
659
+ if held:
660
+ failures.append((name, f"expected nothing, got {held}"))
661
+
662
+ def refusal(call):
663
+ try:
664
+ call()
665
+ except Refused as exc:
666
+ return str(exc)
667
+ except Exception as exc: # noqa: BLE001 - a control that dies is not a control
668
+ return f"RAISED {type(exc).__name__}: {exc}"
669
+ return ""
670
+
671
+ def answered_by(**occasion):
672
+ """`rule=<id>` for this occasion, or the exception as text.
673
+
674
+ The prefix is the point: `EXPOSURE_RULE_AMBIGUOUS create_or_edit, executable_installer ...`
675
+ CONTAINS the id a control is looking for, so a bare substring check read a refusal as the
676
+ right answer — this unit's own revert trial found the precedence control passing under a
677
+ mutation that made every match a tie.
678
+ """
679
+ try:
680
+ return f"rule={rule_for(occasion)['id']}"
681
+ except BaseException as exc: # noqa: BLE001 - the exception is the answer here
682
+ return f"RAISED {type(exc).__name__}: {exc}"
683
+
684
+ def guarded(call):
685
+ """The call's answer, or the exception as text.
686
+
687
+ A control that reads an answer a revert can make raise must not die on it: the exception IS
688
+ the finding, and it has to reach a [FAIL] line to be one.
689
+ """
690
+ try:
691
+ return call()
692
+ except BaseException as exc: # noqa: BLE001 - the exception is the answer here
693
+ return f"RAISED {type(exc).__name__}: {exc}"
694
+
695
+ def row_of(held, name):
696
+ """The mutable row with this id, inside a `with_table` copy.
697
+
698
+ By id rather than by position: a control that indexes `rules[4]` mutates whatever sits
699
+ there, and a table reordered later would leave the control green while testing another
700
+ branch.
701
+ """
702
+ for row in held["rules"]:
703
+ if row["id"] == name:
704
+ return row
705
+ raise AssertionError(f"the suite's own fixture is stale: no rule {name!r} to mutate")
706
+
707
+ def with_table(mutate, call):
708
+ held = json.loads(json.dumps(table()))
709
+ try:
710
+ mutate(_TABLE)
711
+ return call()
712
+ finally:
713
+ _TABLE.clear()
714
+ _TABLE.update(held)
715
+
716
+ # ---- the table -------------------------------------------------------------------------------
717
+ clean("the rule table is well formed", table_problems())
718
+ control("an empty rule set is refused, because a predicate over no rule answers nothing",
719
+ "; ".join(with_table(lambda t: t.__setitem__("rules", []), table_problems)),
720
+ "RULE_SET_EMPTY")
721
+ control("two rows claiming one branch are refused",
722
+ "; ".join(with_table(lambda t: t["rules"].append(dict(t["rules"][0])), table_problems)),
723
+ "RULE_REPEATED create_or_edit")
724
+ control("a row answering for no operation and no role is refused: it is never picked",
725
+ "; ".join(with_table(lambda t: t["rules"][0].__setitem__("applies_to", {"note": "x"}),
726
+ table_problems)),
727
+ "RULE_APPLIES_TO_NOTHING")
728
+ control("a row missing its design clause is refused, since the clause is what the branch rests on",
729
+ "; ".join(with_table(lambda t: t["rules"][0].pop("design"), table_problems)),
730
+ "RULE_INCOMPLETE create_or_edit: no design")
731
+ control("the table's verdicts and the code's are held against each other",
732
+ "; ".join(with_table(lambda t: t["verdicts"].pop("not_exposed"), table_problems)),
733
+ "VERDICT_SET")
734
+
735
+ # ---- which rule answers ----------------------------------------------------------------------
736
+ control("a created unit is answered by the create-or-edit branch",
737
+ str(rule_for({"operation": "create"})["id"]), "create_or_edit")
738
+ control("a deleted UNIT by the delete-or-merge branch",
739
+ str(rule_for({"operation": "delete"})["id"]), "delete_or_merge")
740
+ control("while a deleted EXECUTABLE is answered by its own branch, which §11 writes separately",
741
+ str(rule_for({"operation": "delete", "role": "wrapper"})["id"]), "executable_deleted")
742
+ control("an invoked wrapper by the invoked branch",
743
+ str(rule_for({"role": "wrapper"})["id"]), "executable_invoked")
744
+ control("the installer by the single installer predicate",
745
+ str(rule_for({"role": "installer"})["id"]), "executable_installer")
746
+ control("an occasion no branch answers for is refused by name, with what it carried",
747
+ refusal(lambda: verdict({"locator": "x", "operation": "rename"})),
748
+ "EXPOSURE_RULE_ABSENT x")
749
+ # Round 2: an EDITED installer. Both rows match at one key each, and the generic row used to
750
+ # win by sitting earlier in the file, so an installer's exposure was judged by the rule for a
751
+ # library unit's delivered version.
752
+ control("an edited INSTALLER is answered by the installer's own branch, not by the generic "
753
+ "create-or-edit row both rows match at one key",
754
+ answered_by(operation="edit", role="installer"), "rule=executable_installer")
755
+ control("and so is a created hook",
756
+ answered_by(operation="create", role="hook"), "rule=executable_invoked")
757
+ control("the role precedence is the TABLE's: with the key order reversed, the generic row wins "
758
+ "and the answer changes, so the declaration is what decides",
759
+ str(guarded(lambda: with_table(
760
+ lambda held: held.__setitem__("precedence", ["operation", "role"]),
761
+ lambda: answered_by(operation="edit", role="installer")))),
762
+ "rule=create_or_edit")
763
+ control("a genuine tie is REFUSED rather than broken by position",
764
+ refusal(lambda: with_table(
765
+ lambda held: row_of(held, "executable_compiler").__setitem__("applies_to", {"role": ["installer"]}),
766
+ lambda: verdict({"locator": "tie", "role": "installer", "at_record": 2,
767
+ "facts": {}}))),
768
+ "EXPOSURE_RULE_AMBIGUOUS tie")
769
+ control("and an unranked applies_to key is a table defect, since nothing could separate two "
770
+ "rows matching on it",
771
+ str(with_table(lambda held: row_of(held, "create_or_edit")["applies_to"].__setitem__("host", ["claude"]),
772
+ table_problems)),
773
+ "RULE_KEY_UNRANKED")
774
+ control("a table with no precedence at all is refused",
775
+ str(with_table(lambda held: held.__setitem__("precedence", []), table_problems)),
776
+ "PRECEDENCE_UNSTATED")
777
+
778
+ # ---- the three verdicts ----------------------------------------------------------------------
779
+ def occasion(**over):
780
+ held = {"locator": "o-1", "operation": "create", "at_record": 10,
781
+ "facts": {"delivered_version": {"value": APPLIED, "at_record": 9}, "applied_version": {"value": APPLIED, "at_record": 9}}}
782
+ held.update(over)
783
+ # POSITIONED before the decision unless the caller said otherwise: a fact the answer rests
784
+ # on records where it was observed, and a fixture that leaves it bare is asking for an
785
+ # answer §11 does not allow. A caller that positions a fact itself — which is how the
786
+ # after-the-decision cases are built — keeps its own value.
787
+ held_at = held.get("at_record")
788
+ held["facts"] = {name: (value if isinstance(value, dict) and "at_record" in value
789
+ or held_at is None
790
+ else {"value": value, "at_record": held_at - 5})
791
+ for name, value in (held.get("facts") or {}).items()}
792
+ return held
793
+
794
+ control("a merge whose merged unit the pin does NOT hold is not exposure, even though the "
795
+ "removal succeeded: the branch has two halves and one generated negative covers only one",
796
+ verdict({"locator": "m-1", "operation": "merge", "at_record": 5,
797
+ "facts": {"pin_units": {"value": ["u-kept"], "at_record": 4}, "removed_unit": {"value": "u-gone", "at_record": 4}, "merged_unit": {"value": "u-merged", "at_record": 4}}})["verdict"], NOT_EXPOSED)
798
+ control("and the why says which half failed",
799
+ verdict({"locator": "m-1", "operation": "merge", "at_record": 5,
800
+ "facts": {"pin_units": {"value": ["u-kept"], "at_record": 4}, "removed_unit": {"value": "u-gone", "at_record": 4}, "merged_unit": {"value": "u-merged", "at_record": 4}}})["why"],
801
+ "does not hold the merged one")
802
+ control("an invocation at the applied PATH but the old HASH is not exposure, for the same "
803
+ "reason: §6.3's levels exist to catch exactly that",
804
+ verdict({"locator": "i-1", "role": "tool", "at_record": 5,
805
+ "facts": {"invocation_path": {"value": "bin/w", "at_record": 4}, "invocation_sha256": {"value": OTHER, "at_record": 4}, "applied_path": {"value": "bin/w", "at_record": 4}, "applied_sha256": {"value": APPLIED, "at_record": 4}}})["verdict"],
806
+ NOT_EXPOSED)
807
+ control("exposure shown makes the occasion eligible", verdict(occasion())["verdict"], ELIGIBLE)
808
+ # Round 2: the table's predicate is EXECUTED. With `shown_when` set to a constant, the answer
809
+ # has to follow the table — and before this it did not move at all, because the branch keyed on
810
+ # the row's id decided and the field was prose beside it.
811
+ control("a row's shown_when set to False makes a shown occasion not_exposed: the table decides",
812
+ with_table(lambda held: row_of(held, "create_or_edit").__setitem__("shown_when", "False"),
813
+ lambda: verdict(occasion())["verdict"]),
814
+ NOT_EXPOSED)
815
+ control("and set to True it makes an unshown one eligible, so neither direction is the code's",
816
+ with_table(lambda held: row_of(held, "create_or_edit").__setitem__("shown_when", "True"),
817
+ lambda: verdict(occasion(facts={"delivered_version": OTHER,
818
+ "applied_version": APPLIED}))["verdict"]),
819
+ ELIGIBLE)
820
+ control("a predicate outside the grammar is refused by name rather than evaluated",
821
+ refusal(lambda: with_table(
822
+ lambda held: row_of(held, "create_or_edit").__setitem__(
823
+ "shown_when", "__import__('os').system('x')"),
824
+ lambda: verdict(occasion()))),
825
+ "EXPOSURE_PREDICATE_UNREADABLE create_or_edit.shown_when")
826
+ control("and an unparseable one too",
827
+ str(with_table(lambda held: row_of(held, "create_or_edit").__setitem__("shown_when", "a =="),
828
+ table_problems)),
829
+ "RULE_PREDICATE_UNREADABLE create_or_edit")
830
+ # Round 2: incomplete evidence was CERTIFIED. Both shapes are the review's own.
831
+ control("a merge carrying only an empty pin is unanswerable, not exposed: without the unit that "
832
+ "was removed, 'the pin does not hold it' is true of every pin",
833
+ verdict({"locator": "m-2", "operation": "merge", "at_record": 5,
834
+ "facts": {"pin_units": {"value": [], "at_record": 4}}})["verdict"], UNKNOWN)
835
+ control("and it names both identities it lacks",
836
+ verdict({"locator": "m-2", "operation": "merge", "at_record": 5,
837
+ "facts": {"pin_units": {"value": [], "at_record": 4}}})["why"], "removed_unit, merged_unit")
838
+ control("while a plain DELETE needs only the removed unit, since no merge was asked for",
839
+ verdict({"locator": "d-2", "operation": "delete", "at_record": 5,
840
+ "facts": {"pin_units": {"value": [], "at_record": 4}, "removed_unit": {"value": "u-gone", "at_record": 4}}})["verdict"], ELIGIBLE)
841
+ control("a deleted wrapper carrying only its own resolution is unanswerable: 'neither the "
842
+ "removed artifact nor an older carrier' needs both of those digests",
843
+ verdict({"locator": "x-2", "operation": "delete", "role": "wrapper", "at_record": 5,
844
+ "facts": {"resolved_path": {"value": "bin/w", "at_record": 4}, "resolved_sha256": {"value": APPLIED, "at_record": 4}}})["verdict"],
845
+ UNKNOWN)
846
+ control("and names them",
847
+ verdict({"locator": "x-2", "operation": "delete", "role": "wrapper", "at_record": 5,
848
+ "facts": {"resolved_path": {"value": "bin/w", "at_record": 4}, "resolved_sha256": {"value": APPLIED, "at_record": 4}}})["why"],
849
+ "removed_sha256, fallback_sha256")
850
+ control("an operation-conditional requirement must belong to a row that claims the operation",
851
+ str(with_table(
852
+ lambda held: row_of(held, "delete_or_merge").__setitem__(
853
+ "requires_by_operation", {"route": ["removed_unit"]}),
854
+ table_problems)),
855
+ "RULE_OPERATION_UNCLAIMED delete_or_merge")
856
+ control("a fact a predicate reads and the row declares nowhere is a table defect",
857
+ str(with_table(lambda held: row_of(held, "create_or_edit").__setitem__(
858
+ "shown_when", "delivered_version == applied_version and vouched is True"),
859
+ table_problems)),
860
+ "RULE_FACT_UNDECLARED create_or_edit.shown_when")
861
+ control("exposure shown ABSENT makes it not_exposed, which is an answer",
862
+ verdict(occasion(facts={"delivered_version": OTHER,
863
+ "applied_version": APPLIED}))["verdict"], NOT_EXPOSED)
864
+ control("a required fact absent makes it exposure_unknown, never not_exposed: an absent fact is "
865
+ "not a negative answer",
866
+ verdict(occasion(facts={"applied_version": APPLIED}))["verdict"], UNKNOWN)
867
+ control("and the why names the fact that was missing",
868
+ verdict(occasion(facts={"applied_version": APPLIED}))["why"],
869
+ "EXPOSURE_FACT_ABSENT delivered_version")
870
+
871
+ # ---- §11's ordering rule ---------------------------------------------------------------------
872
+ control("a fact observed AFTER the decision is not exposure to it",
873
+ verdict(occasion(facts={"delivered_version": {"value": APPLIED, "at_record": 20},
874
+ "applied_version": APPLIED}))["verdict"], UNKNOWN)
875
+ control("and the refusal names the two positions",
876
+ verdict(occasion(facts={"delivered_version": {"value": APPLIED, "at_record": 20},
877
+ "applied_version": APPLIED}))["why"],
878
+ "observed at record 20 and the decision is at 10")
879
+ control("a fact observed AT the decision is not before it either",
880
+ verdict(occasion(facts={"delivered_version": {"value": APPLIED, "at_record": 10},
881
+ "applied_version": APPLIED}))["verdict"], UNKNOWN)
882
+ control("one observed before it is read",
883
+ verdict(occasion(facts={"delivered_version": {"value": APPLIED, "at_record": 9},
884
+ "applied_version": APPLIED}))["verdict"], ELIGIBLE)
885
+ control("an occasion with no position at all is unknown: 'before the decision' has nothing to "
886
+ "be before", verdict(occasion(at_record=None))["verdict"], UNKNOWN)
887
+
888
+ # ---- the O9 cases the plan names -------------------------------------------------------------
889
+ def said(occasion, field="verdict"):
890
+ """One occasion's answer, or the exception as text: a rule that vanished from the table made
891
+ `verdict` raise straight through the control that needed to report it."""
892
+ try:
893
+ return verdict(occasion)[field]
894
+ except Exception as exc: # noqa: BLE001 - the exception IS the answer here
895
+ return f"RAISED {type(exc).__name__}: {exc}"
896
+
897
+ control("O9: an installer change whose receipt names ANOTHER installer version is "
898
+ "exposure_unknown, not not_exposed — §11 calls a transaction finished by another "
899
+ "version unknown, and the condition said so only for the recovery field",
900
+ said({"locator": "o9-a", "role": "installer", "at_record": 5,
901
+ "facts": {"installer_digest": {"value": OTHER, "at_record": 4}, "applied_sha256": {"value": APPLIED, "at_record": 4}, "begun_by_installer_digest": {"value": None, "at_record": 4}}}), UNKNOWN)
902
+ control("O9: a recovery BEGUN by the old installer is exposure_unknown, not not_exposed — §11 "
903
+ "writes that case into the branch itself",
904
+ said({"locator": "o9-b", "role": "installer", "at_record": 5,
905
+ "facts": {"installer_digest": {"value": APPLIED, "at_record": 4}, "applied_sha256": {"value": APPLIED, "at_record": 4}, "begun_by_installer_digest": {"value": OTHER, "at_record": 4}}}), UNKNOWN)
906
+ control("and the why says why nobody knows",
907
+ said({"locator": "o9-b", "role": "installer", "at_record": 5,
908
+ "facts": {"installer_digest": {"value": APPLIED, "at_record": 4}, "applied_sha256": {"value": APPLIED, "at_record": 4}, "begun_by_installer_digest": {"value": OTHER, "at_record": 4}}}, "why"),
909
+ "finished by another version")
910
+ control("a table whose unknown condition this module does not read is refused, so the field "
911
+ "cannot sit there with no reader",
912
+ "; ".join(with_table(
913
+ lambda t: t["rules"].append({"id": "unread", "applies_to": {"operation": ["x"]},
914
+ "requires": ["a"], "shown_when": "a",
915
+ "unknown_when": "never", "design": "d",
916
+ "$comment": "planted"}),
917
+ table_problems)),
918
+ "RULE_UNKNOWN_UNREAD unread")
919
+ control("O9: a pre-receipt transaction, with no installer digest at all, is exposure_unknown",
920
+ said({"locator": "o9-c", "role": "installer", "at_record": 5,
921
+ "facts": {"applied_sha256": {"value": APPLIED, "at_record": 4}}}), UNKNOWN)
922
+ control("O9: a removed wrapper resolving to an OLDER carrier is shown not exposed",
923
+ said({"locator": "o9-d", "operation": "delete", "role": "wrapper", "at_record": 5,
924
+ "facts": {"resolved_path": {"value": "bin/old", "at_record": 4}, "resolved_sha256": {"value": "fa" + "l" * 62, "at_record": 4}, "removed_sha256": {"value": OTHER, "at_record": 4}, "fallback_sha256": {"value": "fa" + "l" * 62, "at_record": 4}, "required_replacement": {"value": APPLIED, "at_record": 4}}}), NOT_EXPOSED)
925
+ control("O9: one with no resolution recorded is exposure_unknown",
926
+ said({"locator": "o9-e", "operation": "delete", "role": "wrapper", "at_record": 5,
927
+ "facts": {"removed_sha256": {"value": OTHER, "at_record": 4}}}), UNKNOWN)
928
+ control("O9: a compiler change with the OLD compiler digest is shown not exposed",
929
+ said({"locator": "o9-f", "role": "catalog_compiler", "at_record": 5,
930
+ "facts": {"compiler_digest": {"value": OTHER, "at_record": 4}, "applied_sha256": {"value": APPLIED, "at_record": 4}}}),
931
+ NOT_EXPOSED)
932
+ control("O9: a personal change with no loading record is exposure_unknown",
933
+ said({"locator": "o9-g", "operation": "personal", "at_record": 5,
934
+ "facts": {"layer_sha256": {"value": APPLIED, "at_record": 4}, "applied_sha256": {"value": APPLIED, "at_record": 4}}}),
935
+ UNKNOWN)
936
+
937
+ # ---- a fact the answer rests on says where it was observed --------------------------------
938
+ #
939
+ # `ordering_problems` skipped any fact without an `at_record`, so an occasion could be certified
940
+ # ELIGIBLE with no evidence at all that its facts precede the decision: the rule had nothing to
941
+ # read (the round-3 review). A fact the answering rule does not require is not part of the
942
+ # answer and is not held to it.
943
+ control("an occasion whose required fact records no position is exposure_unknown, not eligible",
944
+ said({"locator": "p-1", "operation": "create", "at_record": 10,
945
+ "facts": {"delivered_version": APPLIED,
946
+ "applied_version": {"value": APPLIED, "at_record": 5}}}), UNKNOWN)
947
+ control("and the why names the fact and says what cannot be shown",
948
+ said({"locator": "p-1", "operation": "create", "at_record": 10,
949
+ "facts": {"delivered_version": APPLIED,
950
+ "applied_version": {"value": APPLIED, "at_record": 5}}}, "why"),
951
+ "FACT_UNPOSITIONED p-1 delivered_version")
952
+ control("the same occasion with both facts positioned before the decision is eligible, so the "
953
+ "refusal is the missing position and not the fact",
954
+ said(occasion(locator="p-2")), ELIGIBLE)
955
+ # Round 5: an envelope is `{value, at_record}` and a position is an integer. Each malformed
956
+ # shape is planted on an occasion that is otherwise ELIGIBLE, so the verdict moving is the fix.
957
+ well = {"locator": "e-1", "operation": "edit", "role": None, "at_record": 10,
958
+ "facts": {"delivered_version": {"value": "v1", "at_record": 5},
959
+ "applied_version": {"value": "v1", "at_record": 5}}}
960
+ control("the well-formed occasion the next three are planted on is eligible", said(well), ELIGIBLE)
961
+ hollow = {**well, "locator": "e-2", "facts": {"delivered_version": {"at_record": 5},
962
+ "applied_version": {"at_record": 5}}}
963
+ control("two envelopes with a position and NO value are not two equal versions",
964
+ (said(hollow), said(hollow, "why").split()[0]), f"('{UNKNOWN}', 'FACT_VALUE_ABSENT')")
965
+ texted = {**well, "locator": "e-3", "at_record": "2",
966
+ "facts": {**well["facts"], "applied_version": {"value": "v1", "at_record": "11"}}}
967
+ control("positions written as text are refused rather than ordered by spelling",
968
+ (said(texted), said(texted, "why").split()[0]),
969
+ f"('{UNKNOWN}', 'OCCASION_POSITION_INVALID')")
970
+ nulled = {**well, "locator": "e-4",
971
+ "facts": {**well["facts"], "applied_version": {"value": "v1", "at_record": None}}}
972
+ control("a fact whose position is null is unknown by name, not a TypeError",
973
+ (said(nulled), said(nulled, "why").split()[0]),
974
+ f"('{UNKNOWN}', 'FACT_POSITION_INVALID')")
975
+ # And the reference identity: each row that compares against the applied artifact, with that
976
+ # identity left out of an occasion that carries every observation.
977
+ for rule_id, lacking in (
978
+ ("executable_invoked", {"locator": "a-1", "operation": "edit", "role": "hook", "at_record": 10,
979
+ "facts": {"invocation_path": {"value": "h", "at_record": 5},
980
+ "invocation_sha256": {"value": "s", "at_record": 5}}}),
981
+ ("executable_compiler", {"locator": "a-2", "operation": "edit", "role": "catalog_compiler",
982
+ "at_record": 10,
983
+ "facts": {"compiler_digest": {"value": "s", "at_record": 5}}}),
984
+ ("personal", {"locator": "a-3", "operation": "personal", "role": None, "at_record": 10,
985
+ "facts": {"layer_sha256": {"value": "s", "at_record": 5},
986
+ "loading_record": {"value": True, "at_record": 5}}})):
987
+ control(f"{rule_id}: an observation with no applied identity to compare it with is unknown",
988
+ (said(lacking, "rule"), said(lacking), said(lacking, "why").split()[0]),
989
+ f"('{rule_id}', '{UNKNOWN}', 'EXPOSURE_FACT_ABSENT')")
990
+ # Round 4: optionality is about EXISTENCE, not timing. An optional fact the predicate READS
991
+ # decides the answer when it is supplied — giving `required_replacement` with no position turned
992
+ # exposure_unknown into eligible, so leaving it out of the position rule was a way past it.
993
+ held_optional = {"locator": "p-4", "operation": "delete", "role": "hook", "at_record": 10,
994
+ "facts": {"resolved_path": {"value": "/a", "at_record": 5},
995
+ "resolved_sha256": {"value": "s", "at_record": 5},
996
+ "required_replacement": "new"}}
997
+ # The WHY, not the verdict: this occasion is exposure_unknown either way — without the fix
998
+ # because its required facts are absent — so a control reading only the verdict passed for the
999
+ # wrong reason, which the revert trial reported as silent.
1000
+ control("an OPTIONAL fact the predicate reads must carry a position too, and the refusal is "
1001
+ "THAT fact's missing position rather than anything else about the occasion",
1002
+ said(held_optional, "why"), "FACT_UNPOSITIONED p-4 required_replacement")
1003
+ control("and the verdict it produces is exposure_unknown, never eligible",
1004
+ said(held_optional), UNKNOWN)
1005
+ clean("the same fact positioned before the decision is no longer an unpositioned-fact "
1006
+ "refusal, so what the rule caught was the missing position and not the fact",
1007
+ [held for held in [said({**held_optional, "locator": "p-5",
1008
+ "facts": {**held_optional["facts"],
1009
+ "required_replacement": {"value": "new",
1010
+ "at_record": 5}}}, "why")]
1011
+ if "FACT_UNPOSITIONED" in str(held)])
1012
+ control("and positioned AFTER it is refused by the ordering rule, which is the half that was "
1013
+ "already working",
1014
+ said({**held_optional, "locator": "p-6",
1015
+ "facts": {**held_optional["facts"],
1016
+ "required_replacement": {"value": "new", "at_record": 11}}}, "why"),
1017
+ "FACT_AFTER_DECISION")
1018
+ equals("the names held to the rule are the required ones plus the supplied ones the predicate "
1019
+ "reads, derived from the predicate's own source rather than listed twice",
1020
+ json.dumps(positioned_facts(
1021
+ next(row for row in table()["rules"] if row["id"] == "executable_deleted"),
1022
+ held_optional)),
1023
+ json.dumps(sorted(set(required_facts(
1024
+ next(row for row in table()["rules"] if row["id"] == "executable_deleted"),
1025
+ held_optional)) | {"required_replacement"})))
1026
+ clean("while a fact the predicate does not read at all is still not held to it, however it is "
1027
+ "supplied",
1028
+ [name for name in positioned_facts(
1029
+ next(row for row in table()["rules"] if row["id"] == "executable_deleted"),
1030
+ {**held_optional, "facts": {**held_optional["facts"], "a_note": "x"}})
1031
+ if name == "a_note"])
1032
+ clean("a fact the rule does NOT require may be unpositioned: it is not part of the answer",
1033
+ [said({"locator": "p-3", "operation": "create", "at_record": 10,
1034
+ "facts": {"delivered_version": {"value": APPLIED, "at_record": 5},
1035
+ "applied_version": {"value": APPLIED, "at_record": 5},
1036
+ "a_note_nobody_requires": "x"}})] and
1037
+ [] if said({"locator": "p-3", "operation": "create", "at_record": 10,
1038
+ "facts": {"delivered_version": {"value": APPLIED, "at_record": 5},
1039
+ "applied_version": {"value": APPLIED, "at_record": 5},
1040
+ "a_note_nobody_requires": "x"}}) == ELIGIBLE
1041
+ else ["an unrequired unpositioned fact changed the answer"])
1042
+
1043
+ # ---- the installer branch answers eligible or unknown, never not_exposed -------------------
1044
+ control("a receipt whose digest is the applied one and whose recovery agrees is eligible",
1045
+ said({"locator": "i-1", "role": "installer", "at_record": 5,
1046
+ "facts": {"installer_digest": {"value": APPLIED, "at_record": 4},
1047
+ "applied_sha256": {"value": APPLIED, "at_record": 4},
1048
+ "begun_by_installer_digest": {"value": None, "at_record": 4}}}),
1049
+ ELIGIBLE)
1050
+ control("an absent applied_sha256 is exposure_unknown: it was OPTIONAL while both conditions "
1051
+ "compare against it, so an absent one produced a negative answer from a fact nobody "
1052
+ "recorded",
1053
+ said({"locator": "i-2", "role": "installer", "at_record": 5,
1054
+ "facts": {"installer_digest": {"value": APPLIED, "at_record": 4}}}), UNKNOWN)
1055
+ control("and the refusal names the absent fact rather than answering not_exposed",
1056
+ said({"locator": "i-2", "role": "installer", "at_record": 5,
1057
+ "facts": {"installer_digest": {"value": APPLIED, "at_record": 4}}}, "why"),
1058
+ "EXPOSURE_FACT_ABSENT applied_sha256")
1059
+ control("the branch has no not_exposed state at all, which is what §11's sentence says: for an "
1060
+ "installer transaction nobody can know the installation was NOT exposed",
1061
+ json.dumps(sorted({said({"locator": f"i-{held}", "role": "installer", "at_record": 5,
1062
+ "facts": {"installer_digest": {"value": digest,
1063
+ "at_record": 4},
1064
+ "applied_sha256": {"value": APPLIED,
1065
+ "at_record": 4},
1066
+ "begun_by_installer_digest": {"value": begun,
1067
+ "at_record": 4}}})
1068
+ for held, (digest, begun) in enumerate(
1069
+ [(APPLIED, None), (OTHER, None), (APPLIED, OTHER),
1070
+ (OTHER, OTHER)])})),
1071
+ '["eligible", "exposure_unknown"]')
1072
+
1073
+ # ---- the generated fixtures ------------------------------------------------------------------
1074
+ clean("every generated case answers with the verdict its construction implies", fixture_problems())
1075
+ control("three cases per branch, generated from the table",
1076
+ f'{len(fixture_cases())}', f'{len(branches()) * 3}')
1077
+ control("a branch added to the table with no cases is refused rather than left untested",
1078
+ refusal(lambda: with_table(
1079
+ lambda t: t["rules"].append({"id": "newly_added", "applies_to": {"operation": ["x"]},
1080
+ "requires": ["a"], "shown_when": "a", "design": "d",
1081
+ "$comment": "planted"}),
1082
+ fixture_cases)),
1083
+ "FIXTURE_UNGENERATED newly_added")
1084
+ control("a branch the table names and this module does not answer is refused, so the predicate "
1085
+ "cannot be narrower than its table",
1086
+ refusal(lambda: _shown({"id": "newly_added"}, {})),
1087
+ "EXPOSURE_BRANCH_UNIMPLEMENTED")
1088
+
1089
+ # ---- what measures receives ------------------------------------------------------------------
1090
+ built = instances_for("eo-1", [occasion(locator="a"),
1091
+ occasion(locator="b", facts={"delivered_version": OTHER,
1092
+ "applied_version": APPLIED}),
1093
+ occasion(locator="c", facts={"applied_version": APPLIED})],
1094
+ "source")
1095
+ control("a not_exposed occasion is excluded from the instances and counted",
1096
+ f'{len(built["instances"])}:{len(built["not_exposed"])}', "2:1")
1097
+ clean("and every instance carries one of the two exposure values measures admits",
1098
+ [row["exposure"] for row in built["instances"] if row["exposure"] not in measures.EXPOSURES])
1099
+ control("the excluded occasion is listed by locator and rule, so the exclusion is visible",
1100
+ json.dumps(built["not_exposed"]), '"locator": "b"')
1101
+ def resolved(*args):
1102
+ """`resolution_for` with any exception as a row: measures refuses an exposure value it does
1103
+ not admit, and a disabled exclusion raised straight through the suite."""
1104
+ try:
1105
+ return resolution_for(*args)
1106
+ except Exception as exc: # noqa: BLE001 - the exception IS the answer here
1107
+ return {"resolution": f"RAISED {type(exc).__name__}: {exc}", "counts": {"not_exposed": -1},
1108
+ "not_exposed": []}
1109
+
1110
+ held = resolved("eo-1", [occasion(locator="a", judged="observed"),
1111
+ occasion(locator="b", facts={"delivered_version": OTHER,
1112
+ "applied_version": APPLIED})],
1113
+ "source")
1114
+ control("the resolution comes from measures, not from a second implementation here",
1115
+ held["resolution"], "observed")
1116
+ control("with the not_exposed count beside it", str(held["counts"]["not_exposed"]), "1")
1117
+ clean("a window whose only occasion is not_exposed resolves as measures resolves an empty "
1118
+ "instance list, rather than as pending on an answered question",
1119
+ [] if resolved("eo-1", [occasion(locator="b",
1120
+ facts={"delivered_version": OTHER,
1121
+ "applied_version": APPLIED})],
1122
+ "source")["resolution"] == "no_occasion"
1123
+ else [resolved("eo-1", [occasion(locator="b",
1124
+ facts={"delivered_version": OTHER,
1125
+ "applied_version": APPLIED})],
1126
+ "source")["resolution"]])
1127
+ control("the resolution question goes to the module that owns it",
1128
+ next(line.strip() for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
1129
+ if "derive_resolution" in line and "held = " in line),
1130
+ "measures.derive_resolution")
1131
+
1132
+ # ---- the branch set against §11 ---------------------------------------------------------------
1133
+ control("the predicate's branches are the table's, named for a reader checking them against §11",
1134
+ ", ".join(document()["branches"]), "create_or_edit, delete_or_merge, route")
1135
+ clean("and every branch carries the design clause it rests on",
1136
+ [name for name, clause in document()["design"].items() if not clause])
1137
+
1138
+ import ast
1139
+ own = ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
1140
+ spawners = sorted({ast.unparse(node.func) for node in ast.walk(own) if isinstance(node, ast.Call)
1141
+ and ast.unparse(node.func).split(".")[0] in ("subprocess", "os")})
1142
+ clean("exposure spawns nothing and reads no environment: the occasion's facts are handed to it",
1143
+ spawners)
1144
+
1145
+ print(f"exposure --self-test: {'FAILED' if failures else 'OK'} ({len(ran)} controls: §11's eight "
1146
+ f"branches with three generated cases each, an absent fact read as unknown rather than as "
1147
+ f"a negative answer, the ordering rule at and after the decision, the seven O9 cases the "
1148
+ f"plan names, and the not_exposed occasions counted rather than handed to measures)")
1149
+ for name, detail in failures:
1150
+ print(f"exposure --self-test [FAIL] {name}: {detail}")
1151
+ return 1 if failures else 0
1152
+
1153
+
1154
+ def main(argv):
1155
+ if "--self-test" in argv:
1156
+ return self_test()
1157
+ print(json.dumps(document(), indent=2, ensure_ascii=False))
1158
+ return 0
1159
+
1160
+
1161
+ if __name__ == "__main__":
1162
+ sys.exit(main(sys.argv[1:]))