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,829 @@
1
+ #!/usr/bin/env python3
2
+ """The commit-sequencing check (S-14, WP-12 commit 3): can a set of items be applied in SOME order
3
+ whose every intermediate tree passes the gate?
4
+
5
+ Before the core freeze, S7b asks this of every core item set. A set with no such order — the classic
6
+ being a route and the carrier it points at proposed as two items, where whichever lands first leaves
7
+ a tree with a route to nothing — is re-formed into one item or deferred, before the freeze rather
8
+ than after an apply has already half happened.
9
+
10
+ **Two gates, and they prove different things.** The suite runs a deterministic stand-in
11
+ (`route_integrity`), which models the one property the ordering exists to protect: no intermediate
12
+ tree holds a route to a path that tree does not have. That proves the SEARCH — that an order is found
13
+ when one exists, that none is reported when none does, and that a subset is judged on its own. It does
14
+ not prove the real hook agrees. The real hook is `--real-hook-check`, a separate command, never a leg
15
+ of the umbrella: the umbrella is itself run by the pre-commit hook, so a leg that ran the hook would
16
+ recurse (this repo has filled a disk that way). That command refuses by name when it detects it is
17
+ running under the hook, and is bounded by a timeout.
18
+
19
+ sequencing.py --self-test
20
+ sequencing.py --real-hook-check [--timeout SECONDS] # the lead runs this at verification and C4
21
+ """
22
+ import hashlib
23
+ import itertools
24
+ import inspect
25
+ import re
26
+ import json
27
+ import os
28
+ import pathlib
29
+ import sys
30
+
31
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
32
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
33
+ from runlib import operations, targets # noqa: E402
34
+ from runlib.records import Refused # noqa: E402
35
+
36
+ HERE = pathlib.Path(__file__).resolve().parents[1]
37
+ # The search is over orders of items, with the reached SET memoised, so the cost is 2^n states and
38
+ # not n!. Beyond this many items the answer is refused rather than computed: a set this large is a
39
+ # formation problem, and a checker that ran for an hour would be routed around.
40
+ SET_LIMIT = 12
41
+ # The real hook's own markers. The pre-commit hook materialises the index into a temp directory and
42
+ # points the gates at it with these, so their spellings are what says "you are inside a commit".
43
+ HOOK_INDEX_PREFIX = "agent-bios-precommit-index"
44
+ HOOK_TREE_PREFIX = "agent-bios-precommit"
45
+
46
+
47
+ def under_the_hook(environ=None):
48
+ """Whether this process is running inside the pre-commit hook, by the hook's own markers.
49
+
50
+ Read from the environment the hook exports rather than from a flag a caller passes: a caller that
51
+ had to remember would be a caller that forgets, and the failure that follows is a recursion."""
52
+ held = os.environ if environ is None else environ
53
+ index = pathlib.Path(held.get("GIT_INDEX_FILE") or "").name
54
+ tree = pathlib.Path(held.get("GIT_WORK_TREE") or "").name
55
+ reasons = []
56
+ if index.startswith(HOOK_INDEX_PREFIX):
57
+ reasons.append(f"GIT_INDEX_FILE names the hook's index snapshot ({index})")
58
+ if tree.startswith(HOOK_TREE_PREFIX):
59
+ reasons.append(f"GIT_WORK_TREE names the hook's materialised tree ({tree})")
60
+ return reasons
61
+
62
+
63
+ # The operation fields the stand-in READS, and therefore the fields a set's identity must bind.
64
+ # `apply_to` is the only reader, and its self-test holds this tuple against the fields it names.
65
+ OPERATION_FIELDS = ("type", "target", "names", "units", "anchor")
66
+
67
+
68
+ def set_hash(items):
69
+ """The identity of a SET of items: its item ids, sorted, with each item's operations.
70
+
71
+ Sorted, because the question "does this set admit an order" is about the set, and a hash that
72
+ changed with the order would make the answer unfindable for the same set presented twice."""
73
+ # EVERY field `apply_to` reads. The set omitted `units`, which a merge's removals come from, so
74
+ # two sets with opposite verdicts shared an identity: with base x,y and route r->x, merging
75
+ # units=[x] is unsequenced and merging units=[y] is not, and both hashed the same. The identity
76
+ # is derived from `OPERATION_FIELDS` rather than listed twice, so a field added to `apply_to`
77
+ # cannot be left out of the identity (the WP-12 review).
78
+ rows = sorted(({"item_id": item["item_id"],
79
+ "operations": [{k: op.get(k) for k in OPERATION_FIELDS}
80
+ for op in item.get("operations") or []]}
81
+ for item in items), key=lambda row: row["item_id"])
82
+ return hashlib.sha256(json.dumps(rows, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()
83
+
84
+
85
+ def _path(value):
86
+ """One file's identity, or the value itself where it has none to give.
87
+
88
+ Every path an operation carries is asked the same question of the same owner: a merge's units
89
+ and a route's destination are files exactly as a target is, and keying them by the string as
90
+ written made `guides/é.md` composed and decomposed two files — a merge removed one while the
91
+ route to the other stood, and the order was certified over a tree that does not exist (the
92
+ round-5 review)."""
93
+ return targets.identity(targets.file_of(value)) or value
94
+
95
+
96
+ def _route_key(key):
97
+ """A base tree's route entry with BOTH of its paths as identities.
98
+
99
+ The entry is `route:<entry>-><destination>`, the shape `apply_to` writes. Left as written, a
100
+ base holding `guides/é.md` and a route to its other spelling was read as a route to nothing, and
101
+ an unrelated edit over that base was refused (the round-6 review)."""
102
+ entry, arrow, named = str(key)[len("route:"):].partition("->")
103
+ return f"route:{_path(entry)}->{_path(named)}" if arrow else str(key)
104
+
105
+
106
+ def canonical_tree(tree):
107
+ """`tree` with every file keyed by its identity, a route entry's two paths included."""
108
+ return {(_route_key(key) if str(key).startswith("route:") else _path(key)): value
109
+ for key, value in (tree or {}).items()}
110
+
111
+
112
+ def apply_to(tree, item):
113
+ """The tree after one item's operations. `tree` is {path: "present"} and is not mutated.
114
+
115
+ A create or an edit puts its target there; a delete removes it; a merge removes the units it
116
+ merges and leaves its target; a route adds the route entry and nothing else — which is exactly
117
+ why a route can precede its carrier and leave a tree that no gate should pass."""
118
+ held = dict(tree)
119
+ for op in item.get("operations") or []:
120
+ kind = op.get("type")
121
+ # The IDENTITY, not the string the operation carries: `claude/g.md`, `./claude/g.md` and
122
+ # `claude//g.md` are one file, and keying the tree by the raw string made them three — a
123
+ # create under one spelling and a delete under another left the file present, and the order
124
+ # this module computed was an order over a tree that does not exist (the round-3 review).
125
+ # `targets.identity` is the one owner of that question; an unspellable target keeps its own
126
+ # string so the order is still computed and the spelling contract reports it by name.
127
+ # The FILE, not the string: `g.md#One` names a section of `g.md` (`runlib/operations.py`), so
128
+ # it shares that file's identity, and a delete that names a section or an anchor removes
129
+ # text and leaves the file. Modelled as the file's removal, a valid set - an anchored
130
+ # deletion beside a route to the same file - came back with no order (the S11 review).
131
+ target = _path(op.get("target"))
132
+ # a section as S11 reads one (`operations.split_target`): an empty or blank suffix (`g.md#`) names no section,
133
+ # so the operation is the whole file's (Codex WP-12 r3 F5: the `#` alone read as a section, and a route to a
134
+ # file S11 deletes was certified)
135
+ in_file = bool(op.get("anchor")) or operations.split_target(op.get("target") or "")[1] is not None
136
+ if kind in ("create", "edit"):
137
+ held[target] = "present"
138
+ elif kind == "delete":
139
+ if not in_file:
140
+ held.pop(target, None)
141
+ elif kind == "merge":
142
+ # a unit that names a section is that section's removal and leaves its file, as a delete of a
143
+ # section does (`operations.removed`); only a unit naming a whole file removes it (Codex WP-12 r2 F11)
144
+ for unit in op.get("units") or []:
145
+ if operations.split_target(str(unit))[1] is None:
146
+ held.pop(_path(unit), None)
147
+ held[target] = "present"
148
+ elif kind == "route":
149
+ held[f"route:{target}->{_path(op.get('names'))}"] = "present"
150
+ else:
151
+ raise Refused(f"OPERATION_UNKNOWN {kind!r} in {item.get('item_id')}: §7.3's types are "
152
+ f"create, edit, delete, merge, route")
153
+ return held
154
+
155
+
156
+ def route_integrity(tree):
157
+ """The deterministic stand-in: every route in the tree names a path the tree holds.
158
+
159
+ This is the property the ordering protects, modelled without running anything: a router entry
160
+ pointing at a guide that is not there yet. The real hook checks far more, which is what
161
+ `--real-hook-check` is for; this one is decidable, instant, and cannot recurse."""
162
+ problems = []
163
+ for key in sorted(tree):
164
+ if not key.startswith("route:"):
165
+ continue
166
+ named = key.split("->", 1)[1]
167
+ if named and named not in tree:
168
+ problems.append(f"ROUTE_TO_NOTHING {key}: the tree holds no {named}")
169
+ return problems
170
+
171
+
172
+ def tree_hash(tree):
173
+ return hashlib.sha256(json.dumps(sorted(tree), ensure_ascii=False).encode("utf-8")).hexdigest()
174
+
175
+
176
+ def sequence(items, gate=route_integrity, base=None, limit=SET_LIMIT):
177
+ """`{set_hash, order, tree_hashes, gate_results}` for an order whose every tree passes, or Refused.
178
+
179
+ The search is depth-first over the items not yet applied, memoised on the frozenset reached, so
180
+ one dead set is explored once however many orders reach it. The first passing order found is
181
+ returned: the question is whether one EXISTS, and a run that returned them all would be answering
182
+ a question nobody asked.
183
+
184
+ `items` is whatever set the caller holds — the full core set at the freeze, or, for WP-20 and
185
+ WP-21, the exact subset the owner approved. The subset is judged on its own evidence, and a full
186
+ set with a valid order says nothing about it."""
187
+ rows = list(items)
188
+ if not rows:
189
+ raise Refused("SEQUENCE_SET_EMPTY: an order over no item proves nothing about any apply")
190
+ if len(rows) > limit:
191
+ raise Refused(f"SEQUENCE_SET_TOO_LARGE {len(rows)} items (limit {limit}): a set this large is a "
192
+ f"formation problem, and the search is 2^n states")
193
+ ids = [item["item_id"] for item in rows]
194
+ if len(set(ids)) != len(ids):
195
+ raise Refused(f"SEQUENCE_ITEM_REPEATED {sorted({i for i in ids if ids.count(i) > 1})}: an item "
196
+ f"appears twice in one set")
197
+ by_id = {item["item_id"]: item for item in rows}
198
+ start = canonical_tree(base)
199
+ dead = set()
200
+ trail = []
201
+
202
+ def walk(tree, applied):
203
+ if len(applied) == len(rows):
204
+ return True
205
+ # Keyed on the applied set AND THE TREE. Keyed on the set alone, a dead end reached by one
206
+ # order marked the set dead for every order, and the operations do not commute: with x in
207
+ # the base, `create x` then `delete x` leaves a different tree than the reverse, so
208
+ # b,a,c passed while the search reported that no order existed at all (the WP-12 review).
209
+ key = (frozenset(applied), tree_hash(tree))
210
+ if key in dead:
211
+ return False
212
+ for item_id in sorted(set(ids) - applied):
213
+ after = apply_to(tree, by_id[item_id])
214
+ problems = gate(after)
215
+ if problems:
216
+ continue
217
+ trail.append((item_id, after, problems))
218
+ if walk(after, applied | {item_id}):
219
+ return True
220
+ trail.pop()
221
+ dead.add(key)
222
+ return False
223
+
224
+ if not walk(start, frozenset()):
225
+ raise Refused(f"SEQUENCE_NONE {set_hash(rows)[:12]} over {len(rows)} item(s) "
226
+ f"({', '.join(sorted(ids))}): no order of these items leaves every intermediate "
227
+ f"tree passing the gate, so the set is re-formed into one item or deferred "
228
+ f"before the freeze")
229
+ return {"set_hash": set_hash(rows),
230
+ "order": [item_id for item_id, _tree, _problems in trail],
231
+ "tree_hashes": [tree_hash(tree) for _item_id, tree, _problems in trail],
232
+ "hook_results": [{"item_id": item_id, "problems": problems}
233
+ for item_id, _tree, problems in trail],
234
+ "gate": getattr(gate, "__name__", "gate")}
235
+
236
+
237
+ def validate_order(items, order, gate=route_integrity, base=None):
238
+ """The row `sequence` returns, for the order the caller GIVES, or Refused naming the step.
239
+
240
+ "Does an order exist" and "does THIS order hold" are different questions, and a caller that
241
+ needed the second asked the first and compared answers. `sequence` returns the first passing
242
+ order its sorted-id search reaches, so a perfectly valid approved order was rejected whenever
243
+ another valid order sorted earlier (the WP-21 round-2 review). Validating is also one pass with
244
+ no search.
245
+ """
246
+ rows = list(items)
247
+ if not rows:
248
+ raise Refused("SEQUENCE_SET_EMPTY: an order over no item proves nothing about any apply")
249
+ by_id = {item["item_id"]: item for item in rows}
250
+ asked = list(order or ())
251
+ if sorted(asked) != sorted(by_id):
252
+ raise Refused(f"SEQUENCE_ORDER_NOT_A_PERMUTATION {', '.join(asked)}: the order names "
253
+ f"{len(asked)} item(s) and the set holds {len(by_id)} "
254
+ f"({', '.join(sorted(by_id))})")
255
+ tree = canonical_tree(base)
256
+ trail = []
257
+ for item_id in asked:
258
+ tree = apply_to(tree, by_id[item_id])
259
+ problems = gate(tree)
260
+ trail.append((item_id, tree, problems))
261
+ if problems:
262
+ raise Refused(f"SEQUENCE_ORDER_FAILS at {item_id} (step {len(trail)} of {len(asked)}): "
263
+ f"{'; '.join(problems)}")
264
+ return {"set_hash": set_hash(rows),
265
+ "order": [item_id for item_id, _tree, _problems in trail],
266
+ "tree_hashes": [tree_hash(held) for _item_id, held, _problems in trail],
267
+ "hook_results": [{"item_id": item_id, "problems": problems}
268
+ for item_id, _tree, problems in trail],
269
+ "gate": getattr(gate, "__name__", "gate")}
270
+
271
+
272
+ def order_answer(items, order, gate=route_integrity, base=None):
273
+ """`validate_order`'s row, RETURNED rather than raised, as `subset_answer` is `sequence`'s."""
274
+ try:
275
+ return {**validate_order(items, order, gate, base), "sequenced": True}
276
+ except Refused as exc:
277
+ return {"set_hash": set_hash(list(items)), "sequenced": False,
278
+ "refusal": str(exc).split(":")[0].split(" at ")[0], "reason": str(exc),
279
+ "order": [], "tree_hashes": [], "hook_results": [],
280
+ "gate": getattr(gate, "__name__", "gate")}
281
+
282
+
283
+ def subset_answer(items, gate=route_integrity, base=None):
284
+ """One `sequencing.json` row for one set, RETURNED rather than raised.
285
+
286
+ This is the entry point WP-20 and WP-21 re-run on the exact subset the owner approved. The answer
287
+ is returned because applying is their caller's decision: a subset with no order comes back as a
288
+ row saying so, carrying its own set hash, and nothing in this module applies anything."""
289
+ try:
290
+ return {**sequence(items, gate, base), "sequenced": True}
291
+ except Refused as exc:
292
+ return {"set_hash": set_hash(list(items)), "sequenced": False,
293
+ "refusal": str(exc).split(":")[0], "reason": str(exc),
294
+ "order": [], "tree_hashes": [], "hook_results": [],
295
+ "gate": getattr(gate, "__name__", "gate")}
296
+
297
+
298
+ def document(sets, gate=route_integrity, base=None):
299
+ """`sequencing.json`: one row per item set, each with its order or the refusal that stopped it."""
300
+ rows = [subset_answer(items, gate, base) for items in sets]
301
+ return {"stage": "S7b", "sets": rows,
302
+ "summary": {"sets": len(rows), "sequenced": sum(1 for row in rows if row["sequenced"]),
303
+ "unsequenced": sum(1 for row in rows if not row["sequenced"])}}
304
+
305
+
306
+ # ---- the real hook: not here, by the dispatch judge's rule ---------------------------------------
307
+ # The real hook runs from `gates/sequencing-real-hook-check.sh`, outside this tree, and consults
308
+ # `--under-the-hook` below for its refusal. Nothing in this module starts a process: `runlib/dispatch.py`
309
+ # judges every program a session-distill file starts, and both shapes tried here - an executor behind a
310
+ # seam, and `bash <path>` - are programs its trace cannot resolve. Keeping the subprocess out is also
311
+ # what makes the suite's controls free: a revert trial that disables the marker check cannot start a
312
+ # five-minute hook, which it did twice before this moved.
313
+
314
+ # ---- self-test -----------------------------------------------------------------------------------
315
+
316
+ def self_test():
317
+ """Positive control first, then one planted violation per rule, each refused BY NAME.
318
+
319
+ Every control here uses the deterministic stand-in. The real hook is not run: this suite is a leg
320
+ of the umbrella, the umbrella is run by the hook, and the recursion is the failure the design of
321
+ this module is built around. What the suite proves is the SEARCH; `--real-hook-check` proves the
322
+ hook runs over an intermediate tree at all, and the two are named separately on purpose.
323
+ The body is wrapped so a control that DIES still speaks: a traceback is not a control firing,
324
+ and a revert trial that reads any output counts one as if it were (the WP-12 review). The
325
+ wrapper prints a [FAIL] line naming the control that was in flight, so the evidence says which
326
+ rule stopped being enforced.
327
+ """
328
+ failures, ran = [], []
329
+ try:
330
+ return _self_test_body(failures, ran)
331
+ except BaseException as exc: # noqa: BLE001 - the suite must speak before it dies
332
+ held = ran[-1] if ran else "<no control ran>"
333
+ print(f"sequencing --self-test [FAIL] the suite died after {held!r}: "
334
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
335
+ for name, detail in failures:
336
+ print(f"sequencing --self-test [FAIL] {name}: {detail}", file=sys.stderr)
337
+ print(f"sequencing --self-test: INCOMPLETE ({len(ran)} controls ran, {len(failures)} failed "
338
+ f"before the suite died)", file=sys.stderr)
339
+ raise
340
+
341
+
342
+ def _self_test_body(failures, ran):
343
+ reporting = []
344
+
345
+ def control(name, got, want):
346
+ if reporting:
347
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
348
+ if not isinstance(got, str):
349
+ raise TypeError(f"CONTROL_GOT_NOT_STR {name}: {type(got).__name__}")
350
+ ran.append(name)
351
+ if want not in got:
352
+ failures.append((name, f"expected {want!r} in {got!r}"))
353
+
354
+ def exact_mismatch(got, want):
355
+ return type(got) is not type(want) or got != want
356
+
357
+ def same(name, got, want):
358
+ """A typed, exact control: a verdict `False` is not the string "false", nor 0 (Codex write-path r4 C8)."""
359
+ if reporting:
360
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
361
+ ran.append(name)
362
+ if exact_mismatch(got, want):
363
+ failures.append((name, f"expected exactly {want!r} ({type(want).__name__}), got {got!r} "
364
+ f"({type(got).__name__})"))
365
+
366
+ def clean(name, problems):
367
+ if reporting:
368
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
369
+ if not isinstance(problems, list):
370
+ raise TypeError(f"CLEAN_PROBLEMS_NOT_LIST {name}: {type(problems).__name__}")
371
+ ran.append(name)
372
+ if problems:
373
+ failures.append((name, f"expected nothing, got {problems}"))
374
+
375
+ def refusal(call):
376
+ try:
377
+ call()
378
+ except Refused as exc:
379
+ return str(exc)
380
+ return ""
381
+
382
+ def guarded(call):
383
+ """The call's answer as text, or the exception as text.
384
+
385
+ `refusal` catches only `Refused`; a revert that makes a control raise KeyError instead ends
386
+ the suite in a traceback, and a trial reading any output counts that as the control firing.
387
+ Found by this unit's own round-2 revert trial on the permutation guard.
388
+ """
389
+ try:
390
+ return str(call())
391
+ except BaseException as exc: # noqa: BLE001 - the exception is the answer here
392
+ return f"RAISED {type(exc).__name__}: {exc}"
393
+
394
+ def sequenced(name, call):
395
+ """A positive control's answer, or a named failure when the call refuses.
396
+
397
+ Without this, reverting the search's own fix raised a Refused out of the first positive
398
+ control and the suite died with a traceback: rc!=0, but no control had spoken, which is
399
+ indistinguishable from a crash. Three rows of the revert trial were silent for exactly
400
+ that reason."""
401
+ try:
402
+ return call()
403
+ except Refused as exc:
404
+ if reporting:
405
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}")
406
+ ran.append(name)
407
+ failures.append((name, f"expected an order, got the refusal {exc}"))
408
+ return {"order": [], "tree_hashes": [], "hook_results": [], "gate": "", "set_hash": ""}
409
+
410
+ # The carrier and the route as ONE item: the order exists trivially.
411
+ together = [{"item_id": "i-together",
412
+ "operations": [{"type": "create", "target": "claude/guides/g.md"},
413
+ {"type": "route", "target": "router/relevant.md",
414
+ "names": "claude/guides/g.md"}]}]
415
+ held = sequenced("one item that creates the carrier and its route is sequenced", lambda: sequence(together))
416
+ control("one item that creates the carrier and its route is sequenced", json.dumps(held["order"]),
417
+ "i-together")
418
+ control("and the row records the tree it passed through", str(len(held["tree_hashes"])), "1")
419
+ control("and names the gate that judged it", held["gate"], "route_integrity")
420
+
421
+ # The carrier and the route as TWO items: one order works, the other does not, and the checker
422
+ # must find the one that does.
423
+ carrier = {"item_id": "i-carrier", "operations": [{"type": "create", "target": "claude/guides/g.md"}]}
424
+ route = {"item_id": "i-route", "operations": [{"type": "route", "target": "router/relevant.md",
425
+ "names": "claude/guides/g.md"}]}
426
+ pair = sequenced("a route and its carrier as two items are sequenced carrier first, whatever order "
427
+ "they arrive in", lambda: sequence([route, carrier]))
428
+ control("a route and its carrier as two items are sequenced carrier first, whatever order they "
429
+ "arrive in", json.dumps(pair["order"]), '["i-carrier", "i-route"]')
430
+ clean("and every intermediate tree of that order passed",
431
+ [row for row in pair["hook_results"] if row["problems"]])
432
+
433
+ # ---- validating ONE given order, which is a different question from searching ----------------
434
+ #
435
+ # "Does an order exist" and "does THIS order hold" are not the same, and WP-21's caller needed
436
+ # the second: it asked the first and compared the answers, so a valid APPROVED order was refused
437
+ # whenever another valid order sorted earlier. The pair below is that case — both orders pass,
438
+ # and the one validated is the one asked about.
439
+ given = sequenced("a given order that holds is returned as given",
440
+ lambda: validate_order([carrier, route], ["i-carrier", "i-route"]))
441
+ control("a given order that holds is returned as given", json.dumps(given["order"]),
442
+ '["i-carrier", "i-route"]')
443
+ control("and its trees are the trees of THAT order, one per step",
444
+ str(len(given["tree_hashes"])), "2")
445
+ control("a given order that does not hold is refused at the step that failed, with the gate's "
446
+ "own words",
447
+ refusal(lambda: validate_order([carrier, route], ["i-route", "i-carrier"])),
448
+ "SEQUENCE_ORDER_FAILS at i-route (step 1 of 2)")
449
+ control("while the search, asked the other question about the same set, finds the order that "
450
+ "does hold — which is why a caller must not read one as the other",
451
+ json.dumps(sequenced("the search on that same set",
452
+ lambda: sequence([carrier, route]))["order"]),
453
+ '["i-carrier", "i-route"]')
454
+ control("an order naming an item the set does not hold is refused rather than validated",
455
+ guarded(lambda: refusal(
456
+ lambda: validate_order([carrier, route], ["i-carrier", "i-ghost"]))),
457
+ "SEQUENCE_ORDER_NOT_A_PERMUTATION")
458
+ control("and so is one that leaves an item out",
459
+ guarded(lambda: refusal(
460
+ lambda: validate_order([carrier, route], ["i-carrier"]))),
461
+ "SEQUENCE_ORDER_NOT_A_PERMUTATION")
462
+ control("an empty set is refused by the same name as the search's, since an order over no item "
463
+ "proves nothing either way",
464
+ refusal(lambda: validate_order([], [])), "SEQUENCE_SET_EMPTY")
465
+ control("`order_answer` returns the refusal as a row, like `subset_answer`",
466
+ json.dumps(order_answer([carrier, route], ["i-route", "i-carrier"])["sequenced"]),
467
+ "false")
468
+ control("and the row carries the reason, so the caller can say which step failed",
469
+ order_answer([carrier, route], ["i-route", "i-carrier"])["reason"],
470
+ "SEQUENCE_ORDER_FAILS at i-route")
471
+ control("while a holding order comes back sequenced",
472
+ json.dumps(order_answer([carrier, route], ["i-carrier", "i-route"])["sequenced"]),
473
+ "true")
474
+
475
+ # F17 / done-when 7: the route and a carrier NOBODY creates. No order can help, and the set is
476
+ # named before the freeze rather than after half of it is applied.
477
+ orphan = {"item_id": "i-route-orphan",
478
+ "operations": [{"type": "route", "target": "router/relevant.md",
479
+ "names": "claude/guides/absent.md"}]}
480
+ said = refusal(lambda: sequence([orphan, carrier]))
481
+ control("F17: a route whose carrier no item creates admits no order, and the set is refused by name",
482
+ said, "SEQUENCE_NONE")
483
+ control("and the refusal names every item of the set, so the re-formation knows what to merge",
484
+ said, "i-carrier, i-route-orphan")
485
+ control("and says what happens to such a set before the freeze", said,
486
+ "re-formed into one item or deferred")
487
+
488
+ # ---- the search, against an INDEPENDENT exhaustive answer ------------------------------------
489
+ #
490
+ # The memo was keyed on the applied SET, so a dead end reached by one order marked the set dead
491
+ # for every order — and these operations do not commute: with x already there, `create x` then
492
+ # `delete x` leaves a different tree than the reverse. The set below has an order (b, a, c) and
493
+ # the search said none existed. The control does not re-implement the search; it enumerates the
494
+ # permutations with `itertools` and applies the module's own `apply_to` and gate, which is an
495
+ # independent answer to the same question (the WP-12 review).
496
+ import itertools
497
+
498
+ def exhaustive(rows, gate_fn=route_integrity, base=None):
499
+ """Every order that passes, by brute force. Decidable for the small sets this gate judges."""
500
+ by = {row["item_id"]: row for row in rows}
501
+ held = []
502
+ for order in itertools.permutations(sorted(by)):
503
+ tree, ok = dict(base or {}), True
504
+ for name in order:
505
+ tree = apply_to(tree, by[name])
506
+ if gate_fn(tree):
507
+ ok = False
508
+ break
509
+ if ok:
510
+ held.append(list(order))
511
+ return held
512
+
513
+ overlapping = [{"item_id": "a-create", "operations": [{"type": "create", "target": "x"}]},
514
+ {"item_id": "b-delete", "operations": [{"type": "delete", "target": "x"}]},
515
+ {"item_id": "c-route", "operations": [{"type": "route", "target": "r",
516
+ "names": "x"}]}]
517
+ held_base = {"x": "present"}
518
+ held_answer = subset_answer(overlapping, base=held_base)
519
+ control("a set whose items touch one target in opposite directions is sequenced, because the "
520
+ "tree an order reaches is part of the state the search remembers",
521
+ json.dumps({"sequenced": held_answer.get("sequenced")}), '{"sequenced": true}')
522
+ control("and the order it returns is one brute force also accepts",
523
+ json.dumps(held_answer.get("order") in exhaustive(overlapping, base=held_base)), "true")
524
+ clean("while brute force finds at least one order, so the question is answerable at all",
525
+ [] if exhaustive(overlapping, base=held_base) else ["no order passes by brute force"])
526
+ # And the other direction: the search must not CLAIM an order where brute force finds none.
527
+ unorderable = [{"item_id": "a-route", "operations": [{"type": "route", "target": "r",
528
+ "names": "gone"}]}]
529
+ control("a set brute force rejects is refused by the search too",
530
+ str(subset_answer(unorderable).get("refusal")), "SEQUENCE_NONE")
531
+ # A delete that names an anchor or a section removes TEXT and leaves the file, so a route to that
532
+ # file still points at something; and `g.md#One` is a section of `g.md`, not a second file.
533
+ partial = [{"item_id": "a-trim", "operations": [{"type": "delete", "target": "g.md", "anchor": "old line"}]},
534
+ {"item_id": "b-route", "operations": [{"type": "route", "target": "r", "names": "g.md"}]},
535
+ {"item_id": "c-section", "operations": [{"type": "delete", "target": "g.md#One"}]}]
536
+ control("an anchored or section deletion leaves its file, so a route to it has an order",
537
+ json.dumps(subset_answer(partial, base={"g.md": "present", "r": "present"}).get("sequenced")), "true")
538
+ whole = [partial[1], {"item_id": "d-gone", "operations": [{"type": "delete", "target": "g.md"}]}]
539
+ control("and a delete that names neither still removes the file",
540
+ str(subset_answer(whole, base={"g.md": "present", "r": "present"}).get("refusal")), "SEQUENCE_NONE")
541
+ clean("and brute force agrees there is none", exhaustive(unorderable))
542
+
543
+ # ---- the tree is keyed by IDENTITY, not by the string an operation carries --------------------
544
+ #
545
+ # `claude/g.md`, `./claude/g.md` and `claude//g.md` are one file. Keyed by the raw string they
546
+ # were three, so a create under one spelling and a delete under another left the file present
547
+ # and every order computed here was an order over a tree that does not exist.
548
+ control("a delete spelled otherwise removes what a create put there, because both name one file",
549
+ json.dumps(apply_to(
550
+ apply_to({}, {"item_id": "i-1",
551
+ "operations": [{"type": "create", "target": "claude/g.md"}]}),
552
+ {"item_id": "i-2",
553
+ "operations": [{"type": "delete", "target": "./claude/g.md"}]})),
554
+ "{}")
555
+ control("and a second spelling of a create is the same key, not a second file",
556
+ json.dumps(sorted(apply_to(
557
+ apply_to({}, {"item_id": "i-1",
558
+ "operations": [{"type": "create", "target": "claude/g.md"}]}),
559
+ {"item_id": "i-2",
560
+ "operations": [{"type": "create", "target": "claude//g.md"}]}))),
561
+ '["claude/g.md"]')
562
+ # A route's entry names the path it points AT (`names`), and the carrier it is written into is
563
+ # the target — so the identity that matters here is the one in the entry's key.
564
+ control("a route written under a second spelling of its carrier is one entry, not two",
565
+ json.dumps(sorted(apply_to(
566
+ apply_to({}, {"item_id": "i-1",
567
+ "operations": [{"type": "route", "target": "claude/g.md",
568
+ "names": "claude/h.md"}]}),
569
+ {"item_id": "i-2", "operations": [{"type": "route", "target": "./claude/g.md",
570
+ "names": "claude/h.md"}]}))),
571
+ '["route:claude/g.md->claude/h.md"]')
572
+ control("an unspellable target keeps its own string, so the order is still computed and the "
573
+ "spelling contract is what reports it",
574
+ json.dumps(sorted(apply_to({}, {"item_id": "i-1",
575
+ "operations": [{"type": "create",
576
+ "target": "/etc/passwd"}]}))),
577
+ '["/etc/passwd"]')
578
+
579
+ # ---- the set identity binds every field the stand-in reads -----------------------------------
580
+ #
581
+ # `units` was missing, so two sets with OPPOSITE verdicts shared one hash: with x and y in the
582
+ # base and a route to x, merging units=[x] breaks the route and merging units=[y] does not.
583
+ merge_x = [{"item_id": "m", "operations": [{"type": "merge", "target": "out",
584
+ "units": ["x"]}]},
585
+ {"item_id": "r", "operations": [{"type": "route", "target": "router/r.md",
586
+ "names": "x"}]}]
587
+ merge_y = [{"item_id": "m", "operations": [{"type": "merge", "target": "out",
588
+ "units": ["y"]}]},
589
+ {"item_id": "r", "operations": [{"type": "route", "target": "router/r.md",
590
+ "names": "x"}]}]
591
+ merge_base = {"x": "present", "y": "present"}
592
+ control("two sets that differ only in a merge's units have different identities",
593
+ json.dumps(set_hash(merge_x) != set_hash(merge_y)), "true")
594
+ control("and their verdicts really do differ, so the identity had to tell them apart",
595
+ json.dumps({"x": subset_answer(merge_x, base=merge_base).get("sequenced"),
596
+ "y": subset_answer(merge_y, base=merge_base).get("sequenced")}),
597
+ '{"x": false, "y": true}')
598
+ # Both ways, from the reader's own source rather than from a list written here (Codex WP-12 r2 F10: the
599
+ # one-way check passed while `apply_to` read `anchor` and the identity left it out)
600
+ read_fields = set(re.findall(r"""op\.get\(["']([a-z_]+)["']""", inspect.getsource(apply_to)))
601
+ clean("the fields `apply_to` reads are found in its source, so the comparison below is not over nothing",
602
+ [] if len(read_fields) >= 4 else [f"found only {sorted(read_fields)}"])
603
+ clean("every field `apply_to` reads is in the identity, and the identity names no field it does not read",
604
+ [f"read, not bound: {f}" for f in sorted(read_fields - set(OPERATION_FIELDS))]
605
+ + [f"bound, not read: {f}" for f in sorted(set(OPERATION_FIELDS) - read_fields)])
606
+ anchored = [{"item_id": "d", "operations": [{"type": "delete", "target": "x", "anchor": "text"}]},
607
+ {"item_id": "r", "operations": [{"type": "route", "target": "router/r.md", "names": "x"}]}]
608
+ whole = [{"item_id": "d", "operations": [{"type": "delete", "target": "x"}]},
609
+ {"item_id": "r", "operations": [{"type": "route", "target": "router/r.md", "names": "x"}]}]
610
+ control("two sets that differ only in a delete's anchor have different identities and opposite verdicts",
611
+ json.dumps([set_hash(anchored) != set_hash(whole),
612
+ subset_answer(anchored, base={"x": "present"}).get("sequenced"),
613
+ subset_answer(whole, base={"x": "present"}).get("sequenced")]), "[true, true, false]")
614
+ section_merge = [{"item_id": "m", "operations": [{"type": "merge", "target": "out.md",
615
+ "units": ["g.md#One"]}]},
616
+ {"item_id": "r", "operations": [{"type": "route", "target": "router/r.md", "names": "g.md"}]}]
617
+ control("the typed control tells a verdict from its spelling: the string, 0 and False itself",
618
+ json.dumps([exact_mismatch("false", False), exact_mismatch(0, False), exact_mismatch(False, False)]),
619
+ "[true, true, false]")
620
+ same("a merge of one section leaves its file, so a route to that file still has it (Codex WP-12 r2 F11)",
621
+ subset_answer(section_merge, base={"g.md": "present", "out.md": "present"}).get("sequenced"), True)
622
+ same("while a merge of the whole file removes it, and the same route then points at nothing",
623
+ subset_answer([{**section_merge[0], "operations": [{"type": "merge", "target": "out.md",
624
+ "units": ["g.md"]}]}, section_merge[1]],
625
+ base={"g.md": "present", "out.md": "present"}).get("sequenced"), False)
626
+ # Codex WP-12 r3 F5: an empty or blank section suffix names no section, as S11 reads it
627
+ for suffix in ("g.md#", "g.md# "):
628
+ for kind, extra in (("merge", {"target": "out.md", "units": [suffix]}), ("delete", {"target": suffix})):
629
+ same(f"a {kind} of {suffix!r} is the whole file's, as S11 reads it, so the route to it points at nothing",
630
+ subset_answer([{"item_id": "m", "operations": [{"type": kind, **extra}]}, section_merge[1]],
631
+ base={"g.md": "present", "out.md": "present"}).get("sequenced"), False)
632
+
633
+ # The exported checker on an approved SUBSET: the full set has an order, the subset does not, and
634
+ # the subset is what is judged (done-when 7's control fixture; WP-20 and WP-21 re-run this).
635
+ full = [carrier, route]
636
+ clean("the full set has an order",
637
+ [row for row in sequenced("the full set has an order", lambda: sequence(full))["hook_results"]
638
+ if row["problems"]])
639
+ control("while the approved subset that keeps the route and drops its carrier has none, and it is "
640
+ "the subset that is answered",
641
+ refusal(lambda: sequence([route])), "SEQUENCE_NONE")
642
+ control("and the refusal names the subset's own hash, not the full set's",
643
+ refusal(lambda: sequence([route])), set_hash([route])[:12])
644
+ # The exported re-run entry: WP-20 and WP-21 hand it the approved subset and get a ROW, because
645
+ # whether to apply is their caller's decision and this module applies nothing.
646
+ answer = subset_answer([route])
647
+ # `.get`, not `[...]`: a mutation that makes this subset sequence removes the key, and indexing it
648
+ # killed the suite with a KeyError instead of failing by name. Four rows of the revert trial were
649
+ # silent for that reason.
650
+ control("the subset entry WP-20 and WP-21 re-run returns the unsequenced answer instead of raising",
651
+ str(answer.get("refusal")), "SEQUENCE_NONE")
652
+ control("and the returned row carries the subset's own hash", str(answer.get("set_hash")),
653
+ set_hash([route]))
654
+ clean("and no order, so nothing downstream can read it as appliable",
655
+ list(answer.get("order") or []) + list(answer.get("tree_hashes") or [])
656
+ + list(answer.get("hook_results") or []))
657
+ control("while an approved subset that does have an order comes back sequenced",
658
+ json.dumps(subset_answer([carrier])["sequenced"]), "true")
659
+ clean("the two hashes differ, so a reader cannot mistake one answer for the other",
660
+ [] if set_hash([route]) != set_hash(full) else ["the subset hashes as the full set"])
661
+
662
+ # Canonically equal spellings are one file in every position an operation names one. The
663
+ # expected verdicts are written out here, not computed: composed and decomposed `é`.
664
+ nfc, nfd = "guides/\u00e9.md", "guides/e\u0301.md"
665
+ route_to = lambda names: {"item_id": "r", "operations": [ # noqa: E731
666
+ {"type": "route", "target": "router.md", "names": names}]}
667
+ merge_of = lambda unit: {"item_id": "m", "operations": [ # noqa: E731
668
+ {"type": "merge", "target": "guides/kept.md", "units": [unit]}]}
669
+ # The verdict is asked for by IDENTITY: `control` matches a substring, and a verdict that came
670
+ # back as the string 'false' — truthy to every caller — passed it (the round-6 review).
671
+ control("a merge that removes a routed file under its OTHER spelling still breaks the route",
672
+ str(order_answer([route_to(nfc), merge_of(nfd)], ["r", "m"],
673
+ base={nfc: "present"}).get("sequenced") is False), "True")
674
+ control("a route spelled the other way reaches the carrier the base holds",
675
+ str(subset_answer([route_to(nfd)], base={nfc: "present"}).get("sequenced") is True), "True")
676
+ control("and a base spelled the other way is the same tree",
677
+ str(subset_answer([route_to(nfc)], base={nfd: "present"}).get("sequenced") is True), "True")
678
+ unrelated = {"item_id": "u", "operations": [{"type": "edit", "target": "guides/other.md"}]}
679
+ control("a route ALREADY in the base, spelled the other way from its carrier, is a route to that "
680
+ "carrier: an unrelated edit over it sequences",
681
+ str(subset_answer([unrelated], base={nfc: "present", f"route:router.md->{nfd}": "present"})
682
+ .get("sequenced") is True), "True")
683
+ # A base tree the carrier is already in: the route alone then sequences, which is the case where
684
+ # the subset is approved AFTER its carrier has landed in an earlier run.
685
+ clean("a route alone sequences where the tree already holds its carrier",
686
+ [row for row in sequenced("a route alone sequences where the tree already holds its carrier",
687
+ lambda: sequence([route], base={"claude/guides/g.md": "present"}))
688
+ ["hook_results"] if row["problems"]])
689
+
690
+ # The guards on the set itself.
691
+ control("an empty set is refused rather than reported as sequenced",
692
+ refusal(lambda: sequence([])), "SEQUENCE_SET_EMPTY")
693
+ control("a set past the search bound is refused rather than computed",
694
+ refusal(lambda: sequence([{"item_id": f"i-{n}", "operations": []} for n in range(SET_LIMIT + 1)])),
695
+ "SEQUENCE_SET_TOO_LARGE")
696
+ control("an item that appears twice in one set is named",
697
+ refusal(lambda: sequence([carrier, carrier])), "SEQUENCE_ITEM_REPEATED")
698
+ control("an operation of a type §7.3 does not have is named",
699
+ refusal(lambda: sequence([{"item_id": "i-x", "operations": [{"type": "rename",
700
+ "target": "a"}]}])),
701
+ "OPERATION_UNKNOWN")
702
+
703
+ # The stand-in gate itself, in both directions.
704
+ clean("the stand-in passes a tree whose every route names a path it holds",
705
+ route_integrity({"claude/guides/g.md": "present",
706
+ "route:router/relevant.md->claude/guides/g.md": "present"}))
707
+ control("and names a route to nothing",
708
+ "; ".join(route_integrity({"route:router/relevant.md->claude/guides/g.md": "present"})),
709
+ "ROUTE_TO_NOTHING")
710
+
711
+ # The document, and what it says about a set with no order.
712
+ doc = document([together, [orphan, carrier]])
713
+ control("the document carries one row per set", str(doc["summary"]["sets"]), "2")
714
+ control("and counts the ones with no order", str(doc["summary"]["unsequenced"]), "1")
715
+ control("the unsequenced row carries the refusal's name",
716
+ json.dumps([row for row in doc["sets"] if not row["sequenced"]]), "SEQUENCE_NONE")
717
+ clean("and no row carries a tree's contents, only its hash",
718
+ [key for row in doc["sets"] for key in row if key in ("tree", "trees", "contents")])
719
+
720
+ # The predicate the real-hook script consults, by the hook's own markers. It is pure, so these
721
+ # controls cost nothing and cannot start anything - which is the point: when the marker check lived
722
+ # beside the subprocess, the revert trial ran the real hook twice in scratch worktrees, once to a
723
+ # 600-second timeout, and left both worktrees behind.
724
+ control("the hook's index snapshot is read as being under the hook",
725
+ "; ".join(under_the_hook({"GIT_INDEX_FILE": f"/tmp/{HOOK_INDEX_PREFIX}.AbCdEf"})),
726
+ "GIT_INDEX_FILE names the hook's index snapshot")
727
+ control("and its materialised tree too",
728
+ "; ".join(under_the_hook({"GIT_WORK_TREE": f"/tmp/{HOOK_TREE_PREFIX}.AbCdEf"})),
729
+ "GIT_WORK_TREE names the hook's materialised tree")
730
+ control("both markers at once give both reasons, so a caller knows which one fired",
731
+ str(len(under_the_hook({"GIT_INDEX_FILE": f"/tmp/{HOOK_INDEX_PREFIX}.A",
732
+ "GIT_WORK_TREE": f"/tmp/{HOOK_TREE_PREFIX}.B"}))), "2")
733
+ clean("while an environment with neither marker is not read as under the hook",
734
+ under_the_hook({"GIT_INDEX_FILE": "/tmp/some-other-index", "GIT_WORK_TREE": "/srv/tree"}))
735
+ clean("and an empty environment is not either", under_the_hook({}))
736
+
737
+ # That this module starts NOTHING is a property of its source, asserted here because the dispatch
738
+ # judge and this suite are checking two different things: dispatch asks whether a program it finds
739
+ # is declared, and this asks that there be none to find. The first form of this control compared a
740
+ # string with itself and could not fail.
741
+ import ast
742
+ own_text = pathlib.Path(__file__).read_text(encoding="utf-8")
743
+ own = ast.parse(own_text)
744
+ starters = {"subprocess", "tempfile", "multiprocessing", "pty", "runpy"}
745
+ imported = sorted({name.name.split(".")[0] for node in ast.walk(own)
746
+ if isinstance(node, ast.Import) for name in node.names}
747
+ | {(node.module or "").split(".")[0] for node in ast.walk(own)
748
+ if isinstance(node, ast.ImportFrom)})
749
+ clean("this module imports nothing that can start a process or make a scratch directory, so the "
750
+ "real hook cannot be reached from here at all",
751
+ sorted(starters.intersection(imported)))
752
+ calls = sorted({ast.unparse(node.func) for node in ast.walk(own) if isinstance(node, ast.Call)
753
+ and ast.unparse(node.func).split(".")[0] in starters})
754
+ clean("and makes no call into one under another name", calls)
755
+ control("while the suite can still see such a call when there is one, so this pair is not vacuous",
756
+ ", ".join(sorted({ast.unparse(node.func) for node in ast.walk(ast.parse(
757
+ "import subprocess\nsubprocess.run(['git', 'status'])"))
758
+ if isinstance(node, ast.Call)})), "subprocess.run")
759
+ # The script that does run the hook, and the two properties that are its alone to prove.
760
+ script = HERE.parent / "gates" / "sequencing-real-hook-check.sh"
761
+ control("the real-hook check lives outside session-distill, as a script the lead runs explicitly",
762
+ "present" if script.is_file() else f"absent at {script}", "present")
763
+ # The script's EXECUTABLE lines, with its comments removed: the first form of these two controls
764
+ # read the whole file and was satisfied by the prose at its top, so removing the real line left
765
+ # them green. A check that a comment can satisfy is a check about comments.
766
+ held = "\n".join(line for line in (script.read_text(encoding="utf-8") if script.is_file() else "")
767
+ .splitlines() if not line.lstrip().startswith("#"))
768
+ control("and it asks this module whether it is under the hook rather than re-deriving the markers",
769
+ "asks" if any("sequencing.py" in line and "--under-the-hook" in line
770
+ for line in held.splitlines()) else "re-derives or does not ask", "asks")
771
+ control("and bounds the hook run by a timeout",
772
+ # "bounded" / "unbounded" was the first pair here, and `control` asks whether the wanted
773
+ # text is IN the got text: "bounded" is a substring of "unbounded", so the control passed
774
+ # over a script with no bound at all. Opposites, not a word and its negation.
775
+ "alarm bounds the hook" if any("alarm" in line and "$HOOK" in line
776
+ for line in held.splitlines())
777
+ else "the hook runs with no time bound", "alarm bounds the hook")
778
+ control("and it is not a leg of the umbrella, which the hook itself runs",
779
+ "not a leg" if "sequencing-real-hook-check" not in
780
+ (HERE.parent / "gates" / "check-parity.sh").read_text(encoding="utf-8") else "a leg",
781
+ "not a leg")
782
+
783
+ # The wrapper that makes a dying control speak. Asserted from the source, because a suite that
784
+ # ends in a traceback prints no control name at all and a revert trial then reads the traceback
785
+ # as the control firing (the WP-12 review).
786
+ # The WRAPPER's own source, not the file's. A scan of the whole file is satisfied by this
787
+ # control's own text — the phrase it looks for appears in the line that looks for it — which is
788
+ # how a planted mutation passed here before. The wrapper lives in `self_test` and this control
789
+ # lives in `_self_test_body`, so asking `self_test` for its source excludes the control.
790
+ wrapper_text = inspect.getsource(self_test)
791
+ control("a control that dies names itself, since a traceback is not a control firing",
792
+ next((line.strip() for line in wrapper_text.splitlines()
793
+ if "died after" in line and "print(" in line), "<no such line>"),
794
+ "self-test [FAIL] the suite died after")
795
+ control("and the wrapper is what the entry point runs, so the body cannot be called around it",
796
+ next((line.strip() for line in wrapper_text.splitlines()
797
+ if "_self_test_body(" in line), "<no such line>"),
798
+ "return _self_test_body(failures, ran)")
799
+
800
+ reporting.append(True)
801
+ if failures:
802
+ for name, detail in failures:
803
+ print(f"sequencing --self-test [FAIL] {name}: {detail}", file=sys.stderr)
804
+ print(f"sequencing --self-test: FAILED ({len(failures)} of {len(ran)} controls)", file=sys.stderr)
805
+ return 1
806
+ print(f"sequencing --self-test: OK ({len(ran)} controls: the search over a set's orders with the "
807
+ f"deterministic stand-in - a route and its carrier in either arrival order, a set no order "
808
+ f"helps refused by name before the freeze, an approved subset judged on its own hash, the "
809
+ f"guards on the set, and the real-hook command's refusal under the hook's own markers; the "
810
+ f"real hook is never run here)")
811
+ return 0
812
+
813
+
814
+ if __name__ == "__main__":
815
+ argv = sys.argv[1:]
816
+ if argv[:1] == ["--self-test"]:
817
+ sys.exit(self_test())
818
+ if argv[:1] == ["--under-the-hook"]:
819
+ # The one owner of the question, read by `gates/sequencing-real-hook-check.sh`: exit 1 and say
820
+ # why when this process is inside a commit, exit 0 when it is not.
821
+ said = under_the_hook()
822
+ if said:
823
+ sys.exit(f"REAL_HOOK_UNDER_HOOK: {'; '.join(said)} - the umbrella is itself run by the "
824
+ f"pre-commit hook, so running the hook from under it recurses; run the check on "
825
+ f"its own")
826
+ print("not under the hook")
827
+ sys.exit(0)
828
+ sys.exit("usage: sequencing.py --self-test | --under-the-hook\n"
829
+ "the real hook check: gates/sequencing-real-hook-check.sh")