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,2575 @@
1
+ #!/usr/bin/env python3
2
+ """Session distill driver: one subcommand per stage, one run directory per run.
3
+
4
+ distill.py declare --run-id ID --from DECLARATION.json S0: write run.json (declaration_seq 0)
5
+ distill.py declare --run-id ID --set PATH=VALUE ... edit it in place, until a stage has read it
6
+ distill.py declare --run-id ID --amend --reason TEXT --set PATH=VALUE ... [--scope S2,S3]
7
+ [--invalidates S1]
8
+ distill.py declare --self-test the declaration's controls
9
+ distill.py --self-test declare -> stage -> amend -> stage, on real files
10
+ distill.py census --run-id ID [--coverage PATH] S1: census.json and coverage.json into the run directory
11
+ distill.py inventory --run-id ID [--pin HOST:SESSION] S2: inventory/<reference>.json, the units per layer
12
+ distill.py census --run-id ID --reconcile RESULTS.json S3's results folded back into the statuses and the coverage
13
+ distill.py views --run-id ID S2: the immutable copies, the redaction projection, the
14
+ windows, the search index and the evidence store
15
+ distill.py form --run-id ID --dry [--index ROWS.json] S4 up to its call: the barrier, the lifecycle intake and the
16
+ formation packet held to its bound; the record stays partial
17
+ distill.py form --run-id ID --cells DIR [--golden-plan PLAN.json] [--index ROWS.json]
18
+ S4: the one formation call, live (the token only as
19
+ CLAUDE_RUN_TOKEN_FILE) or, with a plan, golden
20
+ distill.py retrieve --run-id ID S5: the retrieval, the quotes verified again, the sessions and
21
+ the recurrence, into checks.json; no model is called
22
+ distill.py judge --run-id ID --dry S6 up to its calls: the judged population, every judgment
23
+ packet built and measured per judge; the record stays partial
24
+ distill.py judge --run-id ID --cells DIR [--golden-plan PLAN.json]
25
+ S6: each judged candidate to Judge A and Judge B
26
+ distill.py <stage command> --run-id ID S3, S6-S12: each runs (`--help` per command); S8 test refuses
27
+
28
+ A run lives in `<run root>/<run-id>/`: `run.json`, `amendments.jsonl`,
29
+ `stages/<stage>/record.json`, and per-call directories. The run root is `--out`, or, unset, the
30
+ XDG state directory `default_out()` resolves. A run root inside the checkout is refused (`inventory` protects the
31
+ checkout, PROTECTED_OVERLAP), so a checkout leaves `--out` unset or names a directory outside every protected root,
32
+ as the runbook says. The declaration, its amendments and the stage records are
33
+ `runlib/declare.py` and `runlib/records.py`; the
34
+ record schemas every stage keeps (claim, evidence, expected observation) are
35
+ `schemas/*.schema.json`, loaded through `runlib/claims.py`; the declaration's own structure is
36
+ `schemas/run.schema.json`. The census (S1) is `runlib/census.py`, over the readers of `runlib/sources.py`,
37
+ `runlib/lineage.py` and the coverage state of `runlib/coverage.py`. The views (S2) are `runlib/views.py`,
38
+ over `runlib/redaction.py`, `runlib/search.py` and the evidence store of `runlib/evidence.py`. Formation (S4) is
39
+ `runlib/stage_form.py`, over the lifecycle intake of `runlib/lifecycle_intake.py`. Retrieval and its checks (S5) are
40
+ `runlib/stage_retrieve.py`, over the derivations' tables read by `runlib/derive.py`.
41
+ Design: §3, §4, §4.1, §5.1-§5.5, §6.2, §7.1, §7.4, §9.
42
+ """
43
+ import argparse
44
+ import ast
45
+ import contextlib
46
+ import inspect
47
+ import io
48
+ import json
49
+ import os
50
+ import pathlib
51
+ import re
52
+ import shutil
53
+ import signal
54
+ import subprocess
55
+ import sys
56
+ import tempfile
57
+ import time
58
+ import types
59
+
60
+ # Before the command's module graph is imported, not inside the functions that load modules by
61
+ # path: `runlib.projection` loads `learn/redact.py` at import, and a cache write lands beside the
62
+ # file it caches — in the checkout, or in a frozen copy this run is about to hash (GB#7).
63
+ sys.dont_write_bytecode = True
64
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
65
+
66
+ def _diagnostic_home():
67
+ """The owner home a diagnostic masks, resolved without ever failing.
68
+
69
+ This runs at import, before either startup boundary, and `pathlib.Path.home()` RAISES
70
+ `RuntimeError` when `$HOME` is unset and the account has no password-database entry — so a
71
+ machine in that state could not run `--out DIR`, or `--help`, or anything at all (review Y r2
72
+ #3). `None` is what every consumer of this value already takes as its default (`entry.say`,
73
+ `entry.failed`, `inventory.overlap_problems`, `projection.project`, which expands `~` itself),
74
+ so an unresolvable home masks exactly what the floor's own default masks and costs no startup."""
75
+ try:
76
+ return str(pathlib.Path.home())
77
+ except (RuntimeError, OSError, KeyError):
78
+ return None
79
+
80
+
81
+ HOME = _diagnostic_home()
82
+ # The bootstrap, and the only thing in this file that runs before the boundary exists. It is
83
+ # stdlib only and its line carries NO path, because what failed is the very code that would have
84
+ # projected one: `from runlib import entry` stood outside every boundary this command has, so an
85
+ # `entry` that cannot import left a traceback on stderr with the importer's absolute paths in it
86
+ # (r3 #2). `BaseException`, because a module can exit during import; a `SystemExit` already carries
87
+ # the code its raiser chose, so it is re-raised rather than relabelled.
88
+ STARTUP_UNAVAILABLE = ("COMMAND_FAILED startup: session distill could not load the boundary that "
89
+ "describes its own failures, so it says nothing further about this one")
90
+ STARTUP_UNAVAILABLE_CODE = 3
91
+
92
+ # The boundary every entry point of this command runs inside, and the one owner of the fixed line
93
+ # printed when even the floor cannot load. It imports nothing but the standard library and reaches
94
+ # the floor lazily, so importing it is unlikely to be the failure it is there to describe — and the
95
+ # bootstrap above answers for the case where it is anyway (R2#2, R2#3, r3 #2).
96
+ try:
97
+ from runlib import entry
98
+ except SystemExit:
99
+ raise
100
+ except BaseException:
101
+ # Imported as a module, the caller owns the failure and gets the exception. Run as a command,
102
+ # there is nothing left to describe it with, so the fixed line stands in for the whole floor.
103
+ if __name__ != "__main__":
104
+ raise
105
+ sys.stderr.write(STARTUP_UNAVAILABLE + "\n")
106
+ raise SystemExit(STARTUP_UNAVAILABLE_CODE)
107
+ STARTUP_WITHHELD = entry.WITHHELD
108
+
109
+ try:
110
+ from runlib import census, coverage, declare, inventory, projection, records, sources, stage_delivery, \
111
+ stage_form, stage_judge, \
112
+ stage_adjudicate, stage_apply, stage_approvals, stage_close, stage_confirm, stage_propose, stage_render, stage_retrieve, \
113
+ stage_review_korean, stage_review_proposals, \
114
+ stagelock, views
115
+ from runlib import ledger as ledger_lib
116
+ from runlib.records import Refused
117
+ except BaseException as _startup_exc: # SystemExit included: `validate` exits at import time
118
+ # The imports used to stand OUTSIDE every boundary this command has: `runlib.validate` exits
119
+ # during import when its jsonschema pin is unreadable, interpolating the absolute pin path, and
120
+ # that path reached stderr unprojected (R1#3). The floor is asked for a projection if it loaded;
121
+ # if the floor itself is what failed, the fixed line stands instead.
122
+ sys.exit(entry.failed(_startup_exc, HOME, label="STARTUP_FAILED", code=2))
123
+
124
+ def _password_home():
125
+ """This process's own home directory, as the password database states it.
126
+
127
+ A named seam rather than an inline lookup, deliberately: it is the one home a control cannot
128
+ override, so the relative-HOME control below reached the REAL account home and created a run
129
+ under `~/.local/state/agent-bios/distill/runs/` while a commit hook was running (review Y r2
130
+ #1). A control states the account home it means by replacing this function; production never
131
+ does, and the resolver it feeds is exercised against the real database by a control of its own."""
132
+ import pwd
133
+ return pwd.getpwuid(os.getuid()).pw_dir
134
+
135
+
136
+ def _account_home():
137
+ """The account's own home directory, which does not come from the environment.
138
+
139
+ `pathlib.Path.home()` reads `$HOME`, so it answered `relative-home` for a relative `$HOME` and
140
+ the "ignored" value came straight back as the base — the default then resolved against the
141
+ working directory and a control of mine wrote a run into this checkout. The password database
142
+ is the authority that cannot be relative. If it cannot be read, no default is better than one
143
+ resolved against whatever directory the caller happens to stand in."""
144
+ try:
145
+ home = _password_home()
146
+ except Exception: # no pwd (Windows), or no entry for this uid
147
+ home = None
148
+ if home and pathlib.PurePath(home).is_absolute():
149
+ return pathlib.Path(home)
150
+ raise Refused("DEFAULT_OUT_UNRESOLVED: this account has no absolute home directory, so the "
151
+ "default run root cannot be resolved; pass --out DIR")
152
+
153
+
154
+ def default_out(environ=None, home=None):
155
+ """The root of the run directories when the caller names none.
156
+
157
+ `${XDG_STATE_HOME:-~/.local/state}/agent-bios/distill/runs`. Three things decide it:
158
+
159
+ * it is NOT inside the package. A run writes `run.json`, stage records and per-call directories;
160
+ writing them next to the code would put a user's work inside a tree the next install replaces.
161
+ * it is NOT inside the owner's state root either. That root — pins, receipts, the ledger — is one
162
+ of the roots `inventory.protected_roots` forbids writing into, because a run once wrote four
163
+ artifacts into it (R1#1), and the answer to this was not to carve an exception out of that
164
+ sentence.
165
+ * the XDG STATE directory, not the data directory: a run is regenerable output, while the data
166
+ directory holds what is the owner's.
167
+
168
+ A run root inside the checkout is REFUSED: `inventory.protected_roots` protects the checkout
169
+ unconditionally, so `--out session-distill/out/<...>` exits `PROTECTED_OVERLAP` before any
170
+ write. The runbook said to pass exactly that, and the stage it documents could not run (the
171
+ WP-22a review). Leave `--out` unset and take the resolved XDG state directory, or name a
172
+ directory outside every protected root.
173
+
174
+ Both inputs are taken only when they are ABSOLUTE. A relative `XDG_STATE_HOME` — `.` is the
175
+ one a shell hands over by accident — resolved against the working directory, which during
176
+ development is this checkout, so the default landed inside the package it must stay out of.
177
+ A relative value is therefore ignored, loudly, rather than honoured or refused: the caller gets
178
+ the documented default and a line saying why. The same rule for `HOME`, whose relative value
179
+ `pathlib.Path.home()` would not have produced either.
180
+
181
+ Where the resolved default lands is a second question, and it is not this function's: nothing
182
+ here can know the owner's roots. `destination_of` judges it before any lock or write.
183
+ """
184
+ environ = os.environ if environ is None else environ
185
+ notes = []
186
+ # XDG FIRST, and the home only when XDG gives no absolute base. An absolute `XDG_STATE_HOME`
187
+ # determines the whole answer, so resolving a home it does not need let an unreadable account
188
+ # entry refuse a destination that was already decided (review Y r2 #4).
189
+ raw_base = environ.get("XDG_STATE_HOME")
190
+ if raw_base is not None and raw_base != "" and not pathlib.PurePath(raw_base).is_absolute():
191
+ notes.append(f"XDG_STATE_HOME={raw_base!r} is relative and is ignored for the default run "
192
+ f"root; the XDG base-directory contract names absolute paths only")
193
+ raw_base = None
194
+ base = pathlib.Path(raw_base) if raw_base else None
195
+ if base is None:
196
+ raw_home = home if home is not None else environ.get("HOME")
197
+ if raw_home is not None and not pathlib.PurePath(str(raw_home)).is_absolute():
198
+ notes.append(f"HOME={str(raw_home)!r} is relative and is ignored for the default run root")
199
+ raw_home = None
200
+ base = (pathlib.Path(raw_home) if raw_home else _account_home()) / ".local" / "state"
201
+ for note in notes:
202
+ say(f"DEFAULT_OUT_INPUT_IGNORED {note}", sys.stderr)
203
+ return pathlib.Path(base).expanduser() / "agent-bios" / "distill" / "runs"
204
+
205
+ # The inline programs this file's own suite runs, as module-level constants rather than locals: a
206
+ # `python -c` program is admitted by DECLARATION (`runlib/dispatch.py` `INLINE_PROGRAMS`, which pins
207
+ # each one's sha256), and a local's text is only visible where it is built, so a local cannot be
208
+ # declared or pinned at all (r3 S3).
209
+ #
210
+ # A TERM-ignoring descendant of a child that exits on TERM: the bound must end the TREE, and a
211
+ # descendant holding the pipe is what kept a runaway filling the disk (r3 #1). Finite on its own.
212
+ # Both sleeps outlast the whole bound — the timeout, `GROUP_DRAIN` and the SIGKILL rounds — so
213
+ # within the control's window only the kill can end either process. A natural lifetime shorter than
214
+ # that bound made the control pass over a removed kill: the descendant was gone because its three
215
+ # seconds were up (r4 R2). Finite all the same, so a cleanup defect ends on its own.
216
+ IGNORES_TERM = ("import signal, subprocess, sys, time\n"
217
+ "g = subprocess.Popen([sys.executable, '-c', 'import signal, time; "
218
+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); time.sleep(90)'])\n"
219
+ "print('DESCENDANT', g.pid, flush=True)\n"
220
+ "signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))\n"
221
+ "time.sleep(90)\n")
222
+ # A child that outlives its bound and nothing else, for the group-ownership control.
223
+ SLEEPS_BRIEFLY = "import time; time.sleep(3)\n"
224
+ # The ordinary shape: the leader exits first while a descendant holds the pipe for a moment.
225
+ LEADER_FIRST = ("import subprocess, sys\n"
226
+ "subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(1)'])\n"
227
+ "print('LEADER DONE', flush=True)\n")
228
+ RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")
229
+
230
+
231
+ def say(text, stream=None):
232
+ """One line this command publishes, through the floor's own entry point (GC#6).
233
+
234
+ A diagnostic is an artifact: a person reads it and whatever captured the terminal keeps it, so
235
+ printing a line the write boundary would refuse is the same leak by another route. Everything
236
+ this driver prints — a report, a refusal, a stage that is not implemented, an argument the parser
237
+ did not understand — leaves through here. `--bad api_key=shortpass` and
238
+ `--run-id api_key=shortpass` each repeated the secret on stderr before a line of the command ran,
239
+ because `parse_args` and `print(str(exc))` stood outside every boundary this run has.
240
+
241
+ `runlib.entry` holds the line and the floor behind it, so the driver and `runlib/inventory.py`'s
242
+ own entry point publish through the same code rather than through two copies of it."""
243
+ entry.say(text, stream if stream is not None else sys.stdout, HOME)
244
+
245
+
246
+ class Parser(argparse.ArgumentParser):
247
+ """`argparse`, with every message it prints passing the floor first.
248
+
249
+ `error()` echoes the argument it did not understand and `print_usage`/`print_help` echo the
250
+ metavars; all three go through `_print_message`, which is the one place to put the boundary."""
251
+
252
+ def _print_message(self, message, file=None):
253
+ if message:
254
+ super()._print_message(projection.diagnostic(message, HOME), file)
255
+
256
+ # Subcommand -> the stage it runs (design §4). `declare` is S0 and has no stage record.
257
+ STAGE_COMMANDS = {
258
+ "census": "S1", "views": "S2", "inventory": "S2", "read": "S3", "form": "S4", "retrieve": "S5",
259
+ "deliver": "S5b", "judge": "S6", "propose": "S7", "review-proposals": "S7b", "test": "S8", "render": "S9",
260
+ "review-korean": "S9b", "parse-decisions": "S10", "adjudicate": "S10", "confirm": "S10b",
261
+ "apply": "S11", "close": "S12",
262
+ }
263
+
264
+
265
+ def protection_for(args, repo):
266
+ """Every root this invocation must not write into, assembled as S2 assembles it.
267
+
268
+ `configured_roots` resolves the owner's roots whether or not this run reads them, and the
269
+ checkout is always one of the protected projects — that is `inventory`'s rule and this reuses
270
+ it rather than keeping a second copy."""
271
+ declared_state, declared_user = inventory.configured_roots(
272
+ getattr(args, "state_root", None), getattr(args, "user_root", None))
273
+ projects = inventory.project_identities([str(repo), *(getattr(args, "project", None) or [])])
274
+ native = {"projects": {identity["path"]: pathlib.Path(identity["path"])
275
+ for identity in projects.values()}}
276
+ return inventory.protected_roots(declared_state, declared_user, native, checkout=repo, repo=repo)
277
+
278
+
279
+ def destination_of(args):
280
+ """`--out` when the caller named one, else the default — and whether it was the default.
281
+
282
+ A DEFAULT destination is judged here, before a run id is checked and long before a lock or a
283
+ directory: `default_out` cannot know the owner's roots, and an environment can put the XDG
284
+ state directory anywhere, including inside the package or inside the data root that holds the
285
+ pins and the receipts. `declare` had no protection of its own — only `inventory` checked — so
286
+ `XDG_STATE_HOME=$HOME/.local/share` was enough to write a run into the owner's state (review Y
287
+ #2). An explicit `--out` keeps its own per-command verdict (`PROTECTED_OVERLAP`); this one is
288
+ about the path the driver chooses for the caller."""
289
+ if getattr(args, "out", None):
290
+ return str(args.out), False
291
+ repo = pathlib.Path(__file__).resolve().parents[1]
292
+ chosen = default_out()
293
+ problems = inventory.overlap_problems([chosen], protection_for(args, repo), home=HOME)
294
+ if problems:
295
+ raise Refused(
296
+ f"DEFAULT_OUT_PROTECTED {chosen}: the default run root resolves inside a root this "
297
+ f"driver must not write into ({'; '.join(problems)}). Nothing was written. Pass "
298
+ f"--out DIR to name a destination outside the owner's roots and outside the package.")
299
+ return str(chosen), True
300
+
301
+
302
+ def run_dir_of(args):
303
+ """`--out`/`<run-id>`: the run id is one path component, and the directory it names resolves
304
+ to a place beneath `--out`. Nothing — no lock, no directory — is created before this holds."""
305
+ out, _from_default = destination_of(args)
306
+ args.out = out
307
+ if not RUN_ID.fullmatch(args.run_id):
308
+ raise Refused(f"RUN_ID_INVALID {args.run_id!r}: a run id is one path component of letters, digits, '.', '_' and '-'")
309
+ run_dir = records.contained(out, args.run_id)
310
+ if run_dir is None:
311
+ raise Refused(f"RUN_DIR_ESCAPE {args.run_id!r}: {pathlib.Path(out) / args.run_id} resolves outside {out}")
312
+ # a run directory inside the instructions makes its locks, records and outputs part of them (release 1's
313
+ # confirmation review, round 2 F2): refused for every command, before any lock or directory
314
+ outside_instructions(run_dir, "RUN_DIR_IN_INSTRUCTIONS", "a run directory", "--out")
315
+ return run_dir
316
+
317
+
318
+ def outside_instructions(path, code, what, flag):
319
+ """Refuse a destination directory the instructions hold (`inventory.instructions_place`: a checkout's trees and
320
+ the hosts' homes as configured), before anything is written beneath it: every file there would be shipped or
321
+ installed as instructions. The one admission for a run directory and for a standalone inventory's `--to`
322
+ (release 1's third confirmation review, F2 and F3). It reads the path as it resolves now; a parent another
323
+ process replaces afterwards is not held (the record of that review)."""
324
+ where = inventory.instructions_place(pathlib.Path(path).resolve())
325
+ if where:
326
+ raise Refused(f"{code} {path}: {what} is not placed inside the instructions, and this one is {where}. "
327
+ f"Nothing was written; pass {flag} DIR outside them")
328
+
329
+
330
+ def split_csv(text):
331
+ return [item for item in (text or "").split(",") if item]
332
+
333
+
334
+ def assignments_of(args):
335
+ pairs = []
336
+ for item in args.set or []:
337
+ path, equals, value = item.partition("=")
338
+ if not (path and equals):
339
+ raise Refused(f"DECLARATION_INVALID --set {item!r}: expected PATH=VALUE")
340
+ pairs.append((path, declare.parse_value(value)))
341
+ return pairs
342
+
343
+
344
+ def cmd_declare(args):
345
+ if args.self_test:
346
+ return declare.self_test()
347
+ if not args.run_id:
348
+ raise Refused("DECLARATION_INVALID --run-id: declare needs the run it declares")
349
+ run_dir = run_dir_of(args)
350
+ if args.from_file and (args.amend or args.set):
351
+ raise Refused("DECLARATION_INVALID --from: a new declaration takes no --set or --amend")
352
+ if args.amend:
353
+ amendment = declare.amend(run_dir, assignments_of(args), args.reason or "", split_csv(args.scope),
354
+ split_csv(args.invalidates))
355
+ say(f"amended {run_dir}: declaration_seq {amendment['seq']}, invalidates {amendment['invalidates']}")
356
+ elif args.from_file:
357
+ run = declare.create(run_dir, json.loads(pathlib.Path(args.from_file).read_text(encoding="utf-8")))
358
+ say(f"declared {run_dir}: declaration_seq {run['declaration_seq']}")
359
+ elif args.set:
360
+ declare.set_fields(run_dir, assignments_of(args))
361
+ say(f"set {len(args.set)} field(s) in {run_dir}/run.json")
362
+ else:
363
+ raise Refused("DECLARATION_INVALID declare: give --from, --set, --amend or --self-test")
364
+ return 0
365
+
366
+
367
+ def cmd_census(args):
368
+ run_dir = run_dir_of(args)
369
+ if args.reconcile:
370
+ before = census.load(run_dir)
371
+ state = coverage.load(run_dir / "coverage.json")[0]
372
+ results = json.loads(pathlib.Path(args.reconcile).read_text(encoding="utf-8"))
373
+ done, after, flags = census.reconcile(before, state, results, before["kind"])
374
+ records.write_text(run_dir, run_dir / "census.reconciled.json", census.dump(done))
375
+ records.write_json(run_dir, run_dir / "coverage.reconciled.json", after)
376
+ counts = census.window_counts(census.rows(done))
377
+ say(f"reconciled {run_dir}: accounted {flags['accounted']} ({counts['accounted']}/{counts['eligible']} sessions), "
378
+ f"fully read {flags['fully_read']} ({counts['fully_read']}/{counts['eligible']})")
379
+ return 0
380
+ say("\n".join(census.report_lines(census.run(run_dir, args.coverage, args.originators, args.jobs))))
381
+ return 0
382
+
383
+
384
+ def register_inventory_outputs(stage, manifest):
385
+ """Every artifact inventory's manifest lists, the shared inventories among them (step 0 S-22), as an
386
+ output of the stage, and the manifest itself, whose own digest lives here rather than in its own
387
+ list. The list is inventory's, never one of this driver's: a file it wrote and this did not name
388
+ would ship unseen."""
389
+ for artifact in manifest.get("artifacts") or []:
390
+ stage.output(artifact["path"])
391
+ stage.output("inventory/manifest.json")
392
+
393
+
394
+ def cmd_inventory(args):
395
+ """S2's inventory: `inventory/<reference>.json` for every reference point of design §6.1."""
396
+ out_dir = run_dir_of(args) if args.run_id else pathlib.Path(args.to or "")
397
+ if not args.run_id and not args.to:
398
+ raise Refused("INPUT_INVALID inventory: give --run-id, or --to DIR to write outside a run")
399
+ if not args.run_id:
400
+ # `--to` enters no run, so `run_dir_of` never judged it: another checkout's skill was a destination
401
+ outside_instructions(out_dir, "INVENTORY_TO_IN_INSTRUCTIONS", "an inventory", "--to")
402
+ repo = pathlib.Path(__file__).resolve().parents[1]
403
+ # Two questions, not one value. The roots are resolved for PROTECTION whatever this run reads,
404
+ # and `--no-state` decides only the reading pair. Setting both to None before the protected set
405
+ # was built made the flag that says "read nothing" also say "write anywhere" (R1#1).
406
+ declared_state, declared_user = inventory.configured_roots(args.state_root, args.user_root)
407
+ state_root = None if args.no_state else str(declared_state)
408
+ user_root = None if args.no_state else str(declared_user)
409
+ # A project is its canonical path. Keyed by basename, two checkouts both called `source` were
410
+ # one project, and one's memory entries were read as the other's (GA#4). A project root is a
411
+ # protected WRITE target: no native file is read, here or anywhere (the 1548 amendment §5).
412
+ #
413
+ # The checkout is ALWAYS one of them: `--project` adds roots to it and never replaces it. It
414
+ # arrived here as the default value of `--project`, so naming any project at all took the
415
+ # checkout out of the protected set and a destination inside it became writable (GC#0 through
416
+ # `--project`). `protected_roots` carries the same rule for every other caller.
417
+ projects = inventory.project_identities([str(repo), *(args.project or [])])
418
+ native = {"projects": {identity["path"]: pathlib.Path(identity["path"]) for identity in projects.values()}}
419
+ # The destination is judged before anything is locked, captured or recorded: a stage record is
420
+ # a write, and a write under a protected root must be refused before it happens (GB#0).
421
+ overlap = inventory.overlap_problems(
422
+ [out_dir], inventory.protected_roots(declared_state, declared_user, native,
423
+ checkout=repo, repo=repo),
424
+ home=HOME)
425
+ if overlap:
426
+ raise Refused("; ".join(overlap))
427
+ # A standalone `--to` enters no stage and reads no declaration, so a run's artifacts are not
428
+ # its to replace (GC#3 by another route).
429
+ if not args.run_id:
430
+ standalone = inventory.standalone_problems(out_dir, HOME)
431
+ if standalone:
432
+ raise Refused("; ".join(standalone))
433
+ # The ledger: what `--ledger` names, else the state root's own (`<state>/distill/ledger.json`).
434
+ # The checkout's ledger under `design/` is not a default any more — a packaged user has no such
435
+ # directory, and the runbook passes the path when a run is meant to read the owner's (WP-24).
436
+ ledger_path = ledger_lib.ledger_path(state_root, args.ledger)
437
+ ledger = records.read_json(ledger_path) if ledger_path and ledger_path.is_file() else None
438
+ head = subprocess.run(["git", "-C", str(repo), "rev-parse", "--short", "HEAD"],
439
+ capture_output=True, text=True)
440
+ # The transcripts come from the run's own census (S1), through its readers and bound to its
441
+ # record. Outside a run there is no census, and every native layer is `unknown` with that reason.
442
+ run_dir = out_dir if args.run_id else None
443
+
444
+ def produce(zstd=None):
445
+ return inventory.run(repo, state_root, user_root, out_dir, pin=args.pin, native_roots=native,
446
+ ledger=ledger, commit=(head.stdout.strip() or None), run_dir=run_dir,
447
+ zstd=zstd, declared_state=str(declared_state), declared_user=str(declared_user),
448
+ ledger_ref=(str(args.ledger) if args.ledger else None))
449
+
450
+ if args.run_id:
451
+ # S2 holds two producers; this is the inventory part, and views owns the other
452
+ # (records.STAGE_PARTS). The census is its S1 input, declared as `views.run` declares it, so
453
+ # a census changed after S1 recorded it is refused by name instead of read (#11).
454
+ with records.run_stage(out_dir, "S2", [{"artifact": inventory.CENSUS, "producer_stage": "S1"}],
455
+ part="inventory") as stage:
456
+ # A compressed transcript is read with the decoder the run DECLARES, taken the way
457
+ # `views.run` takes it: none was passed, so a zstd rollout could not be read here at all
458
+ # (#11). It is the declaration the stage was admitted against, never a read of run.json,
459
+ # which an amendment landing after the admission could have changed (X review of WP-08 r2).
460
+ manifest = produce(sources.declared(stage.declaration).get("zstd"))
461
+ register_inventory_outputs(stage, manifest)
462
+ # The stage record is a document this run wrote, so it answers the same question every
463
+ # other written document answers.
464
+ disclosed = inventory.stage_record_problems(out_dir, "S2", str(pathlib.Path.home()))
465
+ if disclosed:
466
+ raise Refused("; ".join(disclosed[:4]))
467
+ else:
468
+ manifest = produce()
469
+ say("\n".join(inventory.report_lines(manifest, HOME)))
470
+ return 0
471
+
472
+
473
+ def cmd_views(args):
474
+ say("\n".join(views.report_lines(views.run(run_dir_of(args)))))
475
+ return 0
476
+
477
+
478
+ def cmd_form(args):
479
+ """S4 (runlib/stage_form.py): dry, up to the call; otherwise its one call through a supervisor made before the stage
480
+ is entered, so a live run without its token is refused before anything is recorded."""
481
+ run_dir = run_dir_of(args)
482
+ index_rows = json.loads(pathlib.Path(args.index).read_text(encoding="utf-8")) if args.index else None
483
+ if args.dry:
484
+ if args.cells or args.golden_plan:
485
+ raise Refused("INPUT_INVALID form --dry: a dry run makes no call, so it takes no --cells or --golden-plan")
486
+ summary = stage_form.run(run_dir, None, dry=True, index_rows=index_rows,
487
+ ledger_ref=args.checkout_ledger)
488
+ else:
489
+ if not args.cells:
490
+ raise Refused("INPUT_INVALID form --cells: the formation call runs in a cell under a cell root; give --cells "
491
+ "DIR, or --dry to stop before the call")
492
+ summary = stage_form.run(run_dir, stage_form.supervisor(run_dir, args.cells, args.golden_plan),
493
+ index_rows=index_rows, ledger_ref=args.checkout_ledger)
494
+ say("\n".join(stage_form.report_lines(summary)))
495
+ return 0
496
+
497
+
498
+ def cmd_read(args):
499
+ """S3 (runlib/stage_read.py): dry, up to the calls; otherwise its window readings through a supervisor made before
500
+ the stage is entered, so a live run without its token is refused before anything is recorded."""
501
+ from runlib import stage_read
502
+ run_dir = run_dir_of(args)
503
+ if args.dry:
504
+ if args.cells or args.golden_plan:
505
+ raise Refused("INPUT_INVALID read --dry: a dry run makes no call, so it takes no --cells or --golden-plan")
506
+ summary = stage_read.run(run_dir, None, dry=True, ledger_ref=args.checkout_ledger)
507
+ say(f"S3 read (dry): no call made; the packets' measures are in {stage_read.DRY_RECORD}, and the stage's "
508
+ f"record is partial")
509
+ return 0
510
+ if not args.cells:
511
+ raise Refused("INPUT_INVALID read --cells: the reading calls run in cells under a cell root; give --cells DIR, "
512
+ "or --dry to stop before the calls")
513
+ if args.golden_plan is None and not os.environ.get("CLAUDE_RUN_TOKEN_FILE"):
514
+ raise Refused("TOKEN_FILE_UNSET S3: a live reading call's token reaches claude-run only as "
515
+ "CLAUDE_RUN_TOKEN_FILE, and this environment does not set it")
516
+ summary = stage_read.run(run_dir, stage_form.supervisor(run_dir, args.cells, args.golden_plan),
517
+ tranche=args.tranche, jobs=args.jobs, ledger_ref=args.checkout_ledger)
518
+ statuses = ", ".join(f"{count} {name}" for name, count in sorted((summary.get("statuses") or {}).items()))
519
+ say(f"S3 read: {len(summary.get('units') or {})} units ({statuses or 'none'}); window accounted="
520
+ f"{summary.get('accounted')}, fully_read={summary.get('fully_read')}; {summary.get('reused', 0)} readings "
521
+ f"reused from an earlier attempt; read.json and read-results.json are the stage's outputs")
522
+ return 0
523
+
524
+
525
+ def name_checkout_ledger(args):
526
+ """Set the module-level reference `lifecycle_intake.ledger_of` reads, from this caller's flag.
527
+
528
+ The hook the intake documents for an author-side caller: the stages that read the pinned ledger
529
+ take no parameter for it, and a driver that guessed the path would be reading whatever file the
530
+ guess lands on. Unset without the flag, so the stage is refused by name."""
531
+ if getattr(args, "checkout_ledger", None):
532
+ from runlib import lifecycle_intake
533
+ lifecycle_intake.CHECKOUT_LEDGER = args.checkout_ledger
534
+
535
+
536
+ def cmd_retrieve(args):
537
+ """S5 (runlib/stage_retrieve.py): code only, over S4's population."""
538
+ name_checkout_ledger(args)
539
+ say("\n".join(stage_retrieve.report_lines(stage_retrieve.run(run_dir_of(args)))))
540
+ return 0
541
+
542
+
543
+ def cmd_review_korean(args):
544
+ """S9b (runlib/stage_review_korean.py): the current review version's Korean, by its supervised calls or over the
545
+ reviews, regenerations and second reviews the caller supplies."""
546
+ run_dir = run_dir_of(args)
547
+ load = lambda path: records.read_json(pathlib.Path(path)) if path else None # noqa: E731
548
+ if args.reviews:
549
+ if args.cells or args.golden_plan:
550
+ raise Refused("INPUT_INVALID review-korean --reviews: reviews in hand make no call, so they take no "
551
+ "--cells or --golden-plan")
552
+ out = stage_review_korean.run(run_dir, load(args.reviews), load(args.regenerations), load(args.second))
553
+ else:
554
+ if not args.cells:
555
+ raise Refused("INPUT_INVALID review-korean --cells: the review calls run in cells under a cell root; give "
556
+ "--cells DIR, or --reviews PATH (and --regenerations, --second) for answers in hand")
557
+ out = stage_review_korean.run(
558
+ run_dir, supervisor=stage_review_korean.supervisor(run_dir, args.cells, args.golden_plan))
559
+ say(f"S9b review-korean: version {out['version']}: {out['reviewed']} reviewed, {out['regenerated']} regenerated, "
560
+ f"{out['marked']} marked, {out['unreviewed']} unreviewed, {out['returned']} returned"
561
+ + (f"; calls: {', '.join(f'{k} {v}' for k, v in out['calls'].items()) or 'none'} over {out['asked']} rows asked"
562
+ if "calls" in out else ""))
563
+ return 0
564
+
565
+
566
+ def cmd_adjudicate(args):
567
+ """S10's adjudicate part (runlib/stage_adjudicate.py): a committed parse's adjudications recomputed with the
568
+ owner's values, and the candidates they newly admit through S7 and S7b again - by the second pass's supervised
569
+ calls (--cells), or over the answers the caller supplies."""
570
+ load = lambda path: records.read_json(pathlib.Path(path)) if path else None # noqa: E731
571
+ run_dir = run_dir_of(args)
572
+ if (args.answers or args.reviews) and (args.cells or args.golden_plan):
573
+ raise Refused("INPUT_INVALID adjudicate --answers: answers in hand make no call, so they take no --cells or "
574
+ "--golden-plan")
575
+ supervisor = None
576
+ if args.cells:
577
+ supervisor = (stage_judge.supervisor(run_dir, args.cells, args.golden_plan) if args.golden_plan
578
+ else stage_propose.supervisor(run_dir, args.cells))
579
+ try:
580
+ out = stage_adjudicate.run(run_dir, args.version, load(args.answers), load(args.reviews),
581
+ supervisor=supervisor)
582
+ except Refused as exc:
583
+ if str(exc).startswith("CALL_NOT_WIRED"):
584
+ say(str(exc), sys.stderr)
585
+ return 2
586
+ raise
587
+ say(f"S10 adjudicate: version {out['version']}: {out['adjudicated']} adjudicated, {out['admitted']} newly admitted, "
588
+ f"{out['rejected']} rejected, {out['still_disputed']} still disputed"
589
+ + ("; resumed a run cut short" if out["resumed"] else ""))
590
+ return 0
591
+
592
+
593
+ def cmd_parse_decisions(args):
594
+ """S10's parse (runlib/stage_approvals.py): the owner's copy of a review version, held to the current rows, into
595
+ approvals.jsonl and adjudications.jsonl; a version is parsed once."""
596
+ out = stage_approvals.run(run_dir_of(args), args.version, args.copy)
597
+ say(f"S10 parse-decisions: version {out['version']} (current {out['current_version']}): {out['decided']} decided, "
598
+ f"{out['undecided']} undecided, {out['stale']} stale; {out['approval_rows']} approval rows, "
599
+ f"{out['adjudications']} adjudications; the review is {out['review_state']}"
600
+ + ("; resumed a parse cut short" if out["resumed"] else ""))
601
+
602
+
603
+ def cmd_confirm(args):
604
+ """S10b (runlib/stage_confirm.py): without --decide, the final set S10's approvals leave, built as the next
605
+ confirmation version for the owner to read and decide; with it, the owner's 확인 line in that version's copy, which
606
+ confirms the set (confirmation.json) or returns it."""
607
+ run_dir = run_dir_of(args)
608
+ if not args.decide:
609
+ out = stage_confirm.build(run_dir)
610
+ say(f"S10b confirm: version {out['version']} built, {out['F']} in F, {out['ledger_only']} ledger-only, "
611
+ f"{out['apart']} apart; " + (f"the owner decides it in {out['copy']}" if out["confirmable"]
612
+ else "nothing in it can be confirmed"))
613
+ return 0
614
+ out = stage_confirm.confirm(run_dir, args.version, args.copy)
615
+ say(f"S10b confirm: version {out['version']} " + ("confirmed" if out["decision"] == "confirm" else "returned")
616
+ + f", {out['approvals']} approvals")
617
+ return 0
618
+
619
+
620
+ def cmd_apply(args):
621
+ """S11 (runlib/stage_apply.py). Release 1 writes no library file (D-20261116-7853bc): a confirmed set that holds a
622
+ change is refused by name before any plan or effect, and a set that changes none is recorded as such. It starts no
623
+ process."""
624
+ say("\n".join(stage_apply.report_lines(stage_apply.run(run_dir_of(args)))))
625
+ return 0
626
+
627
+
628
+ def cmd_close(args):
629
+ """S12 (runlib/stage_close.py), release 1: the run's decisions and window recorded in the checkout's ledger, a
630
+ periodic run's coverage promoted, and nothing outside the checkout and the run directory. It starts no process;
631
+ its report ends with the commands the owner runs. The recovery close stays reserved."""
632
+ if args.recovery:
633
+ say("RECOVERY_RESERVED close --recovery: the recovery close is reserved and not implemented", sys.stderr)
634
+ return 2
635
+ name_checkout_ledger(args)
636
+ say("\n".join(stage_close.report_lines(stage_close.run(run_dir_of(args), args.checkout_ledger,
637
+ args.checkout_coverage))))
638
+ return 0
639
+
640
+
641
+ def cmd_render(args):
642
+ """S9 (runlib/stage_render.py): the review of S4's population through S7, its owner copy and its rows, written once
643
+ as the next version. It reads the pinned ledger S4 read, for the legacy groups."""
644
+ name_checkout_ledger(args)
645
+ out = stage_render.run(run_dir_of(args))
646
+ say(f"S9 render: version {out['version']}, {out['rows']} rows; {out['render']}, the owner's copy {out['copy']}")
647
+
648
+
649
+ def cmd_judge(args):
650
+ """S6 (runlib/stage_judge.py): dry, up to the calls; otherwise both judges' calls through a supervisor made before
651
+ the stage is entered, so a live run without its token is refused before anything is recorded."""
652
+ name_checkout_ledger(args)
653
+ run_dir = run_dir_of(args)
654
+ if args.dry:
655
+ if args.cells or args.golden_plan:
656
+ raise Refused("INPUT_INVALID judge --dry: a dry run makes no call, so it takes no --cells or --golden-plan")
657
+ summary = stage_judge.run(run_dir, dry=True)
658
+ else:
659
+ if not args.cells:
660
+ raise Refused("INPUT_INVALID judge --cells: the judgment calls run in cells under a cell root; give --cells "
661
+ "DIR, or --dry to stop before the calls")
662
+ summary = stage_judge.run(run_dir, stage_judge.supervisor(run_dir, args.cells, args.golden_plan))
663
+ say("\n".join(stage_judge.report_lines(summary)))
664
+ return 0
665
+
666
+
667
+ def cmd_propose(args):
668
+ """S7 (runlib/stage_propose.py): dry, up to the calls; a golden run over answers the caller
669
+ supplies; otherwise the supervised calls, through a supervisor made before the stage is entered
670
+ so a live run without its token is refused before anything is recorded."""
671
+ name_checkout_ledger(args)
672
+ run_dir = run_dir_of(args)
673
+ if args.answers:
674
+ if args.dry or args.cells or args.golden_plan:
675
+ raise Refused("INPUT_INVALID propose --answers: answers in hand make no call, so they take no --dry, "
676
+ "--cells or --golden-plan")
677
+ answers = records.read_json(pathlib.Path(args.answers))
678
+ stage, doc = stage_propose.run(run_dir, answers, legacy=stage_propose.PINNED_LEGACY)
679
+ say(f"S7: {doc['counts']['proposed']} proposed, {doc['counts']['returned']} returned, "
680
+ f"{doc['counts']['awaiting_R']} awaiting R")
681
+ return 0
682
+ if args.dry:
683
+ if args.cells or args.golden_plan:
684
+ raise Refused("INPUT_INVALID propose --dry: a dry run makes no call, so it takes no --cells or --golden-plan")
685
+ summary, _doc = stage_propose.live(run_dir, dry=True)
686
+ else:
687
+ if not args.cells:
688
+ raise Refused("INPUT_INVALID propose --cells: the proposal calls run in cells under a cell root; give "
689
+ "--cells DIR, --dry to stop before the calls, or --answers PATH for answers in hand")
690
+ summary, _doc = stage_propose.live(run_dir, stage_propose.supervisor(run_dir, args.cells, args.golden_plan))
691
+ say("\n".join(stage_propose.live_report_lines(summary)))
692
+ return 0
693
+
694
+
695
+ def cmd_review_proposals(args):
696
+ """S7b (runlib/stage_review_proposals.py): dry, up to the calls; golden over reviews the caller
697
+ supplies; otherwise the supervised calls. See cmd_propose."""
698
+ run_dir = run_dir_of(args)
699
+ if args.reviews:
700
+ if args.dry or args.cells or args.golden_plan:
701
+ raise Refused("INPUT_INVALID review-proposals --reviews: reviews in hand make no call, so they take no "
702
+ "--dry, --cells or --golden-plan")
703
+ reviews = records.read_json(pathlib.Path(args.reviews))
704
+ stage, doc = stage_review_proposals.run(run_dir, reviews)
705
+ say(f"S7b: {doc['counts']['reviewed']} reviewed, {doc['counts']['disagreements']} disagreements, "
706
+ f"{doc['counts']['returned']} returned, {doc['counts']['unreviewed']} unreviewed")
707
+ return 0
708
+ if args.dry:
709
+ if args.cells or args.golden_plan:
710
+ raise Refused("INPUT_INVALID review-proposals --dry: a dry run makes no call, so it takes no --cells or "
711
+ "--golden-plan")
712
+ summary, _doc = stage_review_proposals.live(run_dir, dry=True)
713
+ else:
714
+ if not args.cells:
715
+ raise Refused("INPUT_INVALID review-proposals --cells: the review calls run in cells under a cell root; "
716
+ "give --cells DIR, --dry to stop before the calls, or --reviews PATH for reviews in hand")
717
+ summary, _doc = stage_review_proposals.live(
718
+ run_dir, stage_review_proposals.supervisor(run_dir, args.cells, args.golden_plan))
719
+ say("\n".join(stage_review_proposals.live_report_lines(summary)))
720
+ return 0
721
+
722
+
723
+ def cmd_deliver(args):
724
+ """S5b (runlib/stage_delivery.py): code only, over S5's checks and S2's inventory."""
725
+ say("\n".join(stage_delivery.report_lines(stage_delivery.run(run_dir_of(args)))))
726
+ return 0
727
+
728
+
729
+ # The handler per subcommand, as ONE table rather than a literal inside the parser builder: a
730
+ # `cmd_` function that nothing dispatches to is a command that reports STAGE_NOT_IMPLEMENTED while
731
+ # its implementation sits in the file, which is how `deliver` shipped unreachable in WP-11b's first
732
+ # commit. The self-test holds this table against the `cmd_` functions that exist.
733
+ HANDLERS = {}
734
+
735
+
736
+ def cmd_stage(args):
737
+ stage = STAGE_COMMANDS[args.command]
738
+ if args.command == "close" and args.recovery:
739
+ say("RECOVERY_RESERVED close --recovery: the recovery close is reserved and not implemented", sys.stderr)
740
+ return 2
741
+ say(f"STAGE_NOT_IMPLEMENTED {args.command} ({stage}): no stage logic has landed for it", sys.stderr)
742
+ return 2
743
+
744
+
745
+ HANDLERS.update({"census": cmd_census, "views": cmd_views, "inventory": cmd_inventory, "read": cmd_read,
746
+ "form": cmd_form, "retrieve": cmd_retrieve, "deliver": cmd_deliver, "judge": cmd_judge,
747
+ "render": cmd_render, "parse-decisions": cmd_parse_decisions, "propose": cmd_propose,
748
+ "review-proposals": cmd_review_proposals, "review-korean": cmd_review_korean,
749
+ "adjudicate": cmd_adjudicate, "confirm": cmd_confirm, "apply": cmd_apply, "close": cmd_close})
750
+
751
+
752
+ def build_parser():
753
+ parser = Parser(prog="distill.py", description=__doc__.split("\n")[0])
754
+ parser.add_argument("--self-test", action="store_true", help="declare -> stage -> amend -> stage on real files")
755
+ commands = parser.add_subparsers(dest="command")
756
+
757
+ def common(sub):
758
+ sub.add_argument("--run-id", help="the run directory name under --out")
759
+ sub.add_argument("--out", default=None,
760
+ help="root of the run directories (default: the XDG state directory's "
761
+ "agent-bios/distill/runs, which is inside neither the package nor the state root)")
762
+
763
+ sub = commands.add_parser("declare", help="S0: the run declaration and its amendments")
764
+ common(sub)
765
+ sub.add_argument("--from", dest="from_file", help="a declaration to write as run.json")
766
+ sub.add_argument("--set", action="append", help="PATH=VALUE (dotted path, JSON value); repeatable")
767
+ sub.add_argument("--amend", action="store_true", help="record the change as an amendment")
768
+ sub.add_argument("--reason", help="why (required with --amend)")
769
+ sub.add_argument("--scope", help="comma-separated stages licensed to read the amendment (default: all)")
770
+ sub.add_argument("--invalidates", help="comma-separated stages whose results it makes stale")
771
+ sub.add_argument("--self-test", action="store_true", help="the declaration's controls")
772
+ sub.set_defaults(handler=cmd_declare)
773
+ for name, stage in STAGE_COMMANDS.items():
774
+ sub = commands.add_parser(name, help=f"{stage}: " + COMMAND_HELP.get(name, "not implemented yet"))
775
+ common(sub)
776
+ if name == "close":
777
+ sub.add_argument("--recovery", action="store_true", help="the recovery close (reserved)")
778
+ sub.add_argument("--checkout-ledger", help="the ledger's path INSIDE the declaration's checkout "
779
+ "destination, which the caller names; without it the stage is "
780
+ "refused LEDGER_UNNAMED rather than writing a guess")
781
+ sub.add_argument("--checkout-coverage", help="the coverage state's path INSIDE the declaration's checkout "
782
+ "destination (a coverage.json), which a periodic run promotes; it is "
783
+ "keyed by session identifiers, so name a path git ignores "
784
+ "(session-distill/local/coverage.json in an agent-bios checkout)")
785
+ if name == "inventory":
786
+ sub.add_argument("--to", help="write inventory/<reference>.json here instead of into a run directory")
787
+ sub.add_argument("--pin", help="HOST:SESSION_ID, the activation pin whose selection and release to read")
788
+ sub.add_argument("--state-root", help="the owner's state root (default: the installed one)")
789
+ sub.add_argument("--user-root", help="the owner's authoring root (default: the installed one)")
790
+ sub.add_argument("--no-state", action="store_true", help="read no state root at all")
791
+ sub.add_argument("--project", action="append",
792
+ help="a project root: a protected write target, and the scope a recorded "
793
+ "injection is attributed to; repeatable")
794
+ sub.add_argument("--ledger", help="the ledger to read the incubating and keep layers from")
795
+ if name == "census":
796
+ sub.add_argument("--coverage", help="the coverage state the declaration pinned (default: session-distill/coverage.json; "
797
+ "a state an earlier close promoted is where --checkout-coverage put it)")
798
+ sub.add_argument("--originators", help="the originator table; refused unless it is the one the declaration names (source 'originators')")
799
+ sub.add_argument("--jobs", type=int, default=8, help="parallel transcript reads")
800
+ sub.add_argument("--reconcile", help="S3's results (a JSON list): fold them back instead of counting")
801
+ if name == "judge":
802
+ sub.add_argument("--dry", action="store_true", help="stop before the calls: every judgment packet's measure")
803
+ sub.add_argument("--cells", help="the cell root the judgment calls run under (made mode 700)")
804
+ sub.add_argument("--golden-plan", help="a golden hosts' plan: the calls are answered from it and start no model")
805
+ if name in ("retrieve", "judge", "render"):
806
+ # S5 and S6 read the pinned ledger through `lifecycle_intake.ledger_of`, which refuses
807
+ # LEDGER_UNNAMED rather than guessing a checkout's layout. Without this flag neither
808
+ # command could run from a checkout at all — the refusal came from the merge of the
809
+ # ship-driver history, where the installed ledger became a parameter, with the two
810
+ # stages that read it on the other side.
811
+ sub.add_argument("--checkout-ledger", help="the ledger's path INSIDE the declaration's checkout "
812
+ "destination, which the caller names because the layout of a "
813
+ "checkout is not this driver's to assume; without it the "
814
+ "stage is refused LEDGER_UNNAMED rather than reading a guess")
815
+ if name == "parse-decisions":
816
+ sub.add_argument("--version", type=int, help="the review version whose copy to parse (default: the current one)")
817
+ sub.add_argument("--copy", help="the owner's edited copy (default: decisions.ko.v<n>.md in the run)")
818
+ if name == "read":
819
+ sub.add_argument("--dry", action="store_true", help="stop before the calls: every window packet's measure")
820
+ sub.add_argument("--cells", help="the cell root the reading calls run under (made mode 700)")
821
+ sub.add_argument("--golden-plan", help="a golden host's plan: the calls are answered from it and start "
822
+ "no model")
823
+ sub.add_argument("--tranche", choices=("broad", "calibration"), default="broad",
824
+ help="calibration reads one unit at a time")
825
+ sub.add_argument("--jobs", type=int, default=12, help="units read at once in a broad tranche (1 to 12)")
826
+ sub.add_argument("--checkout-ledger", help="the ledger's path INSIDE the declaration's checkout "
827
+ "destination, which the caller names; without it the stage is "
828
+ "refused LEDGER_UNNAMED rather than reading a guess")
829
+ if name == "form":
830
+ sub.add_argument("--dry", action="store_true", help="stop before the call: the intake and the packet's measure")
831
+ sub.add_argument("--cells", help="the cell root the formation call runs under (made mode 700)")
832
+ sub.add_argument("--golden-plan", help="a golden host's plan: realization golden, no model is started")
833
+ sub.add_argument("--index", help="the occasion index's rows (a JSON list; WP-21, golden until it lands)")
834
+ sub.add_argument("--checkout-ledger", help="the ledger's path INSIDE the declaration's checkout "
835
+ "destination, which the caller names because the layout of a "
836
+ "checkout is not this driver's to assume; without it the "
837
+ "stage is refused LEDGER_UNNAMED rather than reading a guess")
838
+ if name == "propose":
839
+ sub.add_argument("--dry", action="store_true", help="stop before any call: who is asked and each packet's measure")
840
+ sub.add_argument("--answers", help="a JSON object of answers by candidate id, for a golden run")
841
+ sub.add_argument("--cells", help="the cell root the proposal calls run under (made mode 700)")
842
+ sub.add_argument("--golden-plan", help="a golden host's plan: the calls are answered from it and start no model")
843
+ sub.add_argument("--checkout-ledger", help="the ledger's path INSIDE the declaration's checkout "
844
+ "destination; without it the stage is refused LEDGER_UNNAMED "
845
+ "rather than reading a guess")
846
+ if name == "review-proposals":
847
+ sub.add_argument("--dry", action="store_true", help="stop before any call: who is asked and each packet's measure")
848
+ sub.add_argument("--reviews", help="a JSON object of reviews by item id, for a golden run")
849
+ sub.add_argument("--cells", help="the cell root the review calls run under (made mode 700)")
850
+ sub.add_argument("--golden-plan", help="a golden host's plan: the calls are answered from it and start no model")
851
+ if name == "adjudicate":
852
+ sub.add_argument("--version", type=int, help="the parsed version whose adjudications to recompute "
853
+ "(default: the latest parse holding any)")
854
+ sub.add_argument("--answers", help="a JSON object of S7's second-pass answers by candidate id")
855
+ sub.add_argument("--reviews", help="a JSON object of S7b's second-pass reviews by item id")
856
+ sub.add_argument("--cells", help="the cell root the second pass's calls run under (made mode 700)")
857
+ sub.add_argument("--golden-plan", help="a golden host's plan: the calls are answered from it and start no model")
858
+ if name == "confirm":
859
+ sub.add_argument("--decide", action="store_true", help="read the owner's 확인 line in the latest version's copy")
860
+ sub.add_argument("--version", type=int, help="with --decide: the confirmation version (default: the latest)")
861
+ sub.add_argument("--copy", help="with --decide: the owner's copy (default: confirm-decision.ko.v<k>.md in the run)")
862
+ if name == "review-korean":
863
+ sub.add_argument("--reviews", help="a JSON object of S9b reviews by item id, the first pass")
864
+ sub.add_argument("--regenerations", help="a JSON object of S7's regenerated answers by item id")
865
+ sub.add_argument("--second", help="a JSON object of S9b's second reviews by item id")
866
+ sub.add_argument("--cells", help="the cell root the review and regeneration calls run under (made mode 700)")
867
+ sub.add_argument("--golden-plan", help="a golden host's plan: the calls are answered from it and start no model")
868
+ sub.set_defaults(handler=HANDLERS.get(name, cmd_stage))
869
+ return parser
870
+
871
+
872
+ # What each implemented command's --help line says. A command with a handler and no line here would read
873
+ # "not implemented yet" in the help while it runs (read, propose and review-proposals did), so the suite
874
+ # holds this table against the dispatch table.
875
+ COMMAND_HELP = {
876
+ "census": "the census",
877
+ "views": "the reading views, the search index and the evidence store",
878
+ "inventory": "every delivered unit of each reference point, with its edges",
879
+ "read": "the density reading of each window, one call per window",
880
+ "form": "candidate formation and the lifecycle intake",
881
+ "retrieve": "retrieval, quote and session checks, and recurrence",
882
+ "deliver": "the delivery evidence of each candidate's units, from the run's own records",
883
+ "judge": "the judges A and B",
884
+ "propose": "one proposal per candidate; code derives everything but the disposition and its reasons",
885
+ "review-proposals": "a second seat reviews each proposal; it shows disagreement and never decides",
886
+ "render": "the review, the owner's decision copy and the rows",
887
+ "review-korean": "the review's Korean against its English payload, one regeneration",
888
+ "parse-decisions": "the owner's decision copy into approvals and adjudications",
889
+ "adjudicate": "the owner's adjudications recomputed, the newly admitted through S7 and S7b",
890
+ "confirm": "the final set built for the owner's confirmation, or (--decide) the owner's 확인",
891
+ "apply": ("release 1 writes no library file: a confirmed set that holds a change is refused by name, and one "
892
+ "that changes none is recorded; runs no git and no installer"),
893
+ "close": ("the run's decisions and window recorded in the checkout's ledger and a periodic run's coverage "
894
+ "promoted; names the commands the owner runs"),
895
+ }
896
+
897
+
898
+ def main(argv=None):
899
+ args = build_parser().parse_args(argv)
900
+ try:
901
+ if args.command is None:
902
+ # The self-test is INSIDE this boundary. It was invoked above it, so an ordinary file
903
+ # failure in a fixture — a scratch directory that cannot be made, a fixture read that is
904
+ # refused — left an unprojected traceback carrying whatever path it named (R2#2).
905
+ if args.self_test:
906
+ return self_test()
907
+ build_parser().print_help()
908
+ return 2
909
+ return args.handler(args)
910
+ except (Refused, stagelock.Locked, stagelock.Escaped) as exc:
911
+ # A HANDLED refusal is an abort too: the suite runs inside this boundary, and a refusal
912
+ # raised from inside it used to leave with every collected failure line unpublished, because
913
+ # only the unexpected-failure handler below published (r4 R1). Empty on every normal path.
914
+ entry.publish_collected(lambda line: entry.emit(line, sys.stderr), through_floor=True)
915
+ say(str(exc), sys.stderr)
916
+ return 1
917
+ except Exception as exc:
918
+ # An unexpected failure is a diagnostic like any other, and an unexpected one is the one most
919
+ # likely to carry a path: an OSError's message IS a path, and a traceback printed by the
920
+ # interpreter crosses no boundary at all. The type is named so the failure is still
921
+ # diagnosable, and the message passes the floor (GC#6).
922
+ # The label names the command, and the suite's label is spelled WITHOUT the flag's dashes:
923
+ # the judge admits the suite argv only where a suite is entered in this process, and buying
924
+ # an exception for a diagnostic label would widen a rule that exists to keep a child from
925
+ # being handed a suite (G3).
926
+ # This handler, not `entry.failed`, is what an abort inside the suite reaches, so the
927
+ # collected report is published here too — before the failure is described.
928
+ entry.publish_collected(lambda line: entry.emit(line, sys.stderr), through_floor=True)
929
+ say(f"COMMAND_FAILED {args.command or 'self-test'}: {type(exc).__name__}: {exc}", sys.stderr)
930
+ return 1
931
+
932
+
933
+ def self_test():
934
+ """The golden end to end: declare, run a stub stage, amend, run another, and judge the
935
+ declaration order of the recorded stages from the files on disk."""
936
+ # Set where this suite begins publishing its report. Past that point a control is not in the
937
+ # number the summary published, and the summary has already said OK — which is a conclusion
938
+ # printed before the judging. The helpers below refuse past it rather than trusting placement.
939
+ reporting = []
940
+ failures, ran = entry.self_test_failures("distill --self-test"), []
941
+ # Registered while this suite runs; removed by `report`, which is where this suite reports. An
942
+ # abort between the two publishes what was collected rather than taking it away.
943
+ entry.SELF_TEST_COLLECTED.append(("distill --self-test", failures))
944
+
945
+ def control(name, ok, detail=""):
946
+ if reporting:
947
+ raise RuntimeError(f"CONTROL_AFTER_SUMMARY {name}: this suite has begun publishing its "
948
+ f"report, so `control` is not in the count it published")
949
+ # A boolean-style helper given a problem LIST passed on whatever its needle said, because a
950
+ # non-empty list is truthy: three controls in this package read correctly and asked nothing
951
+ # until S8a found them. The signature is enforced here rather than remembered.
952
+ if not isinstance(ok, bool):
953
+ raise TypeError(f"CONTROL_CONDITION_NOT_BOOL {name}: this file's `control` judges a "
954
+ f"boolean condition and was given {type(ok).__name__}")
955
+ ran.append(name)
956
+ if not ok:
957
+ failures.append((name, detail))
958
+
959
+ def type_refusal(call):
960
+ """The message a self-test helper raises when it is given the wrong KIND of argument. The
961
+ control below catches it here, so asking the guard does not fail the suite."""
962
+ try:
963
+ call()
964
+ except TypeError as exc:
965
+ return str(exc)
966
+ return ""
967
+
968
+ control("a boolean-style control given a problem list is refused by name",
969
+ "CONTROL_CONDITION_NOT_BOOL" in type_refusal(lambda: control("a planted non-boolean", ["a problem"])),
970
+ "the guard admitted a non-boolean condition, so a control in the other file's style would pass on a truthy list")
971
+
972
+ # Chosen and judged by the same rule production uses, never probed: this suite writes run
973
+ # directories, fixture state roots and a copy of the checkout (R1#5).
974
+ with inventory.self_test_scratch("wp07-driver-self-test-") as scratch:
975
+ out = scratch / "out"
976
+ out.mkdir()
977
+ run_dir = out / "r1"
978
+ (out / "declaration.json").write_text(json.dumps(declare.fixture()), encoding="utf-8")
979
+
980
+ def cli(*argv):
981
+ err = io.StringIO()
982
+ with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
983
+ try:
984
+ code = main([*argv, "--out", str(out)])
985
+ except SystemExit as exc: # argparse's own exit: a named control failure, not a dead suite
986
+ code, _ = (exc.code if isinstance(exc.code, int) else 2), err.write(f"EXITED {exc.code!r}")
987
+ except Exception as exc: # a reverted check fails its control by name, not by a traceback
988
+ code, _ = 99, err.write(f"RAISED {exc!r}")
989
+ return code, err.getvalue()
990
+
991
+ def stage(name, inputs=(), at=None):
992
+ """A stub stage: it consumes `inputs`, writes one output, and finishes complete.
993
+
994
+ A stage with parts (`records.STAGE_PARTS`) is written as one of them: these controls are
995
+ about declarations and inputs, and a part-less write there is refused by name."""
996
+ where = at or run_dir
997
+ part = records.STAGE_PARTS[name][0] if name in records.STAGE_PARTS else None
998
+ with records.run_stage(where, name, inputs, part=part) as run:
999
+ (pathlib.Path(where) / f"{name}.out").write_text(f"{name}\n", encoding="utf-8")
1000
+ run.output(f"{name}.out")
1001
+
1002
+ def refused(name, inputs=()):
1003
+ try:
1004
+ stage(name, inputs)
1005
+ except Refused as exc:
1006
+ return str(exc)
1007
+ return ""
1008
+
1009
+ def need(stage_name):
1010
+ return [{"artifact": f"{stage_name}.out", "producer_stage": stage_name}]
1011
+
1012
+ code, err = cli("declare", "--run-id", "r1", "--from", str(out / "declaration.json"))
1013
+ control("declare writes run.json at declaration_seq 0",
1014
+ code == 0 and records.read_json(records.run_json_path(run_dir))["declaration_seq"] == 0, err)
1015
+ bad = {**declare.fixture(), "seats": {**declare.fixture()["seats"], "S4": "claude:claude-opus-9-9/high"}}
1016
+ (out / "bad.json").write_text(json.dumps(bad), encoding="utf-8")
1017
+ code, err = cli("declare", "--run-id", "r2", "--from", str(out / "bad.json"))
1018
+ control("declare refuses a seat no prompting guide covers",
1019
+ code == 1 and "SEAT_UNCOVERED claude:claude-opus-9-9/high" in err
1020
+ and not records.run_json_path(out / "r2").exists(), err)
1021
+ code, err = cli("declare", "--run-id", "r1", "--set", "budget.reserve=0.3")
1022
+ control("declare --set before any stage is applied", code == 0
1023
+ and records.read_json(records.run_json_path(run_dir))["budget"]["reserve"] == 0.3, err)
1024
+
1025
+ stage("S1") # a stub stage, at declaration_seq 0
1026
+ code, err = cli("declare", "--run-id", "r1", "--set", "budget.reserve=0.4")
1027
+ control("declare --set after a stage recorded is refused", code == 1 and "AMEND_REQUIRED S1" in err, err)
1028
+ code, err = cli("declare", "--run-id", "r1", "--amend", "--reason", "raise the reserve", "--scope", "S2,S3",
1029
+ "--set", "budget.reserve=0.4")
1030
+ control("the same change as an amendment is accepted",
1031
+ code == 0 and records.read_json(records.run_json_path(run_dir))["declaration_seq"] == 1, err)
1032
+ stage("S2", need("S1")) # amended, S2 licensed, S1 not invalidated
1033
+ stage("S3", need("S2"))
1034
+ control("a stage consuming across a licensed amendment pins both sequences",
1035
+ records.producing_part(records.read_json(records.record_path(run_dir, "S2")),
1036
+ "S2.out")[1]["inputs"][0]["producer_seq"] == 0
1037
+ and records.producing_part(records.read_json(records.record_path(run_dir, "S2")),
1038
+ "S2.out")[1]["declaration_seq"] == 1)
1039
+ code, err = cli("declare", "--run-id", "r1", "--set", "checks.view_complete_share_min=0.95")
1040
+ control("declare --set of checks{} after S3 recorded is refused naming S3 and changes nothing",
1041
+ code == 1 and "AMEND_REQUIRED" in err and "S3" in err
1042
+ and records.read_json(records.run_json_path(run_dir))["checks"]["view_complete_share_min"] == 0.9, err)
1043
+ code, err = cli("declare", "--run-id", "r1", "--amend", "--reason", "tighten the criterion",
1044
+ "--set", "checks.view_complete_share_min=0.95")
1045
+ amendments = records.read_amendments(run_dir)
1046
+ control("an amendment of checks{} after S3 marks S3 invalidated",
1047
+ code == 0 and amendments[-1]["invalidates"] == ["S3"], f"{err} {amendments}")
1048
+ control("S4 refuses the stale S3", "INPUT_STALE S3" in refused("S4", need("S3")))
1049
+ stage("S3", need("S2")) # S3 re-run under declaration 2; S2 (declaration 1) is licensed and not invalidated
1050
+ stage("S4", need("S3"))
1051
+ control("S3 re-run under the new declaration is accepted, and S4 consumes it",
1052
+ records.read_json(records.record_path(run_dir, "S3"))["declaration_seq"] == 2
1053
+ and records.read_json(records.record_path(run_dir, "S4"))["inputs"][0]["producer_seq"] == 2)
1054
+
1055
+ # check_declaration_order on the real files: every recorded input, then the log with an amendment removed
1056
+ def recorded_pairs():
1057
+ # A stage with parts keeps one entry per producer, so the pairs come from the entries
1058
+ # rather than from the record's top level (records.STAGE_PARTS).
1059
+ entries = []
1060
+ for record in records.stage_records(run_dir).values():
1061
+ entries += list((record.get("parts") or {}).values()) or [record]
1062
+ return [(r["stage"], r["declaration_seq"], i["producer_stage"], i["producer_seq"])
1063
+ for r in entries for i in r.get("inputs", [])]
1064
+
1065
+ pairs, log = recorded_pairs(), records.amendments_path(run_dir).read_text(encoding="utf-8")
1066
+ control("recorded stages pass the declaration order", len(pairs) == 3 and not any(
1067
+ records.check_declaration_order(c, cs, p, ps, records.read_amendments(run_dir)) for c, cs, p, ps in pairs),
1068
+ str(pairs))
1069
+ lines = log.splitlines() # the declaration (seq 0), then amendments 1 and 2: drop amendment 1
1070
+ records.amendments_path(run_dir).write_text("\n".join(lines[:1] + lines[2:]) + "\n", encoding="utf-8")
1071
+ control("an amendment removed from the log is a silent advance",
1072
+ "DECLARATION_DRIFT S2" in "\n".join(
1073
+ e for c, cs, p, ps in pairs
1074
+ for e in records.check_declaration_order(c, cs, p, ps, records.read_amendments(run_dir))))
1075
+ control("a log that no longer ends at declaration_seq stops the next stage",
1076
+ "DECLARATION_DRIFT" in refused("S5", need("S4")))
1077
+ records.amendments_path(run_dir).write_text(log, encoding="utf-8")
1078
+ run = records.read_json(records.run_json_path(run_dir))
1079
+ records.run_json_path(run_dir).write_text(records.json_text({**run, "question": "edited by hand"}), encoding="utf-8")
1080
+ control("run.json edited by hand stops the next stage", "DECLARATION_DRIFT S5" in refused("S5", need("S4")))
1081
+ records.run_json_path(run_dir).write_text(records.json_text(run), encoding="utf-8")
1082
+ stage("S5", need("S4"))
1083
+ control("the restored declaration lets the next stage start",
1084
+ records.read_json(records.record_path(run_dir, "S5"))["status"] == "complete")
1085
+
1086
+ # a run id cannot name a place outside --out, and nothing is created before that is known
1087
+ elsewhere = scratch / "elsewhere"
1088
+ elsewhere.mkdir()
1089
+ (out / "link").symlink_to(elsewhere)
1090
+
1091
+ def listing():
1092
+ return sorted(str(p.relative_to(scratch)) for p in scratch.rglob("*"))
1093
+ before = listing()
1094
+ for run_id, why in ((str(elsewhere / "abs"), "absolute"), ("../escape", "parent traversal"), ("a/b", "two components"),
1095
+ ("..", "dot-dot"), (".", "dot"), (".hidden", "leading dot")):
1096
+ code, err = cli("declare", "--run-id", run_id, "--from", str(out / "declaration.json"))
1097
+ control(f"run id {why} is refused as RUN_ID_INVALID", code == 1 and "RUN_ID_INVALID" in err, err)
1098
+ code, err = cli("declare", "--run-id", "link", "--from", str(out / "declaration.json"))
1099
+ control("run id naming a symlink out of --out is refused as RUN_DIR_ESCAPE", code == 1 and "RUN_DIR_ESCAPE" in err, err)
1100
+ control("a refused run id created nothing, in or beside --out or in the escape target",
1101
+ before == listing(), f"{before} -> {listing()}")
1102
+ code, err = cli("declare", "--run-id", "r-2.a_b", "--from", str(out / "declaration.json"))
1103
+ control("an ordinary run id with '.', '_' and '-' is accepted", code == 0 and records.run_json_path(out / "r-2.a_b").is_file(), err)
1104
+
1105
+ # the same run with every path spelled relative to the working directory: declare, a stub stage, an
1106
+ # amendment, another stub stage — each file lands at <cwd>/<out>/<run-id>/..., and no doubled path exists
1107
+ cwd = scratch / "cwd"
1108
+ cwd.mkdir()
1109
+ (cwd / "declaration.json").write_text(json.dumps(declare.fixture()), encoding="utf-8")
1110
+ here = pathlib.Path.cwd()
1111
+ os.chdir(cwd)
1112
+ try:
1113
+ relative = pathlib.Path("rel-out") / "r1"
1114
+
1115
+ def relative_cli(*argv):
1116
+ err = io.StringIO()
1117
+ with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
1118
+ try:
1119
+ code = main([*argv, "--out", "rel-out"])
1120
+ except Exception as exc:
1121
+ code, _ = 99, err.write(f"RAISED {exc!r}")
1122
+ return code, err.getvalue()
1123
+
1124
+ def relative_stage(name, inputs=()):
1125
+ """The stub stage over the relative spelling; what it raises is its control's detail."""
1126
+ try:
1127
+ stage(name, inputs, at=relative)
1128
+ return ""
1129
+ except Exception as exc:
1130
+ return f"RAISED {exc!r}"
1131
+
1132
+ code, err = relative_cli("declare", "--run-id", "r1", "--from", "declaration.json")
1133
+ control("a relative --out declares the run at <cwd>/<out>/<run-id>", code == 0 and (cwd / relative / "run.json").is_file(), err)
1134
+ detail = relative_stage("S1")
1135
+ control("a stub stage runs over the relative spelling of the run directory", not detail, detail)
1136
+ code, err = relative_cli("declare", "--run-id", "r1", "--amend", "--reason", "raise the reserve", "--set", "budget.reserve=0.4")
1137
+ control("a relative --out amends the run after a stage recorded", code == 0
1138
+ and records.read_json(cwd / relative / "run.json")["declaration_seq"] == 1, err)
1139
+ detail = relative_stage("S2", [{"artifact": "S1.out", "producer_stage": "S1"}])
1140
+ control("a second stub stage consumes the first across the amendment", not detail, detail)
1141
+ found = sorted(str(path.relative_to(cwd)) for path in cwd.rglob("*") if path.is_file())
1142
+ expected = sorted(f"rel-out/r1/{name}" for name in (
1143
+ "run.json", "amendments.jsonl", "S1.out", "S2.out", "locks/declaration.lock", "locks/stage-S1.lock",
1144
+ "locks/stage-S2.lock", "stages/S1/record.json", "stages/S2/record.json")) + ["declaration.json"]
1145
+ control("a relative run keeps every file under <cwd>/<out>/<run-id> and creates no doubled path",
1146
+ found == sorted(expected), f"found {found}")
1147
+ finally:
1148
+ os.chdir(here)
1149
+
1150
+ # each implemented command has its own controls (form's and retrieve's runs in runlib/stage_form.py's and
1151
+ # runlib/stage_retrieve.py's suites, as a process); the rest are named and refused
1152
+ implemented = ("census", "views", "inventory", "read", "form", "retrieve", "deliver", "judge", "propose",
1153
+ "review-proposals", "render", "parse-decisions", "review-korean", "adjudicate", "confirm",
1154
+ "apply", "close")
1155
+ # The structural half, which is what this suite lacked: a `cmd_` function the parser never
1156
+ # dispatches to is an implemented command that answers STAGE_NOT_IMPLEMENTED, and the loop
1157
+ # below cannot see it — it ASSERTED that answer for `deliver` while `cmd_deliver` sat in the
1158
+ # file unreachable (WP-11b, found by running S5b on a real run). Both directions, by name; a
1159
+ # function's name spells a command's dash as an underscore.
1160
+ own = {name[len("cmd_"):].replace("_", "-") for name in globals() if name.startswith("cmd_")
1161
+ and name not in ("cmd_stage", "cmd_declare")}
1162
+ control("every command with a handler of its own is dispatched to it",
1163
+ not (own - set(HANDLERS)), f"undispatched: {sorted(own - set(HANDLERS))}")
1164
+ control("and every dispatched command has one", not (set(HANDLERS) - own),
1165
+ f"dispatched to nothing of its own: {sorted(set(HANDLERS) - own)}")
1166
+ control("every dispatched command's help line says what it does, and no other command has one",
1167
+ set(COMMAND_HELP) == set(HANDLERS),
1168
+ f"help without a handler: {sorted(set(COMMAND_HELP) - set(HANDLERS))}; "
1169
+ f"handler without help: {sorted(set(HANDLERS) - set(COMMAND_HELP))}")
1170
+ control("the implemented list is the dispatch table, so neither can drift from the other",
1171
+ set(implemented) == set(HANDLERS),
1172
+ f"implemented={sorted(implemented)} dispatched={sorted(HANDLERS)}")
1173
+ for command, stage_id in STAGE_COMMANDS.items():
1174
+ if command in implemented:
1175
+ continue
1176
+ code, err = cli(command, "--run-id", "r1")
1177
+ control(f"{command} ({stage_id}) is named and refused",
1178
+ code == 2 and f"STAGE_NOT_IMPLEMENTED {command} ({stage_id})" in err, err)
1179
+ # `propose` and `review-proposals` left the loop above when they gained handlers, so their own
1180
+ # refusal paths are controlled here instead: moving a command out of "named and refused"
1181
+ # without controlling what it now does would be two controls removed and none added.
1182
+ def no_stage_record():
1183
+ return not (out / "r1" / "stages" / "S7.json").exists() \
1184
+ and not (out / "r1" / "stages" / "S7b.json").exists()
1185
+ code, err = cli("propose", "--run-id", "r1")
1186
+ control("propose (S7) with neither --cells, --dry nor --answers is refused by name, and records no "
1187
+ "stage", code == 1 and "INPUT_INVALID propose --cells" in err and no_stage_record(), f"{code} {err}")
1188
+ code, err = cli("review-proposals", "--run-id", "r1")
1189
+ control("review-proposals (S7b) with neither --cells, --dry nor --reviews is refused the same way, by its "
1190
+ "own name",
1191
+ code == 1 and "INPUT_INVALID review-proposals --cells" in err and no_stage_record(),
1192
+ f"{code} {err}")
1193
+ code, err = cli("propose", "--run-id", "r1", "--dry")
1194
+ control("propose --dry over a run S6 has not written is refused by name, and still records no "
1195
+ "stage", code != 0 and "derivations.json" in err and no_stage_record(), f"{code} {err}")
1196
+ def stage_files():
1197
+ return {str(p): p.read_bytes() for p in sorted((out / "r1" / "stages").rglob("*")) if p.is_file()}
1198
+ before = stage_files()
1199
+ code, err = cli("retrieve", "--run-id", "r1")
1200
+ control("retrieve (S5) over a run S4 has not run is refused by name, and no stage record is written or changed",
1201
+ code == 1 and "INPUT_INVALID S4" in err and stage_files() == before, f"{code} {err}")
1202
+ code, err = cli("deliver", "--run-id", "r1")
1203
+ control("deliver (S5b) over a run whose immutable copy is absent is refused by name, and no "
1204
+ "stage record is written or changed",
1205
+ code == 1 and "DELIVERY_SOURCES_MISSING" in err and stage_files() == before, f"{code} {err}")
1206
+ before = stage_files()
1207
+ code, err = cli("apply", "--run-id", "r1")
1208
+ control("apply (S11) over a run whose final set is not confirmed is refused by name, and no stage record is "
1209
+ "written or changed",
1210
+ code == 1 and "CONFIRMATION_ABSENT S11" in err and stage_files() == before, f"{code} {err}")
1211
+ # a run directory inside the instructions (release 1's confirmation review, round 2 F2): refused for every
1212
+ # command before any lock or directory, here the two that write the most
1213
+ skill_repo = scratch / "skill-repo" # under the suite's declared scratch
1214
+ from runlib import lifecycle_intake as held_intake
1215
+ held_checkout_ledger = held_intake.CHECKOUT_LEDGER # `close` names it for the process; restored below
1216
+ try:
1217
+ for d in ("claude/skills/understand", "codex"):
1218
+ (skill_repo / d).mkdir(parents=True)
1219
+ inside = skill_repo / "claude" / "skills" / "understand"
1220
+ # and a standalone inventory's --to, which enters no run (release 1's third confirmation review, F3);
1221
+ # --no-state, so that a reverted admission reads nothing but this checkout
1222
+ for command, code_named in ((["apply", "--run-id", "r1", "--out", str(inside)], "RUN_DIR_IN_INSTRUCTIONS"),
1223
+ (["close", "--run-id", "r1", "--checkout-ledger", "l.json", "--out", str(inside)],
1224
+ "RUN_DIR_IN_INSTRUCTIONS"),
1225
+ (["inventory", "--to", str(inside), "--no-state"],
1226
+ "INVENTORY_TO_IN_INSTRUCTIONS")):
1227
+ held_err = io.StringIO()
1228
+ with contextlib.redirect_stderr(held_err), contextlib.redirect_stdout(io.StringIO()):
1229
+ try:
1230
+ held_code = main(command)
1231
+ except Exception as exc: # noqa: BLE001 - reported by name
1232
+ held_code, _ = 99, held_err.write(f"RAISED {exc!r}")
1233
+ control(f"{command[0]} with a destination inside a skill is refused by name and writes nothing there",
1234
+ held_code == 1 and code_named in held_err.getvalue()
1235
+ and not any(inside.iterdir()), f"{held_code} {held_err.getvalue()[-300:]}")
1236
+ finally:
1237
+ held_intake.CHECKOUT_LEDGER = held_checkout_ledger
1238
+ shutil.rmtree(skill_repo, ignore_errors=True)
1239
+ code, err = cli("close", "--run-id", "r1")
1240
+ control("close (S12) with no ledger reference is refused by name: no path inside a checkout is assumed",
1241
+ code == 1 and "LEDGER_UNNAMED S12" in err and stage_files() == before, f"{code} {err}")
1242
+ code, err = cli("close", "--run-id", "r1", "--checkout-ledger", "book/ledger.json")
1243
+ control("close (S12) over a run whose final set is not confirmed is refused by name, and no stage record is "
1244
+ "written or changed",
1245
+ code == 1 and "CONFIRMATION_ABSENT S12" in err and stage_files() == before, f"{code} {err}")
1246
+ code, err = cli("judge", "--run-id", "r1")
1247
+ control("judge (S6) with neither --dry nor --cells is refused by name before anything is recorded",
1248
+ code == 1 and "INPUT_INVALID judge --cells" in err and stage_files() == before, f"{code} {err}")
1249
+ code, err = cli("judge", "--run-id", "r1", "--dry", "--cells", str(out / "judge-cells"))
1250
+ control("judge --dry (S6) with --cells is refused by name: a dry run makes no call",
1251
+ code == 1 and "INPUT_INVALID judge --dry" in err and stage_files() == before, f"{code} {err}")
1252
+ held_token = os.environ.pop("CLAUDE_RUN_TOKEN_FILE", None)
1253
+ try:
1254
+ code, err = cli("judge", "--run-id", "r1", "--cells", str(out / "judge-cells"))
1255
+ finally:
1256
+ if held_token is not None:
1257
+ os.environ["CLAUDE_RUN_TOKEN_FILE"] = held_token
1258
+ control("a live judge (S6) with no CLAUDE_RUN_TOKEN_FILE is refused by name before its cell root or any stage "
1259
+ "record is made", code == 1 and "TOKEN_FILE_UNSET S6" in err and not (out / "judge-cells").exists()
1260
+ and stage_files() == before, f"{code} {err}")
1261
+ code, err = cli("judge", "--run-id", "r1", "--dry")
1262
+ control("judge --dry (S6) over a run S5 has not run is refused by name, and no stage record is written or changed",
1263
+ code == 1 and "INPUT_INVALID S5" in err and stage_files() == before, f"{code} {err}")
1264
+ code, err = cli("read", "--run-id", "r-read")
1265
+ control("read (S3) with neither --dry nor --cells is refused by name before anything is recorded",
1266
+ code == 1 and "INPUT_INVALID read --cells" in err and not (out / "r-read").exists(), err)
1267
+ code, err = cli("read", "--run-id", "r-read", "--dry", "--cells", str(out / "read-cells"))
1268
+ control("read --dry with a cell root is refused by name: a dry run makes no call",
1269
+ code == 1 and "INPUT_INVALID read --dry" in err, err)
1270
+ held_token = os.environ.pop("CLAUDE_RUN_TOKEN_FILE", None)
1271
+ try:
1272
+ code, err = cli("read", "--run-id", "r-read", "--cells", str(out / "read-cells"))
1273
+ finally:
1274
+ if held_token is not None:
1275
+ os.environ["CLAUDE_RUN_TOKEN_FILE"] = held_token
1276
+ control("a live read with no CLAUDE_RUN_TOKEN_FILE is refused by name before its cell root or any record is made",
1277
+ code == 1 and "TOKEN_FILE_UNSET S3" in err and not (out / "read-cells").exists()
1278
+ and not (out / "r-read").exists(), err)
1279
+ code, err = cli("read", "--run-id", "r1", "--dry")
1280
+ control("read --dry (S3) reaches the stage: over a run S2 has not run it is refused on its input, by name, "
1281
+ "and no stage record is written or changed",
1282
+ code == 1 and "INPUT_INVALID S2" in err and stage_files() == before, f"{code} {err}")
1283
+ code, err = cli("form", "--run-id", "r-form")
1284
+ control("form (S4) with neither --dry nor --cells is refused by name before anything is recorded",
1285
+ code == 1 and "INPUT_INVALID form --cells" in err and not (out / "r-form").exists(), err)
1286
+ code, err = cli("form", "--run-id", "r-form", "--dry", "--cells", str(out / "form-cells"))
1287
+ control("form --dry with a cell root is refused by name: a dry run makes no call",
1288
+ code == 1 and "INPUT_INVALID form --dry" in err, err)
1289
+ held_token = os.environ.pop("CLAUDE_RUN_TOKEN_FILE", None)
1290
+ try:
1291
+ code, err = cli("form", "--run-id", "r-form", "--cells", str(out / "form-cells"))
1292
+ finally:
1293
+ if held_token is not None:
1294
+ os.environ["CLAUDE_RUN_TOKEN_FILE"] = held_token
1295
+ control("a live form with no CLAUDE_RUN_TOKEN_FILE is refused by name before its cell root or any record is made",
1296
+ code == 1 and "TOKEN_FILE_UNSET S4" in err and not (out / "form-cells").exists()
1297
+ and not (out / "r-form").exists(), err)
1298
+ # inventory (S2) reads no stage of this run, so it refuses on what it cannot resolve rather
1299
+ # than on a missing input: with neither a run directory nor an output directory it has nowhere
1300
+ # to write, and that is the refusal the driver owns
1301
+ code, err = cli("inventory")
1302
+ control("inventory (S2) refuses by name with no run and no output directory",
1303
+ code == 1 and "INPUT_INVALID inventory" in err, f"{code} {err}")
1304
+ # No mode reads a host home any more, so there is no inspection to label and no native root
1305
+ # to validate: a run outside a run directory has no census, and every native layer is
1306
+ # `unknown` with that reason (the 1548 amendment §5, §8).
1307
+ bare_to = scratch / "inv-bare"
1308
+ code, err = cli("inventory", "--to", str(bare_to), "--no-state")
1309
+ document = json.loads((bare_to / "inventory" / "current.json").read_text(encoding="utf-8")) if code == 0 else {}
1310
+ statuses = {row["layer"]: row["status"] for row in document.get("layers", [])}
1311
+ reasons = "; ".join(document.get("reference", {}).get("incomplete_reasons", []))
1312
+ control("inventory (S2) outside a run reports every native layer unknown, with the reason",
1313
+ code == 0 and all(statuses.get(layer) == "unknown" for layer in inventory.NATIVE_LAYERS)
1314
+ and "census" in reasons, f"{code} {err} {statuses}")
1315
+ control("and it names no mode that reads a host home",
1316
+ "mode" not in document.get("produced_by", {}) and "--native-live" not in err,
1317
+ f"{sorted(document.get('produced_by', {}))}")
1318
+ # ---- GC#0 through `--project`: the checkout is a protected root whatever is declared, and
1319
+ # the refusal is observed as an attempted write that did not happen.
1320
+ #
1321
+ # The destination has to be inside "the checkout", which is the one root this rule is about —
1322
+ # so the checkout under test is a DISPOSABLE COPY and the driver run is that copy's own. The
1323
+ # first version used the review checkout and then removed the destination unconditionally: a
1324
+ # failing control appended its failure and execution carried on to the `rmtree`, so a
1325
+ # leftover from an interrupted revert — or anything else that happened to be at that path —
1326
+ # was deleted inside the reviewer's tree (R1#2). Nothing here deletes anything: the copy
1327
+ # lives under the judged scratch parent and goes with it.
1328
+ protect_copy = scratch / "protection-checkout"
1329
+ inventory.checkout_copy(protect_copy)
1330
+ other_project = scratch / "another-project"
1331
+ other_project.mkdir()
1332
+
1333
+ def copy_cli(*argv):
1334
+ """The COPY's own driver, as a real process: `repo` is resolved from `__file__`, so only
1335
+ the copy's driver treats the copy as the checkout."""
1336
+ # The program is produced by `inventory.copied_member`, the owner of "a closure member
1337
+ # inside a tree this process copied": that call is what the closure gate admits, so the
1338
+ # admission is bound to this call and not to text elsewhere in this file (R2#5).
1339
+ ran = entry.bounded(lambda: subprocess.Popen(
1340
+ [sys.executable,
1341
+ str(inventory.copied_member(protect_copy, "session-distill/distill.py")),
1342
+ *argv], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
1343
+ start_new_session=True), what="the copy's own driver")
1344
+ return ran.returncode, ran.stdout + ran.stderr
1345
+
1346
+ @contextlib.contextmanager
1347
+ def owning(name):
1348
+ """A control's own fixtures. A crash inside is a failure of THIS name, not a dead suite:
1349
+ under a revert the write these controls expect to be refused actually lands, and a
1350
+ `mkdir` in the next control then raised `FileExistsError` out of the whole run — which
1351
+ is also why no two of them share a destination any more."""
1352
+ ran.append(name)
1353
+ try:
1354
+ yield
1355
+ except Exception as exc:
1356
+ failures.append((name, f"RAISED {exc!r}"))
1357
+
1358
+ with owning("the checkout-protection controls' own fixtures"):
1359
+ # Each control owns its destination, and no other control names it.
1360
+ in_checkout = protect_copy / "session-distill" / "out" / "a-destination-no-run-owns"
1361
+ code, err = copy_cli("inventory", "--to", str(in_checkout), "--no-state",
1362
+ "--project", str(other_project))
1363
+ control("inventory (S2) refuses a destination inside the checkout when another project is declared",
1364
+ code == 1 and "PROTECTED_OVERLAP" in err, f"{code} {err}")
1365
+ control("and the attempted write did not happen", not in_checkout.exists(),
1366
+ f"{in_checkout} exists after a refused run")
1367
+ # The shape the old cleanup would have destroyed: a destination that already exists,
1368
+ # holding something this test does not own. It is still refused, and the sentinel is
1369
+ # still there afterwards — nothing here removes anything.
1370
+ existing = protect_copy / "session-distill" / "out" / "a-destination-that-already-exists"
1371
+ sentinel = existing / "sentinel.txt"
1372
+ existing.mkdir(parents=True, exist_ok=True)
1373
+ sentinel.write_text("left here by something that is not this test\n", encoding="utf-8")
1374
+ code, err = copy_cli("inventory", "--to", str(existing), "--no-state",
1375
+ "--project", str(other_project))
1376
+ control("a pre-existing destination inside the checkout is refused and nothing of it is removed",
1377
+ code == 1 and "PROTECTED_OVERLAP" in err and sentinel.is_file()
1378
+ and sentinel.read_text(encoding="utf-8").startswith("left here"),
1379
+ f"{code} {sentinel.exists()} {err[:200]}")
1380
+
1381
+ def cli_refused_before_run(*argv):
1382
+ """`(code, err, reached)`: the CLI's answer with `inventory.run` replaced by a recorder.
1383
+
1384
+ Protection is enforced in two layers — the driver judges the destination, and
1385
+ `inventory.run` judges it again over its own protected set. With both in place a
1386
+ refusal cannot be attributed to either, so reverting one layer left the other refusing
1387
+ and the control stayed green (R1#1, and the same shape at #17). Here the producer is
1388
+ not there to refuse anything: what is observed is that THIS layer refused, and that the
1389
+ producer was never reached."""
1390
+ reached = []
1391
+ kept = inventory.run
1392
+ try:
1393
+ inventory.run = lambda *args, **kwargs: (reached.append(argv) or
1394
+ {"references": {}, "state_root_unchanged": True})
1395
+ return (*cli(*argv), reached)
1396
+ finally:
1397
+ inventory.run = kept
1398
+
1399
+ # The CLI layer alone, for each of the two destinations it must refuse: inside the checkout
1400
+ # when another project is declared, and inside the owner's state root under `--no-state`.
1401
+ # The first destination is inside THIS checkout, because that is the root the rule names and
1402
+ # the in-process driver's own `repo`. Nothing writes there in either direction: the producer
1403
+ # is the recorder, and the driver creates no destination of its own — the control asserts it
1404
+ # afterwards rather than trusting that.
1405
+ unwritten = pathlib.Path(__file__).resolve().parents[1] / "out" / "a-cli-layer-destination"
1406
+ cli_checkout = scratch / "cli-layer-reachable-destination"
1407
+ guarded_state_cli = scratch / "cli-layer-state"
1408
+ (guarded_state_cli / "runtime").mkdir(parents=True)
1409
+ code, err, reached = cli_refused_before_run(
1410
+ "inventory", "--to", str(unwritten), "--no-state", "--project", str(other_project))
1411
+ control("the driver itself refuses a destination inside the checkout, before the producer is called",
1412
+ code == 1 and "PROTECTED_OVERLAP" in err and not reached, f"{code} {reached} {err}")
1413
+ control("and that destination inside this checkout was never created",
1414
+ not unwritten.exists(), f"{unwritten} exists after the control ran")
1415
+ code, err, reached = cli_refused_before_run(
1416
+ "inventory", "--to", str(guarded_state_cli / "out"), "--state-root", str(guarded_state_cli),
1417
+ "--user-root", str(scratch / "cli-layer-user"), "--no-state")
1418
+ control("the driver itself refuses a destination inside the unread state root, before the producer is called",
1419
+ code == 1 and "PROTECTED_OVERLAP" in err and not reached, f"{code} {reached} {err}")
1420
+ control("and the producer is reachable at all when the destination is not protected",
1421
+ bool(cli_refused_before_run("inventory", "--to", str(cli_checkout), "--no-state")[2]),
1422
+ "the recorder was never called, so the two controls above judge nothing")
1423
+
1424
+ # ---- r7 R17b: "the checkout is ALWAYS a project" was watched only through a REFUSAL, and
1425
+ # `inventory.run` refuses the same destination over its own protected set. With the checkout
1426
+ # dropped from this set the driver admitted the destination and the producer refused it, so
1427
+ # the control stayed green while the rule was gone. What is read here is the set itself, as
1428
+ # the driver hands it over, at a destination nothing refuses.
1429
+ handed = {}
1430
+ kept_producer = inventory.run
1431
+ try:
1432
+ inventory.run = lambda *a, **k: (handed.update(k) or
1433
+ {"references": {}, "state_root_unchanged": True})
1434
+ with contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()):
1435
+ main(["inventory", "--to", str(scratch / "project-set-reader"), "--no-state",
1436
+ "--project", str(other_project)])
1437
+ finally:
1438
+ inventory.run = kept_producer
1439
+ handed_projects = sorted((handed.get("native_roots") or {}).get("projects") or {})
1440
+ # Observe only that the CALL happened. Its condition used to be `len(handed_projects) == 2`,
1441
+ # which is the next control's subject: with the set wrong both failed, and this one's message
1442
+ # said the producer was never reached when it had been (r8 R17b). Two controls, two facts.
1443
+ control("and that project set was read from a call that really happened",
1444
+ "native_roots" in handed, f"{sorted(handed)} — the producer was never reached")
1445
+ control("the project set the driver hands over names the other project AND this checkout",
1446
+ str(pathlib.Path(__file__).resolve().parents[1]) in handed_projects
1447
+ and str(pathlib.Path(other_project).resolve()) in handed_projects,
1448
+ f"{handed_projects}")
1449
+
1450
+ # ---- r3 #7: the driver's own preflight over a CONFIGURED host home. The host homes are
1451
+ # protected whether or not a run reads them, and which directory each one IS comes from
1452
+ # `CLAUDE_CONFIG_DIR` and `CODEX_HOME` (R2#1). The controls above never set either, so
1453
+ # restoring `NATIVE`'s defaults at this call site alone was unobserved by all of them.
1454
+ #
1455
+ # Asked of THIS layer: the producer is a recorder, so nothing downstream can refuse on the
1456
+ # driver's behalf, and the destination is named with `--run-id` so that a stage record —
1457
+ # itself a write — would be entered before `inventory.run` could be reached at all.
1458
+ def cli_with_environment(environment, *argv):
1459
+ """`(code, err, reached)` for one invocation under `environment`, producer recorded.
1460
+
1461
+ The driver reads the environment where it resolves roots, not where it starts, so the
1462
+ variables are placed for the duration of the call and taken away afterwards."""
1463
+ reached, kept_run, kept_environ = [], inventory.run, dict(os.environ)
1464
+ try:
1465
+ inventory.run = lambda *a, **k: (reached.append(argv) or
1466
+ {"references": {}, "state_root_unchanged": True})
1467
+ os.environ.update(environment)
1468
+ err = io.StringIO()
1469
+ with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
1470
+ try:
1471
+ code = main(list(argv))
1472
+ except SystemExit as exc:
1473
+ code, _ = (exc.code if isinstance(exc.code, int) else 2), err.write(f"EXITED {exc.code!r}")
1474
+ except Exception as exc:
1475
+ code, _ = 99, err.write(f"RAISED {exc!r}")
1476
+ return code, err.getvalue(), reached
1477
+ finally:
1478
+ inventory.run = kept_run
1479
+ os.environ.clear()
1480
+ os.environ.update(kept_environ)
1481
+
1482
+ host_home_fixture = scratch / "configured-host-homes"
1483
+ (host_home_fixture / "home").mkdir(parents=True)
1484
+ fixture_environment = {"HOME": str(host_home_fixture / "home"),
1485
+ "CLAUDE_CONFIG_DIR": str(host_home_fixture / "elsewhere" / "claude"),
1486
+ "CODEX_HOME": str(host_home_fixture / "elsewhere" / "codex")}
1487
+ moved_homes = [str(home) for home in inventory.host_homes(fixture_environment)]
1488
+ control("the two variables really move the homes this driver protects",
1489
+ moved_homes == [fixture_environment["CLAUDE_CONFIG_DIR"],
1490
+ fixture_environment["CODEX_HOME"]], f"{moved_homes}")
1491
+ # the admission resolves the homes as the environment configures them, a default home that is a link to a
1492
+ # directory of another name among them (release 1's third confirmation review, F2)
1493
+ (host_home_fixture / "dot-claude" / "skills").mkdir(parents=True)
1494
+ (host_home_fixture / "linked-home").mkdir()
1495
+ (host_home_fixture / "linked-home" / ".claude").symlink_to(host_home_fixture / "dot-claude")
1496
+ placed = [bool(inventory.instructions_place(where, environment)) for where, environment in (
1497
+ (host_home_fixture / "elsewhere" / "claude" / "skills" / "r1", fixture_environment),
1498
+ (host_home_fixture / "elsewhere" / "codex" / "r1", fixture_environment),
1499
+ (host_home_fixture / "dot-claude" / "skills" / "r1", {"HOME": str(host_home_fixture / "linked-home")}),
1500
+ (host_home_fixture / "dot-claude" / "skills" / "r1", {"HOME": str(host_home_fixture / "home")}),
1501
+ (host_home_fixture / "elsewhere" / "r1", fixture_environment))]
1502
+ control("the admission names a destination inside either configured home and inside a default home that is a "
1503
+ "link, and not the same directory when no home is it, nor a sibling of the homes",
1504
+ placed == [True, True, True, False, False], f"{placed}")
1505
+ for variable in ("CLAUDE_CONFIG_DIR", "CODEX_HOME"):
1506
+ configured = pathlib.Path(fixture_environment[variable])
1507
+ # A run directory under the configured home, named through `--out` and `--run-id`, so
1508
+ # the refusal has to come before `records.run_stage` is entered.
1509
+ code, err, reached = cli_with_environment(
1510
+ fixture_environment, "inventory", "--run-id", "r-host-home",
1511
+ "--out", str(configured / "runs"), "--no-state",
1512
+ "--state-root", str(host_home_fixture / "state"),
1513
+ "--user-root", str(host_home_fixture / "user"))
1514
+ # refused at the run directory's admission now, before inventory's own overlap check is asked: a
1515
+ # configured home is the host's home for every command (release 1's third confirmation review, F2)
1516
+ control(f"the driver itself refuses a run destination inside the home {variable} names",
1517
+ code == 1 and "RUN_DIR_IN_INSTRUCTIONS" in err and "configured home" in err and not reached,
1518
+ f"{code} {reached} {err.strip()[:300]}")
1519
+ written = sorted(str(path.relative_to(host_home_fixture))
1520
+ for path in host_home_fixture.rglob("record.json"))
1521
+ control(f"and nothing of that run exists afterwards, so no stage was entered ({variable})",
1522
+ not configured.exists() and not written,
1523
+ f"{configured} exists={configured.exists()} records={written}")
1524
+ # The same environment with a destination OUTSIDE those homes: the recorder is reached, so
1525
+ # the two refusals above are the configured homes' doing and not this environment refusing
1526
+ # every destination. It is a standalone `--to`, because a run id would need a declaration
1527
+ # and `RUN_UNDECLARED` is a different refusal that would satisfy the same control.
1528
+ reachable_out = scratch / "configured-host-homes-reachable"
1529
+ code, err, reached = cli_with_environment(
1530
+ fixture_environment, "inventory", "--to", str(reachable_out), "--no-state",
1531
+ "--state-root", str(host_home_fixture / "state"),
1532
+ "--user-root", str(host_home_fixture / "user"))
1533
+ control("and the same run outside those homes reaches the producer", len(reached) == 1,
1534
+ f"the recorder was called {len(reached)} time(s): {code} {err.strip()[:300]}")
1535
+ # ---- GC#3 by another route: a standalone `--to` is not a way into a run's artifacts. The
1536
+ # run's own bytes and its stage record are the subject: both must be exactly as they were.
1537
+ standalone_run = out / "r-standalone"
1538
+ standalone_run.mkdir(parents=True)
1539
+ for name in ("run.json", "amendments.jsonl"):
1540
+ (standalone_run / name).write_text((out / "r1" / name).read_text(encoding="utf-8"), encoding="utf-8")
1541
+ (standalone_run / "inventory").mkdir()
1542
+ (standalone_run / "inventory" / "current.json").write_text(
1543
+ '{"units": ["the bytes a census-backed run produced"]}\n', encoding="utf-8")
1544
+ with records.run_stage(standalone_run, "S2", part="inventory") as held:
1545
+ held # a recorded S2, so the refusal is about the destination and not about the run
1546
+ kept_bytes = (standalone_run / "inventory" / "current.json").read_bytes()
1547
+ kept_record = records.record_path(standalone_run, "S2").read_bytes()
1548
+ code, err = cli("inventory", "--to", str(standalone_run), "--no-state")
1549
+ control("inventory (S2) refuses a standalone --to that names a declared run",
1550
+ code == 1 and "RUN_DESTINATION" in err, f"{code} {err}")
1551
+ code, err = cli("inventory", "--to", str(standalone_run / "inventory"), "--no-state")
1552
+ control("and one inside that run directory",
1553
+ code == 1 and "RUN_DESTINATION" in err, f"{code} {err}")
1554
+ control("the run's inventory bytes and its stage record are unchanged",
1555
+ kept_bytes == (standalone_run / "inventory" / "current.json").read_bytes()
1556
+ and kept_record == records.record_path(standalone_run, "S2").read_bytes(),
1557
+ "a refused standalone attempt changed the run")
1558
+ held_elsewhere = scratch / "inv-held"
1559
+ (held_elsewhere / "inventory").mkdir(parents=True)
1560
+ (held_elsewhere / "inventory" / "current.json").write_text("{}\n", encoding="utf-8")
1561
+ code, err = cli("inventory", "--to", str(held_elsewhere), "--no-state")
1562
+ control("and a destination that already holds an inventory",
1563
+ code == 1 and "INVENTORY_PRESENT" in err, f"{code} {err}")
1564
+ # ---- #11: the inventory part through the driver. Its census is an S1 input, so a census
1565
+ # changed after S1 recorded it is refused by name, and a compressed transcript is read with the
1566
+ # decoder the run declares. Both used to be missing: the part declared no input and was handed
1567
+ # no decoder, so a zstd rollout was unreadable to it and a moved census was read anyway.
1568
+ inventory_run = out / "r-inventory"
1569
+ code, err = cli("declare", "--run-id", "r-inventory", "--from", str(out / "declaration.json"))
1570
+ control("a fixture run for the inventory part is declared", code == 0, f"{code}")
1571
+ rollouts = scratch / "inventory-transcripts"
1572
+ rollouts.mkdir()
1573
+ block_marker = "the block a compressed rollout carried"
1574
+ plain_rollout = rollouts / "rollout-2026-10-10T09-00-00-cccc.jsonl"
1575
+ plain_rollout.write_text(json.dumps(
1576
+ {"type": "session_meta", "timestamp": "2026-10-10T09:00:00+00:00",
1577
+ "payload": {"id": "cccc", "cwd": str(scratch),
1578
+ "base_instructions": {"text": f"# Codex\n\n- {block_marker}\n"}}})
1579
+ + "\n", encoding="utf-8")
1580
+ plain_bytes = plain_rollout.read_bytes()
1581
+ compressed_rollout = rollouts / "rollout-2026-10-10T09-00-00-cccc.jsonl.zst"
1582
+
1583
+ def zstd_frame(data):
1584
+ """TEST ONLY, never called by a product path: `data` as one zstd frame (RFC 8878 §3.1.1)
1585
+ holding raw, uncompressed blocks only, split into blocks of at most 128 KB. A real zstd
1586
+ file, written without starting a program, so this suite runs no program dispatch.py has
1587
+ not admitted; the declared decoder still reads it, through `sources.checked_zstd`."""
1588
+ size = len(data)
1589
+ header = (bytes([0x20]) + size.to_bytes(1, "little") if size < 256 else
1590
+ bytes([0x60]) + (size - 256).to_bytes(2, "little") if size < 65792 else
1591
+ bytes([0xA0]) + size.to_bytes(4, "little"))
1592
+ chunks = [data[at:at + 131072] for at in range(0, size, 131072)] or [b""]
1593
+ return (0xFD2FB528).to_bytes(4, "little") + header + b"".join(
1594
+ ((len(chunk) << 3) | (index == len(chunks) - 1)).to_bytes(3, "little") + chunk
1595
+ for index, chunk in enumerate(chunks))
1596
+
1597
+ compressed_rollout.write_bytes(zstd_frame(plain_bytes))
1598
+ plain_rollout.unlink()
1599
+ zstd = sources.declared(declare.fixture()).get("zstd")
1600
+
1601
+ def read_back(path):
1602
+ """What the declared decoder makes of `path`, or None: a machine without it fails the
1603
+ controls that need it by name, and none of them is skipped."""
1604
+ try:
1605
+ return b"".join(sources.read_lines(path, zstd))
1606
+ except Exception:
1607
+ return None
1608
+
1609
+ # The frame itself, positively: without this, a broken frame and an undelivered decoder would
1610
+ # both look like a rollout with no event. Every size branch of the frame is read back - the
1611
+ # fixture rollout, a two-byte content size, and a payload split into three blocks.
1612
+ framed = {"the fixture rollout": (compressed_rollout, plain_bytes)}
1613
+ for label, payload in (("a two-byte content size", b"y" * 999 + b"\n"),
1614
+ ("three blocks", b"x" * 299_999 + b"\n")):
1615
+ framed[label] = (rollouts / f"frame-{len(payload)}.jsonl.zst", payload)
1616
+ framed[label][0].write_bytes(zstd_frame(payload))
1617
+ back = {label: read_back(path) == payload for label, (path, payload) in framed.items()}
1618
+ control("the test-only zstd frame is read back byte for byte by the declared decoder",
1619
+ all(back.values()), f"{back}")
1620
+ bound = records.sha256_bytes(plain_bytes)
1621
+ # a Codex row holds its file in segments (D-20261103-a7128a)
1622
+ inventory_census = {"transcripts": [{
1623
+ "host": "codex", "id": "cccc", "source": "codex_sessions", "status": "eligible", "parent": None,
1624
+ "segments": [{"stem": census.stem_of(compressed_rollout), "source": "codex_sessions", "path": str(compressed_rollout),
1625
+ "sha256": bound, "versions": [{"sha": bound, "record_count": 1, "prefix_sha": bound}],
1626
+ "owned": [], "work": {"version": 0, "in_window": [], "backlog": []}}]}]}
1627
+ with records.run_stage(inventory_run, "S1") as recorded:
1628
+ records.write_text(inventory_run, inventory_run / "census.json", json.dumps(inventory_census))
1629
+ recorded.output("census.json")
1630
+ code, err = cli("inventory", "--run-id", "r-inventory", "--no-state")
1631
+ control("an ordinary run of the inventory part through the driver succeeds", code == 0, f"{code}")
1632
+ inventory_part = ((records.stage_records(inventory_run).get("S2") or {}).get("parts") or {}).get("inventory") or {}
1633
+ recorded_outputs = {row.get("artifact"): row.get("sha256") for row in inventory_part.get("outputs") or []}
1634
+ written_outputs = {path.relative_to(inventory_run).as_posix(): records.sha256_file(path)
1635
+ for path in (inventory_run / "inventory").rglob("*") if path.is_file()}
1636
+ control("every file the inventory part wrote is an output its stage record names, by its bytes",
1637
+ code == 0 and len(written_outputs) >= 5 and recorded_outputs == written_outputs,
1638
+ f"written={len(written_outputs)} recorded={len(recorded_outputs)}")
1639
+ current_path = inventory_run / "inventory" / "current.json"
1640
+ current_units = (json.loads(current_path.read_text(encoding="utf-8"))["units"]
1641
+ if code == 0 and current_path.is_file() else [])
1642
+ control("a zstd-compressed Codex rollout yields its event, by the decoded block's own text",
1643
+ any(block_marker in unit["text"] for unit in current_units if unit["layer"] == "native_undivided"),
1644
+ f"units={len(current_units)}")
1645
+ census_bytes = (inventory_run / "census.json").read_bytes()
1646
+ (inventory_run / "census.json").write_bytes(census_bytes.replace(b'"cccc"', b'"dddd"'))
1647
+ code, err = cli("inventory", "--run-id", "r-inventory", "--no-state")
1648
+ control("a census changed after S1 recorded it is refused by name",
1649
+ code == 1 and "INPUT_INVALID S1" in err and "census.json is not the output S1 recorded" in err,
1650
+ f"{code}")
1651
+ (inventory_run / "census.json").write_bytes(census_bytes)
1652
+ # X review of WP-08 r2: the inventory part takes the declaration it was admitted against, whichever side of the
1653
+ # admission an amendment lands on
1654
+ for when in ("before", "after"):
1655
+ seq_before = records.read_json(records.run_json_path(inventory_run))["declaration_seq"]
1656
+ given, real_declared = [], sources.declared
1657
+ sources.declared = lambda declaration: (given.append(declaration.get("declaration_seq")), real_declared(declaration))[1]
1658
+ try:
1659
+ with records.fx_amended_at_admission("S2", [("question", f"amended {when} the inventory's admission")], when):
1660
+ code, err = cli("inventory", "--run-id", "r-inventory", "--no-state")
1661
+ finally:
1662
+ sources.declared = real_declared
1663
+ admitted_seq = (((records.stage_records(inventory_run).get("S2") or {}).get("parts") or {})
1664
+ .get("inventory") or {}).get("declaration_seq")
1665
+ landed = records.read_json(records.run_json_path(inventory_run))["declaration_seq"]
1666
+ control(f"X r2: an amendment just {when} the inventory part's admission leaves it reading the declaration it "
1667
+ "was admitted against", code == 0 and given and given[-1] == admitted_seq and landed == seq_before + 1
1668
+ and admitted_seq == (landed if when == "before" else seq_before),
1669
+ f"{code} given={given} admitted={admitted_seq} run.json {seq_before}->{landed}")
1670
+
1671
+ # ---- S-22 (lead, P2.4b): the inventory part registers every artifact inventory's OWN manifest lists,
1672
+ # the shared inventories among them, by its bytes, and the manifest. Asked of the registration itself
1673
+ # over a planted output, inside a real stage: the --no-state run above writes no shared inventory.
1674
+ code, err = cli("declare", "--run-id", "r-register", "--from", str(out / "declaration.json"))
1675
+ control("a fixture run for the registration is declared", code == 0, f"{code}")
1676
+ register_run = out / "r-register"
1677
+ shared_paths = [f"inventory/shared/selection-{inventory.inventory_id('selection', 'a' * 64)}.json",
1678
+ f"inventory/shared/release-{inventory.inventory_id('release', 'ref-a')}.json"]
1679
+ single_paths = [f"inventory/{name}.json" for name in (*inventory.REFERENCES, inventory.SESSIONS)] \
1680
+ + [f"inventory/{inventory.STORE_REL}"]
1681
+ every_path = single_paths + shared_paths + ["inventory/manifest.json"]
1682
+ for n, path in enumerate(every_path):
1683
+ (register_run / path).parent.mkdir(parents=True, exist_ok=True)
1684
+ records.write_text(register_run, register_run / path, json.dumps({"planted": n}))
1685
+ registered_error = None
1686
+ try:
1687
+ with records.run_stage(register_run, "S2", part="inventory") as stage:
1688
+ register_inventory_outputs(stage, {"artifacts": [{"path": path} for path in single_paths + shared_paths]})
1689
+ except Exception as exc: # the control names what refused, never the suite
1690
+ registered_error = exc
1691
+ register_part = ((records.stage_records(register_run).get("S2") or {}).get("parts") or {}).get("inventory") or {}
1692
+ registered = {row.get("artifact"): row.get("sha256") for row in register_part.get("outputs") or []}
1693
+ control("the inventory part registers every artifact inventory's manifest lists, a shared selection and a "
1694
+ "shared release among them, by its bytes, and the manifest",
1695
+ registered_error is None and set(registered) == set(every_path)
1696
+ and all(registered.get(path) == records.sha256_file(register_run / path)
1697
+ for path in shared_paths + ["inventory/manifest.json"]),
1698
+ f"{type(registered_error).__name__ if registered_error else None} registered={sorted(registered)}")
1699
+
1700
+ # ---- GC#6: what the CLI prints crosses the disclosure boundary. `parse_args` and the
1701
+ # refusal printer both stood outside every boundary this run has.
1702
+ secret_argument = "api_key=shortpass"
1703
+ code, err = cli("--bad", secret_argument)
1704
+ control("an argument the parser did not understand is not echoed unprojected",
1705
+ "shortpass" not in err and "REDACTED" in err, f"{code} {err}")
1706
+ code, err = cli("inventory", "--run-id", secret_argument)
1707
+ control("a refusal naming the argument it refused is not printed unprojected",
1708
+ code == 1 and "shortpass" not in err and "RUN_ID_INVALID" in err, f"{code} {err}")
1709
+ missing_under_home = f"{HOME}/a-file-no-run-of-this-suite-creates.json"
1710
+ code, err = cli("declare", "--run-id", "r-file-error", "--from", missing_under_home)
1711
+ control("an unexpected file error is a projected diagnostic, not a raw traceback",
1712
+ code == 1 and HOME not in err and "<HOME>" in err and "COMMAND_FAILED" in err,
1713
+ f"{code} {err}")
1714
+ # The destination is judged before anything is written, locked or recorded: the run
1715
+ # directory itself is a write, so a destination under the state root must be refused by the
1716
+ # CLI and must leave nothing behind (GB#0).
1717
+ guarded_state = scratch / "guarded-state"
1718
+ (guarded_state / "runtime").mkdir(parents=True)
1719
+ inside = guarded_state / "out"
1720
+ code, err = cli("inventory", "--to", str(inside), "--state-root", str(guarded_state),
1721
+ "--user-root", str(scratch / "guarded-user"))
1722
+ control("inventory (S2) refuses a destination inside the owner's state root",
1723
+ code == 1 and "PROTECTED_OVERLAP" in err, f"{code} {err}")
1724
+ control("and writes nothing there", not inside.exists(), f"{sorted(p.name for p in inside.rglob('*'))}"
1725
+ if inside.exists() else "")
1726
+ # The same destination with `--no-state`, which says "read no state root at all". Protection
1727
+ # and reading were one value here: the flag set both roots to None before the protected set
1728
+ # was built, so this exact command exited 0 and wrote current.json, release.json,
1729
+ # selection.json and manifest.json under the owner's own state root (R1#1).
1730
+ code, err = cli("inventory", "--to", str(inside), "--state-root", str(guarded_state),
1731
+ "--user-root", str(scratch / "guarded-user"), "--no-state")
1732
+ control("inventory (S2) refuses that destination with --no-state as well",
1733
+ code == 1 and "PROTECTED_OVERLAP" in err, f"{code} {err}")
1734
+ control("and the attempted write under the unread state root did not happen",
1735
+ not inside.exists() and sorted(p.name for p in guarded_state.rglob("*")) == ["runtime"],
1736
+ f"{sorted(str(p.relative_to(guarded_state)) for p in guarded_state.rglob('*'))}")
1737
+ guarded_user = scratch / "guarded-user-root"
1738
+ guarded_user.mkdir()
1739
+ code, err = cli("inventory", "--to", str(guarded_user / "out"), "--state-root", str(guarded_state),
1740
+ "--user-root", str(guarded_user), "--no-state")
1741
+ control("and the authoring root it does not read is protected under the same flag",
1742
+ code == 1 and "PROTECTED_OVERLAP" in err and not (guarded_user / "out").exists(),
1743
+ f"{code} {err}")
1744
+ # The DEFAULT destination has to satisfy that same protection, or the driver would refuse
1745
+ # its own default when a user runs it with no `--out`. The default is not carved out of the
1746
+ # protected set: it is placed outside it. Judged with the CLI's own predicate, under a HOME
1747
+ # no part of this suite writes to, so the answer is about the rule and not about this tree.
1748
+ default_home = scratch / "default-home"
1749
+ (default_home / ".local" / "state").mkdir(parents=True)
1750
+ default_environ = {"HOME": str(default_home), "PATH": os.environ.get("PATH", "")}
1751
+ default_root = default_out(default_environ, home=default_home)
1752
+ default_state, default_user = inventory.configured_roots(environ=default_environ, home=default_home)
1753
+ package_tree = pathlib.Path(__file__).resolve().parents[1]
1754
+ default_native = {"projects": {str(package_tree): package_tree}}
1755
+ default_protected = inventory.protected_roots(default_state, default_user, default_native,
1756
+ checkout=package_tree, environ=default_environ,
1757
+ repo=package_tree)
1758
+ control("the default run root is outside every protected root",
1759
+ not inventory.overlap_problems([default_root], default_protected, home=str(default_home)),
1760
+ f"{default_root} :: {inventory.overlap_problems([default_root], default_protected, home=str(default_home))}")
1761
+ control("and outside the package tree, so an install does not replace a user's runs",
1762
+ package_tree not in default_root.resolve().parents
1763
+ and default_root.resolve() != package_tree,
1764
+ f"{default_root} under {package_tree}")
1765
+ # review Y #2: where the DEFAULT lands is decided by the environment, and the environment
1766
+ # can put it inside the package or inside the owner's data root. `declare` had no
1767
+ # protection of its own, so the only thing standing between those values and a write was
1768
+ # that nobody had tried them. Each case runs the real CLI with no `--out` at all.
1769
+ def no_out(*argv, **overrides):
1770
+ # the variables that move the roots are the case's own: one the caller's environment sets would place the
1771
+ # owner's data root elsewhere, and the case would test that place instead (a fake environment exports them)
1772
+ overrides = {"XDG_DATA_HOME": None, "AGENT_BIOS_STATE_DIR": None, "AGENT_BIOS_SESSION_DISTILL_STATE": None,
1773
+ **overrides}
1774
+ kept = {name: os.environ.get(name) for name in ("HOME", "XDG_STATE_HOME", *overrides)}
1775
+ err = io.StringIO()
1776
+ try:
1777
+ for name, value in overrides.items():
1778
+ if value is None:
1779
+ os.environ.pop(name, None)
1780
+ else:
1781
+ os.environ[name] = value
1782
+ with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
1783
+ try:
1784
+ code = main(list(argv))
1785
+ except SystemExit as exc:
1786
+ code, _ = (exc.code if isinstance(exc.code, int) else 2), err.write(f"EXITED {exc.code!r}")
1787
+ except Exception as exc:
1788
+ code, _ = 99, err.write(f"RAISED {exc!r}")
1789
+ finally:
1790
+ for name, value in kept.items():
1791
+ if value is None:
1792
+ os.environ.pop(name, None)
1793
+ else:
1794
+ os.environ[name] = value
1795
+ return code, err.getvalue()
1796
+
1797
+ fake_home = scratch / "y2-home"
1798
+ (fake_home / ".local" / "share" / "agent-bios").mkdir(parents=True)
1799
+ (fake_home / ".local" / "state").mkdir(parents=True)
1800
+ declaration = scratch / "y2-declaration.json"
1801
+ declaration.write_text(json.dumps(declare.fixture()), encoding="utf-8")
1802
+ state_root_xdg = str(fake_home / ".local" / "share")
1803
+ code, err = no_out("declare", "--run-id", "y2-data-root", "--from", str(declaration),
1804
+ HOME=str(fake_home), XDG_STATE_HOME=state_root_xdg)
1805
+ control("review Y #2: a default run root inside the owner's DATA root is refused, by name",
1806
+ code == 1 and "DEFAULT_OUT_PROTECTED" in err, f"{code} {err[:300]}")
1807
+ control("and nothing is written under it",
1808
+ not (fake_home / ".local" / "share" / "agent-bios" / "distill").exists(),
1809
+ f"{sorted(q.name for q in (fake_home / '.local' / 'share' / 'agent-bios').rglob('*'))}")
1810
+ linked = scratch / "y2-link"
1811
+ linked.symlink_to(fake_home / ".local" / "share")
1812
+ code, err = no_out("declare", "--run-id", "y2-link", "--from", str(declaration),
1813
+ HOME=str(fake_home), XDG_STATE_HOME=str(linked))
1814
+ control("review Y #2: a SYMLINKED base that lands in the same root is refused too",
1815
+ code == 1 and "DEFAULT_OUT_PROTECTED" in err, f"{code} {err[:300]}")
1816
+ code, err = no_out("declare", "--run-id", "y2-relative-xdg", "--from", str(declaration),
1817
+ HOME=str(fake_home), XDG_STATE_HOME=".")
1818
+ control("review Y #2: a RELATIVE XDG_STATE_HOME is ignored and said so, not resolved "
1819
+ "against the working directory",
1820
+ code == 0 and "DEFAULT_OUT_INPUT_IGNORED" in err and "is relative" in err,
1821
+ f"{code} {err[:300]}")
1822
+ control("and the run landed under the documented default instead",
1823
+ (fake_home / ".local" / "state" / "agent-bios" / "distill" / "runs"
1824
+ / "y2-relative-xdg").is_dir(),
1825
+ f"{sorted(q.name for q in (fake_home / '.local' / 'state').rglob('*'))[:6]}")
1826
+ here = pathlib.Path.cwd()
1827
+ # review Y r2 #1: with a relative $HOME and no XDG, the destination comes from the password
1828
+ # database — the one home this suite could not state, so the run landed in the REAL account
1829
+ # home and a commit hook created `~/.local/state/agent-bios/distill/runs/y2-relative-home/`
1830
+ # there. The control now states the account home it means through the production seam, and a
1831
+ # CANARY reads the real one (names only, never contents) to prove nothing arrived in it.
1832
+ real_account = pathlib.Path(_password_home())
1833
+ canary_root = real_account / ".local" / "state" / "agent-bios"
1834
+ canary_before = (sorted(str(q.relative_to(canary_root)) for q in canary_root.rglob("*"))
1835
+ if canary_root.is_dir() else None)
1836
+ account = scratch / "account-home"
1837
+ account.mkdir()
1838
+ kept_seam = globals()["_password_home"]
1839
+ try:
1840
+ globals()["_password_home"] = lambda: str(account)
1841
+ code, err = no_out("declare", "--run-id", "y2-relative-home", "--from", str(declaration),
1842
+ HOME="relative-home", XDG_STATE_HOME=None)
1843
+ finally:
1844
+ globals()["_password_home"] = kept_seam
1845
+ landed = account / ".local" / "state" / "agent-bios" / "distill" / "runs" / "y2-relative-home"
1846
+ control("review Y #2: a RELATIVE HOME is ignored for the default run root as well",
1847
+ "DEFAULT_OUT_INPUT_IGNORED" in err and "HOME=" in err, f"{code} {err[:300]}")
1848
+ control("review Y r2 #1: and the run lands in the account home the password database states, "
1849
+ "which this control states for itself",
1850
+ code == 0 and (landed / "run.json").is_file(), f"{code} {landed} {err[:200]}")
1851
+ canary_after = (sorted(str(q.relative_to(canary_root)) for q in canary_root.rglob("*"))
1852
+ if canary_root.is_dir() else None)
1853
+ control("review Y r2 #1: and the REAL account home is untouched by this suite",
1854
+ canary_after == canary_before,
1855
+ f"{canary_root}: before {None if canary_before is None else len(canary_before)} "
1856
+ f"after {None if canary_after is None else len(canary_after)}; "
1857
+ f"new {sorted(set(canary_after or []) - set(canary_before or []))[:5]}")
1858
+ # review Y r2 #4: an absolute XDG base determines the whole answer, so a home it does not
1859
+ # need must not be able to refuse it. The home resolution ran FIRST, and an account whose
1860
+ # database home is unreadable then raised DEFAULT_OUT_UNRESOLVED over a destination that was
1861
+ # already fully decided.
1862
+ kept_seam = globals()["_password_home"]
1863
+ try:
1864
+ globals()["_password_home"] = lambda: "not-absolute"
1865
+ try:
1866
+ with contextlib.redirect_stderr(io.StringIO()):
1867
+ xdg_only = default_out({"HOME": "relative-home", "XDG_STATE_HOME": str(scratch / "xdg")})
1868
+ except Refused as exc:
1869
+ # The pre-fix order raises here, and a raised refusal must read as THIS control's
1870
+ # failure rather than ending the suite: a control whose text never prints is a
1871
+ # control a reader cannot act on.
1872
+ xdg_only = f"REFUSED {exc}"
1873
+ try:
1874
+ with contextlib.redirect_stderr(io.StringIO()):
1875
+ refused = f"RETURNED {default_out({'HOME': 'relative-home'})}"
1876
+ except Refused as exc:
1877
+ refused = str(exc)
1878
+ finally:
1879
+ globals()["_password_home"] = kept_seam
1880
+ control("review Y r2 #4: an absolute XDG_STATE_HOME is the base even when no home resolves",
1881
+ isinstance(xdg_only, pathlib.Path)
1882
+ and xdg_only == scratch / "xdg" / "agent-bios" / "distill" / "runs", str(xdg_only))
1883
+ control("review Y r2 #4: and with no XDG base, an unresolvable home is still refused by name",
1884
+ refused.startswith("DEFAULT_OUT_UNRESOLVED"), refused)
1885
+ # review Y r2 #3: an account with no password-database entry and no $HOME. `HOME =
1886
+ # str(pathlib.Path.home())` ran at IMPORT, before either startup boundary, and `Path.home()`
1887
+ # raises in that state — so the machine could not run the command at all, with `--out` or
1888
+ # without, and no boundary could describe why.
1889
+ #
1890
+ # Two decidable controls rather than a re-execution of the module body. Running this file
1891
+ # again as `__main__` (through a child or through `runpy`) is the shape the closure inventory
1892
+ # refuses: a child needs a program a declaration can name, and `runpy.run_path` of a runtime
1893
+ # path is a load the trace cannot resolve. Both refusals are right — this suite has no
1894
+ # business starting the driver again — so the import-time property is asserted where it
1895
+ # lives: in the function that answers, and in the module's own top level.
1896
+ stub = types.ModuleType("pwd")
1897
+ stub.getpwuid = stub.getpwnam = lambda *_a, **_k: (_ for _ in ()).throw(KeyError("no entry"))
1898
+ stub.error = KeyError
1899
+ kept = {"pwd": sys.modules.get("pwd"), "home": os.environ.get("HOME")}
1900
+ try:
1901
+ sys.modules["pwd"] = stub
1902
+ os.environ.pop("HOME", None)
1903
+ answered = _diagnostic_home()
1904
+ raised = None
1905
+ except BaseException as exc: # the defect, reported rather than fatal
1906
+ answered, raised = "RAISED", f"{type(exc).__name__}: {exc}"
1907
+ finally:
1908
+ if kept["pwd"] is None:
1909
+ sys.modules.pop("pwd", None)
1910
+ else:
1911
+ sys.modules["pwd"] = kept["pwd"]
1912
+ if kept["home"] is not None:
1913
+ os.environ["HOME"] = kept["home"]
1914
+ control("review Y r2 #3: with no $HOME and no account entry, the home a diagnostic masks is "
1915
+ "None rather than an exception",
1916
+ answered is None, f"{answered!r} {raised}")
1917
+ # And nothing at the module's TOP LEVEL may ask for a home, which is what made the failure
1918
+ # unreachable by any boundary. Asked of the module's own source, so the next edit that puts
1919
+ # such a call back fails here.
1920
+ def asks_for_a_home(node):
1921
+ return any(isinstance(inner, ast.Attribute) and inner.attr in ("home", "expanduser")
1922
+ for inner in ast.walk(node))
1923
+
1924
+ module = ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8"))
1925
+ top = [node for node in module.body
1926
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
1927
+ and asks_for_a_home(node)]
1928
+ control("review Y r2 #3: and no statement of this module's top level asks for a home at all",
1929
+ not top, [f"line {node.lineno}" for node in top])
1930
+ # That the PRODUCTION path goes through the seam is asserted on the source, not by reverting
1931
+ # it: reverting an inline lookup back into `_account_home` has exactly one observable, a run
1932
+ # written into the owner's real home, which is the damage the fix exists to prevent. A text
1933
+ # assertion is decidable and costs nothing, so an edit that inlines the lookup again fails
1934
+ # here instead of in someone's home directory.
1935
+ resolver = inspect.getsource(_account_home)
1936
+ control("review Y r2 #1: the production resolver reaches the account home only through the "
1937
+ "seam a control can state",
1938
+ "_password_home()" in resolver and "getpwuid" not in resolver,
1939
+ resolver.splitlines()[-6:])
1940
+ # The production resolver itself, against the real database, reading and writing nothing:
1941
+ # the seam above is a control's instrument, and a seam nothing exercises for real is a
1942
+ # second implementation.
1943
+ control("review Y r2 #1: and the production resolver reads an absolute home from the account "
1944
+ "database itself",
1945
+ _account_home().is_absolute(), str(_account_home()))
1946
+ # And the fallback is the ACCOUNT's home, not `Path.home()`, which reads the same relative
1947
+ # $HOME back: this control wrote `relative-home/.local/state/...` into the checkout the
1948
+ # first time it ran, which is the defect it now holds shut.
1949
+ control("and nothing is written relative to the working directory",
1950
+ not (here / "relative-home").exists(),
1951
+ f"{sorted(q.name for q in (here / 'relative-home').rglob('*'))[:5]}"
1952
+ if (here / "relative-home").exists() else "")
1953
+ # The function's own answer, not the write's: a relative $HOME used to come straight back
1954
+ # through `pathlib.Path.home()`, and the only thing that then stopped the write was the
1955
+ # checkout being a protected root — which a packaged install does not have. So the default
1956
+ # is required to be ABSOLUTE at the source, from the account's own home.
1957
+ kept_home = os.environ.get("HOME")
1958
+ try:
1959
+ os.environ["HOME"] = "relative-home" # the ambient value too, or the fallback hides
1960
+ with contextlib.redirect_stderr(io.StringIO()):
1961
+ resolved = default_out({"HOME": "relative-home"})
1962
+ finally:
1963
+ if kept_home is None:
1964
+ os.environ.pop("HOME", None)
1965
+ else:
1966
+ os.environ["HOME"] = kept_home
1967
+ control("review Y #2: the default run root is absolute even when $HOME is not",
1968
+ resolved.is_absolute() and "relative-home" not in resolved.parts, str(resolved))
1969
+ code, err = no_out("declare", "--run-id", "y2-ordinary", "--from", str(declaration),
1970
+ HOME=str(fake_home), XDG_STATE_HOME=None)
1971
+ control("and an ordinary environment still declares a run without being told a destination",
1972
+ code == 0 and (fake_home / ".local" / "state" / "agent-bios" / "distill" / "runs"
1973
+ / "y2-ordinary").is_dir(), f"{code} {err[:300]}")
1974
+ control("and it is the XDG state directory's, not the data directory's",
1975
+ default_root == default_home / ".local" / "state" / "agent-bios" / "distill" / "runs"
1976
+ and str(default_state) not in str(default_root),
1977
+ f"{default_root} / state root {default_state}")
1978
+ # The same destination as a RUN: the stage record is the first write, so the refusal has to
1979
+ # come before the stage is entered at all.
1980
+ # `cli` appends its own --out, so the guarded run lives under it and the state root is that
1981
+ # same directory: the run directory is then inside a root this inventory reads.
1982
+ declared_run = out / "r-guarded"
1983
+ declared_run.mkdir(parents=True)
1984
+ for name in ("run.json", "amendments.jsonl"): # a declared run, so the refusal is about the destination
1985
+ (declared_run / name).write_text((out / "r1" / name).read_text(encoding="utf-8"), encoding="utf-8")
1986
+ code, err = cli("inventory", "--run-id", "r-guarded",
1987
+ "--state-root", str(out), "--user-root", str(scratch / "guarded-user"))
1988
+ control("inventory (S2) refuses a run directory inside the owner's state root",
1989
+ code == 1 and "PROTECTED_OVERLAP" in err, f"{code} {err}")
1990
+ control("and enters no stage, so no stage record is written",
1991
+ not (declared_run / "stages").exists(),
1992
+ f"{sorted(p.name for p in (declared_run / 'stages').rglob('*'))}"
1993
+ if (declared_run / "stages").exists() else "")
1994
+ code, err = cli("views", "--run-id", "r1")
1995
+ control("views (S2) refuses by name when the census it reads is not in the run",
1996
+ code == 1 and "INPUT_INVALID S1" in err, err)
1997
+ # the ruling of 2026-10-22: (d) reserves the cap the S3 call declares. WP-08 gave it a home in run.json
1998
+ # (`output_caps`), so the flag that stood in for it is gone: a caller cannot cut against another number
1999
+ code, err = cli("views", "--run-id", "r1", "--output-cap", "32000")
2000
+ control("views (S2) takes its output cap from run.json, not from a flag",
2001
+ code == 2 and "--output-cap" in err, f"{code} {err}")
2002
+ # the census (S1) through the driver: a declared run over sources that are not there is unknown coverage, not zero
2003
+ coverage_file = scratch / "coverage.json"
2004
+ coverage_file.write_text(records.json_text(coverage.new_state()), encoding="utf-8")
2005
+ table = {"name": census.ORIGINATORS_SOURCE, "path": str(census.ORIGINATORS_PATH), "sha256": census.load_originators()[1]}
2006
+ pinned = {**declare.fixture(), "starting_hashes": {**declare.fixture()["starting_hashes"], "coverage": coverage.load(coverage_file)[1]}}
2007
+ pinned["sources"] = [*pinned["sources"], table]
2008
+ (out / "pinned.json").write_text(json.dumps(pinned), encoding="utf-8")
2009
+ cli("declare", "--run-id", "rc", "--from", str(out / "pinned.json"))
2010
+ code, err = cli("census", "--run-id", "rc", "--coverage", str(coverage_file))
2011
+ document = json.loads((out / "rc" / "census.json").read_text(encoding="utf-8")) if (out / "rc" / "census.json").is_file() else {}
2012
+ control("census over sources that are not there succeeds and reports them unknown",
2013
+ code == 0 and {n: s["totals"] for n, s in document.get("sources", {}).items() if s["state"] == "missing"}
2014
+ == {"claude_projects": None, "codex_sessions": None} and document["transcripts"] == [], err)
2015
+ control("census recorded its stage", records.read_json(records.record_path(out / "rc", "S1"))["status"] == "complete")
2016
+ pinned_stale = {**pinned, "starting_hashes": {**pinned["starting_hashes"], "coverage": "1" * 64}}
2017
+ (out / "stale.json").write_text(json.dumps(pinned_stale), encoding="utf-8")
2018
+ cli("declare", "--run-id", "rs", "--from", str(out / "stale.json"))
2019
+ code, err = cli("census", "--run-id", "rs", "--coverage", str(coverage_file))
2020
+ control("census over a coverage state the declaration did not pin is refused", code == 1 and "COVERAGE_BASE_STALE" in err, err)
2021
+ code, err = cli("census", "--run-id", "nobody", "--coverage", str(coverage_file))
2022
+ control("census of a run that was never declared is refused", code == 1 and "RUN_UNDECLARED" in err, err)
2023
+ results = scratch / "results.json"
2024
+ results.write_text("[]", encoding="utf-8")
2025
+ code, err = cli("census", "--run-id", "rc", "--reconcile", str(results))
2026
+ reconciled = (out / "rc" / "census.reconciled.json").is_file() and (out / "rc" / "coverage.reconciled.json").is_file()
2027
+ control("census --reconcile folds S3's (empty) results back into new files beside S1's own", code == 0 and reconciled, err)
2028
+
2029
+ code, err = cli("close", "--run-id", "r1", "--recovery")
2030
+ control("close --recovery is reserved", code == 2 and "RECOVERY_RESERVED" in err, err)
2031
+ code, err = cli("declare", "--run-id", "r1")
2032
+ control("declare with nothing to do is refused", code == 1 and "DECLARATION_INVALID" in err, err)
2033
+ code, err = cli("declare", "--run-id", "r1", "--set", "budget.reserve")
2034
+ control("--set without a value is refused", code == 1 and "expected PATH=VALUE" in err, err)
2035
+ code, err = cli("declare", "--set", "budget.reserve=1")
2036
+ control("declare without a run is refused", code == 1 and "needs the run it declares" in err, err)
2037
+ code, err = cli("declare", "--run-id", "r1", "--from", str(out / "declaration.json"), "--set", "budget.reserve=1")
2038
+ control("a new declaration takes no --set", code == 1 and "takes no --set or --amend" in err, err)
2039
+ code, err = cli("declare", "--run-id", "r1", "--from", str(out / "declaration.json"))
2040
+ control("a declaration is never replaced", code == 1 and "RUN_EXISTS" in err, err)
2041
+
2042
+ # ---- R1#3: startup and this suite's own output cross the same boundary.
2043
+ #
2044
+ # A startup failure is a real process: the imports run before anything this file controls, so
2045
+ # the only way to observe them is to start the driver with the failure in place. The fixture
2046
+ # is `runlib/validate.py`'s own refusal — it exits during import when the jsonschema pin is
2047
+ # unreadable, interpolating the absolute pin path — reproduced in a COPY of the checkout, so
2048
+ # nothing in this one is touched and `validate.py`'s exits are left exactly as they are (other
2049
+ # modules and gates import it).
2050
+ startup_copy = scratch / "startup-checkout"
2051
+ inventory.checkout_copy(startup_copy)
2052
+ pin_file = startup_copy / "launch" / "provision-venv.sh"
2053
+ pin_file.write_text("JSONSCHEMA_PIN is not where this reads it from\n", encoding="utf-8")
2054
+ # The child's HOME is the fixture's, so "the owner's home" is a path this control owns and
2055
+ # the floor has something to mask. Without it the fixture sits under the system temp
2056
+ # directory, which is nobody's home, and the control would pass on a message that happened
2057
+ # to carry no home path rather than on one the floor projected.
2058
+ startup_env = {**os.environ, "HOME": str(scratch)}
2059
+ startup = entry.bounded(lambda: subprocess.Popen(
2060
+ [sys.executable,
2061
+ str(inventory.copied_member(startup_copy, "session-distill/distill.py")),
2062
+ "inventory", "--to", str(scratch / "startup-out"), "--no-state"],
2063
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=startup_env,
2064
+ start_new_session=True), what="the copy's driver at startup")
2065
+ control("an unreadable pin at startup is a projected diagnostic, not an unprojected path",
2066
+ startup.returncode != 0 and "JSONSCHEMA_PIN_UNREADABLE" in startup.stderr
2067
+ and str(startup_copy) not in startup.stderr and "<HOME>" in startup.stderr,
2068
+ f"{startup.returncode} {startup.stdout[-200:]} {startup.stderr[-400:]}")
2069
+ control("and it wrote no artifact", not (scratch / "startup-out").exists(),
2070
+ "a refused startup still wrote its output directory")
2071
+ # The other half: when the FLOOR is what failed, there is nothing that can project a message,
2072
+ # so a fixed path-free line with a constant code stands instead of an exception text.
2073
+ (startup_copy / "learn" / "redact.py").write_text(
2074
+ "raise RuntimeError('the floor is broken')\n", encoding="utf-8")
2075
+ floorless = entry.bounded(lambda: subprocess.Popen(
2076
+ [sys.executable,
2077
+ str(inventory.copied_member(startup_copy, "session-distill/distill.py")),
2078
+ "inventory", "--to", str(scratch / "floorless-out"), "--no-state"],
2079
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=startup_env,
2080
+ start_new_session=True), what="the copy's driver with no floor")
2081
+ control("a startup whose floor cannot load prints the fixed path-free line",
2082
+ floorless.returncode != 0 and floorless.stderr.strip() == STARTUP_WITHHELD,
2083
+ f"{floorless.returncode} {floorless.stderr[-300:]}")
2084
+ # Earlier in startup than both: the boundary module itself does not import, so only the
2085
+ # bootstrap at the top of this file can answer (r3 #2). Its line and its own code, and nothing
2086
+ # after them: without the exit the bootstrap falls through to `entry.WITHHELD`, and the
2087
+ # NameError's traceback carries the copy's paths under code 1. Inventory's suite asks this of
2088
+ # the copy too; this suite asks it of its own entry point, so removing the exit fails here.
2089
+ (startup_copy / "session-distill" / "runlib" / "entry.py").unlink()
2090
+ boundaryless = entry.bounded(lambda: subprocess.Popen(
2091
+ [sys.executable,
2092
+ str(inventory.copied_member(startup_copy, "session-distill/distill.py")),
2093
+ "inventory", "--to", str(scratch / "boundaryless-out"), "--no-state"],
2094
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=startup_env,
2095
+ start_new_session=True), what="the copy's driver with no boundary")
2096
+ control("a startup whose boundary module cannot load prints the bootstrap's line, exits with its code "
2097
+ "and prints no traceback",
2098
+ boundaryless.returncode == STARTUP_UNAVAILABLE_CODE
2099
+ and boundaryless.stderr.strip() == STARTUP_UNAVAILABLE
2100
+ and "Traceback" not in boundaryless.stderr and str(startup_copy) not in boundaryless.stderr
2101
+ and not (scratch / "boundaryless-out").exists(),
2102
+ f"{boundaryless.returncode} {boundaryless.stderr[-300:]}")
2103
+ # This suite's own failure lines leave through `say`, so a planted path in one is masked. The
2104
+ # printer is called directly with rows this control builds, which is the only way to observe
2105
+ # a FAILING self-test without failing this one.
2106
+ planted_failure = io.StringIO()
2107
+ with contextlib.redirect_stderr(planted_failure):
2108
+ code = report([("a fixture control", f"read {HOME}/Documents/x")], [], "fixture --self-test")
2109
+ printed = planted_failure.getvalue()
2110
+ control("a self-test failure line carrying the owner's home path is projected",
2111
+ code == 1 and HOME not in printed and "<HOME>" in printed, f"{code} {printed!r}")
2112
+
2113
+ # ---- N3: `main`'s OWN boundary, observed alone and in this process. A real child cannot
2114
+ # tell the two layers apart: `main`'s handler and the `entry.guarded` around `__main__` both
2115
+ # print a COMMAND_FAILED line, so moving the self-test back outside `main`'s `try` left every
2116
+ # control green — the outer layer caught the same failure and said the same thing. Here the
2117
+ # suite is replaced by one that raises a file error carrying a path, `main` is called
2118
+ # directly, and the failure has to be caught, named with the command, and projected without
2119
+ # the exception leaving `main` at all. The inner layer names the command; the outer does not.
2120
+ # What is patched is the SUITE'S SCRATCH, not the suite: `self_test_scratch` is this suite's
2121
+ # first operation, so an ordinary file failure there is the real shape — the inner run gets
2122
+ # no further and cannot recurse. This replaced a child process running the whole suite, which
2123
+ # is what made recursion possible at all (S4).
2124
+ held_scratch = inventory.self_test_scratch
2125
+ inner_stream, inner_code = io.StringIO(), "RAISED nothing"
2126
+ try:
2127
+ def _unwritable_scratch(*_args, **_kwargs):
2128
+ raise PermissionError(13, "Permission denied", f"{HOME}/Documents/fixture-scratch")
2129
+ inventory.self_test_scratch = _unwritable_scratch
2130
+ with contextlib.redirect_stderr(inner_stream):
2131
+ inner_code = main(["--self-test"])
2132
+ except BaseException as escaped:
2133
+ inner_code = f"RAISED {type(escaped).__name__}"
2134
+ finally:
2135
+ inventory.self_test_scratch = held_scratch
2136
+ inner_text = inner_stream.getvalue()
2137
+ control("a file failure inside the self-test is caught by main's own boundary, not the one outside it",
2138
+ inner_code == 1 and "COMMAND_FAILED self-test:" in inner_text
2139
+ and HOME not in inner_text and "<HOME>" in inner_text,
2140
+ f"{inner_code} {inner_text!r}")
2141
+ control("and the interpreter printed no traceback and no raw fixture path",
2142
+ "Traceback" not in inner_text and f"{HOME}/Documents" not in inner_text,
2143
+ f"{inner_text!r}")
2144
+
2145
+ # The layer OUTSIDE `main` needs its own control, and the two layers are behaviourally
2146
+ # indistinguishable from a child process: everything `main` catches it also names, and what
2147
+ # only the outer layer catches — a `BaseException` that is not an `Exception`, a `SystemExit`
2148
+ # carrying a message — cannot be provoked through the CLI from outside. So the layer is
2149
+ # asked in two parts: what it does, in this process, and that `__main__` is wired to it.
2150
+ exit_stream = io.StringIO()
2151
+ exit_code = entry.guarded(lambda: (_ for _ in ()).throw(SystemExit(f"{HOME}/Documents/x")),
2152
+ home=HOME, stream=exit_stream)
2153
+ exit_text = exit_stream.getvalue()
2154
+ control("the layer outside main projects an exit message main never sees",
2155
+ exit_code == 2 and HOME not in exit_text and "<HOME>" in exit_text,
2156
+ f"{exit_code} {exit_text!r}")
2157
+ entry_calls = [node for node in ast.walk(ast.parse(pathlib.Path(__file__).read_text(encoding="utf-8")))
2158
+ if isinstance(node, ast.If) and ast.unparse(node.test) == "__name__ == '__main__'"
2159
+ for node in ast.walk(node) if isinstance(node, ast.Call)
2160
+ and ast.unparse(node.func) == "entry.guarded"]
2161
+ control("and this entry point is wired to that layer rather than calling main itself",
2162
+ len(entry_calls) == 1 and "main" in ast.unparse(entry_calls[0]),
2163
+ f"{[ast.unparse(call) for call in entry_calls]}")
2164
+
2165
+ # ---- R2#7, in this process. The judged parent is what decides where this suite writes,
2166
+ # and both halves of it are decidable here: with a fixture `TMPDIR` inside a fixture host
2167
+ # home the one scratch function REFUSES by name and creates nothing, and with an ordinary
2168
+ # one the directory it returns has that parent. Observing this used to take a child running
2169
+ # the whole suite, with `--self-test` in its argv — which is how one revert recursed 594
2170
+ # deep. No child of this suite runs a suite any more (S4).
2171
+ fixture_home = scratch / "entry-fixture-home"
2172
+ guarded_tmp = fixture_home / ".claude" / "tmp"
2173
+ guarded_tmp.mkdir(parents=True)
2174
+ guarded_env = {"HOME": str(fixture_home), "CLAUDE_CONFIG_DIR": str(fixture_home / ".claude"),
2175
+ "TMPDIR": str(guarded_tmp), "PATH": os.environ.get("PATH", "/usr/bin:/bin")}
2176
+ refused_scratch = ""
2177
+ try:
2178
+ with inventory.self_test_scratch("wp07-refused-", environ=guarded_env):
2179
+ refused_scratch = "the judged parent accepted a location inside a host home"
2180
+ except Exception as exc:
2181
+ refused_scratch = f"{type(exc).__name__}: {exc}"
2182
+ control("the driver's self-test passes the judged parent to TemporaryDirectory",
2183
+ "PROTECTED_OVERLAP" in refused_scratch, refused_scratch[:300])
2184
+ control("and nothing was created in the location the judgement refused",
2185
+ not any(guarded_tmp.iterdir()),
2186
+ f"{sorted(path.name for path in guarded_tmp.iterdir())}")
2187
+ # The other half: the fixtures really do land under the parent the rule chose. This is what
2188
+ # the child's own report line used to say from outside.
2189
+ open_tmp = scratch / "open-tmp"
2190
+ open_tmp.mkdir()
2191
+ open_env = {**guarded_env, "TMPDIR": str(open_tmp)}
2192
+ with inventory.self_test_scratch("wp07-accepted-", environ=open_env) as nested_scratch:
2193
+ placed = (nested_scratch.parent, nested_scratch.is_dir())
2194
+ control("and the suite's own fixtures are created under that parent, nowhere else",
2195
+ placed == (inventory.scratch_parent(open_env), True)
2196
+ and inventory.scratch_parent(open_env) == open_tmp,
2197
+ f"{inventory.masked(placed[0])} vs {inventory.masked(open_tmp)} created={placed[1]}")
2198
+ # ---- the child bound ends a TREE, not a process. Returning as soon as the leader exited
2199
+ # left every descendant running, and a descendant holding the pipe is what kept a runaway
2200
+ # filling the disk after each kill (r3 #1). Both fixtures are FINITE — three seconds and
2201
+ # gone — so a cleanup defect here ends on its own instead of leaving a process behind.
2202
+ held_group = entry.bounded(lambda: subprocess.Popen(
2203
+ [sys.executable, "-c", IGNORES_TERM], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2204
+ text=True, start_new_session=True), timeout=0.5, what="a TERM-ignoring descendant")
2205
+ descendant = [int(line.split()[1]) for line in held_group.stdout.splitlines()
2206
+ if line.startswith("DESCENDANT")]
2207
+ control("a bound reached with a descendant holding the pipe is a named failure, not a wait",
2208
+ held_group.returncode == entry.TIMED_OUT
2209
+ and "CHILD_TIMEOUT" in held_group.stderr, f"{held_group.returncode} {held_group.stderr!r}")
2210
+ def process_alive(pid):
2211
+ """Whether THIS PROCESS still stands. The descendant leads no group of its own, so
2212
+ `group_alive` asked `killpg` about a group that never existed and read the
2213
+ `ProcessLookupError` as "gone" whether the descendant lived or not — the control passed
2214
+ over a removed kill (r4 R2). It is reparented and reaped by init when its leader dies, so
2215
+ a pid that is gone raises here rather than lingering as a zombie."""
2216
+ try:
2217
+ os.kill(pid, 0)
2218
+ return True
2219
+ except ProcessLookupError:
2220
+ return False
2221
+ except PermissionError: # it exists and is not ours to signal
2222
+ return True
2223
+
2224
+ def process_gone(pid, within_s=5.0):
2225
+ """Whether the pid stops standing within `within_s`. A killed orphan stands as a zombie until init reaps
2226
+ it, and under a loaded commit hook that reaping lags, so one look read a killed descendant as living (one
2227
+ hook run, 2026-11-12). The descendant sleeps 90 seconds, so a kill that was removed still leaves it
2228
+ standing past the bound, and this control fails by its name."""
2229
+ deadline = time.monotonic() + within_s
2230
+ while process_alive(pid):
2231
+ if time.monotonic() >= deadline:
2232
+ return False
2233
+ time.sleep(0.05)
2234
+ return True
2235
+
2236
+ control("and the descendant that outlived its leader is gone afterwards",
2237
+ len(descendant) == 1 and process_gone(descendant[0]),
2238
+ f"{descendant} alive={[process_alive(pid) for pid in descendant]} {held_group.stdout!r}")
2239
+ control("and that pid was really a process this control could have seen alive",
2240
+ len(descendant) == 1 and descendant[0] > 1, f"{descendant}")
2241
+ # ---- r4 R2: that SIGTERM and that SIGKILL, asked of `end_group` ALONE. No process, no
2242
+ # fixture and no `finish_group`: the leader reports itself exited the moment the SIGTERM is
2243
+ # recorded, which is the shape the unconditional SIGKILL exists for — returning as soon as
2244
+ # the leader exited left every descendant running (r3 #1). A control that reads a fixture's
2245
+ # aftermath cannot tell a kill that fired from a lifetime that ran out.
2246
+ class _ExitsOnTerm:
2247
+ """A leader that is not a process: it reports running until the group is signalled, and
2248
+ exited after. `end_group` reads only `poll`, `pid` and `kill`."""
2249
+ args, returncode, pid = ("a leader that exits on SIGTERM",), None, 4322
2250
+
2251
+ def poll(self):
2252
+ return 0 if group_signals else None
2253
+
2254
+ def kill(self):
2255
+ group_signals.append((self.pid, "kill()"))
2256
+
2257
+ held_killpg, group_signals = os.killpg, []
2258
+ try:
2259
+ os.killpg = lambda pgid, sig: group_signals.append((pgid, sig))
2260
+ end_note = entry.end_group(_ExitsOnTerm(), 4322)
2261
+ finally:
2262
+ os.killpg = held_killpg
2263
+ control("end_group signals SIGTERM and then SIGKILL even though the leader exited after the SIGTERM",
2264
+ group_signals == [(4322, signal.SIGTERM), (4322, signal.SIGKILL)] and end_note == "",
2265
+ f"{group_signals} note={end_note!r}")
2266
+ control("and os.killpg is the real one again after that control",
2267
+ os.killpg is held_killpg, f"{os.killpg}")
2268
+ # The same, for a leader that never exits: the second signal still goes, and nothing waits on
2269
+ # the group emptying — that is `finish_group`'s question, not this one's.
2270
+ held_killpg, standing_signals = os.killpg, []
2271
+
2272
+ class _NeverExits(_ExitsOnTerm):
2273
+ def poll(self):
2274
+ return None
2275
+
2276
+ try:
2277
+ os.killpg = lambda pgid, sig: standing_signals.append((pgid, sig))
2278
+ # It waits out its own eight quarter-second rounds per signal, which is the real
2279
+ # behaviour and costs four seconds; nothing here is a process, so nothing is left behind.
2280
+ standing_note = entry.end_group(_NeverExits(), 4322)
2281
+ finally:
2282
+ os.killpg = held_killpg
2283
+ control("and a leader that never exits is sent both signals too, without waiting for the group to empty",
2284
+ standing_signals == [(4322, signal.SIGTERM), (4322, signal.SIGKILL)] and standing_note == "",
2285
+ f"{standing_signals} note={standing_note!r}")
2286
+
2287
+ # ---- the group-end ROUND, which S4 added and no control read: with `for _ in range(rounds)`
2288
+ # emptied, every suite of this package stayed green (S8b's probe). Driven IN THIS PROCESS with
2289
+ # a counting probe in place of `entry.group_alive` and a counting `os.killpg`, so no process
2290
+ # and no waiting on one is involved. What the round says is that the group is SIGNALLED once
2291
+ # per round until it is empty — "it returns False" is not the rule: a group that never empties
2292
+ # gives False with no rounds at all, which is exactly what the emptied loop does.
2293
+ class _NeverAnswers:
2294
+ """A child that never answers, and is not a process. `bounded`'s timeout path reads only
2295
+ these members; `poll` reports an exited leader so `end_group` waits on nothing."""
2296
+ args, returncode, pid = ("a child that never answers",), None, 4321
2297
+
2298
+ def communicate(self, timeout=None):
2299
+ raise subprocess.TimeoutExpired(self.args, timeout)
2300
+
2301
+ def kill(self):
2302
+ pass
2303
+
2304
+ def poll(self):
2305
+ return 0
2306
+
2307
+ held_alive, held_killpg, held_getpgid = entry.group_alive, os.killpg, os.getpgid
2308
+ held_finish, asked, signalled = entry.finish_group, [], []
2309
+ try:
2310
+ entry.group_alive = lambda pgid: (asked.append(pgid), True)[1]
2311
+ os.killpg = lambda pgid, sig: signalled.append((pgid, sig))
2312
+ standing = entry.finish_group(4321, rounds=2)
2313
+ standing_kills, standing_asked = list(signalled), list(asked)
2314
+ asked.clear()
2315
+ signalled.clear()
2316
+ answers = [True, False]
2317
+ entry.group_alive = lambda pgid: (asked.append(pgid),
2318
+ answers.pop(0) if answers else False)[1]
2319
+ cleared, cleared_asked = entry.finish_group(4321, rounds=5), None
2320
+ cleared_asked = list(asked)
2321
+ # The NAME the round's failure carries belongs to `bounded`, which is the round's only
2322
+ # caller. Reached with the same probe and a two-round bound, so this leg waits on nothing
2323
+ # either; the round logic itself is the real one.
2324
+ entry.group_alive = lambda pgid: (asked.append(pgid), True)[1]
2325
+ entry.finish_group = lambda pgid, rounds=2: held_finish(pgid, rounds=rounds)
2326
+ os.getpgid = lambda _pid: 4321
2327
+ never = entry.bounded(_NeverAnswers, timeout=0.01, what="a child that never answers")
2328
+ finally:
2329
+ entry.group_alive, os.killpg, os.getpgid = held_alive, held_killpg, held_getpgid
2330
+ entry.finish_group = held_finish
2331
+ control("the group-end round signals the group once per round until it is empty",
2332
+ standing is False and len(standing_kills) == 2
2333
+ and all(sig == signal.SIGKILL for _pgid, sig in standing_kills)
2334
+ and cleared is True and len(cleared_asked) >= 2,
2335
+ f"standing={standing} kills={standing_kills} asked={standing_asked}/{cleared_asked} "
2336
+ f"cleared={cleared}")
2337
+ control("and every swap this control made is back, so no later control runs against a fake",
2338
+ (entry.group_alive, os.killpg, os.getpgid, entry.finish_group)
2339
+ == (held_alive, held_killpg, held_getpgid, held_finish),
2340
+ f"{entry.group_alive} {os.killpg} {os.getpgid} {entry.finish_group}")
2341
+ control("and a group that never empties is named, not waited on",
2342
+ never.returncode == entry.TIMED_OUT
2343
+ and "CHILD_CLEANUP_UNFINISHED" in never.stderr
2344
+ and "still holds a process after" in never.stderr,
2345
+ f"{never.returncode} {never.stderr!r}")
2346
+
2347
+ # Ownership not established is child-only. `os.getpgid` refusing used to fall back to the
2348
+ # child's pid as the group id, which points `killpg` at whatever group the child is in — this
2349
+ # process's own, when the child was started without a session (G1).
2350
+ held_getpgid, held_killpg, signalled = os.getpgid, os.killpg, []
2351
+ try:
2352
+ os.getpgid = lambda _pid: (_ for _ in ()).throw(OSError(3, "No such process"))
2353
+ os.killpg = lambda pgid, sig: signalled.append((pgid, sig))
2354
+ unowned = entry.bounded(lambda: subprocess.Popen(
2355
+ [sys.executable, "-c", SLEEPS_BRIEFLY], stdout=subprocess.PIPE,
2356
+ stderr=subprocess.PIPE, text=True, start_new_session=True),
2357
+ timeout=0.5, what="a child whose group cannot be established")
2358
+ finally:
2359
+ os.getpgid, os.killpg = held_getpgid, held_killpg
2360
+ control("a child whose group cannot be established is ended alone, with no group signalled",
2361
+ signalled == [] and unowned.returncode == entry.TIMED_OUT
2362
+ and "could not be established" in unowned.stderr,
2363
+ f"{signalled} {unowned.returncode} {unowned.stderr!r}")
2364
+
2365
+ # ---- S8f: default-deny at spawn. A child that leads no group of its own is one no bound
2366
+ # here can end, so it is refused rather than recorded — r8's W6 showed the shape, where the
2367
+ # shell was ended and the tree it had started was not, and only a control written for that
2368
+ # one fixture noticed. `os.killpg` is a recorder, as in the branch above, so "no group was
2369
+ # signalled" is READ and not assumed; the child is finite either way.
2370
+ started, held_killpg, signalled_group = [], os.killpg, []
2371
+ try:
2372
+ os.killpg = lambda pgid, sig: signalled_group.append((pgid, sig))
2373
+ no_session = entry.bounded(lambda: started.append(subprocess.Popen(
2374
+ [sys.executable, "-c", SLEEPS_BRIEFLY], stdout=subprocess.PIPE,
2375
+ stderr=subprocess.PIPE, text=True)) or started[-1],
2376
+ timeout=20, what="a child without a session of its own")
2377
+ finally:
2378
+ os.killpg = held_killpg
2379
+ control("a child started without a session of its own is refused by name, and no group is signalled",
2380
+ no_session.returncode == entry.NOT_GROUP_LEADER
2381
+ and "CHILD_NOT_GROUP_LEADER" in no_session.stderr and signalled_group == [],
2382
+ f"{no_session.returncode} {no_session.stderr!r} {signalled_group}")
2383
+ control("and that child is gone, ended alone rather than left to the bound",
2384
+ len(started) == 1 and started[0].poll() is not None,
2385
+ f"{[proc.poll() for proc in started]}")
2386
+ control("and os.killpg is the real one again, so no later control reads a recorder",
2387
+ os.killpg is held_killpg, f"{os.killpg}")
2388
+
2389
+ # The ordinary shape: the leader exits first and a descendant holds the pipe for a moment.
2390
+ # The bound must not fire, and the leader's own code must come back.
2391
+ early = entry.bounded(lambda: subprocess.Popen(
2392
+ [sys.executable, "-c", LEADER_FIRST], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
2393
+ text=True, start_new_session=True), timeout=20, what="a leader that exits first")
2394
+ control("a leader that exits before its descendant still returns its own result",
2395
+ early.returncode == 0 and "LEADER DONE" in early.stdout
2396
+ and "CHILD_TIMEOUT" not in early.stderr,
2397
+ f"{early.returncode} {early.stdout!r} {early.stderr!r}")
2398
+
2399
+ # A suite inside a suite inside a suite is the recursion, and the depth is counted in this
2400
+ # process rather than in an environment a child would inherit. Depth 2 is this file's own
2401
+ # inner run above and stays allowed; depth 3 is refused by name.
2402
+ held_depth = inventory.SELF_TEST_DEPTH[0]
2403
+ too_deep = ""
2404
+ try:
2405
+ inventory.SELF_TEST_DEPTH[0] = inventory.SELF_TEST_DEPTH_LIMIT
2406
+ with inventory.self_test_scratch("wp07-too-deep-"):
2407
+ too_deep = "a third suite was given a scratch directory"
2408
+ except Exception as exc:
2409
+ too_deep = f"{type(exc).__name__}: {exc}"
2410
+ finally:
2411
+ inventory.SELF_TEST_DEPTH[0] = held_depth
2412
+ control("a suite starting inside a suite at the depth limit is refused by name",
2413
+ "SELF_TEST_TOO_DEEP" in too_deep, too_deep[:200])
2414
+
2415
+ # ---- r4 R1: THIS runner's own abort handlers, driven. `main`'s handled-refusal handler said
2416
+ # the refusal and returned, so a refusal raised inside the suite took every collected failure
2417
+ # line with it; only the unexpected-failure handler published. The claim was read out of the
2418
+ # source in inventory's suite, where any handler of a file reaching the call satisfied it.
2419
+ # The handler is exercised here instead, through `main` with a planted command handler.
2420
+ held_handler = globals()["cmd_census"]
2421
+ for kind, planted_exc in (("a refusal", Refused("a planted refusal")),
2422
+ ("a stage lock held elsewhere", stagelock.Locked("a planted lock")),
2423
+ ("an escaped path", stagelock.Escaped("a planted escape")),
2424
+ ("an unexpected failure", RuntimeError("a planted failure"))):
2425
+ planted_row = ("a planted suite --self-test", ["a failure an abort must not swallow"])
2426
+ entry.SELF_TEST_COLLECTED.append(planted_row)
2427
+ buffer = io.StringIO()
2428
+ try:
2429
+ def raising_handler(_args, _exc=planted_exc):
2430
+ raise _exc
2431
+
2432
+ globals()["cmd_census"] = raising_handler
2433
+ held_stderr, sys.stderr = sys.stderr, buffer
2434
+ try:
2435
+ code = main(["census"])
2436
+ finally:
2437
+ sys.stderr = held_stderr
2438
+ finally:
2439
+ globals()["cmd_census"] = held_handler
2440
+ entry.SELF_TEST_COLLECTED.remove(planted_row)
2441
+ control(f"main publishes the failures the suite collected when the command raises {kind}",
2442
+ "a failure an abort must not swallow" in buffer.getvalue() and code == 1,
2443
+ f"code={code} out={buffer.getvalue()[:300]!r}")
2444
+ control("and the real census handler is back, so no later control runs a raiser",
2445
+ globals()["cmd_census"] is held_handler, f"{globals()['cmd_census']}")
2446
+ clean_buffer = io.StringIO()
2447
+ held_stderr, sys.stderr = sys.stderr, clean_buffer
2448
+ try:
2449
+ entry.SELF_TEST_COLLECTED.append(("a planted suite --self-test", ["a failure nothing aborted"]))
2450
+ try:
2451
+ main(["--help"])
2452
+ except SystemExit:
2453
+ pass
2454
+ finally:
2455
+ sys.stderr = held_stderr
2456
+ entry.SELF_TEST_COLLECTED.pop()
2457
+ control("and a command that does not abort publishes nothing of what a suite collected",
2458
+ "a failure nothing aborted" not in clean_buffer.getvalue(),
2459
+ f"{clean_buffer.getvalue()[:200]!r}")
2460
+
2461
+ # ---- Stop at the first failure (`entry.STOP_AT_FIRST_FAILURE`). A planted miniature suite in
2462
+ # this process, collecting through `entry.self_test_failures` and run through the same
2463
+ # `entry.guarded` the real suites run inside: two passing controls around two failing ones.
2464
+ # This suite's own row is set aside while it runs, so an abort of the miniature publishes only
2465
+ # the miniature's lines, and the variable is put back as this suite found it.
2466
+ def miniature(results, outcomes=(True, False, False, True), nested=None, publish=None, add="append"):
2467
+ def suite():
2468
+ mini_failures, mini_ran = entry.self_test_failures("a planted suite --self-test", publish), []
2469
+ results["list"] = type(mini_failures).__name__
2470
+ entry.SELF_TEST_COLLECTED.append(("a planted suite --self-test", mini_failures))
2471
+ if nested is not None:
2472
+ results["nested"] = nested()
2473
+ for at, ok in enumerate(outcomes):
2474
+ mini_ran.append(f"planted control {at}")
2475
+ planted = [] if ok else [(f"planted control {at}", "planted to fail")]
2476
+ if add == "+=":
2477
+ # Every control adds, a passing one nothing, as projection's `+=` of a
2478
+ # comprehension does: an empty addition must not stop the suite.
2479
+ mini_failures += planted
2480
+ elif planted:
2481
+ mini_failures.append(planted[0])
2482
+ results["ran"] = len(mini_ran)
2483
+ entry.SELF_TEST_COLLECTED.remove(("a planted suite --self-test", mini_failures))
2484
+ for name, detail in mini_failures:
2485
+ entry.emit(entry.failure_text("a planted suite --self-test", name, detail), sys.stderr)
2486
+ if mini_failures:
2487
+ return 1
2488
+ say(f"a planted suite --self-test: OK ({len(mini_ran)} controls)")
2489
+ return 0
2490
+ return suite
2491
+
2492
+ def run_miniature(stop, **kwargs):
2493
+ results, buffer = {}, io.StringIO()
2494
+ held_rows, held_mode = entry.SELF_TEST_COLLECTED[:], os.environ.get(entry.STOP_AT_FIRST_FAILURE)
2495
+ entry.SELF_TEST_COLLECTED[:] = []
2496
+ if stop:
2497
+ os.environ[entry.STOP_AT_FIRST_FAILURE] = "1"
2498
+ else:
2499
+ os.environ.pop(entry.STOP_AT_FIRST_FAILURE, None)
2500
+ try:
2501
+ with contextlib.redirect_stdout(buffer), contextlib.redirect_stderr(buffer):
2502
+ results["code"] = entry.guarded(miniature(results, **kwargs), stream=buffer)
2503
+ results["left"] = os.environ.get(entry.STOP_AT_FIRST_FAILURE)
2504
+ finally:
2505
+ entry.SELF_TEST_COLLECTED[:] = held_rows
2506
+ if held_mode is None:
2507
+ os.environ.pop(entry.STOP_AT_FIRST_FAILURE, None)
2508
+ else:
2509
+ os.environ[entry.STOP_AT_FIRST_FAILURE] = held_mode
2510
+ return results, buffer.getvalue()
2511
+
2512
+ stopped, stopped_text = run_miniature(True)
2513
+ control("stop at the first failure: set, a suite leaves right after its first failure with a non-zero "
2514
+ "exit, that failure's line and no later one",
2515
+ stopped.get("code") == 1 and stopped.get("list") == "FailuresThatStop"
2516
+ and "a planted suite --self-test [FAIL] planted control 1:" in stopped_text
2517
+ and "planted control 2" not in stopped_text and "ran" not in stopped
2518
+ and "stopped at its first failure" in stopped_text and stopped.get("left") is None,
2519
+ f"{stopped} {stopped_text[:300]!r}")
2520
+ clean_run, clean_text = run_miniature(True, outcomes=(True, True, True, True), add="+=")
2521
+ control("stop at the first failure: set, a suite with no failure runs to its end with its OK line and "
2522
+ "count, though each control added an empty list",
2523
+ clean_run.get("code") == 0 and clean_run.get("ran") == 4
2524
+ and "a planted suite --self-test: OK (4 controls)" in clean_text and "stopped" not in clean_text,
2525
+ f"{clean_run} {clean_text[:300]!r}")
2526
+ full, full_text = run_miniature(False)
2527
+ control("stop at the first failure: unset, a suite with an early failure runs on and reports every failure",
2528
+ full.get("code") == 1 and full.get("ran") == 4 and full.get("list") == "list"
2529
+ and "[FAIL] planted control 1:" in full_text and "[FAIL] planted control 2:" in full_text
2530
+ and "stopped" not in full_text, f"{full} {full_text[:300]!r}")
2531
+ inner = {}
2532
+ outer, outer_text = run_miniature(True, nested=lambda: (miniature(inner)(), inner)[1])
2533
+ control("stop at the first failure: a suite started inside a stopping suite is not stopped, it runs in full",
2534
+ outer.get("code") == 1 and outer.get("list") == "FailuresThatStop" and inner.get("list") == "list"
2535
+ and inner.get("ran") == 4, f"outer={outer} inner={inner} {outer_text[:300]!r}")
2536
+ added, added_text = run_miniature(True, add="+=")
2537
+ control("stop at the first failure: set, a failure added with += stops the suite as an append does",
2538
+ added.get("code") == 1 and "[FAIL] planted control 1:" in added_text
2539
+ and "planted control 2" not in added_text and "ran" not in added, f"{added} {added_text[:300]!r}")
2540
+ printed = []
2541
+ own, own_text = run_miniature(True, publish=lambda failure: printed.append(failure))
2542
+ control("stop at the first failure: a suite outside the shared boundary is handed its first failure to "
2543
+ "print before it leaves",
2544
+ own.get("code") == 1 and printed == [("planted control 1", "planted to fail")],
2545
+ f"{own} printed={printed}")
2546
+
2547
+ reporting.append("the report begins here")
2548
+ return report(failures, ran)
2549
+
2550
+
2551
+ def report(failures, ran, label="distill --self-test"):
2552
+ """A self-test's own diagnostics, through the SAME printer every other line leaves by.
2553
+
2554
+ A failure line carries whatever the control put in it — a path, a fixture's planted text — and it
2555
+ was printed directly, so a self-test could publish what every other route is checked for (R1#3).
2556
+ It goes to stderr because it is a diagnostic; the per-control listing stays on stdout."""
2557
+ if (label, failures) in entry.SELF_TEST_COLLECTED:
2558
+ entry.SELF_TEST_COLLECTED.remove((label, failures))
2559
+ for name, detail in failures:
2560
+ # Name and detail projected separately when the joined line would be withheld whole, so a
2561
+ # failing control cannot lose its own name (r4 R8).
2562
+ entry.emit(entry.failure_text(label, name, detail), sys.stderr)
2563
+ if failures:
2564
+ return 1
2565
+ for name in ran:
2566
+ say(f" control {name}")
2567
+ say(f"{label}: OK ({len(ran)} controls)")
2568
+ return 0
2569
+
2570
+
2571
+ if __name__ == "__main__":
2572
+ # Outside `main` there is still a boundary: an exception from `build_parser().parse_args` itself,
2573
+ # or a `BaseException` no handler above names, is described through the floor rather than by the
2574
+ # interpreter.
2575
+ sys.exit(entry.guarded(main, sys.argv[1:], HOME))