agent-bios 0.19.3 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/DEPENDENCIES.md +62 -20
  2. package/INSTALL.md +1 -1
  3. package/README.md +16 -21
  4. package/claude/agents/frontier.md +1 -1
  5. package/claude/agents/sweep.md +2 -1
  6. package/claude/agents/workhorse.md +2 -2
  7. package/claude/guides/claude-prompting.md +494 -167
  8. package/claude/guides/cli-multi-model-workflow.md +8 -7
  9. package/claude/guides/gpt-prompting.md +241 -111
  10. package/claude/guides/session-distill-workflow.md +93 -43
  11. package/claude/guides/tooling-gotchas.md +3 -1
  12. package/codex/agents/reviewer.toml +2 -2
  13. package/codex/agents/sweep.toml +1 -1
  14. package/codex/agents/workhorse.toml +2 -2
  15. package/codex/guides/claude-prompting.md +494 -167
  16. package/codex/guides/cli-multi-model-workflow.md +8 -7
  17. package/codex/guides/gpt-prompting.md +241 -111
  18. package/codex/guides/session-distill-workflow.md +93 -43
  19. package/codex/guides/tooling-gotchas.md +3 -1
  20. package/compose/assemble.py +4 -1
  21. package/compose/canary.sh +8 -6
  22. package/compose/host_platform.py +158 -15
  23. package/compose/instructions-state.py +183 -41
  24. package/compose/instructions_app.py +2 -2
  25. package/compose/instructions_install.py +222 -27
  26. package/compose/instructions_session.py +250 -75
  27. package/compose/instructions_setup.py +6 -6
  28. package/compose/instructions_setup_cli.py +2 -36
  29. package/compose/instructions_setup_i18n.py +3 -3
  30. package/compose/instructions_store.py +160 -3
  31. package/compose/instructions_transaction.py +29 -5
  32. package/compose/instructions_ui_runtime.py +2 -2
  33. package/compose/setup/START.md +1 -1
  34. package/docs/advanced-launch.md +4 -0
  35. package/docs/releases/0.19.4.md +99 -0
  36. package/docs/releases/0.20.0.md +102 -0
  37. package/docs/setup.md +4 -4
  38. package/install.sh +54 -20
  39. package/launch/agent-launch.py +171 -22
  40. package/launch/agent-launch.toml +64 -29
  41. package/launch/agent-launch.zsh +104 -13
  42. package/launch/claude_subcommands.py +179 -0
  43. package/launch/provision-venv.sh +1 -1
  44. package/launch/shell_integration.py +7 -1
  45. package/learn/collect-learning.py +60 -9
  46. package/learn/migrate-learnings.py +70 -4
  47. package/learn/redact.py +2 -1
  48. package/package.json +37 -4
  49. package/provenance.json +1 -1
  50. package/session-cost.py +141 -18
  51. package/session-distill/coverage.json +6 -0
  52. package/session-distill/distill.py +2575 -0
  53. package/session-distill/grammar/__init__.py +0 -0
  54. package/session-distill/grammar/owner_lines.py +874 -0
  55. package/session-distill/originators.json +9 -0
  56. package/session-distill/packets/cross_review.md +31 -0
  57. package/session-distill/packets/form.md +86 -0
  58. package/session-distill/packets/judge.md +81 -0
  59. package/session-distill/packets/placement_contract.md +90 -0
  60. package/session-distill/packets/propose.md +124 -0
  61. package/session-distill/packets/read.md +57 -0
  62. package/session-distill/packets/reconsider.md +53 -0
  63. package/session-distill/packets/s7b.md +65 -0
  64. package/session-distill/packets/s9b.md +39 -0
  65. package/session-distill/packets/stitch.md +35 -0
  66. package/session-distill/packets/sweep.md +33 -0
  67. package/session-distill/runlib/__init__.py +0 -0
  68. package/session-distill/runlib/bound.py +1102 -0
  69. package/session-distill/runlib/breaker.py +467 -0
  70. package/session-distill/runlib/census.py +2347 -0
  71. package/session-distill/runlib/claims.py +420 -0
  72. package/session-distill/runlib/controls.py +902 -0
  73. package/session-distill/runlib/coverage.py +881 -0
  74. package/session-distill/runlib/declare.py +888 -0
  75. package/session-distill/runlib/delivery_evidence.py +1145 -0
  76. package/session-distill/runlib/derive.py +812 -0
  77. package/session-distill/runlib/destinations.py +3072 -0
  78. package/session-distill/runlib/dispatch.py +7939 -0
  79. package/session-distill/runlib/drift.py +1077 -0
  80. package/session-distill/runlib/entry.py +401 -0
  81. package/session-distill/runlib/evidence.py +890 -0
  82. package/session-distill/runlib/exposure.py +1162 -0
  83. package/session-distill/runlib/gate.py +2727 -0
  84. package/session-distill/runlib/gitread.py +79 -0
  85. package/session-distill/runlib/inventory.py +19624 -0
  86. package/session-distill/runlib/journal.py +1919 -0
  87. package/session-distill/runlib/ledger.py +3210 -0
  88. package/session-distill/runlib/ledger_compat.py +101 -0
  89. package/session-distill/runlib/ledger_migration.py +190 -0
  90. package/session-distill/runlib/lifecycle_intake.py +693 -0
  91. package/session-distill/runlib/lineage.py +454 -0
  92. package/session-distill/runlib/measures.py +249 -0
  93. package/session-distill/runlib/monitor.py +1180 -0
  94. package/session-distill/runlib/operations.py +522 -0
  95. package/session-distill/runlib/packet.py +838 -0
  96. package/session-distill/runlib/placement.py +1769 -0
  97. package/session-distill/runlib/projection.py +4090 -0
  98. package/session-distill/runlib/ranking.py +740 -0
  99. package/session-distill/runlib/receipts.py +200 -0
  100. package/session-distill/runlib/records.py +1965 -0
  101. package/session-distill/runlib/search.py +249 -0
  102. package/session-distill/runlib/sequencing.py +829 -0
  103. package/session-distill/runlib/sources.py +641 -0
  104. package/session-distill/runlib/stage_adjudicate.py +845 -0
  105. package/session-distill/runlib/stage_apply.py +1378 -0
  106. package/session-distill/runlib/stage_approvals.py +758 -0
  107. package/session-distill/runlib/stage_close.py +1220 -0
  108. package/session-distill/runlib/stage_confirm.py +929 -0
  109. package/session-distill/runlib/stage_delivery.py +3080 -0
  110. package/session-distill/runlib/stage_form.py +2576 -0
  111. package/session-distill/runlib/stage_judge.py +4248 -0
  112. package/session-distill/runlib/stage_propose.py +3307 -0
  113. package/session-distill/runlib/stage_read.py +5179 -0
  114. package/session-distill/runlib/stage_render.py +2739 -0
  115. package/session-distill/runlib/stage_retrieve.py +924 -0
  116. package/session-distill/runlib/stage_review_korean.py +1002 -0
  117. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  118. package/session-distill/runlib/stagelock.py +412 -0
  119. package/session-distill/runlib/stop.py +1061 -0
  120. package/session-distill/runlib/targets.py +809 -0
  121. package/session-distill/runlib/usage.py +280 -0
  122. package/session-distill/runlib/validate.py +319 -0
  123. package/session-distill/runlib/views.py +4327 -0
  124. package/session-distill/schemas/adjudication.schema.json +35 -0
  125. package/session-distill/schemas/approval.schema.json +35 -0
  126. package/session-distill/schemas/census.schema.json +128 -0
  127. package/session-distill/schemas/checks.schema.json +207 -0
  128. package/session-distill/schemas/claim.schema.json +16 -0
  129. package/session-distill/schemas/confirmation.schema.json +24 -0
  130. package/session-distill/schemas/coverage.schema.json +66 -0
  131. package/session-distill/schemas/cross_review.schema.json +24 -0
  132. package/session-distill/schemas/event.schema.json +20 -0
  133. package/session-distill/schemas/evidence.schema.json +20 -0
  134. package/session-distill/schemas/expected_observation.schema.json +18 -0
  135. package/session-distill/schemas/form.schema.json +103 -0
  136. package/session-distill/schemas/intake.schema.json +71 -0
  137. package/session-distill/schemas/inventory.schema.json +872 -0
  138. package/session-distill/schemas/judge.schema.json +77 -0
  139. package/session-distill/schemas/ledger.schema.json +313 -0
  140. package/session-distill/schemas/observation.schema.json +16 -0
  141. package/session-distill/schemas/propose.schema.json +555 -0
  142. package/session-distill/schemas/read.schema.json +76 -0
  143. package/session-distill/schemas/reconsider.schema.json +122 -0
  144. package/session-distill/schemas/run.schema.json +150 -0
  145. package/session-distill/schemas/s7b.schema.json +200 -0
  146. package/session-distill/schemas/s9b.schema.json +28 -0
  147. package/session-distill/schemas/stitch.schema.json +25 -0
  148. package/session-distill/schemas/sweep.schema.json +25 -0
  149. package/session-distill/seats.json +149 -0
  150. package/session-distill/tables/allowed_pairs.json +257 -0
  151. package/session-distill/tables/controls.json +30 -0
  152. package/session-distill/tables/delivery_evidence.json +36 -0
  153. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  154. package/session-distill/tables/destinations.json +684 -0
  155. package/session-distill/tables/drift_layers.json +68 -0
  156. package/session-distill/tables/exposure_rules.json +192 -0
  157. package/session-distill/tables/placement_rules.json +148 -0
  158. package/session-distill/tables/propose_fixtures.json +154 -0
  159. package/session-distill/tables/ranking.json +194 -0
  160. package/session-distill/tables/redundancy.json +10 -0
  161. package/session-distill/tables/structural_rules.json +44 -0
  162. package/session-distill/tables/transition_fixtures.json +398 -0
  163. package/session-distill/tables/transitions.json +69 -0
  164. package/session-distill/tables/unit_outcome.json +67 -0
  165. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  166. package/wrappers/claude-run.sh +481 -33
  167. package/wrappers/claude_hermetic_evidence.py +1423 -0
  168. package/wrappers/codex-helm.sh +44 -13
  169. package/wrappers/codex-run.sh +183 -20
  170. package/wrappers/codex_frame_filter.py +1199 -0
  171. package/wrappers/codex_protocol.py +737 -0
  172. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,401 @@
1
+ #!/usr/bin/env python3
2
+ """The one diagnostic boundary every entry point of this command runs inside.
3
+
4
+ Every line an entry point publishes — a report line, a refusal, the description of a failure nobody
5
+ expected — passes the redaction floor before it is printed, and every entry point is wrapped by the
6
+ same guard. There were two copies of that idea and a third place with none: the driver's `main`
7
+ projected what it printed but invoked the top-level self-test OUTSIDE its own `try`, so an ordinary
8
+ file failure in a fixture left an unprojected traceback; and `runlib/inventory.py`'s own `__main__`
9
+ printed its self-test's report with `print`, which carried a planted credential and a fixture path
10
+ out verbatim (R2#2, R2#3).
11
+
12
+ This module imports nothing but the standard library and reaches the floor LAZILY, so importing it
13
+ cannot itself be the failure. When the floor is what failed there is nothing that can project a
14
+ message, and `WITHHELD` — a fixed line, with a constant code and no path in it — is printed instead.
15
+ It lives here because two files need it and a constant copied into both is two constants.
16
+
17
+ **Scope.** This is package A's two entry points: `session-distill/distill.py` and
18
+ `session-distill/runlib/inventory.py`. The other runlib modules each have a standalone
19
+ `--self-test` that still prints directly; they are not this package's subject, and that is said here
20
+ rather than left to be inferred from which files import this one. One exception: the four suites a
21
+ revert sweep or an audit runs (distill, inventory, dispatch, projection) collect their failures
22
+ through `self_test_failures`, so the stop-at-first-failure mode is one mechanism, not four.
23
+ """
24
+ import os
25
+ import signal
26
+ import subprocess
27
+ import sys
28
+ import time
29
+
30
+ WITHHELD = ("STARTUP_FAILED: the command's modules could not be imported, and the redaction "
31
+ "floor is not available to describe why; nothing about the failure is printed")
32
+
33
+ TIMEOUT = 300
34
+ TIMED_OUT = 99
35
+ # A child that leads no group of its own, refused at spawn. Nonzero, so no caller can read it as a
36
+ # result; distinct from TIMED_OUT, so a caller that tests for a timeout does not report one for a
37
+ # child that never got to run; and distinct from STARTUP_UNAVAILABLE_CODE, the only other code this
38
+ # package synthesizes. The two this module makes are adjacent on purpose: they are the two ways a
39
+ # bound answers with something other than the child's own code.
40
+ NOT_GROUP_LEADER = 98
41
+
42
+
43
+ def _text(stream):
44
+ """What a timed-out child had produced, as text whatever the call asked for."""
45
+ if stream is None:
46
+ return ""
47
+ return stream if isinstance(stream, str) else stream.decode("utf-8", "replace")
48
+
49
+
50
+ GROUP_DRAIN = 10 # seconds allowed for a killed group's pipes to drain
51
+ GROUP_ROUNDS = 20 # SIGKILL rounds, 0.25s apart, after the leader has been reaped
52
+
53
+
54
+ def group_alive(pgid):
55
+ """Whether any process still stands in this group."""
56
+ try:
57
+ os.killpg(pgid, 0)
58
+ return True
59
+ except ProcessLookupError:
60
+ return False
61
+ except PermissionError: # it exists and is not ours to signal
62
+ return True
63
+ except OSError:
64
+ return False
65
+
66
+
67
+ def end_group(proc, pgid):
68
+ """Signal the process group `proc` leads: SIGTERM, then SIGKILL, unconditionally.
69
+
70
+ `pgid` is taken at spawn and never re-derived, because the leader's own group id is unreadable
71
+ once it has been reaped. `None` means OWNERSHIP WAS NEVER ESTABLISHED — `os.getpgid` refused at
72
+ spawn — and then no group is signalled at all: assuming the child leads its own group when the
73
+ question could not be answered points `killpg` at whatever group it happens to be in, which may
74
+ be this process's own. Ownership not established is child-only, and the note says so.
75
+
76
+ The leader check is the same rule read the other way: a child started WITHOUT a session sits in
77
+ this process's group, so only the child is ended. `bounded` now REFUSES that case at spawn, so
78
+ this branch answers for a child that becomes a non-leader after it — which it cannot under
79
+ `setsid`, and the branch costs nothing.
80
+
81
+ SIGKILL is not conditional on the leader surviving SIGTERM. Returning as soon as the leader
82
+ exited left every descendant running — a leader that exits politely while its children do not is
83
+ the ordinary shape, not an edge case (r3 #1)."""
84
+ if pgid is None:
85
+ proc.kill()
86
+ return ("the child's group could not be established, so no group was signalled and only the "
87
+ "child was ended")
88
+ if pgid != proc.pid:
89
+ proc.kill()
90
+ return "the child led no group of its own, so only the child was ended"
91
+ notes = []
92
+ for sig in (signal.SIGTERM, signal.SIGKILL):
93
+ try:
94
+ os.killpg(pgid, sig)
95
+ except (ProcessLookupError, PermissionError, OSError) as exc:
96
+ notes.append(f"{sig.name} on {pgid}: {type(exc).__name__}")
97
+ break
98
+ for _ in range(8):
99
+ if proc.poll() is not None:
100
+ break
101
+ time.sleep(0.25)
102
+ return "; ".join(notes)
103
+
104
+
105
+ def finish_group(pgid, rounds=GROUP_ROUNDS):
106
+ """Keep SIGKILLing the group until nothing stands in it. `True` when the group is gone.
107
+
108
+ Called AFTER the leader has been reaped: while the leader is an unreaped zombie it still stands
109
+ in its own group, so "the group is empty" is unaskable until then — which is why this is a
110
+ second pass rather than part of `end_group`."""
111
+ for _ in range(rounds):
112
+ if not group_alive(pgid):
113
+ return True
114
+ try:
115
+ os.killpg(pgid, signal.SIGKILL)
116
+ except (ProcessLookupError, PermissionError, OSError):
117
+ return not group_alive(pgid)
118
+ time.sleep(0.25)
119
+ return not group_alive(pgid)
120
+
121
+
122
+ def bounded(spawn, timeout=TIMEOUT, what="a child process"):
123
+ """The result of the process `spawn()` starts, run to completion under a bound.
124
+
125
+ `spawn` STARTS the process and is written at the call site, rather than this function making the
126
+ call: the closure gate judges a dispatch where it is written, so moving it here would move every
127
+ self-test's dispatch into this module and strip it of the admission its own site carries. It
128
+ must start the child in a session of its own (`start_new_session=True`), which is what lets a
129
+ bound end a tree rather than one process — and that requirement is REFUSED at spawn when it is
130
+ not met (`CHILD_NOT_GROUP_LEADER`), rather than stated here and left unchecked.
131
+
132
+ An unbounded child is a control that cannot fail. When one hangs, or spawns a suite of its own,
133
+ the run never reaches a verdict and has to be killed from outside — which leaves whatever the
134
+ run was testing on disk and no result at all. A bound makes that a named failure instead: the
135
+ returned `CompletedProcess` carries a nonzero code and a line saying what did not finish, so the
136
+ control reading it fails by its own name and the diagnostic leaves through the floor.
137
+
138
+ Every step after the bound is itself bounded: the drain that reaps the leader, and the rounds
139
+ that end what outlived it. What does not finish is NAMED (`CHILD_CLEANUP_UNFINISHED`) rather
140
+ than waited for, because an unbounded cleanup is the same defect one level down."""
141
+ proc = spawn()
142
+ try:
143
+ pgid = os.getpgid(proc.pid)
144
+ except OSError: # ownership unestablished: see `end_group`
145
+ pgid = None
146
+ # Default-deny, decided at SPAWN. This bound ends a GROUP, so a child that leads none is a child
147
+ # no bound here can end: its descendants outlive the bound and nothing says so — r8's W6 showed
148
+ # the shape, where the shell was ended and the sleep it had backgrounded was not, and only a
149
+ # control written for that one fixture noticed. The requirement stood in this docstring and
150
+ # nothing checked it, so it is checked here.
151
+ #
152
+ # Refusing is NOT signalling: the child is ended alone, exactly as `end_group`'s non-leader
153
+ # branch does, and what changes is that a named failure comes back instead of a result. No
154
+ # `killpg` is reached, which is the whole point — the group is this process's own.
155
+ #
156
+ # `pgid is None` is a different case and is NOT refused: ownership was never established, which
157
+ # an ordinary child that exits before the read produces, and `end_group` answers for it at the
158
+ # timeout (F3).
159
+ if pgid is not None and pgid != proc.pid:
160
+ proc.kill()
161
+ try:
162
+ out, err = proc.communicate(timeout=GROUP_DRAIN)
163
+ except subprocess.TimeoutExpired:
164
+ out, err = "", ""
165
+ return subprocess.CompletedProcess(
166
+ proc.args, NOT_GROUP_LEADER, _text(out),
167
+ "\n".join([_text(err), f"CHILD_NOT_GROUP_LEADER {what}: started without a session of "
168
+ f"its own, so no bound could end its tree"]))
169
+ try:
170
+ out, err = proc.communicate(timeout=timeout)
171
+ return subprocess.CompletedProcess(proc.args, proc.returncode, _text(out), _text(err))
172
+ except subprocess.TimeoutExpired:
173
+ ended, unfinished = end_group(proc, pgid), []
174
+ try:
175
+ out, err = proc.communicate(timeout=GROUP_DRAIN)
176
+ except subprocess.TimeoutExpired:
177
+ out, err = "", ""
178
+ unfinished.append(f"the pipes did not drain within {GROUP_DRAIN}s")
179
+ if pgid == proc.pid and not finish_group(pgid):
180
+ unfinished.append(f"the group {pgid} still holds a process after {GROUP_ROUNDS} rounds")
181
+ if unfinished and not out and not err:
182
+ try: # the group is gone now, so one short drain may still answer
183
+ out, err = proc.communicate(timeout=1)
184
+ except subprocess.TimeoutExpired:
185
+ pass
186
+ lines = [_text(err), f"CHILD_TIMEOUT {what}: no verdict within {timeout}s"]
187
+ if ended:
188
+ lines.append(f"CHILD_GROUP_ENDED: {ended}")
189
+ if unfinished:
190
+ lines.append(f"CHILD_CLEANUP_UNFINISHED: {'; '.join(unfinished)}")
191
+ return subprocess.CompletedProcess(proc.args, TIMED_OUT, _text(out), "\n".join(lines))
192
+
193
+
194
+ def floor():
195
+ """The redaction floor, or `None` when the floor is the thing that failed.
196
+
197
+ Imported here rather than at module scope: `runlib.validate` exits during import when its schema
198
+ pin is unreadable, and the floor's own import can fail the same way. An entry point must still
199
+ have a boundary to run inside when that happens."""
200
+ try:
201
+ from runlib import projection
202
+ return projection
203
+ except BaseException:
204
+ return None
205
+
206
+
207
+ def projected(text, home=None, schema=()):
208
+ """`text` through the floor, or the fixed line when there is no floor to ask."""
209
+ layer = floor()
210
+ return WITHHELD if layer is None else layer.diagnostic(text, home, schema)
211
+
212
+
213
+ def say(text, stream=None, home=None, schema=()):
214
+ """One line this command publishes, through the floor's own entry point."""
215
+ print(projected(text, home, schema), file=stream if stream is not None else sys.stdout)
216
+
217
+
218
+ def failed(exc, home=None, label="COMMAND_FAILED", code=1, stream=None):
219
+ """Describe a failure nobody expected, and the exit code for it.
220
+
221
+ An unexpected failure is the one most likely to carry a path — an `OSError`'s message IS a path —
222
+ and a traceback printed by the interpreter crosses no boundary at all. The type is named so the
223
+ failure stays diagnosable; the message passes the floor."""
224
+ # Before the failure is described: whatever a suite had collected, which the abort is about to
225
+ # take with it. Nothing on an ordinary failure path, where no suite is running.
226
+ publish_collected(lambda line: emit(line, stream if stream is not None else sys.stderr),
227
+ home=home, through_floor=True)
228
+ say(f"{label}: {type(exc).__name__}: {exc}", stream if stream is not None else sys.stderr, home)
229
+ return code
230
+
231
+
232
+ # A self-test COLLECTS its failures and prints them at the end, so an exception leaving the suite
233
+ # used to take every line with it: r7 recorded three reverted rules as "no [FAIL] line at all" when
234
+ # the cause was an abort rather than a silent rule. A suite registers `(label, failures)` here while
235
+ # it runs and removes it when it reports, so what is left is exactly what an abort would have
236
+ # swallowed. A nested suite pushes a list of its own; nothing is shared between runs.
237
+ SELF_TEST_COLLECTED = []
238
+
239
+ # A person narrowing one failure, or a harness that only asks whether a planted fault is caught, does
240
+ # not need the rest of a suite: with this variable "1", a suite that collects its failures through
241
+ # `self_test_failures` leaves right after its first. Unset, the list is a plain list and the suite is
242
+ # what it was. The commit umbrella and its hook unset it, so an inherited shell never shortens a gate.
243
+ STOP_AT_FIRST_FAILURE = "AGENT_BIOS_SELF_TEST_STOP_AT_FIRST_FAILURE"
244
+
245
+
246
+ class StoppedAtFirstFailure(SystemExit):
247
+ """A suite leaving right after its first recorded failure: a `SystemExit` with code 1, so a section
248
+ guard that catches `Exception` lets it through, and `guarded` publishes what the suite collected
249
+ (that failure, as its `[FAIL]` line) before it returns the code."""
250
+
251
+
252
+ class FailuresThatStop(list):
253
+ """A suite's failure list in stop-at-first-failure mode. A failure added by `append`, `+=` or
254
+ `extend` is recorded first; then the suite says it stopped and `StoppedAtFirstFailure` leaves.
255
+ `publish`, for a suite that runs outside `guarded` and prints its own report, prints what was
256
+ recorded before it leaves."""
257
+
258
+ def __init__(self, label, publish=None):
259
+ super().__init__()
260
+ self.label, self.publish = label, publish
261
+
262
+ def append(self, failure):
263
+ super().append(failure)
264
+ self._stop()
265
+
266
+ def extend(self, failures):
267
+ held = len(self)
268
+ super().extend(failures)
269
+ if len(self) > held:
270
+ self._stop()
271
+
272
+ def __iadd__(self, failures):
273
+ self.extend(failures)
274
+ return self
275
+
276
+ def _stop(self):
277
+ if self.publish is not None:
278
+ for failure in self:
279
+ self.publish(failure)
280
+ say(f"{self.label}: stopped at its first failure ({STOP_AT_FIRST_FAILURE}=1)", sys.stderr)
281
+ raise StoppedAtFirstFailure(1)
282
+
283
+
284
+ def self_test_failures(label, publish=None):
285
+ """The list a suite collects its failures in: a plain list, or one that ends the suite at its first
286
+ failure when STOP_AT_FIRST_FAILURE is "1". The variable is read here and removed from the
287
+ environment, so a suite this one starts, in this process or as a child, runs in full."""
288
+ if os.environ.pop(STOP_AT_FIRST_FAILURE, None) == "1":
289
+ return FailuresThatStop(label, publish)
290
+ return []
291
+
292
+
293
+ FAIL_TAG = "[FAIL]"
294
+
295
+
296
+ class FailureLine(str):
297
+ """A `[FAIL]` line `failure_text` has already projected, piece by piece or whole.
298
+
299
+ A MARKER for this module's own callers, not proof of projection: anyone can write
300
+ `FailureLine("…")` around any string. What it rules out is a string reaching `emit` by accident
301
+ — a plain diagnostic, a caller's format string, a line from another module — which is what the
302
+ docstring naming its callers did not rule out. A caller that deliberately wraps unprojected text
303
+ is outside what this type answers for; that is the residual `forged_failure_line` (r5 F5)."""
304
+
305
+
306
+ def failure_text(label, name, detail, home=None):
307
+ """One `[FAIL]` line, projected so the control's NAME is never what gets withheld.
308
+
309
+ The WHOLE line is projected first, because a whole-line judgement is the strongest one the floor
310
+ makes and it is what every other diagnostic gets. When that judgement withholds the line
311
+ entirely, what is published is the label, the tag and the name, with the DETAIL REPLACED BY THE
312
+ PLACEHOLDER — never the detail in any form. The floor withheld the line precisely because the
313
+ name and the detail read as a credential key and its value TOGETHER, and a detail re-judged
314
+ alone loses that context: projecting it again would publish the value the whole-line judgement
315
+ had just refused (r4 R8 correction). The same reasoning is why the label and the name are
316
+ published only as the floor returns them — unchanged, or as the placeholder, with the line
317
+ saying which part it is, so a reader can tell a withheld detail from a withheld name.
318
+
319
+ What this preserves is the tag and the name, which is what a harness reads: r4's R0 revert
320
+ published nothing but the placeholder — no name, no tag, no suite label — so a named failure
321
+ read as an unnamed one. The name is never split out of a formatted string, because a control
322
+ name may itself hold `": "`."""
323
+ whole = projected(f"{label} {FAIL_TAG} {name}: {detail}", home)
324
+ layer = floor()
325
+ withheld = (layer.blank_for("x") if layer is not None else WITHHELD).strip()
326
+ if whole.strip() != withheld:
327
+ return FailureLine(whole)
328
+ shown_label = label if projected(label, home) == label else withheld
329
+ shown_name = name if projected(name, home) == name else withheld
330
+ which = ("the detail" if shown_name == name
331
+ else "the name and the detail" if shown_label == label else "the whole line")
332
+ return FailureLine(f"{shown_label} {FAIL_TAG} {shown_name}: {withheld} ({which} withheld)")
333
+
334
+
335
+ def emit(text, stream=None):
336
+ """Publish a line THIS MODULE has already projected (`failure_text`).
337
+
338
+ The one printer here that does not project what it is given: projecting again would hand the
339
+ floor the joined line it has already withheld, and take the name back out. The TYPE keeps a
340
+ string from reaching it BY ACCIDENT — anything that is not a `FailureLine` is refused by name —
341
+ but it is a marker, not proof: a caller that wraps unprojected text in `FailureLine` is
342
+ publishing it, and nothing here can tell. See the residual `forged_failure_line`."""
343
+ if not isinstance(text, FailureLine):
344
+ raise TypeError(f"EMIT_UNPROJECTED: this printer publishes without projecting and takes only "
345
+ f"a FailureLine from `failure_text`, not a {type(text).__name__}")
346
+ print(text, file=stream if stream is not None else sys.stderr)
347
+
348
+
349
+ def _failure_parts(failure):
350
+ """A collected failure as `(name, detail)`. A suite that collects plain strings has no
351
+ structural name, and its line is published whole, as before."""
352
+ return failure if isinstance(failure, tuple) else (None, failure)
353
+
354
+
355
+ def publish_collected(publish, home=None, through_floor=False):
356
+ """The failure lines the suites running in this process had already collected, published as the
357
+ suite itself publishes them, and returned so a control can read them.
358
+
359
+ `through_floor` builds each line through `failure_text`, for the callers that publish into a
360
+ floor-bearing stream; without it the line is joined as the suite would print it.
361
+
362
+ Empty on every normal path: a suite that reaches its own report removes its list first."""
363
+ lines = []
364
+ for label, failures in SELF_TEST_COLLECTED:
365
+ for failure in failures:
366
+ name, detail = _failure_parts(failure)
367
+ if name is None:
368
+ # A suite that collects plain strings has no name to keep, so the line is published
369
+ # whole — projected first when it is going to `emit`, which takes nothing else.
370
+ lines.append(FailureLine(projected(f"{label} {FAIL_TAG} {detail}", home)) if through_floor
371
+ else f"{label} {FAIL_TAG} {detail}")
372
+ else:
373
+ lines.append(failure_text(label, name, detail, home) if through_floor
374
+ else f"{label} {FAIL_TAG} {name}: {detail}")
375
+ for line in lines:
376
+ publish(line)
377
+ return lines
378
+
379
+
380
+ def guarded(entry, argv=None, home=None, stream=None, label="COMMAND_FAILED"):
381
+ """`entry()`'s exit code, with anything it raises described through the floor.
382
+
383
+ `SystemExit` keeps its own code — argparse's 2, or `validate`'s at import time — and its message,
384
+ when it carries one, is projected like any other line rather than printed by the interpreter."""
385
+ try:
386
+ return entry() if argv is None else entry(argv)
387
+ except SystemExit as exc:
388
+ # `SystemExit` is an abort like any other for a suite running inside this boundary: a
389
+ # `sys.exit` from a fixture, or argparse's own, took every collected failure line with it
390
+ # while only the `BaseException` branch below published (r4 R1). Empty on every normal path,
391
+ # which is why it sits before the code is decided rather than in one branch of it.
392
+ publish_collected(lambda line: emit(line, stream if stream is not None else sys.stderr),
393
+ home=home, through_floor=True)
394
+ if exc.code is None:
395
+ return 0
396
+ if isinstance(exc.code, int):
397
+ return exc.code
398
+ say(str(exc.code), stream if stream is not None else sys.stderr, home)
399
+ return 2
400
+ except BaseException as exc:
401
+ return failed(exc, home, label, stream=stream)