agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,1077 @@
1
+ #!/usr/bin/env python3
2
+ """Drift and order, before the first effect (WP-21 commit 3).
3
+
4
+ Design §10.5: "The live configuration manifest is recomputed and compared with F's manifest minus
5
+ the approved interventions — any difference is drift and stops the affected items. F fixes the order
6
+ of operations; operations sharing a target are chained, each expecting the previous operation's
7
+ after-hash as its before-hash, and each operation re-checks its own target before running."
8
+
9
+ Three questions, each answered by data rather than by judgement here:
10
+
11
+ **Did anything move that the run did not approve?** `drift_problems` compares the recomputed live
12
+ manifest with B's manifest minus the approved interventions. A layer some approved operation targets
13
+ is `DRIFT_TARGET`; one no operation targets is `DRIFT_UNTARGETED`. Both stop items; they are reported
14
+ apart because O8 names them apart.
15
+
16
+ **Was every target's layer compared at all?** The comparison runs over the layers
17
+ `config_manifest_B` carries (the lead's reading of 2026-11-12). Layers it does not carry are named
18
+ by `unchecked_layers` for the run record — a layer silently skipped is how this repository has most
19
+ often been wrong — and an approved operation whose target lies in such a layer is refused BEFORE any
20
+ effect (`OPERATION_LAYER_UNCHECKED`). The per-operation `before_state_sha256` is the second guard on
21
+ the target, not a substitute: it says this file has not moved, while the manifest says this layer has
22
+ not moved.
23
+
24
+ **Does F admit the order it was approved in?** `order_problems` re-validates F through
25
+ `runlib/sequencing.py` — the same module WP-12 built for the commit-sequencing question — and
26
+ `chain_problems` holds operations sharing a target to the hash chain.
27
+
28
+ This module reads no configuration: the live manifest is handed to it. That is what keeps it away
29
+ from the owner's homes, and its suite asserts it spawns nothing. Its one look at the filesystem is
30
+ where a destination lands (`library_place`): the path's symlinks resolved and its ancestors asked
31
+ whether they hold `claude/` and `codex/`, no file read; the hosts' homes are handed to it too. The
32
+ suite's effect audit does not see that function, because only the suite calls it in this module
33
+ (FINDINGS F-46).
34
+
35
+ drift.py --self-test
36
+ """
37
+ import json
38
+ import os
39
+ import pathlib
40
+ import posixpath
41
+ import sys
42
+
43
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
44
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
45
+ from runlib import destinations, sequencing, targets # noqa: E402
46
+ from runlib.records import Refused # noqa: E402
47
+
48
+ HERE = pathlib.Path(__file__).resolve().parents[1]
49
+ TABLE_PATH = HERE / "tables" / "drift_layers.json"
50
+ DESIGN_10_5_DRIFT = (
51
+ "the live configuration manifest is recomputed and compared with F's manifest minus the "
52
+ "approved interventions — any difference is drift and stops the affected items")
53
+ _TABLE = {}
54
+
55
+
56
+ def table():
57
+ if not _TABLE:
58
+ _TABLE.update(json.loads(TABLE_PATH.read_text(encoding="utf-8")))
59
+ return _TABLE
60
+
61
+
62
+ def layers():
63
+ return tuple(row["layer"] for row in table()["layers"])
64
+
65
+
66
+ def table_problems():
67
+ """What is wrong with the layer table itself, by name."""
68
+ problems, rows = [], table()["layers"]
69
+ if not rows:
70
+ problems.append("LAYER_SET_EMPTY: a layer map over no layer decides nothing")
71
+ return problems
72
+ seen = set()
73
+ for row in rows:
74
+ name = row.get("layer")
75
+ if not name:
76
+ problems.append("LAYER_UNNAMED: a row with no layer")
77
+ continue
78
+ if name in seen:
79
+ problems.append(f"LAYER_REPEATED {name}: two rows claiming one layer")
80
+ seen.add(name)
81
+ if not row.get("prefixes"):
82
+ problems.append(f"LAYER_WITHOUT_PREFIX {name}: a layer no path belongs to claims no "
83
+ f"target, so it can never be the layer a refusal names")
84
+ if not row.get("$comment"):
85
+ problems.append(f"LAYER_UNREASONED {name}: every row carries its own reason")
86
+ # A prefix claimed by two layers makes `layer_of` arbitrary, which is worse than unmapped.
87
+ owners = {}
88
+ for row in rows:
89
+ for prefix in row.get("prefixes") or ():
90
+ if prefix in owners:
91
+ problems.append(f"PREFIX_SHARED {prefix}: claimed by {owners[prefix]} and "
92
+ f"{row['layer']}, so a target under it has no one layer")
93
+ owners[prefix] = row["layer"]
94
+ return problems
95
+
96
+
97
+ def target_identity(target):
98
+ """The canonical identity of a target path, or None when it is not a target at all.
99
+
100
+ One identity for validation, layer mapping, chaining, journalling and application — and one
101
+ OWNER for it: `runlib/targets.py`. This was a copy of those rules, and the journal carried a
102
+ third, which is how `./claude/CLAUDE.md` came to be refused here and accepted there.
103
+ """
104
+ return targets.identity(targets.file_of(target))
105
+
106
+
107
+ # The instruction trees by their top directory, read from a checkout's root: a file beneath one is shipped or
108
+ # installed as instructions whatever its name, as a skill's bundle takes every file beneath it
109
+ # (`compose/instructions_catalog.py`). And the hosts' installed homes, whose files the hosts read as instructions.
110
+ LIBRARY_TREES = ("claude", "codex", "ko")
111
+ INSTALLED_HOMES = (".claude", ".codex")
112
+
113
+
114
+ def _relative_place(rel):
115
+ held = pathlib.PurePosixPath(rel).as_posix()
116
+ layers = {layer_of(held), layer_of(held.casefold())} - {None, "ledger"}
117
+ if layers:
118
+ return f"in the {', '.join(sorted(layers))} layer"
119
+ tree = held.casefold().split("/", 1)[0]
120
+ if tree in LIBRARY_TREES:
121
+ return f"under the instruction tree {tree}/"
122
+ return None
123
+
124
+
125
+ def library_place(path, homes=()):
126
+ """Where a path falls inside the instructions, or None (release 1's confirmation review, F1 and F2 of all three
127
+ rounds). A relative path is read from a checkout's root: its layer, any but `ledger`, or its instruction tree,
128
+ case-folded. An absolute path is resolved with its symlinks followed and read the same way from every ancestor
129
+ that holds both `claude/` and `codex/` - an agent-bios checkout or package, so a checkout or a run directory
130
+ placed inside a skill is named - and inside a host's home: a `.claude` or `.codex` component, or any of `homes`,
131
+ compared case-folded. `homes` are the hosts' homes as the environment configures them, resolved by the caller
132
+ (`inventory.instructions_place`), because this module reads no configuration."""
133
+ held = pathlib.PurePosixPath(str(path))
134
+ if not held.is_absolute():
135
+ return _relative_place(held.as_posix())
136
+ parts = pathlib.Path(os.path.realpath(str(path))).parts
137
+ for n, part in enumerate(parts):
138
+ if part.casefold() in INSTALLED_HOMES:
139
+ return f"inside the host's installed home {pathlib.Path(*parts[:n + 1])}"
140
+ folded = [part.casefold() for part in parts]
141
+ for home in homes:
142
+ home_parts = [part.casefold() for part in pathlib.Path(home).parts]
143
+ if len(home_parts) > 1 and folded[:len(home_parts)] == home_parts:
144
+ return f"inside the host's configured home {home}"
145
+ for n in range(1, len(parts)):
146
+ root = pathlib.Path(*parts[:n])
147
+ if (root / "claude").is_dir() and (root / "codex").is_dir():
148
+ where = _relative_place("/".join(parts[n:]))
149
+ if where:
150
+ return f"{where} of {root}"
151
+ return None
152
+
153
+
154
+ def target_problems(target, checkout=None):
155
+ """Why this target may not be applied, by name. Empty means it is canonical and contained.
156
+
157
+ With a checkout, the path the KERNEL will walk is judged too: a symlink anywhere in the chain
158
+ is refused, because `claude/guides/to-root/CLAUDE.md` reaches the always-loaded global file
159
+ while being classified as a guide, and the global-file judgment, the merge requirement and the
160
+ ceiling all belong to the layer the path was classified as.
161
+ """
162
+ return targets.problems(targets.file_of(target), checkout)
163
+
164
+
165
+ def layer_of(target):
166
+ """The layer a target lies in, or None. The longest matching prefix wins.
167
+
168
+ Longest, not first: `claude/CLAUDE.md` is the global file while `claude/guides/` is the guides
169
+ layer, and a first-match rule would make the answer depend on the table's order.
170
+ """
171
+ held = target_identity(target)
172
+ if held is None:
173
+ return None
174
+ # By COMPONENT, and a prefix ending in `/` is a DIRECTORY while one that does not is an exact
175
+ # file. Treating every prefix as unrestricted text made `install.sh.backup` enforcement and
176
+ # `claude/CLAUDE.md.extra` the global file — a sibling by name became the thing itself, and with
177
+ # those layers in B an operation on it was certified as drift-checked (the WP-21 review).
178
+ parts = held.split("/")
179
+ best, best_length = None, -1
180
+ for row in table()["layers"]:
181
+ for prefix in row.get("prefixes") or ():
182
+ if prefix.endswith("/"):
183
+ held_parts = prefix.rstrip("/").split("/")
184
+ matched = parts[:len(held_parts)] == held_parts and len(parts) > len(held_parts)
185
+ else:
186
+ matched = held == posixpath.normpath(prefix)
187
+ if matched and len(prefix) > best_length:
188
+ best, best_length = row["layer"], len(prefix)
189
+ return best
190
+
191
+
192
+ def declared_layers(declaration):
193
+ """The layers B's manifest carries — the ones drift is compared over."""
194
+ return tuple(sorted((declaration or {}).get("config_manifest_B") or {}))
195
+
196
+
197
+ def unchecked_layers(declaration):
198
+ """Layers this table knows that B's manifest does not carry, for the run record.
199
+
200
+ Named rather than skipped: the run record says which layers nobody compared, because a layer
201
+ quietly left out of a comparison reads as a layer that did not move.
202
+ """
203
+ held = set(declared_layers(declaration))
204
+ return tuple(name for name in layers() if name not in held)
205
+
206
+
207
+ def expected_manifest(declaration, interventions):
208
+ """F's manifest minus the approved interventions: what the live manifest should equal.
209
+
210
+ `interventions` maps a layer to the digest its approved operations are expected to leave. A layer
211
+ with an approved intervention is expected to CHANGE, so comparing it against B would report the
212
+ approved change as drift — which is exactly what "minus the approved interventions" prevents.
213
+ """
214
+ held = dict((declaration or {}).get("config_manifest_B") or {})
215
+ for layer, digest in (interventions or {}).items():
216
+ if layer in held:
217
+ held[layer] = digest
218
+ return held
219
+
220
+
221
+ def drift_problems(live, declaration, interventions=None, targeted=()):
222
+ """Every drift, by name: a targeted layer apart from an untargeted one (O8).
223
+
224
+ `live` is the recomputed manifest, handed in. A layer B carries and `live` does not is drift too:
225
+ the layer the run was declared against is no longer there to compare.
226
+ """
227
+ problems = []
228
+ expected = expected_manifest(declaration, interventions)
229
+ targeted = set(targeted)
230
+ for layer in sorted(expected):
231
+ want = expected[layer]
232
+ if layer not in (live or {}):
233
+ problems.append(f"DRIFT_LAYER_ABSENT {layer}: the declaration carries it and the live "
234
+ f"manifest does not, so there is nothing to compare")
235
+ continue
236
+ got = live[layer]
237
+ if got == want:
238
+ continue
239
+ code = "DRIFT_TARGET" if layer in targeted else "DRIFT_UNTARGETED"
240
+ problems.append(f"{code} {layer}: live {got[:12]}… is not the expected {want[:12]}…, so "
241
+ f"every item {'targeting' if layer in targeted else 'in this run'} stops "
242
+ f"for rebuild, retest and re-confirmation")
243
+ return problems
244
+
245
+
246
+ def effect_paths(operation):
247
+ """Every file one operation changes: its target, and for a merge the units it removes.
248
+
249
+ A merge is executed as deletes plus one edit, so the files it removes are effects exactly as its
250
+ target is. Asking only the target let a merge into a compared layer remove a file in a layer
251
+ nobody compared (the round-5 review)."""
252
+ held = [operation.get("target")]
253
+ if operation.get("type") == "merge":
254
+ held += list(operation.get("units") or ())
255
+ return held
256
+
257
+
258
+ def operation_problems(f, declaration):
259
+ """Every approved operation whose target no comparison covers, by name. Before any effect.
260
+
261
+ Two refusals, apart on purpose: a target in a layer the declaration did not carry was never
262
+ compared (`OPERATION_LAYER_UNCHECKED`), and a target no layer claims at all cannot be compared
263
+ (`OPERATION_LAYER_UNKNOWN`) — the second is a table gap, the first a declaration gap.
264
+ """
265
+ problems, held = [], set(declared_layers(declaration))
266
+ # The declared checkout root, which is what the identity contract is bound to. Absent, the
267
+ # spelling is still judged and the walk is not claimed — `targets.problems` says which.
268
+ checkout = ((declaration or {}).get("destinations") or {}).get("checkout")
269
+ held_targets = [path for item in f or () for operation in item.get("operations") or ()
270
+ for path in effect_paths(operation)]
271
+ problems += targets.set_problems(held_targets, checkout if checkout
272
+ and pathlib.Path(checkout).is_dir() else None)
273
+ for item in f or ():
274
+ for target in (path for operation in item.get("operations") or ()
275
+ for path in effect_paths(operation)):
276
+ layer = layer_of(target)
277
+ if layer is None:
278
+ problems.append(f"OPERATION_LAYER_UNKNOWN {item.get('item_id')} {target!r}: no "
279
+ f"layer in tables/drift_layers.json claims this path, so no "
280
+ f"manifest covers it")
281
+ continue
282
+ if layer not in held:
283
+ problems.append(f"OPERATION_LAYER_UNCHECKED {item.get('item_id')} {target!r}: its "
284
+ f"layer {layer!r} is not in the declaration's config_manifest_B, so "
285
+ f"nobody compared that layer's state")
286
+ return problems
287
+
288
+
289
+ def targeted_layers(f):
290
+ """The layers F's approved operations target, for `drift_problems`."""
291
+ held = []
292
+ for item in f or ():
293
+ for operation in item.get("operations") or ():
294
+ for path in effect_paths(operation):
295
+ layer = layer_of(path)
296
+ if layer and layer not in held:
297
+ held.append(layer)
298
+ return tuple(held)
299
+
300
+
301
+ def chain_problems(f):
302
+ """Operations sharing a target held to the hash chain, in F's own order.
303
+
304
+ §10.5: each expects the previous operation's after-hash as its before-hash. F as lane E's S10
305
+ writes it carries `before_state_sha256` per operation and no after-hash, so the chain is checked
306
+ where an after-hash is present and reported as unstated where it is not — an unstated link is a
307
+ gap in the input, not a passing check.
308
+ """
309
+ problems, last = [], {}
310
+ for item in f or ():
311
+ for operation in item.get("operations") or ():
312
+ raw = operation.get("target")
313
+ for held in target_problems(raw):
314
+ problems.append(f"{held.split()[0]} {item.get('item_id')}: {held}")
315
+ # Keyed on the CANONICAL identity: keyed on the raw string, `claude/guides//g.md` and
316
+ # `claude/guides/g.md` were two targets, so one file could be edited twice with neither
317
+ # operation seeing the other's after-hash.
318
+ target = target_identity(raw)
319
+ before = operation.get("before_state_sha256")
320
+ if target in last:
321
+ after = last[target]["after"]
322
+ if after is None:
323
+ problems.append(f"CHAIN_UNSTATED {target}: {last[target]['item']} states no "
324
+ f"after-hash, so the next operation's before-hash has nothing "
325
+ f"to equal")
326
+ elif before != after:
327
+ problems.append(f"TARGET_MISMATCH {item.get('item_id')} {target}: its "
328
+ f"before-hash {str(before)[:12]}… is not the previous "
329
+ f"operation's after-hash {str(after)[:12]}…")
330
+ # A merge REMOVES its units, and a removed file's state is `absent` for whatever comes
331
+ # next. The chain read the target alone, so an edit expecting the removed file's old
332
+ # hash followed the merge that deleted it and nothing said so (the round-6 review).
333
+ # The units FIRST and the target after, as `sequencing.apply_to` does: a merge whose
334
+ # units include its own target removes it and then leaves it, so the target's state is
335
+ # its after-hash, and written the other way round the survivor was recorded absent (the
336
+ # round-7 review).
337
+ if operation.get("type") == "merge":
338
+ for unit in operation.get("units") or ():
339
+ for held in target_problems(unit):
340
+ problems.append(f"{held.split()[0]} {item.get('item_id')}: {held}")
341
+ last[target_identity(unit)] = {"after": "absent", "item": item.get("item_id")}
342
+ last[target] = {"after": operation.get("after_state_sha256"),
343
+ "item": item.get("item_id")}
344
+ return problems
345
+
346
+
347
+ def order_problems(f, gate=None, base=None):
348
+ """Whether F's approved order is one every intermediate state admits.
349
+
350
+ Through `runlib/sequencing.py`, the module WP-12 built for the same question: a set of items
351
+ admits an order whose every intermediate tree passes the gate. A set with no valid order is
352
+ returned as a row rather than raised, so the caller can return the items instead of stopping the
353
+ run.
354
+ """
355
+ # The COMPLETE operations, not a two-field summary. The adapter kept only `type` and `target`,
356
+ # and `sequencing.apply_to` reads `names` for route destinations and `units` for removals: a
357
+ # valid carrier-then-route set therefore could not be sequenced at all, and a merge's removals
358
+ # were invisible to the intermediate trees (the WP-21 review).
359
+ items = [{"item_id": item.get("item_id"),
360
+ "operations": [dict(operation) for operation in item.get("operations") or ()]}
361
+ for item in f or ()]
362
+ if not items:
363
+ return {"ordered": [], "problems": []}
364
+ approved = [item["item_id"] for item in items]
365
+ held_gate = gate or sequencing.route_integrity
366
+ # The APPROVED order is what the owner read and what the hash chain was validated against, so it
367
+ # is the order this function asks about FIRST and returns when it holds.
368
+ #
369
+ # Round 2 found the cost of asking the other question: this used to run the SEARCH and compare
370
+ # its answer with the approved order. The search returns the first passing order it reaches in
371
+ # sorted-id order, so a valid approved order was reported as ORDER_REARRANGED whenever another
372
+ # valid order sorted earlier — `z-first` then `a-second`, both orders passing, and the approved
373
+ # one refused. A valid approved order is now validated directly, in one pass and with no search.
374
+ answer = sequencing.order_answer(items, approved, gate=held_gate, base=base)
375
+ if answer.get("sequenced"):
376
+ return {"ordered": list(answer.get("order") or []), "problems": [], "answer": answer}
377
+ # Only now is the search worth running, and only to say WHICH of two things is true: another
378
+ # order exists (the owner is asked again, because applying that one would apply a sequence
379
+ # nobody approved and whose chain was never checked), or none does.
380
+ reason = answer.get("reason") or "the approved order does not hold"
381
+ found = sequencing.subset_answer(items, gate=held_gate, base=base)
382
+ if found.get("sequenced"):
383
+ return {"ordered": [], "answer": answer, "alternative": found,
384
+ "problems": [f"ORDER_REARRANGED {', '.join(found.get('order') or [])}: the approved "
385
+ f"order ({', '.join(approved)}) does not hold — {reason} — and this "
386
+ f"other order does; the chain was validated against the approved one, "
387
+ f"so applying this one would apply a sequence nobody approved"]}
388
+ return {"ordered": [], "answer": answer, "alternative": found,
389
+ "problems": [f"ORDER_NONE {found.get('reason') or reason}: the approved set has no "
390
+ f"order whose every intermediate state passes, so the items are returned "
391
+ f"rather than applied"]}
392
+
393
+
394
+ # The global file takes deletions and merges only (§7.4, WP-14). The author-side ceiling gate holds
395
+ # it to a 20 KiB CEILING and DISCLOSES every added line without blocking it, which makes S11's
396
+ # refusal the only thing between "an unrelated line entered the always-loaded file under cover of a
397
+ # deletion" and the owner's global file: below the ceiling the gate passes any edit, so a deletion
398
+ # paired with an unrelated shorter line passes it with room to spare.
399
+ GLOBAL_LAYER = "global"
400
+ MERGE_OPERATIONS = ("merge", "reduce")
401
+ ADDING_OPERATIONS = ("create", "edit", "route")
402
+
403
+
404
+ def global_op_problems(f, judgments=None):
405
+ """An approved global-file operation that ADDS, with no merge judgment, by name.
406
+
407
+ §10.5 with done-when 1's O10: the operation passes WP-14's gate (it is under the ceiling) and S11
408
+ refuses it unless S7b judged the merge faithful. `judgments` maps an item id to its S7b
409
+ `faithful_merge` answer, which is `yes`, `no` or `n/a`.
410
+
411
+ A deletion alone is never refused here: the global file taking deletions is the whole point of
412
+ the ceiling being reusable room.
413
+ """
414
+ problems, judgments = [], judgments or {}
415
+ for item in f or ():
416
+ item_id = item.get("item_id")
417
+ operations = item.get("operations") or ()
418
+ if not any(layer_of(operation.get("target")) == GLOBAL_LAYER for operation in operations):
419
+ continue
420
+ # A MERGE can add content to the always-loaded file as surely as an edit can, and it was
421
+ # not in this list: a merge alone produced an empty `adding` and returned before reading its
422
+ # judgment at all, so `faithful_merge` absent, `no` and `n/a` all passed (the WP-21 review).
423
+ # A pure deletion stays the exception, because the global file taking deletions is what
424
+ # makes the ceiling reusable room.
425
+ adding = [operation for operation in operations
426
+ if layer_of(operation.get("target")) == GLOBAL_LAYER
427
+ and operation.get("type") in ADDING_OPERATIONS + MERGE_OPERATIONS]
428
+ if not adding:
429
+ continue
430
+ merging = any(operation.get("type") in MERGE_OPERATIONS for operation in operations)
431
+ judged = judgments.get(item_id)
432
+ if judged == "yes":
433
+ continue
434
+ kinds = ", ".join(sorted({operation.get("type") for operation in adding}))
435
+ problems.append(f"GLOBAL_OP_UNJUDGED {item_id}: {kinds} into the always-loaded file with "
436
+ f"faithful_merge={judged!r}"
437
+ f"{' and no merge operation' if not merging else ''} — the ceiling gate "
438
+ f"passes any edit under 20 KiB and only discloses the added line, so "
439
+ f"nothing but this refusal stands between an unrelated line and the global "
440
+ f"file")
441
+ return problems
442
+
443
+
444
+ def problems(live, declaration, f, interventions=None, judgments=None):
445
+ """Everything that stops an effect, in the order a reader needs it. Empty means apply may begin."""
446
+ held = table_problems()
447
+ if held:
448
+ return held
449
+ return (operation_problems(f, declaration)
450
+ + global_op_problems(f, judgments)
451
+ + drift_problems(live, declaration, interventions, targeted_layers(f))
452
+ + chain_problems(f)
453
+ + order_problems(f)["problems"])
454
+
455
+
456
+ def document(live, declaration, f, interventions=None, judgments=None):
457
+ """What apply records before its first effect, or Refused naming what stops it."""
458
+ held = problems(live, declaration, f, interventions, judgments)
459
+ if held:
460
+ raise Refused("; ".join(held))
461
+ return {"stage": "S11", "design": DESIGN_10_5_DRIFT,
462
+ "compared": list(declared_layers(declaration)),
463
+ "not_drift_checked": list(unchecked_layers(declaration)),
464
+ "targeted": list(targeted_layers(f)),
465
+ "order": order_problems(f)["ordered"],
466
+ "$comment": "The layers compared are the ones `config_manifest_B` carries; every other "
467
+ "layer this run knows is listed as not drift-checked, and no approved "
468
+ "operation targets one of those (refused before any effect)."}
469
+
470
+
471
+ # ---- self-test ---------------------------------------------------------------------------------
472
+
473
+
474
+ def self_test():
475
+ failures, ran = [], []
476
+
477
+ def control(name, got, want):
478
+ ran.append(name)
479
+ if want not in str(got):
480
+ failures.append((name, f"expected {want!r} in {str(got)[:400]!r}"))
481
+
482
+ def clean(name, held):
483
+ ran.append(name)
484
+ if held:
485
+ failures.append((name, f"expected nothing, got {held}"))
486
+
487
+ def guarded(call):
488
+ """The call's answer, or the exception as text. A control that dies is not a control."""
489
+ try:
490
+ return call()
491
+ except Exception as exc: # noqa: BLE001 - the exception IS the answer here
492
+ return [f"RAISED {type(exc).__name__}: {exc}"]
493
+
494
+ def refusal(call):
495
+ try:
496
+ call()
497
+ except Refused as exc:
498
+ return str(exc)
499
+ except Exception as exc: # noqa: BLE001 - a control that dies is not a control
500
+ return f"RAISED {type(exc).__name__}: {exc}"
501
+ return ""
502
+
503
+ def with_table(mutate, call):
504
+ held = json.loads(json.dumps(table()))
505
+ try:
506
+ mutate(_TABLE)
507
+ return call()
508
+ finally:
509
+ _TABLE.clear()
510
+ _TABLE.update(held)
511
+
512
+ A, B, C = "a" * 64, "b" * 64, "c" * 64
513
+
514
+ def fx_declaration(**manifest):
515
+ held = {"global": A, "guides": B}
516
+ held.update(manifest)
517
+ return {"config_manifest_B": held}
518
+
519
+ def fx_item(item_id="i-1", target="claude/guides/g.md", before=A, after=None, kind="edit"):
520
+ operation = {"type": kind, "target": target, "before_state_sha256": before}
521
+ if after is not None:
522
+ operation["after_state_sha256"] = after
523
+ return {"item_id": item_id, "operations": [operation]}
524
+
525
+ # ---- one canonical target identity -----------------------------------------------------------
526
+ #
527
+ # Four readers used to key on the raw string: the layer map, the chain, the journal and whatever
528
+ # applies the operation. Two spellings of one file were then two files.
529
+ control("two spellings of one path have one identity",
530
+ f'{target_identity("claude/guides//g.md")}|{target_identity("claude/guides/g.md")}',
531
+ "claude/guides/g.md|claude/guides/g.md")
532
+ control("and the non-canonical spelling is REFUSED rather than quietly normalized, because the "
533
+ "owner approved the text they read",
534
+ "; ".join(target_problems("claude/guides//g.md")), "TARGET_SPELLING")
535
+ for bad, want in (("/etc/passwd", "TARGET_ABSOLUTE"), ("~/x", "TARGET_ABSOLUTE"),
536
+ ("a/../../x", "TARGET_TRAVERSAL"), ("a/./x", "TARGET_SPELLING"),
537
+ ("claude/guides/", "TARGET_SPELLING")):
538
+ control(f"a target spelled {bad!r} is refused by name",
539
+ "; ".join(target_problems(bad)), want)
540
+ clean("while a canonical target passes", target_problems("claude/guides/g.md"))
541
+ control("the chain keys on that identity, so one file edited twice is one chain",
542
+ "; ".join(chain_problems([
543
+ fx_item("i-1", target="claude/guides/g.md", before=A, after=B),
544
+ fx_item("i-2", target="claude/guides//g.md", before=A)])),
545
+ "TARGET_MISMATCH")
546
+ control("and the second spelling is refused on its own account too",
547
+ "; ".join(chain_problems([fx_item("i-2", target="claude/guides//g.md")])),
548
+ "TARGET_SPELLING")
549
+
550
+ # ---- the layer map matches COMPONENTS, not text ----------------------------------------------
551
+ control("a suffix sibling of an exact-file entry is NOT that file",
552
+ json.dumps({"install.sh": layer_of("install.sh"),
553
+ "install.sh.backup": layer_of("install.sh.backup"),
554
+ "claude/CLAUDE.md": layer_of("claude/CLAUDE.md"),
555
+ "claude/CLAUDE.md.extra": layer_of("claude/CLAUDE.md.extra")}),
556
+ '{"install.sh": "enforcement", "install.sh.backup": null, '
557
+ '"claude/CLAUDE.md": "global", "claude/CLAUDE.md.extra": null}')
558
+ control("a directory prefix matches a path INSIDE it and not a sibling that starts with its name",
559
+ json.dumps({"claude/guides/g.md": layer_of("claude/guides/g.md"),
560
+ "claude/guidesextra/g.md": layer_of("claude/guidesextra/g.md"),
561
+ "claude/guides": layer_of("claude/guides")}),
562
+ '{"claude/guides/g.md": "guides", "claude/guidesextra/g.md": null, '
563
+ '"claude/guides": null}')
564
+ control("and an equivalent spelling lands in the same layer",
565
+ json.dumps(layer_of("claude/guides//g.md")), '"guides"')
566
+
567
+ # ---- the order that comes back is the order that was approved ---------------------------------
568
+ #
569
+ # The APPROVED order is validated directly and returned when it holds. Asking the search instead
570
+ # and comparing its answer refused a valid approved order whenever another valid order sorted
571
+ # earlier, which is what round 2 found with exactly this pair: `z-first` then `a-second`, both
572
+ # orders passing, the approved one reported as ORDER_REARRANGED.
573
+ reordered = order_problems([fx_item("z-first", target="claude/guides/z.md"),
574
+ fx_item("a-second", target="claude/guides/a.md")])
575
+ clean("an approved order that holds is not refused because another order sorts earlier",
576
+ reordered["problems"])
577
+ control("and it is the APPROVED order that comes back, not the search's",
578
+ json.dumps(reordered["ordered"]), '["z-first", "a-second"]')
579
+ # ORDER_REARRANGED is for the case it names: the approved order does NOT hold and another does.
580
+ # A route cannot be applied before the carrier it names, so the approved order fails at step 1
581
+ # while the reverse passes.
582
+ rearranged = order_problems([
583
+ {"item_id": "b-route", "operations": [{"type": "route", "target": "claude/CLAUDE.md",
584
+ "names": "claude/guides/g.md",
585
+ "before_state_sha256": A}]},
586
+ {"item_id": "a-carrier", "operations": [{"type": "create", "target": "claude/guides/g.md",
587
+ "before_state_sha256": A}]}])
588
+ control("while an approved order that does NOT hold, where another one does, is refused by name",
589
+ "; ".join(rearranged["problems"]), "ORDER_REARRANGED")
590
+ control("and the refusal says why the approved order failed, not only that another exists",
591
+ "; ".join(rearranged["problems"]), "SEQUENCE_ORDER_FAILS at b-route")
592
+ clean("with nothing returned to apply", rearranged["ordered"])
593
+ held_in_order = order_problems([fx_item("a-first", target="claude/guides/a.md"),
594
+ fx_item("z-second", target="claude/guides/z.md")])
595
+ control("while the approved order is returned unchanged when it is the one that passes",
596
+ json.dumps(held_in_order["ordered"]), '["a-first", "z-second"]')
597
+ # The adapter kept only `type` and `target`. `sequencing.apply_to` reads `names` for a route's
598
+ # destination and `units` for a merge's removals, so a carrier-then-route set could not be
599
+ # sequenced at all: the route named nothing and every intermediate tree failed route integrity.
600
+ fx_carrier = {"item_id": "a-carrier",
601
+ "operations": [{"type": "create", "target": "claude/guides/g.md",
602
+ "before_state_sha256": A}]}
603
+ fx_route = {"item_id": "b-route",
604
+ "operations": [{"type": "route", "target": "claude/CLAUDE.md",
605
+ "names": "claude/guides/g.md", "before_state_sha256": A}]}
606
+ held_full = order_problems([fx_carrier, fx_route])
607
+ clean("a carrier-then-route set sequences, which it cannot do unless the route's own `names` "
608
+ "reached sequencing", held_full["problems"])
609
+ control("and the approved order is what comes back", json.dumps(held_full["ordered"]),
610
+ '["a-carrier", "b-route"]')
611
+ held_reversed = order_problems([fx_route, fx_carrier])
612
+ control("while routing before the carrier is refused, since the route would name nothing",
613
+ "; ".join(held_reversed["problems"]), "ORDER_REARRANGED")
614
+ held_merge = order_problems([{"item_id": "m-1",
615
+ "operations": [{"type": "create", "target": "claude/guides/g.md",
616
+ "before_state_sha256": A},
617
+ {"type": "merge", "target": "claude/CLAUDE.md",
618
+ "units": ["claude/guides/g.md"],
619
+ "before_state_sha256": A}]}])
620
+ clean("and a merge's `units` reach it too, so its removals are in the intermediate trees",
621
+ held_merge["problems"])
622
+
623
+ # ---- the table -------------------------------------------------------------------------------
624
+ clean("the layer map is well formed", table_problems())
625
+ control("an empty layer map is refused, because it decides nothing",
626
+ "; ".join(with_table(lambda t: t.__setitem__("layers", []), table_problems)),
627
+ "LAYER_SET_EMPTY")
628
+ control("two rows claiming one layer are refused",
629
+ "; ".join(with_table(lambda t: t["layers"].append(dict(t["layers"][0])), table_problems)),
630
+ "LAYER_REPEATED global")
631
+ control("a layer no path belongs to is refused: it can never be the layer a refusal names",
632
+ "; ".join(with_table(lambda t: t["layers"][1].__setitem__("prefixes", []),
633
+ table_problems)),
634
+ "LAYER_WITHOUT_PREFIX")
635
+ control("a row without its own reason is refused",
636
+ "; ".join(with_table(lambda t: t["layers"][0].pop("$comment"), table_problems)),
637
+ "LAYER_UNREASONED global")
638
+ control("a prefix claimed by two layers is refused: a target under it has no one layer",
639
+ "; ".join(with_table(
640
+ lambda t: t["layers"][1]["prefixes"].append(t["layers"][0]["prefixes"][0]),
641
+ table_problems)),
642
+ "PREFIX_SHARED claude/CLAUDE.md")
643
+
644
+ # ---- the mapping -----------------------------------------------------------------------------
645
+ control("the global file is the global layer", str(layer_of("claude/CLAUDE.md")), "global")
646
+ control("a guide is the guides layer", str(layer_of("claude/guides/g.md")), "guides")
647
+ control("a guide under a deeper path is still the guides layer",
648
+ str(layer_of("claude/guides/deep/g.md")), "guides")
649
+ # No two prefixes in the shipped table nest, so the longest-prefix rule has no live case: it is
650
+ # tested on a PLANTED nesting, which is what the rule is for.
651
+ control("with one layer's prefix inside another's, the LONGEST wins rather than the table's "
652
+ "order deciding",
653
+ with_table(lambda t: t["layers"].insert(0, {"layer": "whole_tree",
654
+ "prefixes": ["claude/"],
655
+ "$comment": "planted"}),
656
+ lambda: str(layer_of("claude/guides/g.md"))),
657
+ "guides")
658
+ control("and the broader layer still claims what no narrower one does",
659
+ with_table(lambda t: t["layers"].insert(0, {"layer": "whole_tree",
660
+ "prefixes": ["claude/"],
661
+ "$comment": "planted"}),
662
+ lambda: str(layer_of("claude/other.md"))),
663
+ "whole_tree")
664
+ control("a commit hook is the hooks layer", str(layer_of(".githooks/pre-commit")), "hooks")
665
+ control("the ko projection of the global file is the same layer",
666
+ str(layer_of("ko/claude/CLAUDE.md")), "global")
667
+ clean("a path no layer claims is None, not a guess",
668
+ [] if layer_of("research/notes.md") is None else [str(layer_of("research/notes.md"))])
669
+ clean("and so is a target of the wrong shape",
670
+ [name for name in (layer_of(None), layer_of(""), layer_of(42)) if name is not None])
671
+
672
+ # ---- the declaration's own coverage ----------------------------------------------------------
673
+ control("the layers compared are the ones B's manifest carries",
674
+ ", ".join(declared_layers(fx_declaration())), "global, guides")
675
+ control("every other layer this run knows is named as not drift-checked",
676
+ ", ".join(unchecked_layers(fx_declaration())), "skills")
677
+ clean("a declaration carrying every layer leaves none unchecked",
678
+ unchecked_layers({"config_manifest_B": {name: A for name in layers()}}))
679
+ control("a declaration carrying none leaves them all unchecked, which is the state a real run "
680
+ "is in today", str(len(unchecked_layers({}))), str(len(layers())))
681
+
682
+ # ---- the drift comparison --------------------------------------------------------------------
683
+ clean("a live manifest equal to B's carries no drift",
684
+ drift_problems({"global": A, "guides": B}, fx_declaration()))
685
+ control("a layer no operation targets that has moved is untargeted drift",
686
+ "; ".join(drift_problems({"global": C, "guides": B}, fx_declaration())),
687
+ "DRIFT_UNTARGETED global")
688
+ control("a layer an approved operation targets that has moved is targeted drift, named apart",
689
+ "; ".join(drift_problems({"global": A, "guides": C}, fx_declaration(),
690
+ targeted=["guides"])),
691
+ "DRIFT_TARGET guides")
692
+ control("and the refusal says what happens to the items",
693
+ "; ".join(drift_problems({"global": C, "guides": B}, fx_declaration())),
694
+ "rebuild, retest and re-confirmation")
695
+ clean("an approved intervention's own change is NOT drift: B minus the interventions is what the "
696
+ "live manifest is compared with",
697
+ drift_problems({"global": A, "guides": C}, fx_declaration(),
698
+ interventions={"guides": C}, targeted=["guides"]))
699
+ control("while a layer that moved to something OTHER than the intervention's digest is drift",
700
+ "; ".join(drift_problems({"global": A, "guides": B}, fx_declaration(),
701
+ interventions={"guides": C}, targeted=["guides"])),
702
+ "DRIFT_TARGET guides")
703
+ control("a layer B carries that the live manifest does not is drift too, not an absence to "
704
+ "pass over",
705
+ "; ".join(guarded(lambda: drift_problems({"global": A}, fx_declaration()))),
706
+ "DRIFT_LAYER_ABSENT guides")
707
+ clean("a live manifest carrying MORE layers than B is not drift: an uncompared layer is "
708
+ "reported by `unchecked_layers`, not invented as a difference",
709
+ guarded(lambda: drift_problems({"global": A, "guides": B, "skills": C},
710
+ fx_declaration())))
711
+
712
+ # ---- the target's layer must have been compared ----------------------------------------------
713
+ clean("an operation whose layer B carries passes", operation_problems([fx_item()], fx_declaration()))
714
+ control("an operation targeting a layer B does not carry is refused before any effect",
715
+ "; ".join(operation_problems([fx_item(target="claude/skills/s/SKILL.md")],
716
+ fx_declaration())),
717
+ "OPERATION_LAYER_UNCHECKED i-1")
718
+ control("and the refusal names the layer nobody compared",
719
+ "; ".join(operation_problems([fx_item(target=".githooks/pre-commit")],
720
+ fx_declaration())),
721
+ "'hooks' is not in the declaration's config_manifest_B")
722
+ control("an operation targeting a path no layer claims is refused as a table gap, apart from a "
723
+ "declaration gap",
724
+ "; ".join(operation_problems([fx_item(target="research/notes.md")], fx_declaration())),
725
+ "OPERATION_LAYER_UNKNOWN i-1")
726
+ clean("an empty F has no operation problem", operation_problems([], fx_declaration()))
727
+ control("the layers F targets are read from its operations, for the drift comparison",
728
+ ", ".join(targeted_layers([fx_item(), fx_item("i-2", "claude/CLAUDE.md")])),
729
+ "guides, global")
730
+
731
+ # ---- the chain -------------------------------------------------------------------------------
732
+ clean("two operations on different targets need no chain",
733
+ chain_problems([fx_item("i-1", "claude/guides/g.md"), fx_item("i-2", "claude/guides/h.md")]))
734
+ clean("two on one target chain when the second's before-hash is the first's after-hash",
735
+ chain_problems([fx_item("i-1", "claude/guides/g.md", before=A, after=B),
736
+ fx_item("i-2", "claude/guides/g.md", before=B)]))
737
+ control("and are refused by name when it is not: the second would write over a file the first "
738
+ "already changed",
739
+ "; ".join(chain_problems([fx_item("i-1", "claude/guides/g.md", before=A, after=B),
740
+ fx_item("i-2", "claude/guides/g.md", before=A)])),
741
+ "TARGET_MISMATCH i-2")
742
+ control("a first operation stating no after-hash leaves the link unstated, which is a gap in F "
743
+ "rather than a passing check",
744
+ "; ".join(chain_problems([fx_item("i-1", "claude/guides/g.md", before=A),
745
+ fx_item("i-2", "claude/guides/g.md", before=B)])),
746
+ "CHAIN_UNSTATED claude/guides/g.md")
747
+
748
+ # ---- the order -------------------------------------------------------------------------------
749
+ held_order = order_problems([fx_item("i-1", "claude/guides/g.md", kind="create"),
750
+ fx_item("i-2", "claude/guides/h.md", kind="create")])
751
+ clean("a set whose every intermediate state passes has an order", held_order["problems"])
752
+ control("and the order names its items", ", ".join(held_order["ordered"]), "i-1")
753
+ control("a set with no valid order comes back as a row, so the items can be returned rather "
754
+ "than the run stopped",
755
+ "; ".join(order_problems([{"item_id": "i-1", "operations": [
756
+ {"type": "route", "target": "claude/guides/absent.md"}]}])["problems"]),
757
+ "ORDER_NONE")
758
+ clean("an empty F has an empty order rather than a refusal", order_problems([])["problems"])
759
+ control("the order question goes to the module that owns it, not a second implementation here",
760
+ next(line.strip() for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
761
+ if "order_answer" in line and "answer = " in line),
762
+ "sequencing.order_answer")
763
+ control("and the search is still that module's too, consulted only after the approved order "
764
+ "fails",
765
+ next(line.strip() for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
766
+ if "subset_answer" in line and "found = " in line),
767
+ "sequencing.subset_answer")
768
+
769
+ # ---- the target's identity, bound to the DECLARED checkout -----------------------------------
770
+ #
771
+ # The lexical rules are `runlib/targets.py`'s now, and so is the walk. What this suite shows is
772
+ # that the walk REACHES an approved operation: `claude/guides/to-root/CLAUDE.md` passes every
773
+ # spelling rule, and with `to-root` a link to `claude/` it reaches the always-loaded global file
774
+ # while `layer_of` calls it a guide — so the global-file judgment, the merge requirement and the
775
+ # ceiling were all decided for the wrong layer (the round-2 review).
776
+ import shutil as _shutil
777
+ import tempfile as _tempfile
778
+ held_checkout = pathlib.Path(_tempfile.mkdtemp(prefix="drift-checkout-", dir="/tmp"))
779
+ try:
780
+ (held_checkout / "claude" / "guides").mkdir(parents=True)
781
+ (held_checkout / "claude" / "CLAUDE.md").write_text("global\n", encoding="utf-8")
782
+ (held_checkout / "claude" / "guides" / "g.md").write_text("guide\n", encoding="utf-8")
783
+ bound = fx_declaration()
784
+ bound["destinations"] = {"checkout": str(held_checkout)}
785
+ clean("an ordinary target inside the declared checkout passes the walk",
786
+ operation_problems([fx_item()], bound))
787
+ os.symlink(held_checkout / "claude", held_checkout / "claude" / "guides" / "to-root")
788
+ held_reach = operation_problems([fx_item(target="claude/guides/to-root/CLAUDE.md")], bound)
789
+ control("a target reaching the global file through a symlinked directory is refused before "
790
+ "any effect", "; ".join(held_reach), "TARGET_SYMLINK")
791
+ control("while `layer_of` alone still calls that path a guide, which is why the walk has to "
792
+ "happen", str(layer_of("claude/guides/to-root/CLAUDE.md")), "guides")
793
+ control("and the refusal reaches `problems`, not only this function",
794
+ "; ".join(problems({"global": A, "guides": B}, bound,
795
+ [fx_item(target="claude/guides/to-root/CLAUDE.md")])),
796
+ "TARGET_SYMLINK")
797
+ control("two targets of one set that differ only by case are judged for collision, with "
798
+ "the filesystem asked rather than assumed",
799
+ "; ".join(operation_problems(
800
+ [fx_item("i-1", target="claude/guides/g.md"),
801
+ fx_item("i-2", target="claude/guides/G.md")], bound)),
802
+ "TARGET_CASE")
803
+ # A CHAIN through one file is valid work, and the identity contract used to refuse it.
804
+ # §10.5's own example: one item creates the file, the next deletes it, a third routes to it,
805
+ # and each operation carries the before-state hash of what the previous one left — which is
806
+ # what orders them. The round-3 review found a valid approved set rejected this way.
807
+ clean("several operations of one set through ONE file are a chain, not a collision",
808
+ operation_problems(
809
+ [fx_item("i-1", target="claude/guides/g.md"),
810
+ fx_item("i-2", target="claude/guides/g.md"),
811
+ fx_item("i-3", target="claude/guides/g.md")], bound))
812
+ control("while two spellings that are one file on this filesystem stay refused, so the "
813
+ "change narrows the rule to distinct spellings and not past it",
814
+ "; ".join(operation_problems(
815
+ [fx_item("i-1", target="claude/guides/g.md"),
816
+ fx_item("i-2", target="claude/guides/G.md")], bound)),
817
+ "TARGET_CASE")
818
+ clean("with no checkout declared, the spelling is still judged and the walk is not claimed",
819
+ operation_problems([fx_item()], fx_declaration()))
820
+ control("and a declaration naming a checkout that is not there does not make the walk "
821
+ "silently pass: the spelling rules still answer",
822
+ "; ".join(operation_problems(
823
+ [fx_item(target="claude/guides//g.md")],
824
+ {**fx_declaration(), "destinations": {"checkout": "/nonexistent-checkout"}})),
825
+ "TARGET_SPELLING")
826
+ finally:
827
+ _shutil.rmtree(held_checkout, ignore_errors=True)
828
+
829
+ # ---- the document ----------------------------------------------------------------------------
830
+ doc = document({"global": A, "guides": B}, fx_declaration(), [fx_item()])
831
+ control("the document says which layers were compared", ", ".join(doc["compared"]),
832
+ "global, guides")
833
+ control("and which were not, by name", ", ".join(doc["not_drift_checked"]), "hooks")
834
+ control("a document over an unchecked target is refused instead of written",
835
+ refusal(lambda: document({"global": A, "guides": B}, fx_declaration(),
836
+ [fx_item(target=".githooks/pre-commit")])),
837
+ "OPERATION_LAYER_UNCHECKED")
838
+ merge_out = {"item_id": "i-merge", "operations": [
839
+ {"type": "merge", "target": "claude/guides/g.md", "units": [".githooks/pre-commit"],
840
+ "before_state_sha256": A}]}
841
+ control("a merge that REMOVES a file in a layer nobody compared is refused by that file's "
842
+ "name: its target lying in a compared layer says nothing of what it deletes",
843
+ [held.split(":")[0] for held in operation_problems([merge_out], fx_declaration())
844
+ if held.startswith("OPERATION_LAYER")],
845
+ "[\"OPERATION_LAYER_UNCHECKED i-merge '.githooks/pre-commit'\"]")
846
+ merge_in = {"item_id": "i-merge", "operations": [
847
+ {"type": "merge", "target": "claude/guides/g.md", "units": ["claude/guides/h.md"],
848
+ "before_state_sha256": A}]}
849
+ clean("and one whose units lie in compared layers raises no layer problem",
850
+ [held for held in operation_problems([merge_in], fx_declaration())
851
+ if held.startswith("OPERATION_LAYER")])
852
+ removed_then_edited = [
853
+ {"item_id": "i-merge", "operations": [
854
+ {"type": "merge", "target": "claude/guides/g.md", "units": ["claude/guides/h.md"],
855
+ "before_state_sha256": A, "after_state_sha256": B}]},
856
+ {"item_id": "i-edit", "operations": [
857
+ {"type": "edit", "target": "claude/guides/h.md", "before_state_sha256": C}]}]
858
+ control("an edit of a file an earlier merge REMOVED is held to that removal: its before-state "
859
+ "is no longer the hash it was approved against",
860
+ [held.split(":")[0] for held in chain_problems(removed_then_edited)],
861
+ "['TARGET_MISMATCH i-edit claude/guides/h.md']")
862
+ clean("and a create of that same path after the merge chains, since the file is absent",
863
+ chain_problems([removed_then_edited[0],
864
+ {"item_id": "i-new", "operations": [
865
+ {"type": "create", "target": "claude/guides/h.md",
866
+ "before_state_sha256": "absent"}]}]))
867
+ survivor = {"item_id": "i-fold", "operations": [
868
+ {"type": "merge", "target": "claude/guides/g.md",
869
+ "units": ["claude/guides/g.md", "claude/guides/h.md"],
870
+ "before_state_sha256": A, "after_state_sha256": B}]}
871
+ clean("a merge whose units include its own target leaves that target at its after-hash: an edit "
872
+ "expecting it chains",
873
+ chain_problems([survivor, {"item_id": "i-next", "operations": [
874
+ {"type": "edit", "target": "claude/guides/g.md", "before_state_sha256": B}]}]))
875
+ control("and a create of the surviving target after it is refused, since the file is there",
876
+ [held.split(":")[0] for held in chain_problems([survivor, {"item_id": "i-again", "operations": [
877
+ {"type": "create", "target": "claude/guides/g.md", "before_state_sha256": "absent"}]}])],
878
+ "['TARGET_MISMATCH i-again claude/guides/g.md']")
879
+ control("and so is one over drift",
880
+ refusal(lambda: document({"global": C, "guides": B}, fx_declaration(), [fx_item()])),
881
+ "DRIFT_UNTARGETED")
882
+ control("the unchecked-target refusal comes BEFORE the drift one, since an uncompared layer "
883
+ "makes the comparison's silence meaningless",
884
+ "; ".join(problems({"global": C, "guides": B}, fx_declaration(),
885
+ [fx_item(target=".githooks/pre-commit")])).split(";")[0],
886
+ "OPERATION_LAYER_UNCHECKED")
887
+
888
+ # ---- the global file, as WP-14's gate leaves it ----------------------------------------------
889
+ # O10 under the CEILING version of the gate: a deletion plus an unrelated shorter line makes the
890
+ # file SMALLER, so the ceiling passes it with room to spare and the added line is disclosed, not
891
+ # blocked. The done-when was written against the earlier byte-growth version, where the pairing
892
+ # mattered because the growth was the signal; under the ceiling the pairing does not even have to
893
+ # net out, and S11's refusal is the only check on the added line.
894
+ def fx_global(item_id="i-g", types=("delete", "edit"), target="claude/CLAUDE.md"):
895
+ return {"item_id": item_id,
896
+ "operations": [{"type": kind, "target": target, "before_state_sha256": A}
897
+ for kind in types]}
898
+
899
+ # A MERGE ALONE. It was not in the adding list, so it produced an empty set and returned before
900
+ # reading its judgment: absent, `no` and `n/a` all passed. A merge adds content to the
901
+ # always-loaded file as surely as an edit does.
902
+ for judged, label in ((None, "absent"), ("no", "no"), ("n/a", "n/a")):
903
+ control(f"a merge alone into the global file with faithful_merge {label} is refused",
904
+ "; ".join(global_op_problems([fx_global(item_id="i-m", types=("merge",))],
905
+ {} if judged is None else {"i-m": judged})),
906
+ "GLOBAL_OP_UNJUDGED i-m")
907
+ clean("and the same merge judged faithful passes",
908
+ global_op_problems([fx_global(item_id="i-m", types=("merge",))], {"i-m": "yes"}))
909
+ clean("while a pure deletion is never refused here, because deletions are what make the "
910
+ "ceiling reusable room",
911
+ global_op_problems([fx_global(item_id="i-d", types=("delete",))]))
912
+ control("a reduce is treated like a merge, since it rewrites the file's content too",
913
+ "; ".join(global_op_problems([fx_global(item_id="i-r", types=("reduce",))])),
914
+ "GLOBAL_OP_UNJUDGED i-r")
915
+ control("a deletion paired with an edit into the global file is refused without a merge "
916
+ "judgment", "; ".join(global_op_problems([fx_global()])), "GLOBAL_OP_UNJUDGED i-g")
917
+ control("naming a SECTION of the global file does not take the operation out of the global layer",
918
+ "; ".join(global_op_problems([fx_global(item_id="i-h", types=("edit",),
919
+ target="claude/CLAUDE.md#A")])),
920
+ "GLOBAL_OP_UNJUDGED i-h")
921
+ control("and a section-qualified target has its file's identity",
922
+ f'{target_identity("claude/CLAUDE.md#A")}|{layer_of("claude/CLAUDE.md#A") == layer_of("claude/CLAUDE.md")}',
923
+ "claude/CLAUDE.md|True")
924
+ control("and the refusal says why the gate does not catch it",
925
+ "; ".join(global_op_problems([fx_global()])),
926
+ "the ceiling gate passes any edit under 20 KiB")
927
+ clean("a deletion ALONE is not refused: reusable room is what the ceiling is for",
928
+ global_op_problems([fx_global(types=("delete",))]))
929
+ clean("an item S7b judged a faithful merge proceeds",
930
+ global_op_problems([fx_global()], {"i-g": "yes"}))
931
+ control("one S7b judged NOT faithful is refused with that answer named",
932
+ "; ".join(global_op_problems([fx_global()], {"i-g": "no"})), "faithful_merge='no'")
933
+ control("and one S7b answered n/a for is refused too, since n/a is not a judgment that the "
934
+ "addition carries what the deletion removed",
935
+ "; ".join(global_op_problems([fx_global()], {"i-g": "n/a"})), "faithful_merge='n/a'")
936
+ clean("an operation on a guide is not a global-file operation",
937
+ global_op_problems([fx_item()]))
938
+ control("an addition to the ko projection of the global file is the same layer, so it is "
939
+ "refused too",
940
+ "; ".join(global_op_problems([fx_global(types=("edit",), target="ko/claude/CLAUDE.md")])),
941
+ "GLOBAL_OP_UNJUDGED")
942
+ control("the refusal reaches `problems`, not only this function",
943
+ "; ".join(problems({"global": A, "guides": B}, fx_declaration(), [fx_global()])),
944
+ "GLOBAL_OP_UNJUDGED")
945
+
946
+ # This module reads no configuration and spawns nothing: the live manifest is handed to it.
947
+ import ast
948
+ own = ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
949
+ # The effect audit, over the RUNTIME code and through import bindings. The old version read the
950
+ # printed first component of each call, so `import os as _o` then `_o.system(...)` passed, a
951
+ # `getattr(os, "system")(...)` passed, and its read assertion only required `TABLE_PATH.read_text`
952
+ # to occur SOMEWHERE in the collected set — a second read of another file would have joined it
953
+ # without changing the answer. All three were the WP-21 review's finding.
954
+ # The audit itself lives in `destinations.py`, which owns what may write where. Two copies of
955
+ # one vocabulary is what round 2 found: each module watched a different tuple of module names,
956
+ # and neither watched a filesystem write. One owner, imported.
957
+ effects_in = destinations.effect_audit
958
+
959
+ def reads_in(source):
960
+ """Every path this module's reachable runtime code reads, by the expression it reads from.
961
+
962
+ The scope is `destinations.effect_scope`'s, so the reads and the effects are judged over
963
+ one set of functions: `main` is in it, and a `self_test` is out of it only while the flag's
964
+ own branch is the only way to reach it.
965
+ """
966
+ tree = ast.parse(source)
967
+ scoped = set(destinations.effect_scope(source))
968
+ runtime = ast.Module(body=[node for node in tree.body
969
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
970
+ or node.name in scoped],
971
+ type_ignores=[])
972
+ held = set()
973
+ for node in ast.walk(runtime):
974
+ if isinstance(node, ast.Call):
975
+ rendered = ast.unparse(node.func)
976
+ if any(mark in rendered for mark in ("read_text", "read_bytes", "open")):
977
+ held.add(rendered)
978
+ return sorted(held)
979
+
980
+ own_source = pathlib.Path(__file__).read_text(encoding="utf-8")
981
+ clean("drift spawns nothing and reads no environment: what it compares, it is given",
982
+ effects_in(own_source))
983
+ control("the audit sees a PLAIN call",
984
+ "; ".join(effects_in("import os\ndef f():\n os.system('x')\n")), "os.system")
985
+ control("and an ALIASED one, which the printed-first-component rule did not",
986
+ "; ".join(effects_in("import os as _o\ndef f():\n _o.system('x')\n")), "os.system")
987
+ control("and names the alias itself", "; ".join(effects_in("import subprocess as sp\n")),
988
+ "import subprocess as sp")
989
+ control("and a dynamic lookup",
990
+ "; ".join(effects_in("import os\ndef f():\n getattr(os, 'system')('x')\n")),
991
+ "getattr(os, 'system')")
992
+ control("and a dynamic import, which names no watched module at its first component",
993
+ "; ".join(effects_in("def f():\n __import__('os').system('x')\n")),
994
+ "cannot name")
995
+ control("and a filesystem write, which names no module at all",
996
+ "; ".join(effects_in("import pathlib\ndef f():\n"
997
+ " pathlib.Path('a').write_text('x')\n")),
998
+ "write_text")
999
+ clean("while the allowed path helpers are not effects",
1000
+ effects_in("import os\ndef f():\n return os.path.normpath('a')\n"))
1001
+ # The scope, asserted rather than assumed: a clean answer over nothing is not a clean answer.
1002
+ # `main` is in it — `python3 runlib/drift.py` runs `main` — and so is the function that decides
1003
+ # every operation this module refuses.
1004
+ for held_name in ("<module>", "main", "problems", "global_op_problems", "order_problems"):
1005
+ control(f"the audit scanned {held_name}",
1006
+ json.dumps(destinations.effect_scope(own_source)), f'"{held_name}"')
1007
+ # The read assertion is an EXACT set, not a containment: a second read would have joined the
1008
+ # old answer without changing it.
1009
+ control("and the only file it reads is its own table",
1010
+ json.dumps(reads_in(own_source)), json.dumps(["TABLE_PATH.read_text"]))
1011
+ control("a second read is named, rather than hiding behind the first",
1012
+ json.dumps(reads_in("import pathlib\nX = pathlib.Path('a').read_text()\n"
1013
+ "Y = pathlib.Path('b').read_bytes()\n")),
1014
+ json.dumps(["pathlib.Path('a').read_text", "pathlib.Path('b').read_bytes"]))
1015
+
1016
+ # ---- where a path falls inside the instructions (release 1's confirmation review, both rounds) ----
1017
+ def same(name, got, want):
1018
+ ran.append(name)
1019
+ if got != want:
1020
+ failures.append((name, f"expected exactly {want!r}, got {got!r}"[:600]))
1021
+ same("a relative path inside a layer or an instruction tree is named, and one outside is not",
1022
+ [bool(library_place(x)) for x in ("claude/skills/u/ledger.json", "Claude/Guides/c.json", "ko/x/ledger.json",
1023
+ "claude/agents/a.md", "compose/ledger.json", "design/session-distill/ledger.json",
1024
+ "session-distill/local/coverage.json", "session-distill/out/r1")],
1025
+ [True, True, True, True, True, False, False, False])
1026
+ place_root = pathlib.Path(_tempfile.mkdtemp(prefix="drift-place-"))
1027
+ try:
1028
+ repo = place_root / "repo"
1029
+ for d in ("claude/skills/understand", "codex", "session-distill/out"):
1030
+ (repo / d).mkdir(parents=True)
1031
+ (place_root / "home" / ".claude" / "skills").mkdir(parents=True)
1032
+ (place_root / "link").symlink_to(repo / "claude" / "skills" / "understand")
1033
+ same("an absolute path is read from every ancestor that is a checkout: inside a skill, through a symlinked "
1034
+ "parent and in a host's installed home it is named, beside a run's output it is not",
1035
+ [bool(library_place(x)) for x in (repo / "claude/skills/understand/ledger.json",
1036
+ place_root / "link" / "ledger.json", place_root / "link" / "r1",
1037
+ place_root / "home" / ".claude" / "skills" / "r1",
1038
+ repo / "session-distill/out/r1", repo / "design/session-distill/ledger.json",
1039
+ place_root / "elsewhere" / "claude" / "skills" / "r1")],
1040
+ [True, True, True, True, False, False, False])
1041
+ # a host home under an ordinary name, as its variable may move it (release 1's third confirmation review, F2):
1042
+ # the homes are given, resolved, and this module compares them
1043
+ for d in ("config-A/skills/x", "config-B", "plain"):
1044
+ (place_root / d).mkdir(parents=True)
1045
+ (place_root / "link-A").symlink_to(place_root / "config-A" / "skills")
1046
+ moved = [pathlib.Path(os.path.realpath(place_root / "config-A")), pathlib.Path(os.path.realpath(place_root / "config-B"))]
1047
+ same("a host's home it is given is named wherever it lies, through a symlink and case-folded, and a sibling "
1048
+ "of it, or the same path with no homes given, is not",
1049
+ [bool(library_place(x, moved)) for x in (place_root / "config-A/skills/x/r1", place_root / "config-B/r1",
1050
+ place_root / "link-A" / "x" / "ledger.json",
1051
+ place_root / "Config-A" / "r1", place_root / "plain" / "r1",
1052
+ place_root / "config-AB" / "r1")]
1053
+ + [bool(library_place(place_root / "config-A/skills/x/r1"))],
1054
+ [True, True, True, True, False, False, False])
1055
+ finally:
1056
+ _shutil.rmtree(place_root, ignore_errors=True)
1057
+
1058
+ print(f"drift --self-test: {'FAILED' if failures else 'OK'} ({len(ran)} controls: the layer map "
1059
+ f"and its longest-prefix rule, targeted drift apart from untargeted, an approved "
1060
+ f"intervention's own change not read as drift, a target in an uncompared layer refused "
1061
+ f"before any effect, the hash chain with an unstated link named, and the order through "
1062
+ f"sequencing)")
1063
+ for name, detail in failures:
1064
+ print(f"drift --self-test [FAIL] {name}: {detail}")
1065
+ return 1 if failures else 0
1066
+
1067
+
1068
+ def main(argv):
1069
+ if "--self-test" in argv:
1070
+ return self_test()
1071
+ print(json.dumps({"design": DESIGN_10_5_DRIFT, "layers": list(layers()),
1072
+ "open_question": table()["open_question"]}, indent=2, ensure_ascii=False))
1073
+ return 0
1074
+
1075
+
1076
+ if __name__ == "__main__":
1077
+ sys.exit(main(sys.argv[1:]))