agent-bios 0.19.4 → 0.20.1

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 (162) hide show
  1. package/DEPENDENCIES.md +20 -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 +8 -7
  6. package/claude/guides/gpt-prompting.md +319 -144
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/agents/frontier.toml +1 -1
  10. package/codex/agents/reviewer.toml +1 -1
  11. package/codex/agents/workhorse.toml +1 -1
  12. package/codex/guides/claude-prompting.md +475 -234
  13. package/codex/guides/cli-multi-model-workflow.md +8 -7
  14. package/codex/guides/gpt-prompting.md +319 -144
  15. package/codex/guides/session-distill-workflow.md +93 -43
  16. package/codex/guides/tooling-gotchas.md +3 -1
  17. package/compose/assemble.py +4 -1
  18. package/compose/canary.sh +8 -6
  19. package/compose/host_platform.py +158 -15
  20. package/compose/instructions-state.py +183 -41
  21. package/compose/instructions_install.py +222 -27
  22. package/compose/instructions_session.py +250 -75
  23. package/compose/instructions_setup_cli.py +2 -36
  24. package/compose/instructions_store.py +160 -3
  25. package/compose/instructions_transaction.py +29 -5
  26. package/docs/advanced-launch.md +5 -1
  27. package/docs/releases/0.20.0.md +102 -0
  28. package/docs/releases/0.20.1.md +76 -0
  29. package/install.sh +42 -14
  30. package/launch/agent-launch.py +152 -18
  31. package/launch/agent-launch.toml +28 -16
  32. package/launch/agent-launch.zsh +104 -13
  33. package/launch/claude_subcommands.py +179 -0
  34. package/launch/shell_integration.py +7 -1
  35. package/learn/collect-learning.py +60 -9
  36. package/learn/migrate-learnings.py +70 -4
  37. package/learn/redact.py +2 -1
  38. package/package.json +36 -3
  39. package/provenance.json +1 -1
  40. package/session-cost.py +80 -9
  41. package/session-distill/coverage.json +6 -0
  42. package/session-distill/distill.py +2575 -0
  43. package/session-distill/grammar/__init__.py +0 -0
  44. package/session-distill/grammar/owner_lines.py +874 -0
  45. package/session-distill/originators.json +9 -0
  46. package/session-distill/packets/cross_review.md +31 -0
  47. package/session-distill/packets/form.md +86 -0
  48. package/session-distill/packets/judge.md +81 -0
  49. package/session-distill/packets/placement_contract.md +90 -0
  50. package/session-distill/packets/propose.md +124 -0
  51. package/session-distill/packets/read.md +57 -0
  52. package/session-distill/packets/reconsider.md +53 -0
  53. package/session-distill/packets/s7b.md +65 -0
  54. package/session-distill/packets/s9b.md +39 -0
  55. package/session-distill/packets/stitch.md +35 -0
  56. package/session-distill/packets/sweep.md +33 -0
  57. package/session-distill/runlib/__init__.py +0 -0
  58. package/session-distill/runlib/bound.py +1102 -0
  59. package/session-distill/runlib/breaker.py +467 -0
  60. package/session-distill/runlib/census.py +2347 -0
  61. package/session-distill/runlib/claims.py +420 -0
  62. package/session-distill/runlib/controls.py +902 -0
  63. package/session-distill/runlib/coverage.py +881 -0
  64. package/session-distill/runlib/declare.py +888 -0
  65. package/session-distill/runlib/delivery_evidence.py +1145 -0
  66. package/session-distill/runlib/derive.py +812 -0
  67. package/session-distill/runlib/destinations.py +3072 -0
  68. package/session-distill/runlib/dispatch.py +7940 -0
  69. package/session-distill/runlib/drift.py +1077 -0
  70. package/session-distill/runlib/entry.py +401 -0
  71. package/session-distill/runlib/evidence.py +890 -0
  72. package/session-distill/runlib/exposure.py +1162 -0
  73. package/session-distill/runlib/gate.py +2727 -0
  74. package/session-distill/runlib/gitread.py +79 -0
  75. package/session-distill/runlib/inventory.py +19624 -0
  76. package/session-distill/runlib/journal.py +1919 -0
  77. package/session-distill/runlib/ledger.py +3210 -0
  78. package/session-distill/runlib/ledger_compat.py +101 -0
  79. package/session-distill/runlib/ledger_migration.py +190 -0
  80. package/session-distill/runlib/lifecycle_intake.py +693 -0
  81. package/session-distill/runlib/lineage.py +454 -0
  82. package/session-distill/runlib/measures.py +249 -0
  83. package/session-distill/runlib/monitor.py +1180 -0
  84. package/session-distill/runlib/operations.py +522 -0
  85. package/session-distill/runlib/packet.py +838 -0
  86. package/session-distill/runlib/placement.py +1769 -0
  87. package/session-distill/runlib/projection.py +4090 -0
  88. package/session-distill/runlib/ranking.py +740 -0
  89. package/session-distill/runlib/receipts.py +200 -0
  90. package/session-distill/runlib/records.py +1965 -0
  91. package/session-distill/runlib/search.py +249 -0
  92. package/session-distill/runlib/sequencing.py +829 -0
  93. package/session-distill/runlib/sources.py +641 -0
  94. package/session-distill/runlib/stage_adjudicate.py +845 -0
  95. package/session-distill/runlib/stage_apply.py +1378 -0
  96. package/session-distill/runlib/stage_approvals.py +758 -0
  97. package/session-distill/runlib/stage_close.py +1220 -0
  98. package/session-distill/runlib/stage_confirm.py +929 -0
  99. package/session-distill/runlib/stage_delivery.py +3080 -0
  100. package/session-distill/runlib/stage_form.py +2576 -0
  101. package/session-distill/runlib/stage_judge.py +4248 -0
  102. package/session-distill/runlib/stage_propose.py +3307 -0
  103. package/session-distill/runlib/stage_read.py +5179 -0
  104. package/session-distill/runlib/stage_render.py +2739 -0
  105. package/session-distill/runlib/stage_retrieve.py +924 -0
  106. package/session-distill/runlib/stage_review_korean.py +1002 -0
  107. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  108. package/session-distill/runlib/stagelock.py +412 -0
  109. package/session-distill/runlib/stop.py +1061 -0
  110. package/session-distill/runlib/targets.py +809 -0
  111. package/session-distill/runlib/usage.py +280 -0
  112. package/session-distill/runlib/validate.py +319 -0
  113. package/session-distill/runlib/views.py +4327 -0
  114. package/session-distill/schemas/adjudication.schema.json +35 -0
  115. package/session-distill/schemas/approval.schema.json +35 -0
  116. package/session-distill/schemas/census.schema.json +128 -0
  117. package/session-distill/schemas/checks.schema.json +207 -0
  118. package/session-distill/schemas/claim.schema.json +16 -0
  119. package/session-distill/schemas/confirmation.schema.json +24 -0
  120. package/session-distill/schemas/coverage.schema.json +66 -0
  121. package/session-distill/schemas/cross_review.schema.json +24 -0
  122. package/session-distill/schemas/event.schema.json +20 -0
  123. package/session-distill/schemas/evidence.schema.json +20 -0
  124. package/session-distill/schemas/expected_observation.schema.json +18 -0
  125. package/session-distill/schemas/form.schema.json +103 -0
  126. package/session-distill/schemas/intake.schema.json +71 -0
  127. package/session-distill/schemas/inventory.schema.json +872 -0
  128. package/session-distill/schemas/judge.schema.json +77 -0
  129. package/session-distill/schemas/ledger.schema.json +313 -0
  130. package/session-distill/schemas/observation.schema.json +16 -0
  131. package/session-distill/schemas/propose.schema.json +555 -0
  132. package/session-distill/schemas/read.schema.json +76 -0
  133. package/session-distill/schemas/reconsider.schema.json +122 -0
  134. package/session-distill/schemas/run.schema.json +150 -0
  135. package/session-distill/schemas/s7b.schema.json +200 -0
  136. package/session-distill/schemas/s9b.schema.json +28 -0
  137. package/session-distill/schemas/stitch.schema.json +25 -0
  138. package/session-distill/schemas/sweep.schema.json +25 -0
  139. package/session-distill/seats.json +149 -0
  140. package/session-distill/tables/allowed_pairs.json +257 -0
  141. package/session-distill/tables/controls.json +30 -0
  142. package/session-distill/tables/delivery_evidence.json +36 -0
  143. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  144. package/session-distill/tables/destinations.json +684 -0
  145. package/session-distill/tables/drift_layers.json +68 -0
  146. package/session-distill/tables/exposure_rules.json +192 -0
  147. package/session-distill/tables/placement_rules.json +148 -0
  148. package/session-distill/tables/propose_fixtures.json +154 -0
  149. package/session-distill/tables/ranking.json +194 -0
  150. package/session-distill/tables/redundancy.json +10 -0
  151. package/session-distill/tables/structural_rules.json +44 -0
  152. package/session-distill/tables/transition_fixtures.json +398 -0
  153. package/session-distill/tables/transitions.json +69 -0
  154. package/session-distill/tables/unit_outcome.json +67 -0
  155. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  156. package/wrappers/claude-run.sh +481 -33
  157. package/wrappers/claude_hermetic_evidence.py +1423 -0
  158. package/wrappers/codex-helm.sh +46 -15
  159. package/wrappers/codex-run.sh +183 -20
  160. package/wrappers/codex_frame_filter.py +1199 -0
  161. package/wrappers/codex_protocol.py +737 -0
  162. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,3072 @@
1
+ #!/usr/bin/env python3
2
+ """Where S11 and S12 are allowed to write, resolved before the first effect (WP-21 commit 1).
3
+
4
+ Design §10.5 with amendment N#4. Every writer S11 and S12 run resolves its destination from the
5
+ environment the run hands it; each destination must be INSIDE the root its class declares in
6
+ `run.json.destinations`; and `destinations.resolved.json` records the whole set before the first
7
+ `planned` journal record exists. A destination outside its root is `DESTINATION_OUTSIDE_ROOT` and a
8
+ required override that is unset is `OVERRIDE_MISSING` — both refusals, both before any effect.
9
+
10
+ Why an unset override is a refusal even when its fallback looks harmless: a fallback is a path the
11
+ run did not declare. `update-state.py` falls back through `pathlib.Path.home()`, which reads HOME
12
+ when it is set and the password database when it is not, so the same code that writes into a fixture
13
+ in one process writes into the real home of whoever runs it in another. This repository has paid for
14
+ that once already (a control exercising a `pw_dir` fallback wrote a run into the owner's home during
15
+ a commit hook). The confinement is therefore the declaration, never the fallback.
16
+
17
+ This module writes nothing except `destinations.resolved.json`, and performs no effect of any kind.
18
+ It is the first commit of WP-21 on purpose: the code that confines writes lands before the code that
19
+ writes.
20
+
21
+ destinations.py --self-test
22
+ """
23
+ import ast
24
+ import json
25
+ import os
26
+ import pathlib
27
+ import re
28
+ import sys
29
+
30
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
31
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
32
+ from runlib import declare, records, targets, validate # noqa: E402
33
+ from runlib.records import Refused # noqa: E402
34
+
35
+ HERE = pathlib.Path(__file__).resolve().parents[1]
36
+ REPO = HERE.parent
37
+ TABLE_PATH = HERE / "tables" / "destinations.json"
38
+ OUTPUT = "destinations.resolved.json"
39
+ # The declared classes come from the declaration's own schema, through declare.py, so this module
40
+ # cannot disagree with what a run is allowed to declare.
41
+ CLASSES = declare.DESTINATIONS
42
+ _TABLE = {}
43
+
44
+
45
+ # The states a row can carry that are NOT a certification, named so a reader of the manifest does
46
+ # not have to infer them. They sat beside the git isolation and left with it; they belong here,
47
+ # with the table they describe.
48
+ RELEASE_1_UNINVOKED = "not_invoked_in_release_1"
49
+ READ_NOT_WRITTEN = "read_not_written"
50
+ RELEASE_1_WHY = ("not invoked by release-1 S11: the apply writes the approved changes into files of "
51
+ "the declared checkout and executes no git, and names the commit and install "
52
+ "commands for the owner to run instead of running them (D-20261113-f22b7d, "
53
+ "narrowing D-20261112-2cf1c4)")
54
+
55
+
56
+ def table():
57
+ """The writer inventory, read once."""
58
+ if not _TABLE:
59
+ _TABLE.update(json.loads(TABLE_PATH.read_text(encoding="utf-8")))
60
+ return _TABLE
61
+
62
+
63
+ def writers():
64
+ return tuple(table()["writers"])
65
+
66
+
67
+ def pairs():
68
+ """Every (writer, override, class) the table declares, in table order."""
69
+ held = []
70
+ for row in writers():
71
+ for entry in row.get("destinations") or ():
72
+ held.append((row.get("writer"), entry.get("override"), entry.get("class")))
73
+ return tuple(held)
74
+
75
+
76
+ def required_overrides():
77
+ """Every environment name some writer's destination depends on, sorted."""
78
+ return tuple(sorted({override for _writer, override, _cls in pairs()}))
79
+
80
+
81
+ def class_of_override():
82
+ """Each override's class, and the overrides two writers place in different classes.
83
+
84
+ An environment variable has one value, so a variable two writers read must resolve to one class
85
+ for both; otherwise its single value would have to be inside two roots at once, which is
86
+ satisfiable only by accident. The disagreement is a table defect, reported by name.
87
+ """
88
+ held, conflicts = {}, {}
89
+ for writer, override, cls in pairs():
90
+ if override in held and held[override] != cls:
91
+ conflicts.setdefault(override, {held[override]}).add(cls)
92
+ held.setdefault(override, cls)
93
+ return held, conflicts
94
+
95
+
96
+ def table_problems(root=None):
97
+ """What is wrong with the table itself, by name.
98
+
99
+ A writer naming a class the declaration does not hold cannot be confined, and a declared class
100
+ no writer uses is a stale declaration — the same bar the lexicon gate applies to a concept home
101
+ that matches no file.
102
+ """
103
+ problems, rows = [], writers()
104
+ if not rows:
105
+ problems.append("WRITER_SET_EMPTY: a destination manifest over no writer confines nothing")
106
+ return problems
107
+ for row in rows:
108
+ if not row.get("writer"):
109
+ problems.append("WRITER_UNNAMED: a row with no writer")
110
+ continue
111
+ named = [entry.get("class") for entry in row.get("destinations") or ()]
112
+ if row.get("writes_without_override"):
113
+ named.append(row["writes_without_override"])
114
+ if not named:
115
+ problems.append(f"DESTINATION_UNDECLARED {row['writer']}: the row names no class, by "
116
+ f"override or otherwise")
117
+ for cls in named:
118
+ if cls not in CLASSES:
119
+ problems.append(f"DESTINATION_UNDECLARED {row['writer']}: class {cls!r} is not one "
120
+ f"of {', '.join(CLASSES)}")
121
+ # A writer may do BOTH, and the real tree settles it: `install.sh` resolves CLAUDE_CONFIG_DIR
122
+ # and CODEX_HOME from the environment while assigning `STATE_DIR` from `$HOME`
123
+ # unconditionally (install.sh:48). The first version of this gate forbade the combination,
124
+ # which would have forced the inventory to misdescribe its largest writer. What must hold is
125
+ # that a fixed root is itself classified and shown where it was derived from.
126
+ if row.get("writes_without_override") and not row.get("writer_unwritten"):
127
+ if row["writes_without_override"] not in CLASSES:
128
+ problems.append(f"FIXED_ROOT_UNCLASSED {row['writer']}: "
129
+ f"{row['writes_without_override']!r} is not a destination class")
130
+ derived_fixed_here = any(e["writer"] == row["writer"] and e["override"] is None
131
+ for e in closure(root))
132
+ if derived_fixed_here and not row.get("fixed_roots"):
133
+ problems.append(f"FIXED_ROOT_UNSHOWN {row['writer']}: the closure derived a "
134
+ f"HOME-fixed root for this writer and the row shows none of the "
135
+ f"lines it came from")
136
+ if not row.get("$comment"):
137
+ problems.append(f"WRITER_UNREASONED {row['writer']}: every row carries its own reason")
138
+ _held, conflicts = class_of_override()
139
+ for override, names in sorted(conflicts.items()):
140
+ problems.append(f"OVERRIDE_CLASS_SPLIT {override}: placed in {', '.join(sorted(names))} by "
141
+ f"different writers, but one variable has one value")
142
+ used = set()
143
+ for row in rows:
144
+ used.update(entry.get("class") for entry in row.get("destinations") or ())
145
+ if row.get("writes_without_override"):
146
+ used.add(row["writes_without_override"])
147
+ for name in CLASSES:
148
+ if name not in used:
149
+ problems.append(f"DESTINATION_CLASS_UNWRITTEN {name}: a declared class no writer writes "
150
+ f"under is a stale declaration")
151
+ return problems
152
+
153
+
154
+ LAYOUT_DECLARATION = "provenance.json"
155
+ LAYOUT_AUTHOR_TREE = "gates"
156
+
157
+
158
+ def install_layout(root=None):
159
+ """`"checkout"`, `"package"`, or None when nothing in the tree declares which.
160
+
161
+ It matters because an author-scope writer's SOURCE is not shipped: `fidelity_problems` reads
162
+ every `fallback_source`, so in a packaged install the manifest failed `WRITER_SOURCE_ABSENT`
163
+ over `session-distill/update-state.py` — a refusal no packaged user can act on, and one no check
164
+ run from a clone can see. Found by the WP-21 review.
165
+
166
+ Decided by a DECLARED fact, not by an absence. `provenance.json` is written by
167
+ `gates/check-publish.sh --stamp` at `npm prepack`, carries the commit the tarball holds, and is
168
+ removed again after packing, so it exists in a published package and in nothing else. The
169
+ author tree (`gates/`) is the checkout's own declaration. Inferring `package` from a missing
170
+ directory made every incomplete copy of this tree a package — including a fixture that had
171
+ simply not copied everything — and the excuses that ride on the layout (an author-scope writer
172
+ may be absent; its source need not be read) were then granted to a tree nobody had published.
173
+ Neither declaration present, or both, is not guessed at: it is None, and `layout_problems` says
174
+ so by name.
175
+ """
176
+ base = pathlib.Path(root or REPO)
177
+ declared = (base / LAYOUT_DECLARATION).is_file()
178
+ author_side = (base / LAYOUT_AUTHOR_TREE).is_dir()
179
+ if declared and not author_side:
180
+ return "package"
181
+ if author_side and not declared:
182
+ return "checkout"
183
+ return None
184
+
185
+
186
+ def layout_problems(root=None):
187
+ """What stops the layout being established, by name — a refusal, not a default."""
188
+ base = pathlib.Path(root or REPO)
189
+ if install_layout(base) is not None:
190
+ return []
191
+ held = ((base / LAYOUT_DECLARATION).is_file(), (base / LAYOUT_AUTHOR_TREE).is_dir())
192
+ if held == (True, True):
193
+ return [f"LAYOUT_AMBIGUOUS {base}: it carries both a package's {LAYOUT_DECLARATION} and the "
194
+ f"author-side {LAYOUT_AUTHOR_TREE}/, so which excuses apply to an author-scope "
195
+ f"writer cannot be established"]
196
+ return [f"LAYOUT_UNDECLARED {base}: neither a package's {LAYOUT_DECLARATION} nor the "
197
+ f"author-side {LAYOUT_AUTHOR_TREE}/ is here, so this tree does not say which layout it "
198
+ f"is, and the excuses that ride on the layout may not be granted by default"]
199
+
200
+
201
+ def author_rows_absent(root=None):
202
+ """The author-scope rows whose writer is not present in this layout, by writer name.
203
+
204
+ In a package these are recorded rather than refused, and their destination is NOT certified: a
205
+ writer that is not installed cannot write, so there is nothing to confine. In a checkout the
206
+ source is required, because that is where the fallback literal is audited.
207
+ """
208
+ base = pathlib.Path(root or REPO)
209
+ return sorted(row["writer"] for row in writers()
210
+ if row.get("writer_scope") == "author" and not (base / row["writer"]).is_file())
211
+
212
+
213
+ def fidelity_problems(root=None):
214
+ """Where the table's stated fallback is no longer the one its writer carries.
215
+
216
+ The fallback is a restatement, tolerated because this makes its drift decidable: the literal must
217
+ still be present in the writer's own source. A row whose source file is gone fails too — the
218
+ inventory would otherwise go on describing a writer that no longer exists.
219
+ """
220
+ problems = []
221
+ base = pathlib.Path(root or REPO)
222
+ for row in writers():
223
+ # An author-scope writer absent from a packaged install is not a fidelity failure: its
224
+ # source is not shipped, and the row's destination is not certified either (see
225
+ # `author_rows_absent`). In a checkout it is required, and absence still fails.
226
+ if (row.get("writer_scope") == "author"
227
+ and install_layout(base) == "package"
228
+ and not (base / row["writer"]).is_file()):
229
+ continue
230
+ source = row.get("fallback_source")
231
+ if source is None:
232
+ if row.get("fallbacks"):
233
+ problems.append(f"FALLBACK_UNSOURCED {row['writer']}: a fallback is stated with no "
234
+ f"source to hold it against")
235
+ continue
236
+ # Against the install this runs in, not against the author's checkout: a check that reads
237
+ # one tree while judging another cannot see a packaged install at all.
238
+ path = base / source
239
+ if not path.is_file():
240
+ problems.append(f"WRITER_SOURCE_ABSENT {row['writer']}: {source} does not exist")
241
+ continue
242
+ text = path.read_text(encoding="utf-8", errors="replace")
243
+ carried = {entry["override"] for entry in row.get("destinations") or ()}
244
+ for held in row.get("fallbacks") or ():
245
+ # A fallback for an override the row does not carry is the same error as a certified
246
+ # class for an override the writer does not read: install.sh's fallbacks listed
247
+ # AGENT_BIOS_STATE_DIR, whose literal IS in install.sh — as an unconditional assignment
248
+ # with no override in it — so the literal check passed over it.
249
+ if held["override"] not in carried:
250
+ problems.append(f"FALLBACK_UNPAIRED {row['writer']} {held['override']}: a fallback "
251
+ f"is stated for an override this row carries no destination for")
252
+ continue
253
+ if held["literal"] not in text:
254
+ problems.append(f"FALLBACK_MOVED {row['writer']} {held['override']}: {source} no "
255
+ f"longer carries {held['literal']!r}")
256
+ return problems
257
+
258
+
259
+ # ---- the inventory derived from the writers' real closure ---------------------------------------
260
+ #
261
+ # The first version of this table was written from memory and was incomplete in both directions: it
262
+ # lacked nine override variables that shipped writers really read, and it certified
263
+ # `AGENT_BIOS_STATE_DIR` for `install.sh`, which assigns `STATE_DIR` from `$HOME` unconditionally and
264
+ # never reads that variable at all — a row certifying a value its writer cannot use. Memory is not a
265
+ # source. These functions derive the closure from the shipped files themselves, so a writer that
266
+ # gains a destination appears here without anyone remembering to add it.
267
+
268
+ # A destination override is one whose fallback is a PATH. `AGENT_LAUNCH_TUI:-1`,
269
+ # `AGENT_BIOS_UPDATE_CHECK:-1` and `AGENT_BIOS_LEGACY_INSTALL` are flags compared to a literal, and a
270
+ # flag is not a place anything is written.
271
+ _OVERRIDE_NAME = (r"(AGENT_BIOS_[A-Z_]+|AGENT_LAUNCH_[A-Z_]+|XDG_[A-Z_]+|CLAUDE_CONFIG_DIR"
272
+ r"|CODEX_HOME|ZDOTDIR|HOME)")
273
+ # Python: ANY mapping's `.get("OVERRIDE"`, over the whole text rather than line by line. Both
274
+ # corrections are findings from the first derivation: it matched only `environ.get(`, so
275
+ # `compose/instructions_install.py`'s `self.env.get("CLAUDE_CONFIG_DIR", ...)` — the same read
276
+ # through an injected environment — looked like an override the writer does not read; and it scanned
277
+ # single lines, so `session-distill/update-state.py`'s three-line `os.environ.get(` was invisible.
278
+ # Both false answers pointed the same way, at the table being wrong where it was right.
279
+ _PY_OVERRIDE = re.compile(r'\.get\(\s*["\']' + _OVERRIDE_NAME + r'["\']\s*(?:,\s*(?P<fb>(?:[^()]|\([^()]*\))*))?',
280
+ re.DOTALL)
281
+ _PY_SUBSCRIPT = re.compile(r'environ\[\s*["\']' + _OVERRIDE_NAME + r'["\']\s*\]')
282
+ _SH_OVERRIDE = re.compile(r'\$\{' + _OVERRIDE_NAME + r':-(?P<fb>[^}]*)\}')
283
+ _PATHISH = re.compile(r'(Path\.home\(\)|expanduser|os\.path\.join|\$HOME|\$\{HOME\}|/|\.local|\.config)')
284
+ _HOME_ROOT = re.compile(r'(Path\.home\(\)|expanduser\(\s*["\']~|\$HOME|\$\{HOME\})')
285
+ _ROOTISH = re.compile(r'(\.local/|\.config/|\.claude|\.codex|\.cache/|\.zsh|/share/|/bin\b)')
286
+
287
+
288
+ def shipped_writers(root=None):
289
+ """Every shipped script the package carries, from `package.json` `files[]`.
290
+
291
+ Derived rather than listed: a writer added to the package is scanned without this module being
292
+ told about it, which is the whole point of deriving the inventory.
293
+
294
+ `root` is the installation being INSPECTED, which is not always the tree this file sits in. A
295
+ packaged install has no `gates/` and no author-side writers, and with the global `REPO` wired
296
+ in here the derivation read the author's checkout instead — so a real package could not produce
297
+ a manifest at all (round 2). The default stays `REPO`, which is what a checkout run means.
298
+ """
299
+ base = pathlib.Path(root or REPO)
300
+ manifest = json.loads((base / "package.json").read_text(encoding="utf-8"))
301
+ held = [base / rel for rel in sorted(_author_writers()) if (base / rel).is_file()]
302
+ for entry in manifest.get("files") or ():
303
+ path = base / entry
304
+ if path.is_file() and path.suffix in (".py", ".sh", ".zsh"):
305
+ held.append(path)
306
+ elif path.is_dir():
307
+ held += [p for p in sorted(path.rglob("*"))
308
+ if p.is_file() and p.suffix in (".py", ".sh", ".zsh")]
309
+ return held
310
+
311
+
312
+ def _author_writers():
313
+ """Writers the table declares as author-side, with the paths they live at.
314
+
315
+ `session-distill/update-state.py` is one: it writes the nudge state the design's §10.6 names, and
316
+ it is NOT in `package.json` `files[]` — the owner runs it from a checkout. Scanning only the
317
+ shipped set therefore cannot see it, and the first derivation reported its real row as
318
+ certifying an override nobody reads. A writer outside the package is admissible in this table,
319
+ but it must say so, and `inventory_problems` holds the declaration against `files[]` in both
320
+ directions so "author-side" cannot be used to excuse a shipped writer from the derivation.
321
+ """
322
+ return {row["writer"] for row in writers() if row.get("writer_scope") == "author"}
323
+
324
+
325
+ # A path-shaped environment read is not yet a destination: `AGENT_BIOS_PACKAGE_ROOT` names where the
326
+ # package is READ from, `AGENT_BIOS_PYTHON_EXECUTABLE` names an interpreter, and the fixture strings
327
+ # in `inventory.py`'s own self-test name paths nothing writes. A derivation that cannot tell a read
328
+ # from a write produces an inventory whose exemption list is the real table — which is the shape this
329
+ # repo refuses everywhere else. So the question asked of each read is whether its value REACHES A
330
+ # WRITE in the same file.
331
+ _WRITE_CALLS = frozenset((
332
+ "write_text", "write_bytes", "mkdir", "makedirs", "touch", "replace", "rename", "symlink_to",
333
+ "copy", "copy2", "copyfile", "copytree", "move", "unlink", "rmtree", "chmod", "write",
334
+ "writelines", "writestr", "add", "extractall", "dump", "mkstemp", "NamedTemporaryFile",
335
+ ))
336
+ _SH_WRITE = re.compile(
337
+ r'(>>?\s*"?\$|\b(cp|mv|mkdir|install|tee|rm|rmdir|ln|chmod|touch|cat\s*>|tar|printf[^|]*>)\b)')
338
+
339
+
340
+ def _py_destination_reads(text):
341
+ """(override, line) for every env read in this Python source whose value reaches a write.
342
+
343
+ Reaching is answered over NAMES, not over a full dataflow: the read's assignment target (a name
344
+ or an attribute like `self.state_root`) must appear somewhere inside a write call's arguments.
345
+ That is deliberately generous — a name used in one write and read in ten still counts — because
346
+ the failure this inventory exists to prevent is a destination nobody declared, and a row too many
347
+ costs a reason while a row too few costs the owner's files.
348
+ """
349
+ try:
350
+ tree = ast.parse(text)
351
+ except SyntaxError:
352
+ return []
353
+ reads = [] # (override, line, target-name)
354
+ for node in ast.walk(tree):
355
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)):
356
+ continue
357
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
358
+ names = set()
359
+ for target in targets:
360
+ for part in ast.walk(target):
361
+ if isinstance(part, ast.Name):
362
+ names.add(part.id)
363
+ elif isinstance(part, ast.Attribute):
364
+ names.add(part.attr)
365
+ if node.value is None:
366
+ continue
367
+ held = ast.unparse(node.value)
368
+ # A CALL, not a text match. `compose/assemble.py` holds
369
+ # `CLAUDE_VAR = "${CLAUDE_CONFIG_DIR:-$HOME/.claude}"` — a token it rewrites text with, and a
370
+ # regex over the unparsed value read that string as an environment read. A string that
371
+ # mentions an override is not a read of it.
372
+ overrides, home_call = set(), False
373
+ for part in ast.walk(node.value):
374
+ if isinstance(part, ast.Subscript) and isinstance(part.slice, ast.Constant):
375
+ base = part.value
376
+ base_name = (base.attr if isinstance(base, ast.Attribute)
377
+ else getattr(base, "id", ""))
378
+ if base_name == "environ" and re.fullmatch(_OVERRIDE_NAME, str(part.slice.value) or ""):
379
+ overrides.add(str(part.slice.value))
380
+ if not isinstance(part, ast.Call):
381
+ continue
382
+ func = part.func
383
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
384
+ if name == "get" and part.args:
385
+ # The key can be chosen at runtime: `compose/instructions_understand.py` reads
386
+ # `.get("CODEX_HOME" if host == "codex" else "CLAUDE_CONFIG_DIR", ...)`, which
387
+ # honours BOTH overrides. Reading only a constant key recorded that writer as
388
+ # fixing its root from HOME — the same error as certifying an override nobody reads,
389
+ # pointing the other way.
390
+ asked_nodes = [part.args[0]]
391
+ if isinstance(part.args[0], ast.IfExp):
392
+ asked_nodes = [part.args[0].body, part.args[0].orelse]
393
+ for node_asked in asked_nodes:
394
+ if not isinstance(node_asked, ast.Constant):
395
+ continue
396
+ asked = str(node_asked.value)
397
+ if re.fullmatch(_OVERRIDE_NAME, asked) and _PATHISH.search(held):
398
+ overrides.add(asked)
399
+ if name in ("home", "expanduser"):
400
+ home_call = True
401
+ for asked in overrides:
402
+ for name in names:
403
+ reads.append((asked, node.lineno, name))
404
+ if not overrides and home_call and _ROOTISH.search(held):
405
+ for name in names:
406
+ reads.append((None, node.lineno, name))
407
+ written = set()
408
+ for node in ast.walk(tree):
409
+ if not isinstance(node, ast.Call):
410
+ continue
411
+ func = node.func
412
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
413
+ opens_for_write = (
414
+ name == "open"
415
+ and any(isinstance(a, ast.Constant) and isinstance(a.value, str)
416
+ and any(mode in a.value for mode in ("w", "a", "x", "+"))
417
+ for a in list(node.args[1:]) + [k.value for k in node.keywords]))
418
+ if name not in _WRITE_CALLS and not opens_for_write:
419
+ continue
420
+ for part in ast.walk(node):
421
+ if isinstance(part, ast.Name):
422
+ written.add(part.id)
423
+ elif isinstance(part, ast.Attribute):
424
+ written.add(part.attr)
425
+ # One name is not enough. `launch/shell_integration.py` reads ZDOTDIR into `self.zdotdir`, builds
426
+ # `self.startup` from it, and writes THAT — so a rule that asks only whether the read's own
427
+ # target appears in a write call calls a correct row a false certificate. The names form a graph
428
+ # (an assignment is an edge from every name in its value to every target), and the question is
429
+ # whether the read's target reaches a written name through it.
430
+ edges = {}
431
+ for node in ast.walk(tree):
432
+ if not isinstance(node, (ast.Assign, ast.AnnAssign)) or node.value is None:
433
+ continue
434
+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]
435
+ outs = set()
436
+ for target in targets:
437
+ for part in ast.walk(target):
438
+ if isinstance(part, ast.Name):
439
+ outs.add(part.id)
440
+ elif isinstance(part, ast.Attribute):
441
+ outs.add(part.attr)
442
+ for part in ast.walk(node.value):
443
+ source = (part.id if isinstance(part, ast.Name)
444
+ else part.attr if isinstance(part, ast.Attribute) else None)
445
+ if source:
446
+ edges.setdefault(source, set()).update(outs)
447
+
448
+ # One hop across a call. `session-distill/update-state.py` reads its override into `STATE` and
449
+ # passes it to a function that writes through `os.replace(temporary, path)` — the write names
450
+ # the PARAMETER, not the module constant, so a graph that stops at function boundaries declares
451
+ # a real destination unwritten. An argument therefore flows to the callee's parameter when the
452
+ # callee is defined in this same module.
453
+ params = {}
454
+ for node in ast.walk(tree):
455
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
456
+ spec = node.args
457
+ params[node.name] = [a.arg for a in
458
+ list(spec.posonlyargs) + list(spec.args) + list(spec.kwonlyargs)]
459
+ for node in ast.walk(tree):
460
+ if not isinstance(node, ast.Call):
461
+ continue
462
+ callee = node.func.attr if isinstance(node.func, ast.Attribute) else getattr(node.func, "id", "")
463
+ if callee not in params:
464
+ continue
465
+ for index, argument in enumerate(node.args):
466
+ if index >= len(params[callee]):
467
+ break
468
+ for part in ast.walk(argument):
469
+ source = (part.id if isinstance(part, ast.Name)
470
+ else part.attr if isinstance(part, ast.Attribute) else None)
471
+ if source:
472
+ edges.setdefault(source, set()).add(params[callee][index])
473
+ for keyword in node.keywords:
474
+ if keyword.arg in params[callee]:
475
+ for part in ast.walk(keyword.value):
476
+ source = (part.id if isinstance(part, ast.Name)
477
+ else part.attr if isinstance(part, ast.Attribute) else None)
478
+ if source:
479
+ edges.setdefault(source, set()).add(keyword.arg)
480
+
481
+ def reaches(name):
482
+ seen, queue = {name}, [name]
483
+ while queue:
484
+ held_name = queue.pop()
485
+ if held_name in written:
486
+ return True
487
+ for nxt in edges.get(held_name, ()):
488
+ if nxt not in seen:
489
+ seen.add(nxt)
490
+ queue.append(nxt)
491
+ return False
492
+
493
+ return [(override, line) for override, line, name in reads if reaches(name)]
494
+
495
+
496
+ def _sh_destination_reads(text):
497
+ """The same question for a shell script: the variable the read is assigned to must appear in a
498
+ redirection or a writing command's arguments."""
499
+ held, lines = [], text.splitlines()
500
+ assigns = {} # variable -> (override|None, line)
501
+ for number, line in enumerate(lines, 1):
502
+ stripped = line.strip()
503
+ if stripped.startswith("#"):
504
+ continue
505
+ assign = re.match(r'(?:local\s+|export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)', stripped)
506
+ if not assign:
507
+ continue
508
+ name, value = assign.group(1), assign.group(2)
509
+ for match in _SH_OVERRIDE.finditer(value):
510
+ if _PATHISH.search(match.group("fb")) or _PATHISH.search(value):
511
+ assigns[name] = (match.group(1), number)
512
+ if name not in assigns and _HOME_ROOT.search(value) and _ROOTISH.search(value):
513
+ assigns[name] = (None, number)
514
+ # Shell carries the same indirection: `install.sh` builds `MANIFEST="$STATE_DIR/manifest.txt"`
515
+ # and writes the manifest. Propagate a root through assignments that mention it, to a fixpoint.
516
+ for _ in range(4):
517
+ for number, line in enumerate(lines, 1):
518
+ stripped = line.strip()
519
+ assign = re.match(r'(?:local\s+|export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)', stripped)
520
+ if not assign or stripped.startswith("#"):
521
+ continue
522
+ name, value = assign.group(1), assign.group(2)
523
+ if name in assigns:
524
+ continue
525
+ for held_name, origin in list(assigns.items()):
526
+ if re.search(r'\$\{?' + re.escape(held_name) + r'\b', value):
527
+ assigns[name] = origin
528
+ break
529
+ for number, line in enumerate(lines, 1):
530
+ if line.strip().startswith("#") or not _SH_WRITE.search(line):
531
+ continue
532
+ for name, (override, where) in assigns.items():
533
+ if re.search(r'\$\{?' + re.escape(name) + r'\b', line):
534
+ held.append((override, where))
535
+ return held
536
+
537
+
538
+ _CLOSURE_CACHE = {}
539
+
540
+
541
+ def closure(root=None):
542
+ """The (writer, override) pairs and HOME-fixed roots the shipped tree really carries.
543
+
544
+ Each entry is `{writer, override|None, line, text}`. `override=None` means the writer defines a
545
+ destination root from HOME with no variable to redirect it, which is a different obligation: the
546
+ run cannot point that writer anywhere, so the table must say so rather than name an override.
547
+ """
548
+ # Scanning every shipped script costs real time, and `table_problems` asks this question once
549
+ # per row: without a cache the self-test's table mutations re-scan the tree dozens of times.
550
+ # The key is the declared author-side set, the only input a caller can vary in one process.
551
+ base = pathlib.Path(root or REPO)
552
+ key = (str(base), tuple(sorted(_author_writers())))
553
+ if key in _CLOSURE_CACHE:
554
+ return _CLOSURE_CACHE[key]
555
+ held = []
556
+ for path in shipped_writers(base):
557
+ rel = str(path.relative_to(base))
558
+ text = path.read_text(encoding="utf-8", errors="replace")
559
+ lines = text.splitlines()
560
+ reached = (_py_destination_reads(text) if path.suffix == ".py"
561
+ else _sh_destination_reads(text))
562
+ for override, number in sorted(set(reached), key=lambda h: (h[0] or "", h[1])):
563
+ line = lines[number - 1] if number - 1 < len(lines) else ""
564
+ held.append({"writer": rel, "override": override, "line": number,
565
+ "text": line.strip()[:160]})
566
+ _CLOSURE_CACHE[key] = held
567
+ return held
568
+
569
+
570
+ def inventory_problems(root=None):
571
+ """Where the table and the derived closure disagree, in both directions.
572
+
573
+ `INVENTORY_INCOMPLETE` is a (writer, override) pair the tree carries and the table does not — the
574
+ run would hand that writer an environment it never certified. `INVENTORY_UNWRITTEN` is the
575
+ reverse and the one that actually shipped: a row certifying an override its writer does not read,
576
+ so the certificate is about a value that cannot reach the writer. A pair may be excused only by
577
+ name, in the table's `not_a_destination`, with its own reason.
578
+ """
579
+ base = pathlib.Path(root or REPO)
580
+ table_data = table()
581
+ excused = {(row["writer"], row.get("override")): row.get("reason")
582
+ for row in table_data.get("not_a_destination") or ()}
583
+ declared, fixed = set(), set()
584
+ for row in writers():
585
+ for held in row.get("destinations") or ():
586
+ declared.add((row["writer"], held["override"]))
587
+ if row.get("writes_without_override"):
588
+ fixed.add(row["writer"])
589
+ problems = []
590
+ derived_pairs, derived_fixed = set(), set()
591
+ for entry in closure(base):
592
+ if entry["override"] is None:
593
+ derived_fixed.add(entry["writer"])
594
+ continue
595
+ derived_pairs.add((entry["writer"], entry["override"]))
596
+ for pair in sorted(derived_pairs - declared):
597
+ if pair in excused:
598
+ continue
599
+ problems.append(f"INVENTORY_INCOMPLETE {pair[0]} {pair[1]}: the shipped writer reads this "
600
+ f"override as a destination and no table row carries the pair")
601
+ forward = {row["writer"] for row in writers() if row.get("writer_unwritten")}
602
+ for writer in sorted(forward):
603
+ if (base / writer).exists():
604
+ problems.append(f"INVENTORY_FORWARD_LANDED {writer}: the row is declared as a writer "
605
+ f"that does not exist yet, and the file now exists — the declaration "
606
+ f"must give way to the derived closure")
607
+ # A writer the table declares author-side and this installation does not have writes nothing
608
+ # here, so its pairs are neither certified nor missing: they are NOT INSTALLED, which is what
609
+ # `author_rows_absent` and the resolved row already say. Without this, a real packaged install
610
+ # could not produce a manifest at all — the table's author-scope rows came back as certifying
611
+ # overrides no source reads, and the only source that reads them is the one npm leaves out.
612
+ # Round 2's finding; the fidelity check already made this exclusion and the inventory did not.
613
+ uninstalled = set(author_rows_absent(base))
614
+ for pair in sorted(declared - derived_pairs):
615
+ if pair in excused or pair[0] in forward or pair[0] in uninstalled:
616
+ continue
617
+ problems.append(f"INVENTORY_UNWRITTEN {pair[0]} {pair[1]}: the table certifies a destination "
618
+ f"class for an override this writer's source never reads, so the class is "
619
+ f"about a value that cannot reach it")
620
+ # The REVERSE direction for fixed-root rows, which this check did not cover: a row claiming a
621
+ # HOME-fixed root for a writer that is not in this tree at all passed, because every leg here
622
+ # asked about (writer, override) PAIRS and a fixed root has none. A nonexistent writer with
623
+ # `writes_without_override` was certified by `path = root, inside = bool(root)` (the round-2
624
+ # review found both halves).
625
+ for row in writers():
626
+ if not row.get("writes_without_override"):
627
+ continue
628
+ if row.get("writer_unwritten") or row["writer"] in uninstalled or row["writer"] == "git":
629
+ continue
630
+ if not (base / row["writer"]).exists():
631
+ problems.append(f"INVENTORY_FIXED_ROOT_ABSENT {row['writer']}: the row claims a fixed "
632
+ f"destination root and the writer is not in this tree, is not declared "
633
+ f"`writer_unwritten` and is not author-side, so the row certifies a "
634
+ f"class for a file nobody has")
635
+ if row.get("root_from") not in ("home", "argument"):
636
+ problems.append(f"INVENTORY_ROOT_FROM_UNSTATED {row['writer']}: a fixed-root row says "
637
+ f"whether the run passes the root (`argument`) or the writer derives it "
638
+ f"from HOME (`home`), because the two are certified differently")
639
+ if row.get("root_from") == "home" and not (row.get("fixed_roots") or ()):
640
+ problems.append(f"INVENTORY_FIXED_ROOT_UNSHOWN {row['writer']}: the row says the root "
641
+ f"is derived from HOME and shows no source line it is derived at, so "
642
+ f"there is nothing to compute the destination from")
643
+ for writer in sorted(derived_fixed):
644
+ if any(w == writer for w, _ in declared) or writer in fixed or writer in forward:
645
+ continue
646
+ if writer in uninstalled:
647
+ continue
648
+ if (writer, None) in excused:
649
+ continue
650
+ problems.append(f"INVENTORY_FIXED_ROOT {writer}: the writer derives a destination root from "
651
+ f"HOME with no override, and the table neither carries the writer nor "
652
+ f"excuses it — a run cannot point that writer anywhere")
653
+ shipped_rel = {str(p.relative_to(base)) for p in shipped_writers(base)}
654
+ packed = set(json.loads((base / "package.json").read_text(encoding="utf-8")).get("files") or ())
655
+ for writer in sorted(_author_writers()):
656
+ if writer in packed or any(writer.startswith(entry) for entry in packed if entry.endswith("/")):
657
+ problems.append(f"INVENTORY_SCOPE_WRONG {writer}: declared author-side while "
658
+ f"package.json files[] ships it, so the declaration excuses a writer "
659
+ f"the derivation can see")
660
+ elif not (base / writer).is_file() and install_layout(base) == "checkout":
661
+ # In a CHECKOUT the file must be there: the declaration says the owner runs it from one.
662
+ # In a package its absence is the layout, not a defect, and `author_rows_absent` is what
663
+ # reports it.
664
+ problems.append(f"INVENTORY_SCOPE_ABSENT {writer}: declared author-side and not present "
665
+ f"in this tree at all")
666
+ if not shipped_rel:
667
+ problems.append("INVENTORY_NO_WRITERS_SCANNED: package.json files[] yielded no script to "
668
+ "scan, so every table row would pass unexamined")
669
+ if not derived_pairs:
670
+ problems.append("INVENTORY_DERIVED_EMPTY: the closure found no (writer, override) pair at "
671
+ "all, so an empty table would satisfy this check")
672
+ return problems
673
+
674
+
675
+ def inside(path, root):
676
+ """Public name for the LEXICAL containment question, so one module answers it.
677
+
678
+ Lexical is half the answer and the smaller half. `os.open` follows symlinks, so a path inside
679
+ this root can still open a file outside it; what closes that is the WRITER opening with
680
+ `O_NOFOLLOW` (`journal.Storage.append` does), not a comparison of strings. A caller that cannot
681
+ open with O_NOFOLLOW must check `links_problem` as well.
682
+
683
+ `journal.py` asks it of its own file: the journal is `runtime_state`, and a journal written
684
+ outside its declared root is the hole this module exists to close.
685
+ """
686
+ return _inside(path, root)
687
+
688
+
689
+ def links_problem(path, root):
690
+ """A symlink on the way from `root` to `path`, by name, or None.
691
+
692
+ For a caller that cannot open with `O_NOFOLLOW`. It walks the parts between the root and the
693
+ path and names the first link it finds, because a link anywhere on the way is enough to put the
694
+ final write outside the root. It answers about the filesystem AS IT IS NOW, so a writer that
695
+ can refuse the follow itself should do that instead: between this check and the open, a link can
696
+ appear.
697
+ """
698
+ path, root = pathlib.Path(path), pathlib.Path(root)
699
+ if not _inside(path, root):
700
+ return f"DESTINATION_OUTSIDE_ROOT {path}: not inside {root}"
701
+ held = root
702
+ for part in path.relative_to(pathlib.PurePosixPath(os.path.normpath(str(root)))).parts:
703
+ held = held / part
704
+ if held.is_symlink():
705
+ return (f"DESTINATION_SYMLINK {held}: a symlink on the way to {path} can put the write "
706
+ f"outside {root}, and a lexical check cannot see it")
707
+ return None
708
+
709
+
710
+ def _inside(path, root):
711
+ """Whether `path` is the root itself or beneath it, decided on normalized absolute paths.
712
+
713
+ No `resolve()`: a symlink is followed by the writer, so the question is what the writer will
714
+ open, and `/var` against `/private/var` has cost this repository a green pretrial and a red hook
715
+ before. Normalizing without resolving keeps the answer the same in both places.
716
+ """
717
+ path = pathlib.PurePosixPath(os.path.normpath(str(path)))
718
+ root = pathlib.PurePosixPath(os.path.normpath(str(root)))
719
+ return path == root or root in path.parents
720
+
721
+
722
+ # ─── The environment a writer is GIVEN ───────────────────────────────────────────────────────────
723
+ # The inversion this unit's round-2 review asked for, and the reason it is the right way round:
724
+ # DERIVING every override that could redirect a write loses the moment a writer resolves one across
725
+ # a module boundary (`environment_value` reads the instructions and corpus aliases in
726
+ # `compose/instructions_install.py`, where this module's scanner does not follow), and what is not
727
+ # derived is not refused. An override that is ABSENT cannot redirect anything.
728
+ #
729
+ # So the run hands each writer an environment holding EXACTLY the names the table declares for it,
730
+ # with HOME set to what the run declares, and the derivation becomes a DISCLOSURE: what does this
731
+ # writer read that it was not given? A non-empty answer withholds certification instead of being
732
+ # weighed.
733
+ #
734
+ # Four channels the environment cannot close, each with its own rule below rather than a hope:
735
+ # the password database (a path from `getpwuid` ignores HOME entirely), an absolute literal in the
736
+ # source, a login shell that re-reads the user's profile and restores what was scrubbed, and a path
737
+ # the writer takes as an ARGUMENT — which is not a hole but the preferred channel, because an
738
+ # argument cannot be inherited by anything.
739
+ ENVIRONMENT_HOME = ("environment", "home")
740
+
741
+
742
+ def declared_home(declaration):
743
+ """The HOME the run declares for its writers, or None.
744
+
745
+ Its own block rather than a destination class: HOME is not a place anything is classified into,
746
+ it is the input from which this writer's fixed roots are computed. Optional in the declaration's
747
+ schema and REQUIRED here, so a lane whose fixtures predate it still declares a valid run while
748
+ no manifest can be written without it.
749
+ """
750
+ held = (declaration or {}).get(ENVIRONMENT_HOME[0]) or {}
751
+ return held.get(ENVIRONMENT_HOME[1])
752
+
753
+
754
+ def environment_for(row, declaration):
755
+ """Exactly what the run hands this writer: the declared overrides, and HOME. Nothing else.
756
+
757
+ `{name: value}`, where each name is one this writer's own table row declares and each value is
758
+ the declared root of that name's class. A variable this writer reads and the table does not
759
+ declare for it is ABSENT from the answer, which is the whole mechanism: it cannot redirect a
760
+ write it is not there for.
761
+ """
762
+ roots = (declaration or {}).get("destinations") or {}
763
+ held = {}
764
+ for entry in row.get("destinations") or ():
765
+ held[entry["override"]] = roots.get(entry.get("class"))
766
+ home = declared_home(declaration)
767
+ if home:
768
+ held["HOME"] = home
769
+ return held
770
+
771
+
772
+ def reads_not_given(writer, environment, root=None):
773
+ """The override names this writer's own source reads that the run did not hand it.
774
+
775
+ The derivation's job after the inversion: not to PROVE containment — the absence of a variable
776
+ does that — but to DISCLOSE what a writer reaches for and is not given. A non-empty answer
777
+ withholds certification, because a writer reading a name the run did not set resolves it through
778
+ a fallback the run never declared, and where that fallback points is not this manifest's answer.
779
+ """
780
+ held = {entry["override"] for entry in closure(root)
781
+ if entry["writer"] == writer and entry["override"]}
782
+ # A pair the table has REASONED about is not an undisclosed read: `not_a_destination` names the
783
+ # writer, the variable and why no §10.6 operation can reach that write. The row carries those
784
+ # names with their reasons (`reads_excused`) so the manifest shows them instead of hiding them;
785
+ # what withholds certification is a read nobody has reasoned about.
786
+ return sorted(held - set(environment or {}) - set(excused_overrides(writer)))
787
+
788
+
789
+ def entry_invoked_in_release_1(row, entry):
790
+ """Whether release-1 S11 may write THIS destination of this writer.
791
+
792
+ The scope is per destination, not per writer, because S11 is itself one of the writers: the
793
+ apply stage edits the declared checkout (invoked) and patches a personal layer (not invoked in
794
+ release 1). An entry says so for itself and otherwise inherits its writer's answer, so a row
795
+ cannot be narrowed by the writer's silence.
796
+ """
797
+ held = entry.get("release_1_invoked")
798
+ return bool(row.get("release_1_invoked")) if held is None else bool(held)
799
+
800
+
801
+ def invoked_in_release_1(writer):
802
+ """Whether release-1 S11 may invoke this writer at all.
803
+
804
+ The scope is a FACT each row carries, not a sentence in a design record: release 1's apply writes
805
+ the declared checkout and makes the git commit, and runs nothing else
806
+ (`D-20261112-2cf1c4`). A row the release may not invoke has its certification WITHHELD by the
807
+ name `not_invoked_in_release_1`, so a reader asking what this release may write reads the
808
+ manifest rather than the record.
809
+ """
810
+ for row in writers():
811
+ if row["writer"] == writer:
812
+ return bool(row.get("release_1_invoked"))
813
+ return False
814
+
815
+
816
+ def excused_overrides(writer):
817
+ """`{override: reason}` the table declares not a destination for this writer."""
818
+ return {row.get("override"): row.get("reason")
819
+ for row in table().get("not_a_destination") or ()
820
+ if row.get("writer") == writer and row.get("override")}
821
+
822
+
823
+ def environment_problems(declaration):
824
+ """What stops an environment being produced at all, by name."""
825
+ problems = []
826
+ if not declared_home(declaration):
827
+ problems.append(f"ENVIRONMENT_HOME_UNDECLARED: the run declares no "
828
+ f"{'.'.join(ENVIRONMENT_HOME)}, so every HOME-derived root is a guess and "
829
+ f"no writer can be handed an environment")
830
+ return problems
831
+
832
+
833
+ # The ways a writer in this tree names the home it derives a root from: the library call, the shell
834
+ # variable, the tilde, and a LOCAL named `home` — `compose/instructions_install.py` assigns
835
+ # `home = Path(self.env.get("HOME", str(Path.home())))` and then builds every root from it, so a
836
+ # pattern that knew only `Path.home()` read that writer's roots as unestablishable.
837
+ _HOME_ROOTED = re.compile(
838
+ r"""(?:pathlib\.Path\.home\(\)|Path\.home\(\)|os\.path\.expanduser\(|\$HOME|\$\{HOME\}"""
839
+ r"""|\bhome\b|~)"""
840
+ r"""\s*(?:/\s*)?["']?/?(?P<suffix>[A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)*)?""")
841
+
842
+
843
+ def source_line(writer, number, base=None):
844
+ """The writer's own line `number`, or None when the file is not in this installation.
845
+
846
+ The table stores a 160-character EXCERPT of that line as evidence for a reader; the computation
847
+ reads the file, because the excerpt cut `str(home / ".config/agent-bios/corpus")` off the end of
848
+ a long line and that root then read as unestablishable. The table says where to look; the source
849
+ says what is there.
850
+ """
851
+ path = pathlib.Path(base or REPO) / writer
852
+ if not path.is_file() or not number:
853
+ return None
854
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
855
+ if not 0 < number <= len(lines):
856
+ return None
857
+ # The STATEMENT, not the line: `INSTRUCTIONS_STATUS_PATH = pathlib.Path(` opens a call whose
858
+ # HOME-derived default is three lines further down, and one line of it establishes nothing. The
859
+ # window ends where the parentheses balance, so it is the statement's own extent rather than a
860
+ # guess, and it is bounded so an unbalanced file cannot read the rest of the module in.
861
+ held = [lines[number - 1]]
862
+ depth = held[0].count("(") - held[0].count(")")
863
+ index = number
864
+ while depth > 0 and index < len(lines) and len(held) < 6:
865
+ held.append(lines[index])
866
+ depth += lines[index].count("(") - lines[index].count(")")
867
+ index += 1
868
+ return " ".join(piece.strip() for piece in held)
869
+
870
+
871
+ def fixed_destination(entry, home, source_text=None):
872
+ """`(path, why)` for one declared fixed root, computed from the GIVEN home.
873
+
874
+ `path=None` with a reason is **certification withheld**: the row's own source line does not say,
875
+ in a form this can read, where the writer will write. That is a state the manifest carries and
876
+ S11 refuses on — not a warning. Before this, a fixed-root row was certified by
877
+ `path = root, inside = bool(root)`, which asserts nothing about the writer at all: `install.sh`
878
+ came back certified at the install_roots root while its source puts STATE_DIR under HOME (the
879
+ round-2 review).
880
+ """
881
+ source = source_text if source_text is not None else ((entry or {}).get("root") or "")
882
+ if not home:
883
+ return None, "the run declares no home, so a HOME-derived root cannot be computed"
884
+ held = _HOME_ROOTED.search(source)
885
+ if not held:
886
+ return None, (f"its source line names no HOME-derived root this can read: {source[:80]!r}")
887
+ suffix = held.group("suffix") or ""
888
+ if not suffix or "(" in suffix or "," in suffix:
889
+ # The line derives its root from HOME and the SUFFIX is an expression this cannot read —
890
+ # `Path(environment_value(..., str(home / ".config/agent-bios/corpus")))` on one line of a
891
+ # multi-line call. What is established is the BOUND: the writer writes under the home it
892
+ # was given. Whether that is a certification depends on the class root, which is the
893
+ # caller's comparison, so the bound is returned and labelled rather than guessed at or
894
+ # refused outright.
895
+ return str(pathlib.Path(home)), ("a HOME-derived root whose suffix this cannot read "
896
+ f"({source[:60]!r}); the home is its upper bound")
897
+ return str(pathlib.Path(home) / suffix), "/".join(["<home>", suffix])
898
+
899
+
900
+ # ─── The four channels an environment cannot close ───────────────────────────────────────────────
901
+ # Scrubbing the environment is the mechanism and it is not sufficient: a writer can reach a path
902
+ # without reading a variable at all. Each channel has a RULE here rather than a hope, and each rule
903
+ # is derived from the writer's own source.
904
+ #
905
+ # * the PASSWORD DATABASE. `getpwuid`/`getpwnam` answer with the account's home whatever HOME says,
906
+ # so a path built from one cannot be redirected by the run at all. No writer may read it: this is
907
+ # not excusable by a statement, because there is nothing the run could do about it. This is the
908
+ # channel that wrote a run into the owner's real home during a commit hook, and it is proved BY
909
+ # SOURCE — never by running a writer with a real HOME to see where it lands.
910
+ # * a LOGIN SHELL. `bash -l`, `zsh -l`, `--login` re-read the user's profile and restore exactly
911
+ # the variables the run scrubbed, so a child shell must not be a login shell.
912
+ # * an ABSOLUTE LITERAL. A path spelled out in the source reads no variable, so the row must state
913
+ # it with its reason.
914
+ # * a PATH ARGUMENT. Not a hole but the PREFERRED channel: an argument cannot be inherited by
915
+ # anything, so a writer that takes one is handed its root that way and the row records it.
916
+ CHANNEL_RULES = {
917
+ "password_database": (
918
+ re.compile(r"\b(?:getpwuid|getpwnam|pwd\.getpw\w+|os\.getlogin)\s*\("),
919
+ "reads the password database, whose answer the run cannot redirect at all"),
920
+ "login_shell": (
921
+ re.compile(r"(?:--login\b|\b(?:ba|z)?sh\s+-[A-Za-z]*l\b)"),
922
+ "starts a login shell, which re-reads the user's profile and restores what was scrubbed"),
923
+ }
924
+ # The path-argument channels THIS TREE declares, by writer. Written out so the control over the
925
+ # live table compares against a specification rather than against the table it is judging: a keyed
926
+ # comparison fails for a row that appears, disappears or changes its option (the round-4 review).
927
+ CHANNEL_STATED_ARGUMENTS = {
928
+ "compose/assemble.py": ("--state-dir",),
929
+ "compose/instructions-state.py": ("--state-dir",),
930
+ "compose/instructions_app.py": ("--state-dir",),
931
+ "compose/instructions_import.py": ("--state-dir",),
932
+ "compose/instructions_understand.py": ("--state-dir",),
933
+ "compose/prune-backups.py": ("--state-dir",),
934
+ "compose/windows_deploy.py": ("--root",),
935
+ "install.sh": ("--state-dir",),
936
+ "wrappers/claude-run.sh": ("--home", "--root"),
937
+ "wrappers/codex-helm.sh": ("--home",),
938
+ "wrappers/codex-run.sh": ("--home",),
939
+ }
940
+ CHANNEL_STATED = {
941
+ "absolute_literals": (
942
+ # The token is the literal's first whitespace-free run: `"/Library/Application Support/x"`
943
+ # identifies itself by `/Library/Application`, and a command string like `"/bin/sleep 30 &"`
944
+ # by `/bin/sleep`, which is what a statement about it should name. The closing quote is NOT
945
+ # required — a literal with a space in it is still an absolute path in the source.
946
+ re.compile(r"""["'](/(?:usr|opt|etc|var|srv|Users|home|Library|private|tmp|bin|sbin)"""
947
+ r"""[^"'\s]*)"""),
948
+ "names an absolute path in its source, which reads no variable"),
949
+ "path_arguments": (
950
+ re.compile(r"(--(?:state-dir|config-home|corpus-dir|instructions-dir|root|prefix"
951
+ r"|home))\b"),
952
+ "takes a path as an argument, which is the channel the run prefers"),
953
+ }
954
+
955
+
956
+ def channel_lines(text, pattern):
957
+ """The line numbers of a pattern's matches outside comments, for one writer's source."""
958
+ held = []
959
+ for number, line in enumerate((text or "").splitlines(), 1):
960
+ stripped = line.strip()
961
+ if stripped.startswith(("#", "//", "*")):
962
+ continue
963
+ if pattern.search(line):
964
+ held.append(number)
965
+ return held
966
+
967
+
968
+ def guarded_by(text, line, name):
969
+ """Whether the statement at `line` runs only when `name` is ABSENT from the environment.
970
+
971
+ The licence for the one channel that cannot otherwise be excused. `compose/instructions_session`
972
+ reads the password database at one line, and only inside `if home is None:` where `home` came
973
+ from `env.get('HOME')` — so with HOME GIVEN, the line is unreachable, and the environment closes
974
+ the channel after all. Two hops, both from the source: the enclosing `if` names the guard, or it
975
+ names a local the enclosing scope assigned from it. Proved by SOURCE, never by running a writer
976
+ against a real home to see where it lands.
977
+ """
978
+ try:
979
+ tree = ast.parse(text)
980
+ except SyntaxError:
981
+ # A shell writer: the guard has to be visible immediately above the line, which is as much
982
+ # as a reader of shell can establish without an interpreter.
983
+ lines = (text or "").splitlines()
984
+ held_name = re.compile(rf"(?<![A-Za-z0-9_]){re.escape(name)}(?![A-Za-z0-9_])")
985
+ return any(held_name.search(held) for held in lines[max(0, line - 6):line - 1])
986
+ for node in ast.walk(tree):
987
+ if not isinstance(node, ast.If):
988
+ continue
989
+ inside = any(getattr(child, "lineno", None) == line
990
+ for part in list(node.body) + list(node.orelse)
991
+ for child in ast.walk(part))
992
+ if not inside:
993
+ continue
994
+ held_name = re.compile(rf"(?<![A-Za-z0-9_]){re.escape(name)}(?![A-Za-z0-9_])")
995
+ test = ast.unparse(node.test)
996
+ if held_name.search(test):
997
+ return True
998
+ asked = {held.id for held in ast.walk(node.test) if isinstance(held, ast.Name)}
999
+ for assign in ast.walk(tree):
1000
+ if isinstance(assign, ast.Assign) and any(
1001
+ isinstance(target, ast.Name) and target.id in asked
1002
+ for target in assign.targets):
1003
+ if held_name.search(ast.unparse(assign.value)):
1004
+ return True
1005
+ return False
1006
+
1007
+
1008
+ def channel_tokens(text, pattern):
1009
+ """The matched tokens of a pattern outside comments: the literal path, the option name."""
1010
+ held = set()
1011
+ for line in (text or "").splitlines():
1012
+ if line.strip().startswith(("#", "//", "*")):
1013
+ continue
1014
+ for found in pattern.finditer(line):
1015
+ held.add(found.group(1) if found.groups() else found.group(0))
1016
+ return held
1017
+
1018
+
1019
+ def channel_problems(root=None):
1020
+ """Every channel a writer's source shows that this module has not answered for, by name.
1021
+
1022
+ Two kinds. A FORBIDDEN channel (the password database, a login shell) is a defect no statement
1023
+ excuses, because the run cannot do anything about it. A STATED channel (an absolute literal, a
1024
+ path argument) must be named in the writer's own row with its reason, and a statement whose
1025
+ channel the source no longer shows is stale — the same bar as every other allowlist here.
1026
+ """
1027
+ base = pathlib.Path(root or REPO)
1028
+ problems, subjects = [], 0
1029
+ for row in writers():
1030
+ path = base / row["writer"]
1031
+ if not path.is_file():
1032
+ continue
1033
+ subjects += 1
1034
+ text = path.read_text(encoding="utf-8", errors="replace")
1035
+ stated = row.get("channels") or {}
1036
+ for name, (pattern, why) in CHANNEL_RULES.items():
1037
+ licences = {held.get("line"): held for held in stated.get(name) or ()
1038
+ if isinstance(held, dict)}
1039
+ for number in channel_lines(text, pattern):
1040
+ licence = licences.get(number)
1041
+ guard = (licence or {}).get("guarded_by")
1042
+ if guard and guarded_by(text, number, guard) and (licence or {}).get("reason"):
1043
+ # Licensed, and the licence is held against the source: the line runs only when
1044
+ # the run does not set `guard`, and the run always sets it. A licence naming no
1045
+ # line, or a guard the source does not show, licenses nothing.
1046
+ continue
1047
+ problems.append(f"CHANNEL_{name.upper()} {row['writer']}:{number}: it {why}, so the "
1048
+ f"environment the run hands it cannot decide where it writes"
1049
+ + (f" — the row licenses line {number} by {guard!r}, which its "
1050
+ f"source does not show guarding it" if guard else ""))
1051
+ for number in sorted(licences):
1052
+ if number not in channel_lines(text, pattern):
1053
+ problems.append(f"CHANNEL_STALE {row['writer']} {name}:{number}: the row "
1054
+ f"licenses a line the source no longer shows")
1055
+ for name, (pattern, why) in CHANNEL_STATED.items():
1056
+ # Keyed to the TOKEN — the literal path, the option name — and not to a line number,
1057
+ # which goes stale on any edit above it and teaches a reader to renumber rather than
1058
+ # re-examine. The licence above is line-keyed on purpose: there is one of it, and a
1059
+ # moved line there has to be looked at again.
1060
+ found = channel_tokens(text, pattern)
1061
+ held_stated = stated.get(name) or {}
1062
+ said = set(held_stated.get("tokens") or ())
1063
+ if found - said:
1064
+ problems.append(f"CHANNEL_UNSTATED {row['writer']} {name}: "
1065
+ f"{', '.join(sorted(found - said)[:4])} — it {why}, and the row "
1066
+ f"says nothing about {'that' if len(found - said) == 1 else 'those'}")
1067
+ if said - found:
1068
+ problems.append(f"CHANNEL_STALE {row['writer']} {name}: the row states "
1069
+ f"{', '.join(sorted(said - found)[:4])} and the source no longer "
1070
+ f"shows it")
1071
+ if found and not held_stated.get("reason"):
1072
+ problems.append(f"CHANNEL_UNREASONED {row['writer']} {name}: the row names the "
1073
+ f"tokens and gives no reason why this channel is safe for a run "
1074
+ f"that confines this writer")
1075
+ if not subjects:
1076
+ problems.append("CHANNEL_NO_WRITERS_READ: no writer's source was read, so every channel "
1077
+ "would pass unexamined")
1078
+ return problems
1079
+
1080
+
1081
+ # ─── git: not this release's to run ──────────────────────────────────────────────────────────────
1082
+ #
1083
+ # Release 1's S11 writes the approved changes into files of the declared checkout and executes NO
1084
+ # git: it ends by naming the commit command and the install command for the owner to run, and the
1085
+ # owner commits as usual, so the repository's hooks run in the owner's own environment
1086
+ # (`D-20261113-f22b7d`, narrowing `D-20261112-2cf1c4`).
1087
+ #
1088
+ # The git environment, the configuration policy, the hooks certificate and the hook-refusal contract
1089
+ # that stood here are REMOVED rather than kept behind a label. Round 4 found five blocking defects in
1090
+ # them — the parser was not git's grammar, repository-layout redirections were not walked, hook files
1091
+ # were not inspected, signing and trailer commands executed arbitrary programs, and the repository's
1092
+ # own hook writes under /tmp and provisions under HOME — and a module still carrying a
1093
+ # `git_certificate` would read as a working certification to the next reader. They live in history at
1094
+ # `0ab9fca2` with that review and
1095
+ # `design/session-distill/2026-11-13T0130--0ab9fca--release-1-s11-writes-files-and-the-owner-commits.md`
1096
+ # beside them, which is where release 2 starts. Two facts measured for it are in that record: one
1097
+ # variable closes both of git's global files, and WHICH git binary runs is decided by the active
1098
+ # developer directory (`DEVELOPER_DIR`), outside any configuration policy.
1099
+ #
1100
+ # What the release needs from git is nothing. The before-state is the file hashes the approvals carry,
1101
+ # checked through `runlib/targets`.
1102
+
1103
+
1104
+ def claim_problems(declaration, environ, scope="release_1"):
1105
+ """Where the caller's CLAIM about the environment differs from what the run produces.
1106
+
1107
+ This used to be asked per destination row, which tied it to a row resting on an override. Once
1108
+ `inventory.py`'s HOME became a read (the round-4 review), release 1 had no such row left and the
1109
+ check went silent — while the run still HANDS every invoked writer a HOME and git its isolation.
1110
+ The question belongs to the produced mapping, so it is asked there: for every writer the scope
1111
+ invokes, a name the caller says it will run with and the run produces differently is refused.
1112
+ """
1113
+ problems = []
1114
+ for row in writers():
1115
+ if scope == "release_1" and not row.get("release_1_invoked"):
1116
+ continue
1117
+ produced = environment_for(row, declaration)
1118
+ for name, value in sorted(produced.items()):
1119
+ claimed = (environ or {}).get(name)
1120
+ if claimed is not None and claimed != value:
1121
+ problems.append(
1122
+ f"ENVIRONMENT_CLAIM_DIFFERS {row['writer']} {name}: the caller says it will run "
1123
+ f"with {claimed!r} and the run produces {value!r}, so what this writer is handed "
1124
+ f"is not established and no effect may proceed")
1125
+ return problems
1126
+
1127
+
1128
+ def resolved_rows(declaration, environ, root=None, scope="release_1"):
1129
+ """One row per writer: `{class, writer, path, root, inside}` as N#4 names it.
1130
+
1131
+ `path` is what the writer will actually write under, taken from the environment the run hands it
1132
+ — never from this process's own environment unless the caller passes it.
1133
+
1134
+ `scope` is the RELEASE, as a parameter rather than a constant: `release_1` resolves only the
1135
+ writers release-1 S11 may invoke and names the rest `not_invoked_in_release_1`
1136
+ (`D-20261112-2cf1c4`), and `all` resolves every row. S11 and the manifest take the default; the
1137
+ wider scope is how the resolution machinery stays exercised for the writers a later release
1138
+ will invoke, so narrowing the release does not quietly retire the mechanism that confines them.
1139
+ """
1140
+ if scope not in ("release_1", "all"):
1141
+ raise Refused(f"RESOLUTION_SCOPE_UNKNOWN {scope!r}: the scopes are 'release_1' and 'all'; "
1142
+ f"a typo that resolved everything would widen the release silently")
1143
+ roots = (declaration or {}).get("destinations") or {}
1144
+ home = declared_home(declaration)
1145
+ rows = []
1146
+ absent = set(author_rows_absent(root))
1147
+ for row in writers():
1148
+ if row["writer"] in absent:
1149
+ # Named, not certified: the writer is not in this install, so it writes nowhere. Saying
1150
+ # so in the manifest is the point — a silent omission would read as "no such writer".
1151
+ rows.append({"class": row.get("writes_without_override")
1152
+ or (row.get("destinations") or [{}])[0].get("class"),
1153
+ "writer": row["writer"], "path": None, "root": None, "inside": None,
1154
+ "certification": "not_installed",
1155
+ "not_installed": "author-side writer, not present in this install"})
1156
+ continue
1157
+ if scope == "release_1" and not row.get("release_1_invoked"):
1158
+ # The SCOPE, as a state of the row: release 1's S11 writes the declared checkout and
1159
+ # commits, and runs nothing else (D-20261112-2cf1c4). Certification is withheld by that
1160
+ # name rather than computed, because computing it would mean certifying what a writer
1161
+ # this release never invokes would do — which is exactly the unbounded surface three
1162
+ # review rounds kept finding new defects in.
1163
+ rows.append({"class": row.get("writes_without_override")
1164
+ or (row.get("destinations") or [{}])[0].get("class"),
1165
+ "writer": row["writer"], "path": None, "root": None, "inside": None,
1166
+ "certification": RELEASE_1_UNINVOKED,
1167
+ # One owner for the sentence: a row says something of its own only where
1168
+ # its reason differs, instead of the same sentence written out 22 times.
1169
+ "why": row.get("$comment_release_1") or RELEASE_1_WHY})
1170
+ continue
1171
+ # What this writer is GIVEN, and what it reads that is not in it. The environment is the
1172
+ # mechanism; the disclosure is what says the mechanism is not enough for this writer.
1173
+ given = environment_for(row, declaration)
1174
+ ungiven = reads_not_given(row["writer"], given, root)
1175
+ excused = excused_overrides(row["writer"])
1176
+ # One row per (writer, override), so a single escaping value cannot hide behind a sibling
1177
+ # of the same writer that is in root.
1178
+ for entry in row.get("destinations") or ():
1179
+ override, cls = entry.get("override"), entry.get("class")
1180
+ if entry.get("read_only"):
1181
+ # A READ, not a destination. The row exists because the derivation sees the read
1182
+ # reach a write, and a row that came back certified presented the owner's home as a
1183
+ # place this release may write (the round-4 review). The state is named and carries
1184
+ # no path, in every scope: what the writer does with the value does not change.
1185
+ rows.append({"class": cls, "writer": f"{row['writer']} [{override}]",
1186
+ "path": None, "root": None, "inside": None,
1187
+ "certification": READ_NOT_WRITTEN, "why": entry["read_only"]})
1188
+ continue
1189
+ if scope == "release_1" and not entry_invoked_in_release_1(row, entry):
1190
+ # The scope is per DESTINATION, because S11 is itself a writer here: the apply
1191
+ # stage edits the declared checkout (invoked) and patches a personal layer (not
1192
+ # invoked in release 1). Naming this row rather than certifying it is what keeps a
1193
+ # deferred finding about the personal layers out of reach.
1194
+ rows.append({"class": cls, "writer": f"{row['writer']} [{override}]",
1195
+ "path": None, "root": None, "inside": None,
1196
+ "certification": RELEASE_1_UNINVOKED,
1197
+ "why": entry.get("$comment_release_1") or RELEASE_1_WHY})
1198
+ continue
1199
+ # `held_root`, not `root`: the parameter names the INSTALLATION being inspected, and
1200
+ # this loop used to rebind it to a class root — so anything later in the function that
1201
+ # needed the installation root got a destination instead.
1202
+ # The certificate is resolved from the environment the run PRODUCES for this writer,
1203
+ # never from the caller's separate dict. The two could disagree — `environment_for`
1204
+ # sets HOME from the declaration, and every override's value is its class's declared
1205
+ # root — so a row certified from `environ` certified a value the writer would not be
1206
+ # handed. `environ` is now read as the caller's CLAIM about what it will run with, and
1207
+ # a claim that differs from what the run produces is refused rather than preferred
1208
+ # (the round-3 review).
1209
+ held_root, value = roots.get(cls), given.get(override)
1210
+ claimed = (environ or {}).get(override)
1211
+ if not value:
1212
+ rows.append({"class": cls, "writer": f"{row['writer']} [{override}]", "path": None,
1213
+ "root": held_root, "inside": False, "unset": [override],
1214
+ "certification": "unset"})
1215
+ continue
1216
+ if claimed is not None and claimed != value:
1217
+ rows.append({"class": cls, "writer": f"{row['writer']} [{override}]",
1218
+ "path": value, "root": held_root, "inside": None,
1219
+ "certification": "withheld",
1220
+ "why": f"the caller says it will run with {override}={claimed!r} and "
1221
+ f"the run produces {value!r} for it, so which path this "
1222
+ f"certificate speaks for cannot be established"})
1223
+ continue
1224
+ rows.append({"class": cls, "writer": f"{row['writer']} [{override}]", "path": value,
1225
+ "root": held_root,
1226
+ "inside": bool(held_root) and _inside(value, held_root),
1227
+ "reads_not_given": ungiven, "reads_excused": excused,
1228
+ "certification": "withheld" if ungiven else "given",
1229
+ "why": (f"its source reads {', '.join(ungiven)}, which the run does not "
1230
+ f"hand it, so it would resolve those through a fallback nobody "
1231
+ f"declared" if ungiven else
1232
+ "the run hands it this value and nothing else can redirect it")})
1233
+ if row.get("writes_without_override"):
1234
+ cls = row["writes_without_override"]
1235
+ held_root = roots.get(cls)
1236
+ fixed = [entry for entry in row.get("fixed_roots") or ()
1237
+ if not entry.get("not_a_destination")]
1238
+ if row.get("writer_unwritten"):
1239
+ # A forward declaration: the file does not exist yet, so there is nothing to
1240
+ # confine and nothing to withhold. `INVENTORY_FORWARD_LANDED` fails the day it
1241
+ # appears, which is when the derived closure takes over from this row.
1242
+ rows.append({"class": cls, "writer": row["writer"], "path": None,
1243
+ "root": held_root, "inside": None, "certification": "forward",
1244
+ "why": "declared as a writer that does not exist yet"})
1245
+ continue
1246
+ if row.get("root_from") == "argument":
1247
+ # The PREFERRED channel, and a certification in its own right: the run hands this
1248
+ # writer its root as an argument, so there is no variable to inherit and nothing to
1249
+ # derive from HOME. An argument cannot be redirected by an environment at all.
1250
+ rows.append({"class": cls, "writer": row["writer"], "path": held_root,
1251
+ "root": held_root, "inside": bool(held_root),
1252
+ "certification": "argument",
1253
+ "why": "the run passes this writer its root; it reads no override for "
1254
+ "it and derives nothing from HOME"})
1255
+ continue
1256
+ if not fixed:
1257
+ # A row that claims a fixed root and shows none of the lines it came from cannot be
1258
+ # certified: there is nothing to compute from. `writer_unwritten` rows are the
1259
+ # exception the table declares for work in flight.
1260
+ rows.append({"class": cls, "writer": row["writer"], "path": None,
1261
+ "root": held_root, "inside": None,
1262
+ "certification": None if row.get("writer_unwritten") else "withheld",
1263
+ "why": ("declared as a writer that does not exist yet"
1264
+ if row.get("writer_unwritten") else
1265
+ "the row claims a HOME-fixed root and shows no source line "
1266
+ "for it, so there is nothing to compute from")})
1267
+ continue
1268
+ for entry in fixed:
1269
+ held_line = source_line(row["writer"], entry.get("derived_at_line"), root)
1270
+ path, why = fixed_destination(entry, home, source_text=held_line)
1271
+ bounded = path is not None and "upper bound" in why
1272
+ # A bound is a certification only where the class root CONTAINS the home: then
1273
+ # every path the writer can compute under the home is inside the root, whatever the
1274
+ # suffix is. Where the root is narrower, the suffix is exactly what would decide,
1275
+ # and it is unread — so certification is withheld rather than guessed either way.
1276
+ if bounded and not (bool(held_root) and _inside(str(pathlib.Path(home)), held_root)):
1277
+ rows.append({"class": cls,
1278
+ "writer": f"{row['writer']} [fixed:{entry.get('derived_at_line')}]",
1279
+ "path": None, "root": held_root, "inside": None,
1280
+ "certification": "withheld",
1281
+ "why": f"{why}, and the declared {cls} root is narrower than the "
1282
+ f"home, so whether this write lands inside it is exactly "
1283
+ f"what the unread suffix would decide"})
1284
+ continue
1285
+ rows.append({"class": cls,
1286
+ "writer": f"{row['writer']} [fixed:{entry.get('derived_at_line')}]",
1287
+ "path": path, "root": held_root,
1288
+ "inside": None if path is None else (bool(held_root)
1289
+ and _inside(path, held_root)),
1290
+ "certification": ("withheld" if path is None
1291
+ else "bounded" if bounded else "computed"),
1292
+ "why": why})
1293
+ return rows
1294
+
1295
+
1296
+ def resolution_problems(rows):
1297
+ """The refusals the resolved set carries, by name, in the order a reader needs them.
1298
+
1299
+ `OVERRIDE_MISSING` comes first: an unset override means the path in the row is not what the
1300
+ writer would use, so judging that path for escape would be judging a value nobody will write to.
1301
+ """
1302
+ problems = []
1303
+ for row in rows:
1304
+ for name in row.get("unset") or ():
1305
+ problems.append(f"OVERRIDE_MISSING {row['writer']} {name}: unset, so this writer would "
1306
+ f"resolve through a fallback the run did not declare")
1307
+ for row in rows:
1308
+ if row.get("unset"):
1309
+ continue
1310
+ if row.get("not_installed"):
1311
+ # Nothing to confine: the writer is not in this install, so it has no path to judge.
1312
+ # Judging it would produce DESTINATION_ROOT_ABSENT for a writer that cannot write,
1313
+ # which is how the packaged manifest refused over a file npm does not ship.
1314
+ continue
1315
+ if row.get("certification") == READ_NOT_WRITTEN:
1316
+ # A read has nothing to confine and needs no root: requiring one would make the owner
1317
+ # declare a destination for a value the writer only reads (the round-4 review).
1318
+ continue
1319
+ if row.get("certification") == RELEASE_1_UNINVOKED:
1320
+ # Not an escape and not a certification: a writer this release does not invoke has
1321
+ # nothing to confine. It is named in the manifest and S11 refuses any operation that
1322
+ # would reach it, which is the apply stage's question rather than this one's.
1323
+ continue
1324
+ if row.get("certification") == "forward":
1325
+ # A forward declaration: no file, no path, nothing to confine. `INVENTORY_FORWARD_LANDED`
1326
+ # is what fails the day the writer appears.
1327
+ continue
1328
+ if row.get("certification") == "withheld":
1329
+ # A NAMED STATE, not a warning: the manifest says certification is withheld for this
1330
+ # destination, and S11 refuses on it. Before, a fixed root was certified by
1331
+ # `path = root, inside = bool(root)`, which asserts nothing about where the writer
1332
+ # writes — `install.sh` was certified at the install_roots root while its own source
1333
+ # puts STATE_DIR under HOME (the round-2 review).
1334
+ problems.append(f"DESTINATION_UNCERTIFIED {row['writer']}: {row.get('why')}, so where "
1335
+ f"this writer writes cannot be established and no effect may proceed")
1336
+ continue
1337
+ if not row.get("root"):
1338
+ problems.append(f"DESTINATION_ROOT_ABSENT {row['writer']}: the run declares no root for "
1339
+ f"class {row['class']}")
1340
+ continue
1341
+ if row.get("path") is None:
1342
+ problems.append(f"DESTINATION_UNRESOLVED {row['writer']}: no path was resolved for it, "
1343
+ f"so there is nothing to judge for containment")
1344
+ continue
1345
+ if not row["inside"]:
1346
+ problems.append(f"DESTINATION_OUTSIDE_ROOT {row['writer']}: {row['path']} is not inside "
1347
+ f"{row['root']}")
1348
+ return problems
1349
+
1350
+
1351
+ def problems(declaration, environ, root=None):
1352
+ """Everything wrong, table and resolution together. Empty means apply may take its first effect."""
1353
+ held = (environment_problems(declaration)
1354
+ + claim_problems(declaration, environ)
1355
+ + layout_problems(root) + channel_problems(root)
1356
+ + table_problems(root) + fidelity_problems(root) + inventory_problems(root))
1357
+ if held:
1358
+ return held
1359
+ return resolution_problems(resolved_rows(declaration, environ, root))
1360
+
1361
+
1362
+ def document(declaration, environ, root=None):
1363
+ """The manifest `apply` writes before any effect, or Refused naming what stops it."""
1364
+ rows = resolved_rows(declaration, environ, root)
1365
+ # The derived inventory is part of the manifest's own correctness, not a separate audit: a
1366
+ # destination the tree writes and the table does not carry is exactly the hole this manifest
1367
+ # exists to close, so `apply` refuses before any effect rather than recording a partial answer.
1368
+ held = (environment_problems(declaration)
1369
+ + claim_problems(declaration, environ)
1370
+ + layout_problems(root) + channel_problems(root)
1371
+ + table_problems(root) + fidelity_problems(root) + inventory_problems(root)
1372
+ + resolution_problems(rows))
1373
+ if held:
1374
+ raise Refused("; ".join(held))
1375
+ return {"stage": "S11", "resolved": rows,
1376
+ # No git key: release 1's S11 executes no git (`D-20261113-f22b7d`), so a certificate
1377
+ # here would speak for a command this release never runs.
1378
+ "release_scope": {"scope": "release_1",
1379
+ "decision": "D-20261112-2cf1c4",
1380
+ "uninvoked": sorted({r["writer"] for r in rows
1381
+ if r.get("certification")
1382
+ == RELEASE_1_UNINVOKED})},
1383
+ "overrides_required": list(required_overrides()),
1384
+ "classes": list(CLASSES),
1385
+ "writers_scanned": sorted({entry["writer"] for entry in closure(root)}),
1386
+ "layout": install_layout(root),
1387
+ "not_installed": author_rows_absent(root),
1388
+ "$comment": "design §10.5 / N#4: every writer's destination, resolved from the "
1389
+ "environment the run hands it and asserted inside its declared root before "
1390
+ "the first effect."}
1391
+
1392
+
1393
+ def write(run_dir, declaration, environ):
1394
+ """Write the manifest into the run. Nothing is written when anything refuses.
1395
+
1396
+ The path is absolute beneath the run and the file is registered with the stage, for the reason
1397
+ `stage_propose.run` states: `records.write_json` confines its path, so a bare name resolves
1398
+ against the working directory and is refused, and an unregistered output leaves the next stage's
1399
+ staleness check nothing to read.
1400
+ """
1401
+ run_dir = pathlib.Path(run_dir)
1402
+ doc = document(declaration, environ) # refuses before the stage record is opened
1403
+ # No declared input: the run declaration is the run's own root, not a stage output, so naming it
1404
+ # as one is refused (`INPUT_INVALID S0: no record for the stage that produces run.json`). Every
1405
+ # stage that reads only the declaration opens its record the same way.
1406
+ # S11's record has parts: this manifest is its optional one (`records.STAGE_OPTIONAL_PARTS`), beside the
1407
+ # apply's plan and effects.
1408
+ with records.run_stage(run_dir, "S11", part="destinations") as stage:
1409
+ records.write_json(run_dir, run_dir / OUTPUT, doc)
1410
+ stage.output(OUTPUT)
1411
+ return stage, doc
1412
+
1413
+
1414
+ # ---- self-test ---------------------------------------------------------------------------------
1415
+
1416
+
1417
+ # ─── The effect audit ───────────────────────────────────────────────────────────────────────────
1418
+ # One owner for one vocabulary. `drift.py` holds itself to this same function rather than carrying a
1419
+ # second copy of the rules, because two copies drift and the first round's copies did: each module
1420
+ # watched a different tuple of module names.
1421
+ #
1422
+ # What the round-2 review found the old rules passing, every item reachable: `__import__('os')
1423
+ # .system(...)` and `importlib.import_module('os').system(...)`, because the call's first printed
1424
+ # component is neither `os` nor `subprocess`; `pathlib.Path(x).write_text(...)` and `open(x, 'w')`,
1425
+ # because a filesystem write names no watched module at all; anything inside `main`, because `main`
1426
+ # was excluded by name although `python3 -m runlib.destinations` runs it; and the effects of a
1427
+ # `self_test` that a runtime function calls, because `self_test` was excluded by name too.
1428
+ #
1429
+ # So the exclusions are now by REACHABILITY, not by name. `self_test` is skipped only while every
1430
+ # path to it passes a branch guarded by a `--self-test` test; called from anywhere else, its effects
1431
+ # are the module's effects.
1432
+ EFFECT_MODULES = ("subprocess", "os", "shutil", "tempfile", "socket", "urllib", "http", "ftplib",
1433
+ "smtplib", "multiprocessing", "ctypes", "signal", "pty", "fcntl", "webbrowser")
1434
+ # Reading a path out of the environment and joining it is not an effect; this is the whole list.
1435
+ EFFECT_ALLOWED = ("os.path.normpath", "os.path.join", "os.path.sep", "os.path.basename",
1436
+ "os.path.dirname", "os.path.isabs", "os.path.splitdrive", "os.path.split",
1437
+ "os.sep", "os.fspath", "os.environ", "os.environ.get", "os.name")
1438
+ # Filesystem writes by METHOD NAME, on any object: `pathlib.Path(p).write_text(...)` names no
1439
+ # watched module, and neither does a handle the function was handed by its caller.
1440
+ EFFECT_METHODS = ("write_text", "write_bytes", "writelines", "mkdir", "makedirs", "touch", "unlink",
1441
+ "rmdir", "rmtree", "rename", "symlink_to", "hardlink_to", "chmod", "chown",
1442
+ "truncate", "copy", "copy2", "copytree", "move")
1443
+ # Anything that can produce a call whose name this audit cannot read.
1444
+ EFFECT_DYNAMIC = ("__import__", "exec", "eval", "compile", "importlib.import_module",
1445
+ "importlib.__import__", "runpy.run_path", "runpy.run_module")
1446
+ EFFECT_WRITE_MODES = set("wax+")
1447
+
1448
+
1449
+ def _self_test_branch(node):
1450
+ """`"body"`, `"orelse"` or None: which half of an `if` the `--self-test` flag guards.
1451
+
1452
+ The skip followed `orelse` for any test mentioning the flag, which is exactly inverted for
1453
+ `if "--self-test" not in sys.argv:` — there the BODY is the runtime path, and the audit skipped
1454
+ it (the round-3 review). Decided from the test's own shape: a `not in` comparison or a `not`
1455
+ puts the runtime code in the body, anything else in the orelse.
1456
+ """
1457
+ rendered = ast.unparse(node.test)
1458
+ if "--self-test" not in rendered:
1459
+ return None
1460
+ # Only the two predicates this audit can PROVE. `"--self-test" not in sys.argv and True` was
1461
+ # read as the negated form and its body — real runtime code — was skipped (the round-4 review).
1462
+ # Anything else mentioning the flag is unsupported, and an unsupported guard means both halves
1463
+ # are scanned rather than one being trusted: a wrong skip hides an effect, a wrong scan only
1464
+ # reports one.
1465
+ # And the LEFT side must be the flag itself, exactly. `'--self-test-other' in argv` mentions
1466
+ # the flag as a substring and guards nothing this audit knows about; its body was skipped (the
1467
+ # round-5 review).
1468
+ if isinstance(node.test, ast.Compare) and len(node.test.ops) == 1 \
1469
+ and isinstance(node.test.left, ast.Constant) and node.test.left.value == "--self-test":
1470
+ # The right side must be the ARGUMENT VECTOR, not any container that happens to hold the
1471
+ # flag: `'--self-test' in held.flags()` is a call this audit cannot evaluate, and reading it
1472
+ # as dispatch skipped a half on the strength of a method name.
1473
+ held = ast.unparse(node.test.comparators[0])
1474
+ if held in ("sys.argv", "argv", "sys.argv[1:]", "argv[1:]"):
1475
+ if isinstance(node.test.ops[0], ast.In):
1476
+ return "orelse"
1477
+ if isinstance(node.test.ops[0], ast.NotIn):
1478
+ return "body"
1479
+ return None
1480
+
1481
+
1482
+ def _effect_reachable(tree):
1483
+ """The top-level function names a runtime entry point can reach.
1484
+
1485
+ Roots are the module's top level and every top-level function except `self_test`; an edge
1486
+ through a branch whose test names `--self-test` is not followed, which is what keeps a suite's
1487
+ own fixture building out of the answer without excluding the suite by name.
1488
+ """
1489
+ functions = {node.name: node for node in tree.body
1490
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
1491
+ # A class's METHODS are code too. The scope was top-level functions only, so
1492
+ # `main()` calling `Writer().go()` reached nothing and an effect inside `go` was invisible (the
1493
+ # round-3 review). Methods are registered as `Class.method`, and reaching the CLASS reaches
1494
+ # them: whether a particular method is called needs an analysis this does not have, and for an
1495
+ # effect audit the over-approximation is the safe direction.
1496
+ methods = {}
1497
+ for node in tree.body:
1498
+ if isinstance(node, ast.ClassDef):
1499
+ for held in node.body:
1500
+ if isinstance(held, (ast.FunctionDef, ast.AsyncFunctionDef)):
1501
+ methods[f"{node.name}.{held.name}"] = held
1502
+ functions[f"{node.name}.{held.name}"] = held
1503
+
1504
+ def called_in(node):
1505
+ held = set()
1506
+
1507
+ def walk(parent):
1508
+ # The node itself first: a top-level `f()` is the root of its own statement, and a walk
1509
+ # that only looked at children never saw it.
1510
+ if isinstance(parent, ast.Call):
1511
+ rendered = ast.unparse(parent.func)
1512
+ held.add(rendered)
1513
+ held.add(rendered.split(".")[0].split("(")[0])
1514
+ for child in ast.iter_child_nodes(parent):
1515
+ held_half = isinstance(child, ast.If) and _self_test_branch(child)
1516
+ if held_half:
1517
+ for part in (child.body if held_half == "body" else child.orelse):
1518
+ walk(part) # the unguarded half still counts
1519
+ continue
1520
+ walk(child)
1521
+
1522
+ walk(node)
1523
+ return held
1524
+
1525
+ # A function the SUITE alone calls is the suite. Excluding `self_test` by name and making every
1526
+ # other function a root read `_self_test_body` — the half of the suite a dying-control wrapper
1527
+ # delegates to — as a runtime entry point, and the suite's own fixture building as module
1528
+ # effects. Decided by reachability like everything else here: a function is test-only when it
1529
+ # has callers and every one of them is test-only, and `self_test` qualifies when nothing
1530
+ # outside that set calls it. A `self_test` a RUNTIME function calls is therefore not test-only,
1531
+ # which is the case a control below plants.
1532
+ callers = {name: set() for name in functions}
1533
+ for held_name, held_node in functions.items():
1534
+ for reached in called_in(held_node) & set(functions):
1535
+ callers[reached].add(held_name)
1536
+ test_only = set()
1537
+ moved = True
1538
+ while moved:
1539
+ moved = False
1540
+ for name in functions:
1541
+ if name in test_only:
1542
+ continue
1543
+ held_callers = callers[name] - test_only
1544
+ if name == "self_test" and not held_callers:
1545
+ test_only.add(name)
1546
+ moved = True
1547
+ elif name != "self_test" and callers[name] and not held_callers:
1548
+ test_only.add(name)
1549
+ moved = True
1550
+ frontier = {name for name in functions if name not in test_only and name not in methods}
1551
+ for node in tree.body:
1552
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
1553
+ held_reached = called_in(node)
1554
+ frontier |= held_reached & set(functions)
1555
+ frontier |= {name for name in methods if name.split(".")[0] in held_reached}
1556
+ held = set()
1557
+ while frontier:
1558
+ name = frontier.pop()
1559
+ if name in held or name not in functions:
1560
+ continue
1561
+ held.add(name)
1562
+ reached = called_in(functions[name])
1563
+ frontier |= reached & set(functions)
1564
+ for held_name in methods:
1565
+ if held_name.split(".")[0] in reached:
1566
+ frontier.add(held_name)
1567
+ return held
1568
+
1569
+
1570
+ def effect_scope(source):
1571
+ """What `effect_audit` scanned: the module's top level and the functions it reached.
1572
+
1573
+ An audit that scanned nothing reports nothing, so the suites assert this set rather than
1574
+ reading a clean answer as proof.
1575
+ """
1576
+ return sorted(_effect_reachable(ast.parse(source)) | {"<module>"})
1577
+
1578
+
1579
+ def effect_audit(source):
1580
+ """Every effect a module's reachable runtime code performs, by canonical name.
1581
+
1582
+ A function over source text rather than a block over one file, so each widened rule can be
1583
+ shown to fire on a planted call. The answer carries the function the call sits in, because
1584
+ `in main` is the difference between a reported effect and an excluded one.
1585
+ """
1586
+ tree = ast.parse(source)
1587
+ bindings = {} # local name -> the module it is bound to
1588
+ for node in ast.walk(tree):
1589
+ if isinstance(node, ast.Import):
1590
+ for alias in node.names:
1591
+ bindings[alias.asname or alias.name.split(".")[0]] = alias.name.split(".")[0]
1592
+ elif isinstance(node, ast.ImportFrom) and node.module:
1593
+ for alias in node.names:
1594
+ bindings[alias.asname or alias.name] = node.module.split(".")[0]
1595
+
1596
+ reachable = _effect_reachable(tree)
1597
+ scope = [("<module>", node) for node in tree.body
1598
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))]
1599
+ scope += [(node.name, node) for node in tree.body
1600
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
1601
+ and node.name in reachable]
1602
+ # And the METHODS the reachability found. Walking only top-level functions left them out of the
1603
+ # scan even once they were reached, which is the half of the finding that mattered: the effect
1604
+ # sits in the method body.
1605
+ # A class BODY runs at definition time, so a statement there is runtime code with no function
1606
+ # to be reached through: `open('/outside', 'w')` beside the methods was invisible (the round-4
1607
+ # review). Included under the class's own name, before its methods.
1608
+ scope += [(held.name, node) for held in tree.body if isinstance(held, ast.ClassDef)
1609
+ for node in held.body
1610
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))]
1611
+ # Everything ELSE that runs when a definition is executed, whoever calls the thing defined: a
1612
+ # class's bases and keywords, any decorator, a function's default arguments, and the whole of a
1613
+ # class nested in a class — body, methods' definitions and all. A default argument that calls
1614
+ # `open` runs at import, in a method nobody ever calls (the round-5 review). A nested class's
1615
+ # method BODIES are scanned too: reachability is computed over top-level names, so the safe
1616
+ # direction for a name it cannot see is to scan it.
1617
+ def definition_time(node, where, nested=False):
1618
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
1619
+ # Annotations are evaluated at definition time too (unless postponed, which this audit
1620
+ # does not try to prove): `def never(self, x: open('/outside', 'w'))` ran the call (the
1621
+ # round-6 review).
1622
+ held_args = [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs,
1623
+ *([node.args.vararg] if node.args.vararg else []),
1624
+ *([node.args.kwarg] if node.args.kwarg else [])]
1625
+ for held in [*node.decorator_list, *node.args.defaults,
1626
+ *[d for d in node.args.kw_defaults if d is not None],
1627
+ *[a.annotation for a in held_args if a.annotation is not None],
1628
+ *([node.returns] if node.returns is not None else [])]:
1629
+ yield f"{where} definition", held
1630
+ if nested:
1631
+ for held in node.body:
1632
+ yield where, held
1633
+ elif isinstance(node, ast.ClassDef):
1634
+ for held in [*node.decorator_list, *node.bases, *[k.value for k in node.keywords]]:
1635
+ yield f"{where} definition", held
1636
+ for held in node.body:
1637
+ if isinstance(held, (ast.FunctionDef, ast.AsyncFunctionDef)):
1638
+ yield from definition_time(held, f"{where}.{held.name}", nested)
1639
+ elif isinstance(held, ast.ClassDef):
1640
+ yield from definition_time(held, f"{where}.{held.name}", True)
1641
+ elif nested:
1642
+ yield where, held
1643
+
1644
+ for held in tree.body:
1645
+ if isinstance(held, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
1646
+ scope += list(definition_time(held, held.name))
1647
+ scope += [(f"{held.name}.{node.name}", node) for held in tree.body
1648
+ if isinstance(held, ast.ClassDef) for node in held.body
1649
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
1650
+ and f"{held.name}.{node.name}" in reachable]
1651
+
1652
+ held = set()
1653
+
1654
+ def say(where, text):
1655
+ held.add(text if where == "<module>" else f"{text} (in {where})")
1656
+
1657
+ def mode_of(node):
1658
+ """The mode an `open` call was given: the string, None for a default read, or '?'."""
1659
+ asked = None
1660
+ if len(node.args) > 1:
1661
+ asked = node.args[1]
1662
+ for keyword in node.keywords:
1663
+ if keyword.arg == "mode":
1664
+ asked = keyword.value
1665
+ if asked is None:
1666
+ return None
1667
+ if isinstance(asked, ast.Constant) and isinstance(asked.value, str):
1668
+ return asked.value
1669
+ return "?"
1670
+
1671
+ for where, root_node in scope:
1672
+ def walk(parent):
1673
+ # Look at `parent`, then recurse. A walk that looked only at CHILDREN never saw a
1674
+ # top-level `import os as _o` or a top-level `os.system(...)`, because each is the root
1675
+ # of its own statement — which is how the alias control came back empty.
1676
+ look(parent)
1677
+ for child in ast.iter_child_nodes(parent):
1678
+ held_half = isinstance(child, ast.If) and _self_test_branch(child)
1679
+ if held_half:
1680
+ for part in (child.body if held_half == "body" else child.orelse):
1681
+ walk(part)
1682
+ continue
1683
+ walk(child)
1684
+
1685
+ def look(child):
1686
+ if isinstance(child, ast.Import):
1687
+ for alias in child.names:
1688
+ if alias.asname and alias.name.split(".")[0] in EFFECT_MODULES:
1689
+ say(where, f"import {alias.name} as {alias.asname} (an alias on a "
1690
+ f"watched module hides its calls from this very check)")
1691
+ if isinstance(child, ast.Call):
1692
+ rendered = ast.unparse(child.func)
1693
+ root_name = rendered.split(".")[0].split("(")[0]
1694
+ # A watched module, under its own name or an alias.
1695
+ if bindings.get(root_name) in EFFECT_MODULES or root_name in EFFECT_MODULES:
1696
+ canonical = rendered.replace(root_name,
1697
+ bindings.get(root_name, root_name), 1)
1698
+ if canonical not in EFFECT_ALLOWED:
1699
+ say(where, canonical)
1700
+ # A dynamic import or dispatch anywhere in the callee expression.
1701
+ for mark in EFFECT_DYNAMIC:
1702
+ if re.search(rf"(?<![\w.]){re.escape(mark)}(?![\w])", rendered):
1703
+ say(where, f"{rendered} — {mark} reaches a module this audit "
1704
+ f"cannot name")
1705
+ # A filesystem write by method name, on whatever object.
1706
+ if rendered.split(".")[-1] in EFFECT_METHODS:
1707
+ say(where, rendered)
1708
+ # `open` for writing, builtin or method, including an undecidable mode.
1709
+ if rendered.split(".")[-1] == "open":
1710
+ mode = mode_of(child)
1711
+ if mode == "?":
1712
+ say(where, f"{rendered}(mode=<not a literal>) — a mode this audit "
1713
+ f"cannot read")
1714
+ elif mode is not None and set(mode) & EFFECT_WRITE_MODES:
1715
+ say(where, f"{rendered}(mode={mode!r})")
1716
+ # `getattr(os, "system")(...)`: the callee is itself a getattr over a module.
1717
+ if isinstance(child.func, ast.Call) \
1718
+ and getattr(child.func.func, "id", "") == "getattr":
1719
+ inner = child.func
1720
+ if inner.args and ast.unparse(inner.args[0]).split(".")[0] in EFFECT_MODULES:
1721
+ say(where, f"getattr({ast.unparse(inner.args[0])}, "
1722
+ f"{ast.unparse(inner.args[1]) if len(inner.args) > 1 else '?'})")
1723
+
1724
+ walk(root_node)
1725
+ return sorted(held)
1726
+
1727
+
1728
+ def self_test():
1729
+ """Positive control first, then one planted violation per rule, each refused BY NAME.
1730
+
1731
+ The body is wrapped so a control that DIES still speaks. The A revert trial planted
1732
+ `for entry in fixed:` -> `for entry in ():`: the fixed-root rows vanished, the control reading
1733
+ the first of them raised StopIteration, and the suite ended with no [FAIL] line at all — a row
1734
+ that reads as CONTROL-SILENT, which is indistinguishable from a rule nobody enforces. A
1735
+ traceback is not a control firing, so the wrapper prints the control that was in flight.
1736
+ """
1737
+ failures, ran = [], []
1738
+ try:
1739
+ return _self_test_body(failures, ran)
1740
+ except BaseException as exc: # noqa: BLE001 - the suite must speak before it dies
1741
+ held = ran[-1] if ran else "<no control ran>"
1742
+ print(f"destinations --self-test [FAIL] the suite died after {held!r}: "
1743
+ f"{type(exc).__name__}: {exc}", file=sys.stderr)
1744
+ for name, detail in failures:
1745
+ print(f"destinations --self-test [FAIL] {name}: {detail}", file=sys.stderr)
1746
+ print(f"destinations --self-test: INCOMPLETE ({len(ran)} controls ran, {len(failures)} "
1747
+ f"failed before the suite died)", file=sys.stderr)
1748
+ raise
1749
+
1750
+
1751
+ def _self_test_body(failures, ran):
1752
+ # Imported here, before anything uses them: a later `import shutil` inside this function makes
1753
+ # the name a local for the WHOLE function, so an earlier use raises UnboundLocalError — the same
1754
+ # shadowing trap as a local named like a module function. They stay out of the module's own
1755
+ # imports because this half of the file is the suite, and the module itself touches no
1756
+ # filesystem of its own.
1757
+ import shutil
1758
+ import tempfile
1759
+
1760
+ def control(name, got, want):
1761
+ ran.append(name)
1762
+ if want not in str(got):
1763
+ failures.append((name, f"expected {want!r} in {str(got)[:400]!r}"))
1764
+
1765
+ def equals(name, got, want):
1766
+ """A control whose expectation is the WHOLE answer, not a fragment of it.
1767
+
1768
+ `control` asks `want in str(got)`, which is right for a refusal's name inside a longer
1769
+ message and wrong for a value: `'true'` is inside `'["false", "true"]'` and `'4=1+3'` is
1770
+ inside `'14=1+3'` (the round-3 review found that class). Every json-dumped answer below is
1771
+ asked for equality.
1772
+ """
1773
+ ran.append(name)
1774
+ if str(got) != str(want):
1775
+ failures.append((name, f"expected exactly {want!r}, got {str(got)[:400]!r}"))
1776
+
1777
+ def clean(name, held):
1778
+ ran.append(name)
1779
+ if held:
1780
+ failures.append((name, f"expected nothing, got {held}"))
1781
+
1782
+ def guarded(call):
1783
+ """The call's answer, or the exception as text.
1784
+
1785
+ Without this a revert that removes a guard raises out of the control and the trial reads a
1786
+ traceback where it needed a named failure: a control that dies is not a control.
1787
+ """
1788
+ try:
1789
+ return call()
1790
+ except Exception as exc: # noqa: BLE001 - the exception IS the answer here
1791
+ return f"RAISED {type(exc).__name__}: {exc}"
1792
+
1793
+ def refusal(call):
1794
+ try:
1795
+ call()
1796
+ except Refused as exc:
1797
+ return str(exc)
1798
+ return ""
1799
+
1800
+ # The declaration's own fixture, so the roots this suite judges are the ones a real run declares
1801
+ # rather than a shape invented here.
1802
+ FIXTURE = declare.fixture()
1803
+ root = str(pathlib.PurePosixPath(FIXTURE["destinations"][CLASSES[0]]).parent.parent)
1804
+
1805
+ # A checkout that is a real repository, because the manifest judges the declared checkout's own
1806
+ # git configuration before any effect. Built as FILES — a `.git/` holding a `config` — and never
1807
+ # by running `git init`, which under a commit hook's exported GIT_DIR rewrites the author's real
1808
+ # `.git/config` (AGENTS.md's first trap).
1809
+ fixture_checkout = pathlib.Path(tempfile.mkdtemp(prefix="dest-checkout-", dir="/tmp"))
1810
+ (fixture_checkout / ".git").mkdir(parents=True, exist_ok=True)
1811
+ (fixture_checkout / ".githooks").mkdir(parents=True, exist_ok=True)
1812
+ # The fixture carries a hooksPath, because this repository does and S11's commit is meant to run
1813
+ # it. A fixture without one would let the manifest control below pass on the "no hooks path"
1814
+ # branch and never assert the resolved directory at all.
1815
+ (fixture_checkout / ".git" / "config").write_text(
1816
+ "[core]\n\tbare = false\n\trepositoryformatversion = 0\n\thooksPath = .githooks\n",
1817
+ encoding="utf-8")
1818
+
1819
+ def fx_declaration(**over):
1820
+ held = dict(FIXTURE["destinations"])
1821
+ held["checkout"] = str(fixture_checkout)
1822
+ held.update(over)
1823
+ return {**FIXTURE, "destinations": held}
1824
+
1825
+ def fx_env(**over):
1826
+ """The environment the RUN produces, built from the declaration like a run's own.
1827
+
1828
+ It used to be built from a hardcoded `/srv/destinations/<class>/<name>`, which meant the
1829
+ suite judged values no declaration had produced: a root the declaration names and a value
1830
+ the fixture invents cannot disagree, because they were never the same answer. Every value
1831
+ is now the declared root of that name's class, with HOME the declared home, which is what
1832
+ `environment_for` hands each writer.
1833
+ """
1834
+ roots = fx_declaration()["destinations"]
1835
+ held = {override: roots.get(cls) for override, cls in class_of_override()[0].items()}
1836
+ held["HOME"] = declared_home(FIXTURE)
1837
+ held.update(over)
1838
+ return held
1839
+
1840
+ def with_source(writer, text, call):
1841
+ """Run `call` with one writer's source replaced in a throwaway copy of the tree."""
1842
+ held_root = pathlib.Path(tempfile.mkdtemp(prefix="dest-channel-", dir="/tmp"))
1843
+ try:
1844
+ for row in writers():
1845
+ source = REPO / row["writer"]
1846
+ if not source.is_file():
1847
+ continue
1848
+ target = held_root / row["writer"]
1849
+ target.parent.mkdir(parents=True, exist_ok=True)
1850
+ target.write_text(text if row["writer"] == writer
1851
+ else source.read_text(encoding="utf-8", errors="replace"),
1852
+ encoding="utf-8")
1853
+ (held_root / "gates").mkdir(exist_ok=True)
1854
+ # `author_rows_absent` reads `files[]` from the tree it is given, so a tree that is to
1855
+ # answer for a real installation carries that file too.
1856
+ (held_root / "package.json").write_bytes((REPO / "package.json").read_bytes())
1857
+ return call(str(held_root))
1858
+ finally:
1859
+ shutil.rmtree(held_root, ignore_errors=True)
1860
+
1861
+ # ---- the table itself ------------------------------------------------------------------------
1862
+ clean("the writer inventory is well formed and every class it names is a declared one",
1863
+ table_problems())
1864
+ clean("and every stated fallback is still the literal its writer's source carries",
1865
+ fidelity_problems())
1866
+ def declared_classes():
1867
+ held = set()
1868
+ for row in writers():
1869
+ held.update(entry["class"] for entry in row.get("destinations") or ())
1870
+ if row.get("writes_without_override"):
1871
+ held.add(row["writes_without_override"])
1872
+ return held
1873
+
1874
+ clean("every declared destination class is written by some writer, so no class is a stale "
1875
+ "declaration", [name for name in CLASSES if name not in declared_classes()])
1876
+ clean("and no override is placed in two classes, since one variable has one value",
1877
+ sorted(class_of_override()[1]))
1878
+ control("the overrides are read from the table rather than named here",
1879
+ next(line for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
1880
+ if line.strip().startswith("return tuple(sorted({override")), "pairs()")
1881
+ control("the classes come from the declaration's schema rather than a list here",
1882
+ next(line for line in pathlib.Path(__file__).read_text(encoding="utf-8").splitlines()
1883
+ if line.startswith("CLASSES = ")), "declare.DESTINATIONS")
1884
+ clean("the required overrides are the union of the table's own pairs, with nothing invented",
1885
+ sorted(set(required_overrides()) - {override for _w, override, _c in pairs()}))
1886
+ control("and update-state.py's nudge override is among them, since its fallback reads the "
1887
+ "password database", ", ".join(required_overrides()),
1888
+ "AGENT_BIOS_SESSION_DISTILL_STATE")
1889
+
1890
+ def _row(data, writer):
1891
+ """The row for this writer, by NAME.
1892
+
1893
+ These controls used to index `writers[0]`, which is the trap AGENTS.md names: the row at
1894
+ index 0 moved when the inventory became derived, and the control then died with a KeyError
1895
+ over a row that simply has no fallbacks instead of failing by name.
1896
+ """
1897
+ for row in data["writers"]:
1898
+ if row["writer"] == writer:
1899
+ return row
1900
+ raise AssertionError(f"self-test needs a {writer} row and the table has none")
1901
+
1902
+ def with_table(mutate, call):
1903
+ """Run `call` with the table mutated, restoring it however the call ends."""
1904
+ held = json.loads(json.dumps(table()))
1905
+ try:
1906
+ mutate(_TABLE)
1907
+ return call()
1908
+ finally:
1909
+ _TABLE.clear()
1910
+ _TABLE.update(held)
1911
+
1912
+ control("a writer naming a class the declaration does not hold is refused by name",
1913
+ with_table(lambda t: _row(t, "install.sh")["destinations"][0].__setitem__("class", "elsewhere"),
1914
+ lambda: "; ".join(table_problems())),
1915
+ "DESTINATION_UNDECLARED install.sh")
1916
+ control("a class no writer writes under is refused as a stale declaration",
1917
+ with_table(lambda t: t.__setitem__(
1918
+ "writers", [r for r in t["writers"]
1919
+ if not any(e["class"] == "nudge" for e in r.get("destinations") or ())]),
1920
+ lambda: "; ".join(table_problems())),
1921
+ "DESTINATION_CLASS_UNWRITTEN nudge")
1922
+ control("one variable placed in two classes by two writers is refused: its single value cannot "
1923
+ "be inside two roots",
1924
+ with_table(lambda t: next(e for e in _row(t, "launch/shell_integration.py")["destinations"]
1925
+ if e["override"] == "AGENT_BIOS_STATE_DIR"
1926
+ ).__setitem__("class", "recovery"),
1927
+ lambda: "; ".join(table_problems())),
1928
+ "OVERRIDE_CLASS_SPLIT AGENT_BIOS_STATE_DIR")
1929
+ # A writer may both take overrides and fix a root from HOME — install.sh does — so what is
1930
+ # refused is a fixed root with no class and a fixed root with nothing to show for it.
1931
+ def with_writer(writer, mutate):
1932
+ def apply(data):
1933
+ for row in data["writers"]:
1934
+ if row["writer"] == writer:
1935
+ mutate(row)
1936
+ return apply
1937
+
1938
+ control("a fixed destination root whose class is not in the vocabulary is refused",
1939
+ with_table(with_writer("install.sh",
1940
+ lambda row: row.__setitem__("writes_without_override", "nowhere")),
1941
+ lambda: "; ".join(table_problems())),
1942
+ "FIXED_ROOT_UNCLASSED install.sh")
1943
+ control("and a fixed root with no derived lines to show is refused, so the row cannot assert a "
1944
+ "root nobody can check",
1945
+ with_table(with_writer("install.sh", lambda row: row.pop("fixed_roots", None)),
1946
+ lambda: "; ".join(table_problems())),
1947
+ "FIXED_ROOT_UNSHOWN install.sh")
1948
+ clean("a writer that does both is accepted, because install.sh really does both",
1949
+ [p for p in table_problems() if "install.sh" in p])
1950
+ control("a row that names no class at all is refused",
1951
+ with_table(lambda t: _row(t, "git").__setitem__("writes_without_override", None),
1952
+ lambda: "; ".join(table_problems())),
1953
+ "DESTINATION_UNDECLARED git")
1954
+ control("an empty writer set is refused, because a manifest over no writer confines nothing",
1955
+ with_table(lambda t: t.__setitem__("writers", []),
1956
+ lambda: "; ".join(table_problems())),
1957
+ "WRITER_SET_EMPTY")
1958
+ control("a writer row without its own reason is refused",
1959
+ with_table(lambda t: _row(t, "install.sh").pop("$comment"),
1960
+ lambda: "; ".join(table_problems())),
1961
+ "WRITER_UNREASONED install.sh")
1962
+ control("a fallback whose literal has left its writer's source is named with the file",
1963
+ with_table(lambda t: _row(t, "install.sh")["fallbacks"][0].__setitem__(
1964
+ "literal", "${CLAUDE_CONFIG_DIR:-$HOME/.claude-gone}"),
1965
+ lambda: "; ".join(fidelity_problems())),
1966
+ "FALLBACK_MOVED install.sh CLAUDE_CONFIG_DIR")
1967
+ control("and a row whose source file is gone is named too, rather than raising",
1968
+ with_table(lambda t: _row(t, "install.sh").__setitem__("fallback_source", "install-gone.sh"),
1969
+ lambda: guarded(lambda: "; ".join(fidelity_problems()))),
1970
+ "WRITER_SOURCE_ABSENT install.sh")
1971
+
1972
+ # ---- the resolution --------------------------------------------------------------------------
1973
+ rows = resolved_rows(fx_declaration(), fx_env(), scope="all")
1974
+ clean("with every override set inside its class's root, nothing refuses", resolution_problems(rows))
1975
+ clean("every writer in the inventory is answered for", [row["writer"] for row in writers()
1976
+ if not any(r["writer"].startswith(row["writer"])
1977
+ for r in rows)])
1978
+ control("and every (writer, override) pair has its own row, so the count is the pair count plus "
1979
+ "the writers that take none",
1980
+ f'{len(rows)}', f'{len(pairs()) + len([r for r in writers() if r.get("writes_without_override")])}')
1981
+ clean("and every row says which class, which root and whether it is inside",
1982
+ [r["writer"] for r in rows if set(r) < {"class", "writer", "path", "root", "inside"}])
1983
+ control("a writer with several overrides is answered once per override, so one escaping value "
1984
+ "cannot hide behind a sibling in root",
1985
+ str(len([r for r in rows if r["writer"].startswith("install.sh [")])),
1986
+ str(len([e for e in next(r for r in writers() if r["writer"] == "install.sh")
1987
+ ["destinations"]])
1988
+ + len([e for e in next(r for r in writers() if r["writer"] == "install.sh")
1989
+ .get("fixed_roots") or []])))
1990
+
1991
+ # OVERRIDE_MISSING: the case that writes into a real home through a fallback. After the
1992
+ # inversion the run BUILDS the environment, so an override is unset when the declaration names
1993
+ # no root for that name's class — the caller can no longer forget one, which is the point.
1994
+ unset = resolution_problems(resolved_rows(
1995
+ {**fx_declaration(), "destinations": {k: v for k, v
1996
+ in fx_declaration()["destinations"].items()
1997
+ if k != "nudge"}}, fx_env(), scope="all"))
1998
+ control("an unset override is refused before anything else, naming the writer and the variable",
1999
+ "; ".join(unset), "OVERRIDE_MISSING session-distill/update-state.py "
2000
+ "[AGENT_BIOS_SESSION_DISTILL_STATE] AGENT_BIOS_SESSION_DISTILL_STATE")
2001
+ control("and the refusal says why a fallback is not an answer", "; ".join(unset),
2002
+ "a fallback the run did not declare")
2003
+ clean("an unset override is not also reported as an escape, since the path in the row is not "
2004
+ "the one the writer would use",
2005
+ [p for p in unset if "DESTINATION_OUTSIDE_ROOT" in p
2006
+ and "update-state" in p])
2007
+ control("the unset override is reported before any other refusal in the same resolution, "
2008
+ "because a path nobody will write to is not worth judging",
2009
+ "|".join(p.split()[0] for p in resolution_problems(resolved_rows(
2010
+ {**fx_declaration(), "destinations": {k: v for k, v
2011
+ in fx_declaration()["destinations"].items()
2012
+ if k != "nudge"}},
2013
+ fx_env(CODEX_HOME=f"{root}-other/codex"), scope="all"))),
2014
+ "OVERRIDE_MISSING")
2015
+
2016
+ # DESTINATION_OUTSIDE_ROOT: an actual escape, under a second fixture root.
2017
+ escaped = resolution_problems(resolved_rows(
2018
+ fx_declaration(), fx_env(AGENT_BIOS_SESSION_DISTILL_STATE=f"{root}-other/nudge/state.json"), scope="all"))
2019
+ # The inversion changes WHERE an escape can come from, and these controls follow it. A
2020
+ # per-override certificate is now the declared root of that name's class, so an override row
2021
+ # cannot escape its own root by construction — testing that it can would be testing a state the
2022
+ # code no longer has. What CAN escape is a fixed root computed from the given home (controlled
2023
+ # above, with the declaration narrowed), and what can disagree is the caller's claim about the
2024
+ # environment it will run with.
2025
+ control("a caller that says it will run with another value is refused by name, naming both the "
2026
+ "value it claims and the value the run produces",
2027
+ "; ".join(escaped),
2028
+ "DESTINATION_UNCERTIFIED session-distill/update-state.py "
2029
+ "[AGENT_BIOS_SESSION_DISTILL_STATE]")
2030
+ control("and the refusal says which path the certificate would have spoken for",
2031
+ "; ".join(escaped), "and the run produces")
2032
+ nudge_root = fx_declaration()["destinations"]["nudge"]
2033
+ clean("a caller whose claim MATCHES what the run produces is no disagreement",
2034
+ resolution_problems(resolved_rows(
2035
+ fx_declaration(), fx_env(AGENT_BIOS_SESSION_DISTILL_STATE=nudge_root), scope="all")))
2036
+ clean("every override row's path IS its class root, which is why it cannot escape: the row "
2037
+ "carries no value the run did not produce",
2038
+ [r["writer"] for r in resolved_rows(fx_declaration(), {}, scope="all")
2039
+ if "[" in r["writer"] and "[fixed:" not in r["writer"]
2040
+ and r.get("path") and r["path"] != r["root"]])
2041
+ # The lexical rule the FIXED roots are judged by, asked of `inside` directly — the question is
2042
+ # the rule's, and the rows that used to carry it could only reach it through a value the run no
2043
+ # longer takes from the caller.
2044
+ equals("a path that IS the root is inside it, not an escape",
2045
+ json.dumps(inside(nudge_root, nudge_root)), "true")
2046
+ equals("a sibling whose name merely starts with the root's is an escape, not a child",
2047
+ json.dumps(inside(f"{nudge_root}-other/s.json", nudge_root)), "false")
2048
+ equals("a traversal that climbs out of the root is an escape even though its text begins "
2049
+ "inside", json.dumps(inside(f"{nudge_root}/../../out.json", nudge_root)), "false")
2050
+ equals("and one that climbs and comes back is inside, because the question is what the writer "
2051
+ "opens", json.dumps(inside(f"{nudge_root}/d/../s.json", nudge_root)), "true")
2052
+ control("a run that declares no root for a class is refused rather than defaulting to one",
2053
+ "; ".join(resolution_problems(resolved_rows(
2054
+ {"destinations": {k: v for k, v in fx_declaration()["destinations"].items()
2055
+ if k != "checkout"}}, fx_env(), scope="all"))),
2056
+ "DESTINATION_ROOT_ABSENT")
2057
+
2058
+ # ---- the derived inventory ---------------------------------------------------------------
2059
+ #
2060
+ # The table was written from memory once and was wrong in both directions. These controls hold
2061
+ # the derivation itself, because the derivation is now what the table rests on.
2062
+ held_closure = closure()
2063
+ clean("the derivation and the table agree in both directions", inventory_problems())
2064
+ control("the closure is not empty, so an empty table could not pass unexamined",
2065
+ "yes" if len(held_closure) > 20 else f"only {len(held_closure)}", "yes")
2066
+ control("a row certifying an override its writer never reads is refused by name — the defect "
2067
+ "that shipped: install.sh assigns STATE_DIR from $HOME and reads no such variable",
2068
+ with_table(lambda t: _row(t, "install.sh")["destinations"].append(
2069
+ {"override": "AGENT_BIOS_STATE_DIR", "class": "install_roots"}),
2070
+ lambda: "; ".join(inventory_problems())),
2071
+ "INVENTORY_UNWRITTEN install.sh AGENT_BIOS_STATE_DIR")
2072
+ control("and a pair the tree carries with no row is refused by name",
2073
+ with_table(lambda t: _row(t, "install.sh").__setitem__(
2074
+ "destinations",
2075
+ [e for e in _row(t, "install.sh")["destinations"]
2076
+ if e["override"] != "CLAUDE_CONFIG_DIR"]),
2077
+ lambda: "; ".join(inventory_problems())),
2078
+ "INVENTORY_INCOMPLETE install.sh CLAUDE_CONFIG_DIR")
2079
+ control("a HOME-fixed root the derivation found and the row does not show is refused",
2080
+ with_table(lambda t: _row(t, "install.sh").pop("fixed_roots"),
2081
+ lambda: "; ".join(table_problems())),
2082
+ "FIXED_ROOT_UNSHOWN install.sh")
2083
+ control("a fallback stated for an override the row carries no destination for is refused: the "
2084
+ "literal check passed over install.sh's AGENT_BIOS_STATE_DIR fallback because the "
2085
+ "literal really is in the file, as an assignment with no override in it",
2086
+ with_table(lambda t: _row(t, "install.sh")["fallbacks"].append(
2087
+ {"override": "AGENT_BIOS_STATE_DIR",
2088
+ "literal": "STATE_DIR=\"$HOME/.local/share/agent-bios\""}),
2089
+ lambda: "; ".join(fidelity_problems())),
2090
+ "FALLBACK_UNPAIRED install.sh AGENT_BIOS_STATE_DIR")
2091
+ control("an author-side writer declared while files[] ships it is refused, so the declaration "
2092
+ "cannot excuse a writer the derivation can see",
2093
+ with_table(lambda t: _row(t, "install.sh").__setitem__("writer_scope", "author"),
2094
+ lambda: "; ".join(inventory_problems())),
2095
+ "INVENTORY_SCOPE_WRONG install.sh")
2096
+ control("a forward declaration for a file that now exists is refused, so the derived closure "
2097
+ "takes over rather than the row standing unchecked",
2098
+ with_table(lambda t: _row(t, "session-distill/runlib/journal.py").__setitem__(
2099
+ "writer_unwritten", True),
2100
+ lambda: "; ".join(inventory_problems())),
2101
+ "INVENTORY_FORWARD_LANDED session-distill/runlib/journal.py")
2102
+
2103
+ # Each of these five shapes was a wrong answer the derivation gave before it was corrected.
2104
+ def derived_for(writer):
2105
+ return sorted({e["override"] or "(fixed)" for e in held_closure if e["writer"] == writer})
2106
+
2107
+ control("a read assigned through an INJECTED environment counts: instructions_install.py reads "
2108
+ "self.env.get(...), which a scan for os.environ.get called a non-reader",
2109
+ ",".join(derived_for("compose/instructions_install.py")),
2110
+ "(fixed),AGENT_BIOS_STATE_DIR,CLAUDE_CONFIG_DIR,CODEX_HOME,HOME,ZDOTDIR")
2111
+ # The author-side writer is addressed through the table's own declaration rather than by its
2112
+ # path: a shipped module naming an author-side path raises on the first packaged user, and
2113
+ # `check-package.sh` caught this line on exactly that rule.
2114
+ control("a read spread over several lines counts: the author-side writer's os.environ.get "
2115
+ "spans three of them",
2116
+ ",".join(derived_for(sorted(_author_writers())[0]) if _author_writers() else ["none"]),
2117
+ "AGENT_BIOS_SESSION_DISTILL_STATE")
2118
+ control("a runtime-chosen override key counts both ways: instructions_understand.py reads "
2119
+ "'CODEX_HOME' if host == 'codex' else 'CLAUDE_CONFIG_DIR'",
2120
+ ",".join(derived_for("compose/instructions_understand.py")),
2121
+ "CLAUDE_CONFIG_DIR,CODEX_HOME,HOME")
2122
+ control("a STRING that merely mentions an override is not a read of it: assemble.py's "
2123
+ "CLAUDE_VAR literal is a token it rewrites text with",
2124
+ "yes" if not any(e["line"] == 39 for e in held_closure
2125
+ if e["writer"] == "compose/assemble.py") else "counted the literal",
2126
+ "yes")
2127
+ control("and a root that reaches a write THROUGH other names counts: shell_integration.py "
2128
+ "reads ZDOTDIR into self.zdotdir, builds self.startup from it, and writes that",
2129
+ "ZDOTDIR" if "ZDOTDIR" in derived_for("launch/shell_integration.py")
2130
+ else "missed the indirection", "ZDOTDIR")
2131
+
2132
+ # ---- the environment a writer is GIVEN ---------------------------------------------------
2133
+ #
2134
+ # The inversion. Deriving every override that could redirect a write loses across a module
2135
+ # boundary, and what is not derived is not refused; a variable that is ABSENT cannot redirect
2136
+ # anything. These controls are about the environment this module PRODUCES — it executes nothing,
2137
+ # so what is asserted is the mapping, not a process.
2138
+ held_install = next(r for r in writers() if r["writer"] == "install.sh")
2139
+ given_install = environment_for(held_install, fx_declaration())
2140
+ equals("a writer is handed exactly the names its own row declares, and HOME",
2141
+ json.dumps(sorted(given_install)),
2142
+ json.dumps(sorted({e["override"] for e in held_install["destinations"]} | {"HOME"})))
2143
+ equals("and each value is the declared root of that name's class, not a value invented here",
2144
+ json.dumps(given_install["CLAUDE_CONFIG_DIR"]),
2145
+ json.dumps(fx_declaration()["destinations"]["install_roots"]))
2146
+ equals("HOME is what the run declares it hands, which is what every fixed root is computed "
2147
+ "from", json.dumps(given_install["HOME"]),
2148
+ json.dumps(declared_home(fx_declaration())))
2149
+ clean("a variable this writer reads and its row does not declare is ABSENT from what it is "
2150
+ "given — the whole mechanism, since what is not there cannot redirect a write",
2151
+ [name for name in ("AGENT_BIOS_UNINSTALL_ARCHIVE", "XDG_CACHE_HOME", "GIT_DIR",
2152
+ "AGENT_LAUNCH_CONFIG", "AGENT_BIOS_INSTRUCTIONS_DIR")
2153
+ if name in given_install])
2154
+ equals("and the environment is the same answer for every writer: the names its row declares "
2155
+ "plus the isolation its row names, with no extras anywhere",
2156
+ json.dumps(sorted({name for row in writers()
2157
+ for name in environment_for(row, fx_declaration())
2158
+ if name != "HOME"
2159
+ and name not in {e["override"]
2160
+ for e in row.get("destinations") or ()}
2161
+ })),
2162
+ "[]")
2163
+ control("a run that declares no home is refused before any writer is handed anything",
2164
+ "; ".join(environment_problems({**FIXTURE, "environment": {}})),
2165
+ "ENVIRONMENT_HOME_UNDECLARED")
2166
+ clean("while the fixture run declares one", environment_problems(FIXTURE))
2167
+ control("and the manifest refuses without it rather than guessing the owner's home",
2168
+ refusal(lambda: document({**fx_declaration(), "environment": {}}, fx_env())),
2169
+ "ENVIRONMENT_HOME_UNDECLARED")
2170
+
2171
+ # ---- the derivation as DISCLOSURE ---------------------------------------------------------
2172
+ control("what a writer reads and is not given is disclosed per row, and withholds "
2173
+ "certification: a fallback nobody declared points nowhere this manifest can speak for",
2174
+ "; ".join(resolution_problems([
2175
+ {"class": "install_roots", "writer": "x [CLAUDE_CONFIG_DIR]", "path": "/a",
2176
+ "root": "/a", "inside": True, "reads_not_given": ["AGENT_BIOS_STATE_DIR"],
2177
+ "certification": "withheld",
2178
+ "why": "its source reads AGENT_BIOS_STATE_DIR, which the run does not hand it"}])),
2179
+ "DESTINATION_UNCERTIFIED x [CLAUDE_CONFIG_DIR]")
2180
+ clean("the real writers read nothing they are not given, once the excused pairs carry their "
2181
+ "reasons",
2182
+ [f"{row['writer']}: {row['reads_not_given']}" for row in
2183
+ resolved_rows(fx_declaration(), fx_env(), scope="all") if row.get("reads_not_given")])
2184
+ equals("and an excused pair is SHOWN with its reason rather than hidden, since the run does "
2185
+ "not hand it and something has to say why that is safe",
2186
+ json.dumps(sorted(excused_overrides("install.sh"))),
2187
+ '["AGENT_BIOS_UNINSTALL_ARCHIVE"]')
2188
+ equals("the disclosure is derived from the writer's own closure, so a name it stops reading "
2189
+ "stops being disclosed",
2190
+ json.dumps(reads_not_given("install.sh", {}, None)),
2191
+ json.dumps(sorted({e["override"] for e in closure(None)
2192
+ if e["writer"] == "install.sh" and e["override"]}
2193
+ - set(excused_overrides("install.sh")))))
2194
+ control("a writer handed nothing at all reads everything it reads ungiven, which is the "
2195
+ "disclosure firing rather than an empty answer",
2196
+ "yes" if reads_not_given("install.sh", {}, None) else "the disclosure is empty", "yes")
2197
+
2198
+ # ---- the fixed roots, computed from the given HOME ----------------------------------------
2199
+ fixed_rows = [r for r in resolved_rows(fx_declaration(), fx_env(), scope="all") if "[fixed:" in r["writer"]]
2200
+ equals("every fixed-root row carries a path computed from the declared home, not the class "
2201
+ "root restated",
2202
+ json.dumps(sorted({r["certification"] for r in fixed_rows})), '["computed"]')
2203
+ control("and the home-rooted statement whose suffix cannot be read is BOUNDED by the home "
2204
+ "instead of being guessed at",
2205
+ fixed_destination({}, "/h", source_text="root = Path(pick(home, other()))")[1],
2206
+ "the home is its upper bound")
2207
+ held_state = next(r for r in fixed_rows if r["writer"].startswith("install.sh"))
2208
+ control("install.sh's own STATE_DIR is computed under the home it is given",
2209
+ held_state["path"],
2210
+ str(pathlib.Path(declared_home(fx_declaration())) / ".local/share/agent-bios"))
2211
+ control("and the manifest says how it was computed, so a reader can check it by hand",
2212
+ held_state["why"], "<home>/.local/share/agent-bios")
2213
+ control("a declaration whose class root does not contain what the writer computes is refused "
2214
+ "by name rather than certified",
2215
+ "; ".join(resolution_problems(resolved_rows(
2216
+ fx_declaration(install_roots="/srv/elsewhere"), fx_env(), scope="all"))),
2217
+ "DESTINATION_OUTSIDE_ROOT install.sh [fixed:")
2218
+ # The bounded BRANCH of `resolved_rows`, exercised through `resolved_rows` itself. It used to be
2219
+ # asked of `fixed_destination` and `_inside` separately, so the branch that decides between
2220
+ # "bounded is a certification" and "withheld" never ran at all (the round-3 review). Every
2221
+ # statement in this tree has a readable suffix, so the subject is PLANTED: install.sh's own
2222
+ # source, replaced in a throwaway tree, with a HOME-derived statement whose suffix is an
2223
+ # expression at exactly the line its row declares.
2224
+ held_line = next(entry["derived_at_line"] for row in writers()
2225
+ if row["writer"] == "install.sh" for entry in row["fixed_roots"])
2226
+ unreadable_source = ("#\n" * (held_line - 1)) + "STATE_DIR=$(pick \"$HOME\" \"$(other)\")\n"
2227
+
2228
+ def bounded_rows(declaration):
2229
+ return with_source("install.sh", unreadable_source,
2230
+ lambda held_root: [r for r in resolved_rows(declaration, fx_env(),
2231
+ held_root, scope="all")
2232
+ if r["writer"].startswith("install.sh [fixed")])
2233
+
2234
+ held_home = declared_home(fx_declaration())
2235
+ equals("a fixed root whose suffix cannot be read is BOUNDED by the home, and the bound is a "
2236
+ "certification where the class root contains the home",
2237
+ json.dumps([(r["certification"], r["path"]) for r in
2238
+ bounded_rows(fx_declaration(install_roots=held_home))]),
2239
+ json.dumps([["bounded", held_home]]))
2240
+ equals("and where the class root is narrower than the home, certification is WITHHELD, because "
2241
+ "the unread suffix is exactly what would decide",
2242
+ json.dumps([r["certification"] for r in bounded_rows(
2243
+ fx_declaration(install_roots=f"{held_home}/.local/share/agent-bios"))]),
2244
+ '["withheld"]')
2245
+ control("and the withheld row says so in those words, so a reader knows which half of the "
2246
+ "question is open",
2247
+ "; ".join(resolution_problems(bounded_rows(
2248
+ fx_declaration(install_roots=f"{held_home}/.local/share/agent-bios")))),
2249
+ "narrower than the home")
2250
+ control("and a row that claims a fixed root while the run declares no home is uncertified, "
2251
+ "never certified at the root",
2252
+ "; ".join(p for p in resolution_problems(resolved_rows(
2253
+ {**fx_declaration(), "environment": {}}, fx_env(), scope="all")) if "UNCERTIFIED" in p),
2254
+ "the run declares no home")
2255
+ equals("a writer the run PASSES its root is certified by that, which is the preferred channel "
2256
+ "because an argument cannot be inherited",
2257
+ json.dumps(sorted({r["certification"] for r in resolved_rows(fx_declaration(), fx_env(), scope="all")
2258
+ if r["writer"] in ("git", "session-distill/runlib/journal.py")})),
2259
+ '["argument"]')
2260
+ control("and the row says so, naming what passes it",
2261
+ next(r["why"] for r in resolved_rows(fx_declaration(), fx_env(), scope="all") if r["writer"] == "git"),
2262
+ "the run passes this writer its root")
2263
+ control("a fixed-root row that says neither how its root is reached is a table defect",
2264
+ "; ".join(with_table(lambda held: [row.pop("root_from") for row in held["writers"]
2265
+ if row["writer"] == "install.sh"],
2266
+ inventory_problems)),
2267
+ "INVENTORY_ROOT_FROM_UNSTATED install.sh")
2268
+ control("and one that says HOME and shows no line to derive it at is another",
2269
+ "; ".join(with_table(lambda held: [row.pop("fixed_roots") for row in held["writers"]
2270
+ if row["writer"] == "install.sh"],
2271
+ inventory_problems)),
2272
+ "INVENTORY_FIXED_ROOT_UNSHOWN install.sh")
2273
+ control("a fixed-root row for a writer this tree does not have is reported, which the pair-only "
2274
+ "legs could not see",
2275
+ "; ".join(with_table(lambda held: held["writers"].append(
2276
+ {"writer": "compose/no-such-writer.py", "destinations": [],
2277
+ "writes_without_override": "install_roots", "root_from": "home",
2278
+ "fixed_roots": [{"derived_at_line": 1, "root": "X = Path.home() / 'x'"}],
2279
+ "$comment": "planted"}), inventory_problems)),
2280
+ "INVENTORY_FIXED_ROOT_ABSENT compose/no-such-writer.py")
2281
+ control("the line the destination is computed from is read from the WRITER's source, not from "
2282
+ "the table's 160-character excerpt of it",
2283
+ "yes" if (source_line("compose/instructions_install.py", 327) or "").endswith(
2284
+ ".expanduser()") else "the excerpt is what was read", "yes")
2285
+ control("and a multi-line statement is read to where its parentheses balance, because one line "
2286
+ "of it establishes nothing",
2287
+ fixed_destination({}, "/h", source_text=source_line("launch/agent-launch.py", 8314))[1],
2288
+ "<home>/.local/share/agent-bios/corpus-status.json")
2289
+
2290
+ # ---- the four channels an environment cannot close ---------------------------------------
2291
+ #
2292
+ # Scrubbing is the mechanism and it is not sufficient: a writer can reach a path without reading
2293
+ # a variable. Each channel is derived from the writer's own source, and each control plants its
2294
+ # subject rather than waiting for a real writer to acquire one.
2295
+ clean("no writer in this tree reaches a path through a channel the run cannot answer for",
2296
+ channel_problems())
2297
+ control("and the check says so about a non-empty set of writers, since an empty one would pass "
2298
+ "unexamined", "named" if "CHANNEL_NO_WRITERS_READ" in "; ".join(
2299
+ channel_problems(str(pathlib.Path(tempfile.mkdtemp(prefix="dest-nowriter-",
2300
+ dir="/tmp"))))) else "silent",
2301
+ "named")
2302
+
2303
+ # The password database: the channel that put a run in the owner's real home during a commit
2304
+ # hook. Proved BY SOURCE in both directions — the defect and its licence — because the only
2305
+ # other way to prove it is to run a writer against a real home and look at what appeared.
2306
+ control("a writer that reads the password database is refused by name: the run cannot redirect "
2307
+ "what `getpwuid` answers",
2308
+ "; ".join(with_source("compose/prune-backups.py",
2309
+ "import pwd, os\nroot = pwd.getpwuid(os.getuid()).pw_dir\n",
2310
+ channel_problems)),
2311
+ "CHANNEL_PASSWORD_DATABASE compose/prune-backups.py:2")
2312
+ equals("and the licence for one is held against the source: the read must sit behind the "
2313
+ "absence of a name the run always gives",
2314
+ json.dumps([guarded_by("home = env.get('HOME')\nif home is None:\n import pwd\n"
2315
+ " home = pwd.getpwuid(os.getuid()).pw_dir\n", 4, "HOME"),
2316
+ guarded_by("home = env.get('XDG_HOME')\nif home is None:\n import pwd\n"
2317
+ " home = pwd.getpwuid(os.getuid()).pw_dir\n", 4, "HOME"),
2318
+ guarded_by("import pwd\nhome = pwd.getpwuid(os.getuid()).pw_dir\n", 2,
2319
+ "HOME")]),
2320
+ "[true, false, false]")
2321
+ control("so a row licensing a line its source does not guard is refused, naming the guard it "
2322
+ "claimed",
2323
+ "; ".join(with_table(
2324
+ lambda held: [row.__setitem__("channels", {"password_database": [
2325
+ {"line": 2, "guarded_by": "HOME", "reason": "planted"}]})
2326
+ for row in held["writers"] if row["writer"] == "compose/prune-backups.py"],
2327
+ lambda: with_source("compose/prune-backups.py",
2328
+ "import pwd, os\nroot = pwd.getpwuid(os.getuid()).pw_dir\n",
2329
+ channel_problems))),
2330
+ "which its source does not show guarding it")
2331
+ control("and a licence with no reason licenses nothing either",
2332
+ "; ".join(with_table(
2333
+ lambda held: [row.__setitem__("channels", {"password_database": [
2334
+ {"line": 4, "guarded_by": "HOME"}]})
2335
+ for row in held["writers"] if row["writer"] == "compose/prune-backups.py"],
2336
+ lambda: with_source("compose/prune-backups.py",
2337
+ "import os, pwd\nhome = os.environ.get('HOME')\n"
2338
+ "if home is None:\n home = pwd.getpwuid(os.getuid()).pw_dir\n",
2339
+ channel_problems))),
2340
+ "CHANNEL_PASSWORD_DATABASE compose/prune-backups.py:4")
2341
+ clean("while the real licence in this tree holds: the read is behind `if home is None` where "
2342
+ "home came from the HOME the run hands it",
2343
+ [p for p in channel_problems() if "PASSWORD_DATABASE" in p])
2344
+
2345
+ # A login shell restores exactly what was scrubbed.
2346
+ control("a child login shell is refused by name, because a profile re-read puts the user's own "
2347
+ "variables back",
2348
+ "; ".join(with_source("wrappers/codex-run.sh",
2349
+ "#!/bin/sh\nexec zsh -l -c \"$1\"\n", channel_problems)),
2350
+ "CHANNEL_LOGIN_SHELL wrappers/codex-run.sh:2")
2351
+ control("and `--login` spelled in full is the same channel",
2352
+ "; ".join(with_source("wrappers/codex-run.sh",
2353
+ "#!/bin/sh\nbash --login -c \"$1\"\n", channel_problems)),
2354
+ "CHANNEL_LOGIN_SHELL wrappers/codex-run.sh:2")
2355
+
2356
+ # An absolute literal and a path argument are STATED, with their reasons, keyed to the token.
2357
+ control("an absolute literal a row does not name is reported with the literal itself",
2358
+ "; ".join(with_source("compose/instructions_setup.py",
2359
+ "DEST = '/Library/Application Support/x'\n", channel_problems)),
2360
+ "CHANNEL_UNSTATED compose/instructions_setup.py absolute_literals: "
2361
+ "/Library/Application")
2362
+ control("a statement whose token the source no longer shows is stale, not approval",
2363
+ "; ".join(with_table(
2364
+ lambda held: [row["channels"]["absolute_literals"]["tokens"].append("/srv/gone")
2365
+ for row in held["writers"]
2366
+ if row["writer"] == "wrappers/codex_frame_filter.py"],
2367
+ channel_problems)),
2368
+ "CHANNEL_STALE wrappers/codex_frame_filter.py absolute_literals: the row states "
2369
+ "/srv/gone")
2370
+ control("and a statement with tokens and no reason is refused: naming a channel is not "
2371
+ "answering for it",
2372
+ "; ".join(with_table(
2373
+ lambda held: [row["channels"]["absolute_literals"].pop("reason")
2374
+ for row in held["writers"]
2375
+ if row["writer"] == "wrappers/codex_frame_filter.py"],
2376
+ channel_problems)),
2377
+ "CHANNEL_UNREASONED wrappers/codex_frame_filter.py absolute_literals")
2378
+ control("a path option a row does not record is reported, because an argument is the channel "
2379
+ "the run PREFERS and it has to know the writer takes one",
2380
+ "; ".join(with_source("compose/instructions_setup.py",
2381
+ "parser.add_argument('--state-dir')\n", channel_problems)),
2382
+ "CHANNEL_UNSTATED compose/instructions_setup.py path_arguments: --state-dir")
2383
+ # KEYED, not positional, and non-empty before anything is indexed: sorting the live rows and
2384
+ # asserting element [0] ignored every other row and raised instead of failing by name when the
2385
+ # set was empty (the round-4 review).
2386
+ held_arguments = {row["writer"]: tuple(row["channels"]["path_arguments"]["tokens"])
2387
+ for row in writers()
2388
+ if (row.get("channels") or {}).get("path_arguments")}
2389
+ control("the tree really declares path-argument channels, so the assertions below are not over "
2390
+ "an empty set", "yes" if held_arguments else "the set is empty", "yes")
2391
+ equals("and every option in this tree is recorded, keyed by its writer, so a row this control "
2392
+ "does not name fails it rather than hiding behind a sorted first element",
2393
+ json.dumps({name: list(tokens) for name, tokens in sorted(held_arguments.items())}),
2394
+ json.dumps({name: list(tokens) for name, tokens
2395
+ in sorted(CHANNEL_STATED_ARGUMENTS.items())}))
2396
+ clean("and each one carries the reason it is preferred, in its own row",
2397
+ [name for name, row in ((row["writer"], row) for row in writers())
2398
+ if (row.get("channels") or {}).get("path_arguments")
2399
+ and not str(row["channels"]["path_arguments"].get("reason") or "").strip()])
2400
+
2401
+ # ---- the release's scope, as a fact the rows carry -----------------------------------------
2402
+ #
2403
+ # Release 1's S11 writes the declared checkout and makes the git commit, and runs nothing else
2404
+ # (D-20261112-2cf1c4). The six findings that were deferred with that decision are all about
2405
+ # writers it never invokes, so the scope has to be checkable rather than asserted in a record.
2406
+ release_rows = resolved_rows(fx_declaration(), fx_env())
2407
+ equals("the rows release 1 may invoke are exactly the stages that write files — git is not "
2408
+ "among them, because this release executes none",
2409
+ json.dumps(sorted({r["writer"].split(" [")[0] for r in release_rows
2410
+ if r["certification"] != RELEASE_1_UNINVOKED})),
2411
+ json.dumps(sorted(["session-distill/runlib/inventory.py",
2412
+ "session-distill/runlib/journal.py",
2413
+ "session-distill/runlib/recovery.py",
2414
+ "session-distill/runlib/stage_apply.py",
2415
+ "session-distill/runlib/stage_close.py"])))
2416
+ clean("and NO row outside that set comes back certified — the installer, the launcher, "
2417
+ "update-state and the personal layers are named, never confined-and-allowed, so a "
2418
+ "deferred finding about one of them cannot become reachable without this failing",
2419
+ [r["writer"] for r in release_rows
2420
+ if r["certification"] != RELEASE_1_UNINVOKED
2421
+ and r["writer"].split(" [")[0] not in ("session-distill/runlib/inventory.py",
2422
+ "session-distill/runlib/journal.py",
2423
+ "session-distill/runlib/recovery.py",
2424
+ "session-distill/runlib/stage_apply.py",
2425
+ "session-distill/runlib/stage_close.py")])
2426
+ # The permitted ENTRIES, asked independently of the writer-name allowlist: the scope control
2427
+ # above strips the `[OVERRIDE]` suffix, so a row for a writer in the set was accepted whatever
2428
+ # destination it carried — which is how `inventory.py [HOME]` came back certified at the
2429
+ # personal-layers root (the round-4 review). This asks the (class, override) pairs themselves.
2430
+ equals("the destination ENTRIES release 1 may write are exactly the checkout-and-state set, "
2431
+ "asked by class and override rather than by the writer's name",
2432
+ json.dumps(sorted({(r["class"], r["writer"].split(" [")[1][:-1]
2433
+ if " [" in r["writer"] else "")
2434
+ for r in release_rows
2435
+ if r["certification"] not in (RELEASE_1_UNINVOKED,
2436
+ READ_NOT_WRITTEN)})),
2437
+ json.dumps(sorted([("checkout", ""), ("runtime_state", ""), ("recovery", "")])))
2438
+ clean("so no destination resting on an environment OVERRIDE is certified in this release at "
2439
+ "all: every writer it invokes is passed its root",
2440
+ [r["writer"] for r in release_rows
2441
+ if " [" in r["writer"] and "[fixed:" not in r["writer"]
2442
+ and r["certification"] not in (RELEASE_1_UNINVOKED, READ_NOT_WRITTEN)])
2443
+ equals("and the owner's home is a READ with no path, not a destination this release may write",
2444
+ json.dumps([(r["certification"], r["path"]) for r in release_rows
2445
+ if r["class"] == "personal_layers"
2446
+ and r["certification"] == READ_NOT_WRITTEN]),
2447
+ json.dumps([[READ_NOT_WRITTEN, None]]))
2448
+ control("and the row says so in its own words rather than leaving the reader to the table",
2449
+ next((r["why"] for r in release_rows if r["certification"] == READ_NOT_WRITTEN),
2450
+ "<no read_not_written row in the release's scope>"),
2451
+ "nothing of this writer's is written under it")
2452
+ # The claim check survived the narrowing because it is asked of the produced MAPPING: with no
2453
+ # override-rooted row left in the release, a check keyed on such a row would have gone silent.
2454
+ control("a caller that says it will run with another HOME is refused by name even though no "
2455
+ "destination rests on HOME any more",
2456
+ "; ".join(claim_problems(fx_declaration(), {"HOME": "/srv/elsewhere"})),
2457
+ "ENVIRONMENT_CLAIM_DIFFERS")
2458
+ control("and the refusal names the writer whose environment it would have been",
2459
+ "; ".join(claim_problems(fx_declaration(), {"HOME": "/srv/elsewhere"})),
2460
+ "session-distill/runlib/stage_apply.py HOME")
2461
+ clean("while a name NO writer the release invokes is handed is not claimed over at all: the "
2462
+ "check speaks for the mapping the run produces, not for every name a caller mentions",
2463
+ claim_problems(fx_declaration(), {"GIT_CONFIG_GLOBAL": "/dev/zero"}))
2464
+ clean("while a claim that matches what the run produces is no disagreement",
2465
+ claim_problems(fx_declaration(), fx_env()))
2466
+ clean("every named row says WHY in its own words rather than leaving the reader to the decision "
2467
+ "record", [r["writer"] for r in release_rows
2468
+ if r["certification"] == RELEASE_1_UNINVOKED
2469
+ and "release-1" not in str(r.get("why"))])
2470
+ clean("and no named row carries a path, so nothing downstream can read one and write there",
2471
+ [r["writer"] for r in release_rows
2472
+ if r["certification"] == RELEASE_1_UNINVOKED and r.get("path") is not None])
2473
+ # The subject is TAKEN FROM THE TABLE rather than written out: a literal author-side path in a
2474
+ # shipped module is refused by the package gate, and a name copied here would go stale the day
2475
+ # the row is renamed.
2476
+ held_uninvoked = next(row["writer"] for row in writers()
2477
+ if not row.get("release_1_invoked") and row.get("destinations")
2478
+ and not row.get("writer_unwritten"))
2479
+ equals("the fact is the TABLE's, so flipping one row's declaration moves it into the release "
2480
+ "and back out",
2481
+ json.dumps(with_table(
2482
+ lambda held: _row(held, held_uninvoked).__setitem__("release_1_invoked", True),
2483
+ lambda: [r["certification"] for r
2484
+ in resolved_rows(fx_declaration(), fx_env())
2485
+ if r["writer"].startswith(held_uninvoked)
2486
+ and r["certification"] == RELEASE_1_UNINVOKED])),
2487
+ json.dumps([]))
2488
+ apply_writer = "session-distill/runlib/stage_apply.py"
2489
+ equals("release 1's apply stage is a written writer with one destination, the checkout it is "
2490
+ "passed: its row is answered from the argument and names no override",
2491
+ json.dumps([(r["class"], r["certification"]) for r in release_rows
2492
+ if r["writer"].startswith(apply_writer)]),
2493
+ json.dumps([["checkout", "argument"]]))
2494
+ # The row as it stood before the stage was written, PLANTED: a forward writer with a
2495
+ # personal-layer destination the release does not invoke. The property is the table's rule and
2496
+ # not that row's history, so it is held on a row built here rather than on one that has gone.
2497
+ equals("the scope is per DESTINATION and not per writer: a writer whose checkout row is "
2498
+ "answered has its uninvoked personal-layer row named, in the same release",
2499
+ json.dumps(with_table(
2500
+ lambda held: _row(held, apply_writer).update(
2501
+ writer_unwritten=True,
2502
+ destinations=[{"override": "HOME", "class": "personal_layers",
2503
+ "release_1_invoked": False}]),
2504
+ lambda: [(r["class"], r["certification"])
2505
+ for r in resolved_rows(fx_declaration(), fx_env())
2506
+ if r["writer"].startswith(apply_writer)])),
2507
+ json.dumps([["personal_layers", RELEASE_1_UNINVOKED], ["checkout", "forward"]]))
2508
+ equals("an entry that says nothing inherits its writer's answer, so a row cannot be narrowed "
2509
+ "by the writer's silence",
2510
+ json.dumps([entry_invoked_in_release_1({"release_1_invoked": True}, {}),
2511
+ entry_invoked_in_release_1({"release_1_invoked": False}, {}),
2512
+ entry_invoked_in_release_1({"release_1_invoked": True},
2513
+ {"release_1_invoked": False})]),
2514
+ "[true, false, false]")
2515
+ # What the narrowing BUYS the declaration: the classes only uninvoked writers write no longer
2516
+ # need a root. The lead asked what `environment.home` is still needed for, and this is the other
2517
+ # half of that answer — the home is required, the class roots for those writers are not.
2518
+ # A read needs no root, so it is not one of the classes the declaration must carry: this set is
2519
+ # what `required` in S0's schema is held against.
2520
+ held_classes = {entry.get("class") for row in writers()
2521
+ for entry in list(row.get("destinations") or ())
2522
+ + list(row.get("fixed_roots") or ())
2523
+ if entry_invoked_in_release_1(row, entry) and not entry.get("read_only")}
2524
+ held_classes |= {row.get("writes_without_override") for row in writers()
2525
+ if row.get("release_1_invoked")}
2526
+ narrowed = {k: v for k, v in fx_declaration()["destinations"].items()
2527
+ if k in held_classes}
2528
+ clean("a declaration carrying roots only for the classes release 1 writes resolves with no "
2529
+ "refusal, so the owner no longer has to name a root for a writer S11 will not run",
2530
+ resolution_problems(resolved_rows({**fx_declaration(), "destinations": narrowed},
2531
+ fx_env())))
2532
+ # Through the SCHEMA as well as the resolution: a clean resolution says the code accepts the
2533
+ # narrowed declaration and nothing about whether S0 would admit it, and the schema still
2534
+ # required all seven roots (the round-4 review).
2535
+ held_declaration = {**fx_declaration(), "destinations": narrowed}
2536
+ equals("the narrowed declaration passes S0's own schema, so the release can actually be "
2537
+ "declared and not only resolved",
2538
+ json.dumps(validate.violations(declare.VALIDATOR, held_declaration)), "[]")
2539
+ equals("and the schema's required classes ARE the table's release-1 classes, so the two cannot "
2540
+ "drift apart",
2541
+ json.dumps(sorted(declare.DESTINATIONS_REQUIRED)),
2542
+ json.dumps(sorted(name for name in held_classes if name)))
2543
+ clean("while the vocabulary stays the whole set, so a wider declaration is still typed and "
2544
+ "still judged rather than becoming undeclared",
2545
+ [name for name in ("install_roots", "personal_layers", "launcher_shell_integration",
2546
+ "nudge") if name not in declare.DESTINATIONS])
2547
+ control("while a declaration missing a class release 1 DOES write is still refused by the "
2548
+ "schema, so the narrowing did not make the requirement empty",
2549
+ "; ".join(str(held) for held in validate.violations(
2550
+ declare.VALIDATOR,
2551
+ {**fx_declaration(),
2552
+ "destinations": {k: v for k, v in narrowed.items() if k != "checkout"}})),
2553
+ "checkout")
2554
+ control("and the same declaration at the WIDER scope refuses by name, which is what says the "
2555
+ "narrowing is the release's and not the mechanism's",
2556
+ "; ".join(resolution_problems(resolved_rows(
2557
+ {**fx_declaration(), "destinations": narrowed}, fx_env(), scope="all"))),
2558
+ "DESTINATION_ROOT_ABSENT")
2559
+ clean("and the same row, unflipped, is named by that state — without this the control above "
2560
+ "would pass over a row that was never named at all",
2561
+ [r["certification"] for r in release_rows
2562
+ if r["writer"].startswith(held_uninvoked)
2563
+ and r["certification"] != RELEASE_1_UNINVOKED])
2564
+ control("an unknown scope is refused rather than read as one of the two, because a typo that "
2565
+ "resolved everything would widen the release silently",
2566
+ refusal(lambda: resolved_rows(fx_declaration(), fx_env(), scope="releaes_1")),
2567
+ "RESOLUTION_SCOPE_UNKNOWN")
2568
+ equals("`environment.home` is still required, and these are what needs it: the HOME handed to "
2569
+ "every writer the release DOES invoke",
2570
+ json.dumps(sorted({r["writer"].split(" [")[0] for r in release_rows
2571
+ if r["certification"] != RELEASE_1_UNINVOKED
2572
+ and "HOME" in environment_for(
2573
+ next(w for w in writers()
2574
+ if w["writer"] == r["writer"].split(" [")[0]),
2575
+ fx_declaration())})),
2576
+ json.dumps(sorted(["session-distill/runlib/inventory.py",
2577
+ "session-distill/runlib/journal.py",
2578
+ "session-distill/runlib/recovery.py",
2579
+ "session-distill/runlib/stage_apply.py",
2580
+ "session-distill/runlib/stage_close.py"])))
2581
+ control("and a declaration without it is refused, so the narrowing did not make the home "
2582
+ "optional", "; ".join(environment_problems({"destinations": {}})),
2583
+ "ENVIRONMENT_HOME_UNDECLARED")
2584
+
2585
+ # ---- git is not this release's to run ------------------------------------------------------
2586
+ #
2587
+ # The configuration policy, the hooks certificate, the hook-refusal contract and the child
2588
+ # environment all stood here, with their controls. Release 1's S11 executes no git
2589
+ # (`D-20261113-f22b7d`), so what is left to assert is that nothing of git's is reachable from
2590
+ # the release's own scope — which the scope controls above do, by name — and that the manifest
2591
+ # the stage reads carries no certificate speaking for a command nobody runs.
2592
+ clean("the manifest carries no git certificate, since a certificate for a command this release "
2593
+ "never runs would be read as one that was checked",
2594
+ [name for name in ("git", "hook_refusal")
2595
+ if name in document(fx_declaration(), fx_env())])
2596
+ equals("and the git row is NAMED by the release's scope, like every other writer it does not "
2597
+ "invoke",
2598
+ json.dumps([(r["class"], r["certification"]) for r in release_rows
2599
+ if r["writer"] == "git"]),
2600
+ json.dumps([["checkout", RELEASE_1_UNINVOKED]]))
2601
+ clean("so the produced environment for it carries no GIT name at all: there is no isolation to "
2602
+ "hand a command that is not run, and the declared HOME is handed to every row alike",
2603
+ [name for name in environment_for(
2604
+ next(row for row in writers() if row["writer"] == "git"), fx_declaration())
2605
+ if name.startswith("GIT")])
2606
+
2607
+ # ---- the two install layouts ----------------------------------------------------------------
2608
+ #
2609
+ # A packaged install has no `gates/` and no author-scope writer source. The manifest used to
2610
+ # refuse WRITER_SOURCE_ABSENT there, over `session-distill/update-state.py`, which npm does not
2611
+ # ship: a refusal no packaged user can act on, invisible from every clone. Found by the WP-21
2612
+ # review. These controls build both layouts as file trees and ask the real functions.
2613
+ layout_root = pathlib.Path(tempfile.mkdtemp(prefix="dest-layout-", dir="/tmp"))
2614
+ try:
2615
+ author_writer = sorted(_author_writers())[0] if _author_writers() else None
2616
+ # The package layout: the shipped file set only. `files[]` decides it, so the fixture cannot
2617
+ # drift from what npm actually packs.
2618
+ packed = json.loads((REPO / "package.json").read_text(encoding="utf-8")).get("files") or []
2619
+ pack = layout_root / "package"
2620
+ (pack / "session-distill" / "tables").mkdir(parents=True)
2621
+ (pack / "package.json").write_bytes((REPO / "package.json").read_bytes())
2622
+ # EVERY script `files[]` ships, not only the writer sources the table happens to name.
2623
+ # The thin fixture is what let the "a packaged install produces a manifest" control pass
2624
+ # while the thing it claimed to test was broken: with the global `REPO` wired into the
2625
+ # derivation, `inventory_problems` scanned the AUTHOR'S CHECKOUT, agreed with the table
2626
+ # there, and never looked at the fixture at all. Scanning the fixture required the fixture
2627
+ # to be a real package — npm installs the whole of `files[]`, and the author-scope writer
2628
+ # is the only thing it leaves out.
2629
+ for entry in packed:
2630
+ source = REPO / entry
2631
+ held_sources = ([source] if source.is_file()
2632
+ else sorted(p for p in source.rglob("*") if p.is_file()))
2633
+ for held_path in held_sources:
2634
+ if held_path.suffix not in (".py", ".sh", ".zsh"):
2635
+ continue
2636
+ target = pack / held_path.relative_to(REPO)
2637
+ target.parent.mkdir(parents=True, exist_ok=True)
2638
+ target.write_bytes(held_path.read_bytes())
2639
+ # What a package DECLARES, written here because npm's own pack writes it: `files[]` carries
2640
+ # `provenance.json`, `check-publish.sh --stamp` writes it at prepack with the commit the
2641
+ # tarball holds, and removes it afterwards — so it is in a published package and in no
2642
+ # checkout. A fixture that models a package carries it, like one that models a checkout
2643
+ # carries `gates/`.
2644
+ (pack / LAYOUT_DECLARATION).write_text(
2645
+ json.dumps({"commit": "0" * 40, "committedAt": "2026-11-12T00:00:00Z", "dirty": False}),
2646
+ encoding="utf-8")
2647
+ control("the package layout is recognised by what a publish DECLARES, not by a directory "
2648
+ "that happens to be missing", install_layout(pack), "package")
2649
+ control("and a checkout is recognised by the author tree it declares itself with",
2650
+ install_layout(REPO), "checkout")
2651
+ bare = layout_root / "bare"
2652
+ (bare / "session-distill").mkdir(parents=True)
2653
+ control("a tree that declares neither is not guessed at: an incomplete copy used to BE a "
2654
+ "package, and every excuse the layout carries was granted to it",
2655
+ str(install_layout(bare)), "None")
2656
+ control("and the manifest refuses over it by name rather than defaulting",
2657
+ "; ".join(layout_problems(bare)), f"LAYOUT_UNDECLARED {bare}")
2658
+ both = layout_root / "both"
2659
+ (both / "gates").mkdir(parents=True)
2660
+ (both / LAYOUT_DECLARATION).write_text("{}", encoding="utf-8")
2661
+ control("a tree carrying both declarations is refused too, since which excuses apply "
2662
+ "cannot be established", "; ".join(layout_problems(both)),
2663
+ f"LAYOUT_AMBIGUOUS {both}")
2664
+ clean("while the real checkout and the package fixture each declare exactly one",
2665
+ layout_problems(REPO) + layout_problems(pack))
2666
+ # Every row carries exactly one certification state, including the two that only a
2667
+ # refused resolution has: `not_installed` for a writer this install does not have, and
2668
+ # `unset` for an override the declaration names no root for. The document is produced only
2669
+ # when nothing refuses, so these are asked of `resolved_rows` where they exist.
2670
+ equals("a writer this install does not have carries `not_installed` rather than an absent "
2671
+ "field",
2672
+ json.dumps(sorted({str(r.get("certification"))
2673
+ for r in resolved_rows(fx_declaration(), fx_env(), str(pack), scope="all")
2674
+ if r.get("not_installed")})),
2675
+ '["not_installed"]')
2676
+ equals("and an override the declaration names no root for carries `unset`",
2677
+ json.dumps(sorted({str(r.get("certification")) for r in resolved_rows(
2678
+ {**fx_declaration(), "destinations": {k: v for k, v
2679
+ in fx_declaration()["destinations"].items()
2680
+ if k != "nudge"}}, fx_env(), str(pack), scope="all")
2681
+ if r.get("unset")})),
2682
+ '["unset"]')
2683
+ control("the author-scope writer is named as not installed there",
2684
+ ", ".join(author_rows_absent(pack)), author_writer or "none")
2685
+ clean("and its absence is not a fidelity failure in that layout",
2686
+ [p for p in fidelity_problems(pack) if "WRITER_SOURCE_ABSENT" in p])
2687
+ held_rows = resolved_rows(fx_declaration(), fx_env(), root=pack, scope="all")
2688
+ control("its row is recorded rather than dropped, so the manifest does not read as though "
2689
+ "no such writer existed",
2690
+ "; ".join(r.get("not_installed", "") for r in held_rows
2691
+ if r["writer"] == author_writer),
2692
+ "author-side writer, not present in this install")
2693
+ clean("and that row is not judged for escape, since a writer that is not there writes "
2694
+ "nowhere",
2695
+ [p for p in resolution_problems(held_rows) if author_writer and author_writer in p])
2696
+ held_doc = guarded(lambda: document(fx_declaration(), fx_env(), root=pack))
2697
+ control("so a packaged install produces a manifest at all",
2698
+ "dict" if isinstance(held_doc, dict) else str(held_doc)[:160], "dict")
2699
+ control("and the manifest says which layout it was written in",
2700
+ held_doc.get("layout") if isinstance(held_doc, dict) else "none", "package")
2701
+ # The derivation must read the root it was GIVEN. It read the module's own checkout through
2702
+ # a global instead, so every answer about a packaged install was an answer about the
2703
+ # author's tree — and the control above passed while what it named was broken.
2704
+ pack_writers = {entry["writer"] for entry in closure(pack)}
2705
+ repo_writers = {entry["writer"] for entry in closure(REPO)}
2706
+ control("the closure scanned the package tree rather than nothing",
2707
+ "scanned" if len(pack_writers) > 3 else f"only {sorted(pack_writers)}", "scanned")
2708
+ control("and the set is the PACKAGE's: the author-scope writer is in the checkout's "
2709
+ "closure and not in the package's, which is the difference npm makes",
2710
+ "differs" if author_writer and author_writer in repo_writers
2711
+ and author_writer not in pack_writers
2712
+ else f"the same answer for both roots ({author_writer})", "differs")
2713
+ clean("the inventory agrees with the table in the packaged layout too, because a writer "
2714
+ "this install does not have certifies nothing", inventory_problems(pack))
2715
+ # The checkout half: the same absence IS a failure where the source is audited.
2716
+ checkout = layout_root / "checkout"
2717
+ (checkout / "gates").mkdir(parents=True)
2718
+ (checkout / "session-distill").mkdir(parents=True)
2719
+ (checkout / "package.json").write_bytes((REPO / "package.json").read_bytes())
2720
+ control("while in a CHECKOUT the author-scope writer's absence is a defect, so the "
2721
+ "exclusion is the layout's and not a blanket excuse",
2722
+ "; ".join(inventory_problems(checkout)), "INVENTORY_SCOPE_ABSENT")
2723
+ control("in a checkout, an author-scope writer whose file is missing fails by name, "
2724
+ "because that is where the fallback literal is held against its source",
2725
+ "; ".join(fidelity_problems(checkout)), "WRITER_SOURCE_ABSENT")
2726
+ finally:
2727
+ shutil.rmtree(layout_root, ignore_errors=True)
2728
+
2729
+ # Lexical containment is half the answer: `os.open` follows symlinks, so a path inside the root
2730
+ # can open a file outside it. `links_problem` is for a caller that cannot open with O_NOFOLLOW;
2731
+ # `journal.Storage.append` does open that way, which is the stronger half.
2732
+ # Plain names, no aliases: `dispatch.py`'s source-shape rule refuses `import os as _os` in a
2733
+ # shipped module because renaming an executing module is how an effect hides from a scan, and it
2734
+ # caught this block. The same blindness is a finding against this unit's own AST check.
2735
+ link_root = pathlib.Path(tempfile.mkdtemp(prefix="dest-link-", dir="/tmp"))
2736
+ try:
2737
+ (link_root / "declared" / "deep").mkdir(parents=True)
2738
+ (link_root / "outside").mkdir()
2739
+ os.symlink(link_root / "outside" / "f.json", link_root / "declared" / "f.json")
2740
+ os.symlink(link_root / "outside", link_root / "declared" / "away")
2741
+ declared = link_root / "declared"
2742
+ control("a path that IS a symlink is lexically inside and named by links_problem",
2743
+ f'{_inside(declared / "f.json", declared)}:'
2744
+ f'{(links_problem(declared / "f.json", declared) or "none")[:20]}',
2745
+ "True:DESTINATION_SYMLINK")
2746
+ control("a symlinked DIRECTORY on the way is named too, since a link anywhere puts the "
2747
+ "write outside the root",
2748
+ (links_problem(declared / "away" / "f.json", declared) or "none"),
2749
+ "DESTINATION_SYMLINK")
2750
+ clean("an ordinary path under the root carries no link problem",
2751
+ [links_problem(declared / "deep" / "f.json", declared)]
2752
+ if links_problem(declared / "deep" / "f.json", declared) else [])
2753
+ control("and a path outside the root is still reported as outside, not as a link, and not "
2754
+ "by raising",
2755
+ guarded(lambda: links_problem(link_root / "outside" / "f.json", declared) or "none"),
2756
+ "DESTINATION_OUTSIDE_ROOT")
2757
+ control("the docstring says why this is the weaker half, so a caller does not read it as "
2758
+ "the whole answer",
2759
+ inside.__doc__, "O_NOFOLLOW")
2760
+ finally:
2761
+ shutil.rmtree(link_root, ignore_errors=True)
2762
+
2763
+ # ---- the document and the write --------------------------------------------------------------
2764
+ # `document` refuses on an inventory problem too, so a mutation to the DERIVATION makes this
2765
+ # call raise. Guarded, so the suite names the inventory failure instead of dying here: four
2766
+ # revert rows reported CONTROL-SILENT with an empty FAIL list because this one line stopped the
2767
+ # run before the controls that would have named the defect.
2768
+ doc_or_refusal = guarded(lambda: document(fx_declaration(), fx_env()))
2769
+ doc = doc_or_refusal if isinstance(doc_or_refusal, dict) else {
2770
+ "resolved": [], "overrides_required": [], "refused": doc_or_refusal}
2771
+ control("the document is produced at all, rather than refusing over its own inventory",
2772
+ "dict" if isinstance(doc_or_refusal, dict) else str(doc_or_refusal)[:200], "dict")
2773
+ # Equality, and of the rows' own keys rather than of a count: `'32' in '132'` passed the
2774
+ # substring helper (the round-5 review). The claim is that the document drops and adds no row of
2775
+ # the resolution it was built from, so the keys are what is compared.
2776
+ equals("the document carries exactly the resolved rows of the RELEASE's scope — the rows above "
2777
+ "are the wider scope, and the document is what S11 reads",
2778
+ json.dumps(sorted((r["writer"], r["class"]) for r in doc["resolved"])),
2779
+ json.dumps(sorted((r["writer"], r["class"])
2780
+ for r in resolved_rows(fx_declaration(), fx_env()))))
2781
+ equals("and that set is not empty", json.dumps(bool(doc["resolved"])), "true")
2782
+ equals("and it carries the release's scope with the decision that set it, so a reader of the "
2783
+ "manifest alone can say which writers this release may not invoke",
2784
+ json.dumps([doc["release_scope"]["scope"], doc["release_scope"]["decision"],
2785
+ len(doc["release_scope"]["uninvoked"])]),
2786
+ json.dumps(["release_1", "D-20261112-2cf1c4",
2787
+ len([r for r in doc["resolved"]
2788
+ if r.get("certification") == RELEASE_1_UNINVOKED])]))
2789
+ control("and the overrides the run must set", json.dumps(doc["overrides_required"]),
2790
+ "AGENT_BIOS_SESSION_DISTILL_STATE")
2791
+ # `inside` is None where there is nothing to confine — a writer this install does not have, and
2792
+ # a forward declaration whose file does not exist. Those rows carry their own state and are not
2793
+ # read as escapes; `False` is an escape and is what this asks about.
2794
+ clean("every row in the written manifest carries a named certification, so a later stage reads "
2795
+ "a state rather than inferring one from a missing field",
2796
+ [r["writer"] for r in doc["resolved"] if not r.get("certification")])
2797
+ equals("and the states are exactly the declared vocabulary, with none invented and none left "
2798
+ "to be inferred from an absent field — at the release's scope `computed` does not "
2799
+ "appear, because the only writer with a computed root is one release 1 never invokes",
2800
+ json.dumps(sorted({str(r.get("certification")) for r in doc["resolved"]})),
2801
+ '["argument", "forward", "not_invoked_in_release_1", "read_not_written"]')
2802
+ equals("and at the WIDER scope the same rows are certified rather than named, so the release "
2803
+ "narrows what S11 may invoke without retiring the confinement that judges the rest "
2804
+ "(this control and the one above were the same assertion written twice until round 3; "
2805
+ "they now ask the two scopes)",
2806
+ json.dumps(sorted({str(r.get("certification")) for r
2807
+ in resolved_rows(fx_declaration(), fx_env(), scope="all")})),
2808
+ '["argument", "computed", "forward", "given", "read_not_written"]')
2809
+ clean("with every row that HAS a path inside its root",
2810
+ [r["writer"] for r in doc["resolved"] if r["inside"] is False])
2811
+ equals("and the rows with nothing to confine say which they are, by a named state, rather "
2812
+ "than reading as escapes or as certified",
2813
+ json.dumps(sorted({str(r.get("certification") or r.get("not_installed"))
2814
+ for r in doc["resolved"] if r["inside"] is None})),
2815
+ '["forward", "not_invoked_in_release_1", "read_not_written"]')
2816
+ control("a document over an environment the caller claims and the run does not produce is "
2817
+ "refused instead of written — asked of the produced MAPPING, so the narrowing that made "
2818
+ "release 1's only override-rooted row a read did not take the check with it",
2819
+ refusal(lambda: document(fx_declaration(),
2820
+ fx_env(HOME=f"{root}-other/home"))),
2821
+ "ENVIRONMENT_CLAIM_DIFFERS")
2822
+ control("and so is one over a mutated table, so the manifest cannot be written from a broken "
2823
+ "inventory",
2824
+ with_table(lambda t: t.__setitem__("writers", []),
2825
+ lambda: refusal(lambda: document(fx_declaration(), fx_env()))),
2826
+ "WRITER_SET_EMPTY")
2827
+
2828
+ held_root = pathlib.Path(tempfile.mkdtemp(prefix="dest-", dir="/tmp"))
2829
+ try:
2830
+ run_dir = held_root / "r1"
2831
+ declare.create(run_dir, fx_declaration())
2832
+ declaration = records.read_json(run_dir / "run.json")
2833
+ try:
2834
+ _stage, written = write(run_dir, declaration, fx_env())
2835
+ except Refused as exc:
2836
+ written = {"problem": str(exc)}
2837
+ control("the manifest is written inside the run", str((run_dir / OUTPUT).is_file()), "True")
2838
+ clean("and holds what the document held",
2839
+ [] if (run_dir / OUTPUT).is_file()
2840
+ and records.read_json(run_dir / OUTPUT).get("resolved") == written.get("resolved")
2841
+ else [f"{written}"])
2842
+ # Guarded for the same reason as the document above: when the manifest refuses, there is no
2843
+ # stage record to read, and reading it kills the suite instead of letting the controls below
2844
+ # name the refusal.
2845
+ record = guarded(lambda: records.read_json(records.record_path(run_dir, "S11")))
2846
+ control("registered with the stage, so a later stage can read its staleness",
2847
+ json.dumps([o.get("artifact") for o in
2848
+ ((record.get("parts") or {}).get("destinations") or {}).get("outputs") or []])
2849
+ if isinstance(record, dict) else str(record)[:200], OUTPUT)
2850
+ # Nothing is written when anything refuses: the escape case must leave no manifest at all.
2851
+ other = held_root / "r2"
2852
+ declare.create(other, fx_declaration())
2853
+ said = refusal(lambda: write(other, declaration, fx_env(HOME=f"{root}-other/home")))
2854
+ control("a refused resolution writes nothing", said, "ENVIRONMENT_CLAIM_DIFFERS")
2855
+ clean("not even an empty manifest, and no stage record either",
2856
+ [name for name in (OUTPUT, "records") if (other / name).exists() and name == OUTPUT]
2857
+ + ([f"an S11 record exists"] if records.record_path(other, "S11").exists() else []))
2858
+ clean("and the escape target itself was never touched: it is a fixture path and has no file",
2859
+ [] if not pathlib.Path(f"{root}-other/home").exists()
2860
+ else [f"{root}-other/home exists"])
2861
+ finally:
2862
+ shutil.rmtree(held_root, ignore_errors=True)
2863
+
2864
+ # This module performs no effect, which is the whole reason it is the first commit. Asserted on
2865
+ # its own source — over the RUNTIME code only, since the self-test builds fixtures — and the
2866
+ # scope is now a real scope rather than an accident. Three corrections, each one a way the old
2867
+ # check could be walked past:
2868
+ #
2869
+ # * it read the whole file, so the only thing keeping it green was that the fixture code used
2870
+ # ALIASED imports (`import os as _os`): removing the aliases, which `dispatch.py`'s source
2871
+ # rule demands, made the check fire on fixtures. A check whose silence depends on a rename is
2872
+ # not a check, and the review of this unit names the same blindness.
2873
+ # * an alias is now refused outright in the runtime code, by comparing the module's own import
2874
+ # bindings against the watched names: `import os as _o` then `_o.system(...)` passed.
2875
+ # * `getattr(os, "system")(...)` passed too, because the call's function is a `getattr` node
2876
+ # whose unparse starts with neither `os` nor `subprocess`.
2877
+ import ast
2878
+
2879
+ effects_in = effect_audit # the module's own function, not a second copy here
2880
+ own_source = pathlib.Path(__file__).read_text(encoding="utf-8")
2881
+ spawners = effects_in(own_source)
2882
+ control("the no-effects check fires on a PLAIN call",
2883
+ "; ".join(effects_in("import os\ndef f():\n os.system('x')\n")), "os.system")
2884
+ control("and on an ALIASED import, which is what kept the old check green",
2885
+ "; ".join(effects_in("import os as _o\ndef f():\n _o.system('x')\n")),
2886
+ "os.system")
2887
+ control("and names the alias itself, since the rename is the hiding place",
2888
+ "; ".join(effects_in("import subprocess as sp\n")),
2889
+ "import subprocess as sp")
2890
+ control("and on a getattr form, which the review of this unit named",
2891
+ "; ".join(effects_in("import os\ndef f():\n getattr(os, 'system')('x')\n")),
2892
+ "getattr(os, 'system')")
2893
+ # Round 2: five shapes the audit passed. Each is the real form, not a near miss.
2894
+ control("and on `__import__`, whose call names no watched module at its first component",
2895
+ "; ".join(effects_in("def f():\n __import__('os').system('x')\n")),
2896
+ "__import__ reaches a module this audit cannot name")
2897
+ control("and on importlib, for the same reason",
2898
+ "; ".join(effects_in("import importlib\ndef f():\n"
2899
+ " importlib.import_module('os').system('x')\n")),
2900
+ "importlib.import_module reaches a module this audit cannot name")
2901
+ control("and on a filesystem write that names no module at all",
2902
+ "; ".join(effects_in("import pathlib\ndef f():\n"
2903
+ " pathlib.Path('a').write_text('x')\n")),
2904
+ "pathlib.Path('a').write_text")
2905
+ control("and on an open for writing, by its mode",
2906
+ "; ".join(effects_in("def f():\n open('a', 'w').close()\n")),
2907
+ "open(mode='w')")
2908
+ control("and on an open whose mode this audit cannot read, rather than assuming a read",
2909
+ "; ".join(effects_in("def f(m):\n open('a', m).close()\n")),
2910
+ "a mode this audit cannot read")
2911
+ control("an effect in `main` is reported, and `main` is a real entry point: "
2912
+ "`python3 runlib/destinations.py` runs it",
2913
+ "; ".join(effects_in("import os\ndef main(argv):\n os.system('x')\n")),
2914
+ "os.system (in main)")
2915
+ control("and so is one in a `self_test` a runtime function calls outright",
2916
+ "; ".join(effects_in("import os\ndef self_test():\n os.symlink('a', 'b')\n"
2917
+ "def run():\n return self_test()\n")),
2918
+ "os.symlink (in self_test)")
2919
+ # Round 4: a class BODY runs at definition time, and a guard the audit cannot prove is not a
2920
+ # guard.
2921
+ control("a statement in a class BODY is runtime code — it runs at definition time and there is "
2922
+ "no function to reach it through",
2923
+ "; ".join(effects_in("class K:\n open('/outside', 'w')\n"
2924
+ " def m(self):\n pass\n")),
2925
+ "open(mode='w') (in K)")
2926
+ control("and it is reported under the class's own name, so the reader knows where to look",
2927
+ "; ".join(effects_in("class Held:\n import os\n os.system('x')\n")),
2928
+ "(in Held)")
2929
+ control("a compound test mentioning the flag is NOT a self-test guard, so both halves are "
2930
+ "scanned: trusting it skipped real runtime code",
2931
+ "; ".join(effects_in("import sys\ndef main():\n"
2932
+ " if '--self-test' not in sys.argv and True:\n"
2933
+ " open('/x', 'w')\n")),
2934
+ "open(mode='w') (in main)")
2935
+ control("and so is a membership test on something other than argv, by the same rule",
2936
+ "; ".join(effects_in("def main(held):\n"
2937
+ " if '--self-test' in held.flags():\n"
2938
+ " open('/x', 'w')\n")),
2939
+ "open(mode='w') (in main)")
2940
+ equals("the two predicates the audit DOES prove are the plain membership tests, and they are "
2941
+ "read in opposite directions",
2942
+ json.dumps([_self_test_branch(ast.parse(
2943
+ "if '--self-test' in sys.argv:\n pass\n").body[0]),
2944
+ _self_test_branch(ast.parse(
2945
+ "if '--self-test' not in sys.argv:\n pass\n").body[0]),
2946
+ _self_test_branch(ast.parse(
2947
+ "if '--self-test' not in sys.argv and True:\n pass\n").body[0])]),
2948
+ json.dumps(["orelse", "body", None]))
2949
+ clean("while a `self_test` reached only through the flag's own branch is fixtures, which is "
2950
+ "reachability deciding the exclusion rather than the name",
2951
+ effects_in("import os\ndef self_test():\n os.symlink('a', 'b')\n"
2952
+ "def main(argv):\n"
2953
+ " if '--self-test' in argv:\n return self_test()\n return 0\n"))
2954
+ clean("while the allowed path helpers are not effects",
2955
+ effects_in("import os\ndef f():\n return os.path.normpath('a')\n"))
2956
+ clean("and a read is not a write",
2957
+ effects_in("def f():\n return open('a').read()\n"))
2958
+ # An audit that scanned nothing reports nothing: the scope is asserted, not assumed.
2959
+ # A class's methods are code, and a branch whose test is NEGATED is the runtime half.
2960
+ control("an effect in a class METHOD the reachable code names is reported, with the method",
2961
+ "; ".join(effects_in("import os\nclass Writer:\n def go(self):\n"
2962
+ " os.symlink('a', 'b')\n"
2963
+ "def main():\n return Writer().go()\n")),
2964
+ "os.symlink (in Writer.go)")
2965
+ clean("while a class nothing reachable names is out of scope, so the rule is reachability and "
2966
+ "not 'every method everywhere'",
2967
+ effects_in("import os\nclass Writer:\n def go(self):\n"
2968
+ " os.symlink('a', 'b')\n"
2969
+ "def main():\n return 1\n"))
2970
+ equals("and the method is in the scanned scope rather than merely reachable, which is the half "
2971
+ "that mattered: the effect sits in the body",
2972
+ json.dumps(effect_scope("import os\nclass Writer:\n def go(self):\n"
2973
+ " os.symlink('a', 'b')\n"
2974
+ "def main():\n return Writer().go()\n")),
2975
+ '["<module>", "Writer.go", "main"]')
2976
+ control("an effect behind `if \'--self-test\' NOT in argv` is reported: that branch is the "
2977
+ "runtime half, and the skip followed the wrong one",
2978
+ "; ".join(effects_in("import os, sys\ndef run():\n"
2979
+ " if '--self-test' not in sys.argv:\n"
2980
+ " os.symlink('a', 'b')\n")),
2981
+ "os.symlink (in run)")
2982
+ clean("while the flag's own branch is still fixtures, which is what the skip is for",
2983
+ effects_in("import os, sys\ndef run():\n if '--self-test' in sys.argv:\n"
2984
+ " os.symlink('a', 'b')\n"))
2985
+ control("and the half NOT guarded by the flag is scanned either way round",
2986
+ "; ".join(effects_in("import os, sys\ndef run():\n"
2987
+ " if '--self-test' in sys.argv:\n pass\n"
2988
+ " else:\n os.symlink('a', 'b')\n")),
2989
+ "os.symlink (in run)")
2990
+ # Round 5: the flag must be the flag, and a definition executes more than its body.
2991
+ equals("a guard on a flag that merely CONTAINS `--self-test` guards nothing this audit knows",
2992
+ json.dumps(effects_in("def main(argv):\n if '--self-test-other' in argv:\n"
2993
+ " open('/outside', 'w')\n")),
2994
+ json.dumps(["open(mode='w') (in main)"]))
2995
+ equals("a class nested in a class runs its body at definition time",
2996
+ json.dumps(effects_in("class Outer:\n class Inner:\n"
2997
+ " open('/outside', 'w')\n")),
2998
+ json.dumps(["open(mode='w') (in Outer.Inner)"]))
2999
+ equals("a default argument runs when the method is DEFINED, called or not",
3000
+ json.dumps(effects_in("class Held:\n def never_called(self, x=open('/outside', 'w')):\n"
3001
+ " return x\n")),
3002
+ json.dumps(["open(mode='w') (in Held.never_called definition)"]))
3003
+ equals("a parameter annotation runs when the method is defined",
3004
+ json.dumps(effects_in("class Held:\n def never(self, x: open('/outside', 'w')):\n"
3005
+ " return x\n")),
3006
+ json.dumps(["open(mode='w') (in Held.never definition)"]))
3007
+ equals("and so does a return annotation",
3008
+ json.dumps(effects_in("class Held:\n def never(self) -> open('/outside', 'w'):\n"
3009
+ " return 1\n")),
3010
+ json.dumps(["open(mode='w') (in Held.never definition)"]))
3011
+ equals("so does a decorator on a top-level function nobody calls from the suite alone",
3012
+ json.dumps(effects_in("import os\n@os.system('x')\ndef self_test():\n pass\n")),
3013
+ json.dumps(["os.system (in self_test definition)"]))
3014
+ equals("and a class's bases",
3015
+ json.dumps(effects_in("import os\nclass Held(os.system('x')):\n pass\n")),
3016
+ json.dumps(["os.system (in Held definition)"]))
3017
+ # Membership, asserted as a membership rather than as a substring of a dumped list.
3018
+ equals("the audit scanned this module's own entry point",
3019
+ json.dumps("main" in effect_scope(own_source)), "true")
3020
+ equals("and its top level",
3021
+ json.dumps("<module>" in effect_scope(own_source)), "true")
3022
+ equals("and the resolution path a destination row is judged by",
3023
+ json.dumps("resolved_rows" in effect_scope(own_source)), "true")
3024
+ clean("this module runs nothing and spawns nothing: the code that confines writes cannot itself "
3025
+ "be a writer", spawners)
3026
+ # The dying-control wrapper, and the audit rule it needed. A suite split across two functions
3027
+ # is still the suite: `_self_test_body` is reached only from `self_test`, so it is test-only by
3028
+ # reachability and its fixture building is not a module effect.
3029
+ control("the suite's own body is out of the audit's scope, because the suite alone calls it",
3030
+ "out" if "_self_test_body" not in effect_scope(own_source) else "in", "out")
3031
+ equals("and the rule is reachability, not the name: a body a RUNTIME function calls is in",
3032
+ json.dumps(effect_scope("def self_test():\n pass\n"
3033
+ "def _self_test_body(f, r):\n pass\n"
3034
+ "def run():\n return _self_test_body([], [])\n")),
3035
+ '["<module>", "_self_test_body", "run"]')
3036
+ control("the wrapper prints the control that was in flight, so a suite that dies is not read "
3037
+ "as a rule nobody enforces",
3038
+ next((line.strip() for line in own_source.splitlines()
3039
+ if "the suite died after" in line), "<no such line>"),
3040
+ 'print(f"destinations --self-test [FAIL] the suite died after {held!r}: "')
3041
+ control("and it says INCOMPLETE rather than OK, since the controls after the death never ran",
3042
+ "yes" if "destinations --self-test: INCOMPLETE" in own_source else "no", "yes")
3043
+ control("and the only file it writes is its own manifest",
3044
+ ", ".join(sorted({ast.unparse(node.func)
3045
+ for node in ast.walk(ast.parse(own_source))
3046
+ if isinstance(node, ast.Call)
3047
+ and ast.unparse(node.func).startswith("records.write_")})),
3048
+ "records.write_json")
3049
+
3050
+ shutil.rmtree(fixture_checkout, ignore_errors=True)
3051
+ print(f"destinations --self-test: {'FAILED' if failures else 'OK'} ({len(ran)} controls: the "
3052
+ f"writer inventory held against its writers' own sources, OVERRIDE_MISSING before any "
3053
+ f"escape judgement, an escape under a second fixture root, the root itself and a "
3054
+ f"name-prefix sibling, traversal in both directions, and a refused resolution writing "
3055
+ f"nothing)")
3056
+ for name, detail in failures:
3057
+ print(f"destinations --self-test [FAIL] {name}: {detail}")
3058
+ return 1 if failures else 0
3059
+
3060
+
3061
+ def main(argv):
3062
+ if "--self-test" in argv:
3063
+ return self_test()
3064
+ print(json.dumps({"classes": list(CLASSES), "overrides_required": list(required_overrides()),
3065
+ "writers": [{"writer": r["writer"], "class": r["class"],
3066
+ "overrides": r.get("overrides") or []} for r in writers()]},
3067
+ indent=2))
3068
+ return 0
3069
+
3070
+
3071
+ if __name__ == "__main__":
3072
+ sys.exit(main(sys.argv[1:]))