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,888 @@
1
+ #!/usr/bin/env python3
2
+ """S0: the run declaration (`run.json`) and its amendments (design §4.1, §13.2, §8.4).
3
+
4
+ `create` validates a declaration and writes `run.json` at `declaration_seq` 0. Until a stage
5
+ has recorded that it read it, `set_fields` edits it in place; from then on a change is an
6
+ amendment (`amend`): one line in `amendments.jsonl`, `declaration_seq` advanced, and the
7
+ stages whose results it makes stale listed in `invalidates[]`. Changing `checks{}` after a
8
+ stage record exists invalidates S3 and everything downstream; changing `output_caps{}` after
9
+ one invalidates S2 and everything downstream, because S2 cut the windows against that cap.
10
+
11
+ A declaration is checked in three steps, each only when the one before it holds. Its structure
12
+ is `schemas/run.schema.json`, validated by jsonschema through `validate.py` (closed objects,
13
+ types, patterns, required fields). Then the semantic checks a schema cannot state: the window
14
+ runs forward in a real zone, source names are unique and name the zstd path, seat strings
15
+ parse and name stages, the four strata are each seated once, and every host allowance is
16
+ measured on the host version the declaration names. Then seat coverage.
17
+
18
+ Failures are named by their first word: ACCOUNT_UNDECLARED, SEAT_UNCOVERED, AMEND_REQUIRED,
19
+ ALLOWANCE_UNDECLARED, HOST_ALLOWANCE_STALE, RUN_EXISTS, DECLARATION_INVALID,
20
+ SEAT_COVERAGE_UNREADABLE, DENSITY_UNPROVENANCED.
21
+
22
+ Every seat of the declaration (stage seats and the four actor strata) must be named in the
23
+ `targets:` of the prompting guide that owns its host. That coverage is read by
24
+ `launch/check-prompting-targets.sh`'s own `OWNERS` and `targets()`, taken out of the script
25
+ at call time: nothing here restates which guide owns which host or how its targets are read.
26
+
27
+ `posture` (production, rehearsal or development) is the failure posture of design §4, added
28
+ to the declaration by `design/session-distill/2026-10-21T0318--2d4fbd4--plan-addendum-wp01.md`;
29
+ it is read by `records.StageRun.run_items`. `host_allowance` is the per-seat allowance of the
30
+ amendment to design §5.4 and `destinations` the root of each class every S11 and S12 writer
31
+ must resolve into. `output_caps` is the output-token cap of S3's calls: S2 cuts every window
32
+ reserving it and S3 declares it on every call, so both read this one number. `density`, the one
33
+ optional field, is an earlier run's measured table of what a token covers per seat and kind
34
+ (WP-08e): each entry names the run, the samples and the time it was measured, and a stage reads
35
+ it only where its own run has measured nothing of that seat and kind (`dispatch.measured_density`).
36
+ Nothing copies it forward; whoever declares the run writes it.
37
+
38
+ declare.py --self-test
39
+ """
40
+ import ast
41
+ import copy
42
+ import datetime
43
+ import json
44
+ import math
45
+ import pathlib
46
+ import re
47
+ import sys
48
+ import tempfile
49
+ import types
50
+ import zoneinfo
51
+
52
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
53
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
54
+ from runlib import gate, records, stagelock, validate
55
+ from runlib.records import Refused
56
+
57
+ REPO = pathlib.Path(__file__).resolve().parents[2]
58
+ SCHEMA = json.loads((pathlib.Path(__file__).resolve().parents[1] / "schemas" / "run.schema.json")
59
+ .read_text(encoding="utf-8"))
60
+ VALIDATOR = validate.compile_schema(SCHEMA)
61
+ STRATA = tuple(SCHEMA["properties"]["actor_seats"]["items"]["properties"]["stratum"]["enum"]) # design §8.4
62
+ # The destination VOCABULARY is the schema's declared properties, not the classes a declaration
63
+ # must carry: release 1 requires only the roots its own writers need (D-20261112-2cf1c4), and
64
+ # reading `required` here narrowed the vocabulary with it, so every other writer's class became
65
+ # undeclared (the round-4 review). `required` is what S0 refuses a declaration for; this is what
66
+ # names exist at all.
67
+ DESTINATIONS = tuple(SCHEMA["properties"]["destinations"]["properties"])
68
+ DESTINATIONS_REQUIRED = tuple(SCHEMA["properties"]["destinations"]["required"])
69
+ # A change to these top-level fields makes the results of the named stage, and every later
70
+ # stage that has a record, stale: criteria applied by S3 no longer describe what it read, and a
71
+ # window S2 cut while reserving one output cap is not the window a call reserving another may
72
+ # send - raising the cap is accepted as an amendment, and the views are cut again under it
73
+ # (`design/session-distill/2026-11-03T2155--6779ed7--the-output-cap-is-declared-and-a-reading-cites-its-own-quotes.md`).
74
+ INVALIDATED_FROM = {"checks": "S3", "output_caps": "S2"}
75
+ # The stage whose calls carry a window of a transcript view (S3 reading and its expansions): the
76
+ # seat of that stage needs a declared host allowance (amendment to design §5.4).
77
+ VIEW_WINDOW_STAGE = "S3"
78
+
79
+
80
+ def _is_text(value):
81
+ return isinstance(value, str) and value.strip() != ""
82
+
83
+
84
+ def parse_seat(seat):
85
+ """(provider, model, effort) of `provider:model/effort`, or None."""
86
+ provider, colon, rest = seat.partition(":")
87
+ model, slash, effort = rest.rpartition("/")
88
+ return (provider, model, effort) if provider and colon and model and slash and effort else None
89
+
90
+
91
+ # --- structure: the schema ------------------------------------------------------------------
92
+
93
+ def structure_errors(run):
94
+ """The schema's violations as `CODE path: message`. `account` has its own code: S0 cannot
95
+ proceed without the owner's declared extra-usage setting and date (design §13.2)."""
96
+ errors = []
97
+ for err in validate.violations(VALIDATOR, run):
98
+ where = [str(part) for part in err.absolute_path]
99
+ if err.validator == "required": # one line per missing name, wherever jsonschema repeats it
100
+ problems = [(where + [name], "missing") for name in err.validator_value if name not in err.instance]
101
+ else:
102
+ problems = [(where, err.message)]
103
+ for path, message in problems:
104
+ code = "ACCOUNT_UNDECLARED" if path[:1] == ["account"] else "DECLARATION_INVALID"
105
+ line = f"{code} {'.'.join(path) or '<root>'}: {message}"
106
+ if line not in errors:
107
+ errors.append(line)
108
+ return errors
109
+
110
+
111
+ # --- semantics: what the schema cannot state ------------------------------------------------
112
+
113
+ def semantic_errors(run):
114
+ """Cross-field and value checks over a declaration that has the schema's structure."""
115
+ errors = []
116
+ window = run["window"]
117
+ try:
118
+ zone = zoneinfo.ZoneInfo(window["tz"])
119
+ start, end = (datetime.datetime.fromisoformat(window[key]) for key in ("start", "end"))
120
+ start, end = (t if t.tzinfo else t.replace(tzinfo=zone) for t in (start, end))
121
+ if not start < end:
122
+ errors.append("DECLARATION_INVALID window: the half-open window [start, end) is empty or reversed")
123
+ except (ValueError, KeyError) as exc: # ZoneInfoNotFoundError is a KeyError
124
+ errors.append(f"DECLARATION_INVALID window: start and end must be ISO-8601 and tz an IANA zone: {exc}")
125
+ try:
126
+ datetime.date.fromisoformat(run["account"]["declared_on"])
127
+ except ValueError:
128
+ errors.append("ACCOUNT_UNDECLARED account.declared_on: not a calendar date")
129
+ names = [source["name"] for source in run["sources"]]
130
+ errors.extend(f"DECLARATION_INVALID sources: source name {name!r} repeats"
131
+ for name in sorted({n for n in names if names.count(n) > 1}))
132
+ if "zstd" not in names:
133
+ errors.append("DECLARATION_INVALID sources: the absolute zstd path must be declared as a source named 'zstd'")
134
+ errors.extend(f"DECLARATION_INVALID budget.per_stage.{key}: key is not a stage"
135
+ for key in run["budget"]["per_stage"] if key not in records.STAGES)
136
+ errors.extend(f"DECLARATION_INVALID seats.{key}: key is not a stage"
137
+ for key in run["seats"] if key.split(".")[0] not in records.STAGES)
138
+ strata = [actor["stratum"] for actor in run["actor_seats"]]
139
+ if sorted(strata) != sorted(STRATA):
140
+ errors.append(f"DECLARATION_INVALID actor_seats: exactly one seat per stratum {list(STRATA)} is required, got {strata}")
141
+ seats = {f"seats.{key}": seat for key, seat in run["seats"].items()}
142
+ seats.update({f"actor_seats.{actor['stratum']}": actor["seat"] for actor in run["actor_seats"]})
143
+ seats.update({f"host_allowance.{seat}": seat for seat in run["host_allowance"]})
144
+ errors.extend(f"DECLARATION_INVALID {where}: not a seat, expected provider:model/effort ({seat!r})"
145
+ for where, seat in seats.items() if parse_seat(seat) is None)
146
+ if errors:
147
+ return errors # what follows reads seats as provider:model/effort
148
+ for actor in run["actor_seats"]:
149
+ if actor["stratum"].split("-")[0] != parse_seat(actor["seat"])[0]:
150
+ errors.append(f"DECLARATION_INVALID actor_seats: the {actor['stratum']} stratum names a seat of another provider: {actor['seat']}")
151
+ declared = {seat for where, seat in seats.items() if not where.startswith("host_allowance.")}
152
+ for seat, entry in run["host_allowance"].items():
153
+ if seat not in declared:
154
+ errors.append(f"DECLARATION_INVALID host_allowance.{seat}: not a seat this declaration names")
155
+ elif entry["host_version"] != run["hosts"].get(parse_seat(seat)[0]):
156
+ errors.append(f"HOST_ALLOWANCE_STALE host_allowance.{seat}: measured on host {entry['host_version']}, "
157
+ f"the declaration names {run['hosts'].get(parse_seat(seat)[0])}")
158
+ view_seat = run["seats"][VIEW_WINDOW_STAGE]
159
+ if view_seat not in run["host_allowance"]:
160
+ errors.append(f"ALLOWANCE_UNDECLARED seats.{VIEW_WINDOW_STAGE}: {view_seat} reads view windows and "
161
+ f"has no host_allowance entry")
162
+ return errors + density_errors(run) + retry_errors(run) + scope_errors(run)
163
+
164
+
165
+ def retry_errors(run):
166
+ """The declared retry's violations (W review of WP-08e r1, F4): a `retry` names its count, its margin or both; an
167
+ empty one re-declares nothing and so could lift a claim stop by changing nothing."""
168
+ held = run.get("retry")
169
+ if held is None:
170
+ return []
171
+ if not any(key in held for key in ("count", "margin")):
172
+ return ["DECLARATION_INVALID retry: a declared retry names its count, its margin or both"]
173
+ # an integer, not an integral float (W r2, F9): the schema's integer admits 2.0, and the claim's arithmetic then
174
+ # ranges over it and raises
175
+ return [f"DECLARATION_INVALID retry.{key}: an integer, not {held[key]!r}" for key in ("count", "margin")
176
+ if key in held and (isinstance(held[key], bool) or not isinstance(held[key], int))]
177
+
178
+
179
+ def scope_errors(run):
180
+ """The declared retrieval counts, sweep sizes and judged scope (plan WP-11, lead decisions on J0's numbers and E2):
181
+ integers, not integral floats, which the schema's integer admits; and, whenever `judge.candidate_kinds` is declared, `formed: all`
182
+ (FORMED_SAMPLED), since design §6.5's planted controls take the formed shape and S6 cannot tell them apart (F27,
183
+ lead decision D4), so sampling or leaving out the formed candidates would drop controls unseen."""
184
+ out = [f"DECLARATION_INVALID {field}.{key}: an integer, not {value!r}"
185
+ for field in ("retrieval", "sweeps")
186
+ for key, value in (run.get(field) or {}).items() if isinstance(value, bool) or not isinstance(value, int)]
187
+ held = run.get("judge") or {}
188
+ kinds = held.get("candidate_kinds")
189
+ if kinds is None:
190
+ return out
191
+ out += [f"DECLARATION_INVALID judge.candidate_kinds.{key}: all or an integer, not {value!r}"
192
+ for key, value in kinds.items() if value != "all" and (isinstance(value, bool) or not isinstance(value, int))]
193
+ if kinds.get("formed") != "all":
194
+ out.append(f"FORMED_SAMPLED judge.candidate_kinds.formed: {kinds.get('formed', 'left out')!r}; the formed candidates "
195
+ "are judged all whenever the map is declared, since the planted controls take their shape")
196
+ return out
197
+
198
+
199
+ DENSITY_KIND = re.compile(r"S[0-9]+[a-z]?:[a-z_]+") # a declared density's kind, matched whole (fullmatch)
200
+
201
+
202
+ def density_errors(run):
203
+ """The declared density table's violations (WP-08e, lead decision): each entry is an earlier run's measured table
204
+ as that run wrote it, so it carries where it was measured (`measured_in`, a run id), on how many calls (`samples`,
205
+ at least one) and when (`at`, ISO-8601); an entry without that is DENSITY_UNPROVENANCED, never a number taken on
206
+ trust. It is keyed as a reservation class is (W review of WP-08e r1, F3): by a seat the declaration names, then by
207
+ a stage's kind (`<stage>:<case type>`)."""
208
+ errors = []
209
+ named = set((run.get("seats") or {}).values()) | {a.get("seat") for a in run.get("actor_seats") or []}
210
+ for seat, kinds in sorted((run.get("density") or {}).items()):
211
+ if parse_seat(seat) is None:
212
+ errors.append(f"DECLARATION_INVALID density.{seat}: not a seat, expected provider:model/effort")
213
+ elif seat not in named:
214
+ errors.append(f"DECLARATION_INVALID density.{seat}: not a seat this declaration names")
215
+ for kind, entry in sorted(kinds.items()):
216
+ where = f"density.{seat}.{kind!r}" if not DENSITY_KIND.fullmatch(kind) else f"density.{seat}.{kind}"
217
+ if not DENSITY_KIND.fullmatch(kind):
218
+ # the whole key, both ends (W r2, F9): the schema's `$` admits a trailing newline, and the reader's
219
+ # exact key would never match it, so the entry would be read as nothing
220
+ errors.append(f"DECLARATION_INVALID {where}: not a kind, expected <stage>:<case type> exactly")
221
+ elif kind.split(":")[0] not in records.STAGES:
222
+ errors.append(f"DECLARATION_INVALID {where}: {kind.split(':')[0]!r} is not a stage")
223
+ value = entry["bytes_per_token"]
224
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
225
+ errors.append(f"DECLARATION_INVALID {where}.bytes_per_token: a finite number, not {value!r}")
226
+ elif not value > 0:
227
+ errors.append(f"DECLARATION_INVALID {where}.bytes_per_token: a token covers more than no bytes")
228
+ missing = [k for k in ("measured_in", "samples", "at") if k not in entry]
229
+ if not _is_text(entry.get("measured_in", "x")):
230
+ missing.append("measured_in (a run id)")
231
+ samples = entry.get("samples", 1)
232
+ if isinstance(samples, bool) or not isinstance(samples, int) or samples < 1:
233
+ missing.append("samples (at least one)")
234
+ try:
235
+ datetime.datetime.fromisoformat(entry.get("at", "2026-01-01"))
236
+ except (TypeError, ValueError):
237
+ missing.append("at (ISO-8601)")
238
+ if missing:
239
+ errors.append(f"DENSITY_UNPROVENANCED {where}: a declared density carries the run that measured it, "
240
+ f"its samples and when; this one lacks {', '.join(missing)}")
241
+ return errors
242
+
243
+
244
+ # --- seat coverage by the prompting-targets gate's own reader ------------------------------
245
+
246
+ class GateUnreadable(Exception):
247
+ """The gate's reader could not be taken out of its script."""
248
+
249
+
250
+ def prompting_reader(repo=REPO):
251
+ """(OWNERS, targets) exactly as `launch/check-prompting-targets.sh` defines them.
252
+
253
+ The gate is a shell script around one Python body, so its reader is not importable. The
254
+ two definitions are compiled out of that body, from the script's own text, and run with
255
+ `pathlib.Path` resolving against `repo` (the script `cd`s there). When the gate changes
256
+ how it reads targets, this follows; when it stops defining them, this fails by name."""
257
+ script = pathlib.Path(repo) / "launch" / "check-prompting-targets.sh"
258
+ try:
259
+ body = re.search(r"<<'PY'\n(.*?)\nPY\n", script.read_text(encoding="utf-8"), re.S).group(1)
260
+ tree = ast.parse(body)
261
+ except (OSError, AttributeError, SyntaxError) as exc:
262
+ raise GateUnreadable(f"{script} has no Python body to read: {exc!r}") from exc
263
+ picked = [node for node in tree.body
264
+ if (isinstance(node, ast.FunctionDef) and node.name == "targets")
265
+ or (isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "OWNERS"
266
+ for t in node.targets))]
267
+ if len(picked) != 2:
268
+ raise GateUnreadable(f"{script} does not define OWNERS and targets() at the top of its Python body")
269
+ namespace = {"re": re, "sys": sys, "pathlib": types.SimpleNamespace(Path=lambda p: pathlib.Path(repo) / p)}
270
+ exec(compile(ast.Module(body=picked, type_ignores=[]), str(script), "exec"), namespace)
271
+ return namespace["OWNERS"], namespace["targets"]
272
+
273
+
274
+ def seat_coverage(run, repo=REPO):
275
+ """SEAT_UNCOVERED for every seat (stage seats and actor strata) whose model the guide
276
+ owning its provider does not name in `targets:`; SEAT_COVERAGE_UNREADABLE when the gate's
277
+ reader or a guide cannot be read."""
278
+ seats = sorted(set(run["seats"].values()) | {actor["seat"] for actor in run["actor_seats"]})
279
+ try:
280
+ owners, targets = prompting_reader(repo)
281
+ covered, errors = {}, []
282
+ for seat in seats:
283
+ provider, model, _effort = parse_seat(seat)
284
+ guide = owners.get(provider)
285
+ if guide is None:
286
+ errors.append(f"SEAT_UNCOVERED {seat}: no prompting guide owns provider {provider!r}")
287
+ continue
288
+ if guide not in covered:
289
+ covered[guide] = targets(guide)
290
+ if model not in covered[guide]:
291
+ errors.append(f"SEAT_UNCOVERED {seat}: {guide} does not name {model} in its targets")
292
+ return errors
293
+ except GateUnreadable as exc:
294
+ return [f"SEAT_COVERAGE_UNREADABLE {exc}"]
295
+ except SystemExit as exc: # the gate's reader exits on a missing guide or an absent targets:
296
+ return [f"SEAT_COVERAGE_UNREADABLE {exc}"]
297
+
298
+
299
+ def check_declaration(run, repo=REPO):
300
+ """Every violation of a declaration, each starting with its code; empty when it holds."""
301
+ return structure_errors(run) or semantic_errors(run) or seat_coverage(run, repo)
302
+
303
+
304
+ # --- actions on a run directory -------------------------------------------------------------
305
+
306
+ def parse_value(text):
307
+ """A `--set` value: JSON when it parses as JSON, else the text itself."""
308
+ try:
309
+ return json.loads(text)
310
+ except ValueError:
311
+ return text
312
+
313
+
314
+ def apply_assignments(run, assignments):
315
+ """(new run, diff) for dotted-path assignments; the last key may be new, the path to it may not."""
316
+ new, diff = copy.deepcopy(run), {}
317
+ for path, value in assignments:
318
+ keys = path.split(".")
319
+ if keys[0] == "declaration_seq":
320
+ raise Refused("DECLARATION_INVALID declaration_seq: set by declare, never assigned")
321
+ parent = new
322
+ for key in keys[:-1]:
323
+ parent = parent.get(key) if isinstance(parent, dict) else None
324
+ if not isinstance(parent, dict):
325
+ raise Refused(f"DECLARATION_INVALID {path}: no such object to assign into")
326
+ diff[path] = {"old": copy.deepcopy(parent.get(keys[-1])), "new": value}
327
+ parent[keys[-1]] = value
328
+ return new, diff
329
+
330
+
331
+ def _validated(run, repo):
332
+ errors = check_declaration(run, repo)
333
+ if errors:
334
+ raise Refused("\n".join(errors))
335
+
336
+
337
+ def create(run_dir, run, repo=REPO):
338
+ """Write `run.json` for a new run at declaration_seq 0 and bind its sha256 to seq 0 in the
339
+ declaration log; a declaration is never replaced."""
340
+ if run.get("declaration_seq", 0) != 0:
341
+ raise Refused("DECLARATION_INVALID declaration_seq: a new declaration starts at 0")
342
+ run = {**run, "declaration_seq": 0}
343
+ _validated(run, repo)
344
+ with stagelock.hold(run_dir, "declaration"):
345
+ records.confine_declaration(run_dir) # before anything is created or looked for
346
+ if records.run_json_path(run_dir).exists() or records.amendments_path(run_dir).exists():
347
+ raise Refused(f"RUN_EXISTS {run_dir}: amend it, never redeclare")
348
+ records.append_amendment(run_dir, {"seq": 0, "at": records.now(), "reason": "declaration", "scope": [],
349
+ "invalidates": [], "diff": {}, "run_json_sha256": records.bound_digest(run)})
350
+ records.write_json(run_dir, records.run_json_path(run_dir), run)
351
+ return run
352
+
353
+
354
+ def set_fields(run_dir, assignments, repo=REPO):
355
+ """Edit the declaration in place while it is still a draft: declaration_seq 0, and no stage
356
+ has recorded that it read it. The seq-0 binding follows the edit."""
357
+ with stagelock.hold(run_dir, "declaration"):
358
+ run, _digest, _amendments = records.declaration_state(run_dir)
359
+ recorded = sorted(records.stage_records(run_dir))
360
+ if recorded:
361
+ raise Refused(f"AMEND_REQUIRED {', '.join(recorded)} already read run.json: "
362
+ f"change it with --amend, which says what it invalidates")
363
+ if run["declaration_seq"] > 0:
364
+ raise Refused(f"AMEND_REQUIRED declaration_seq {run['declaration_seq']}: an amended declaration "
365
+ f"changes only by a further amendment")
366
+ new, _diff = apply_assignments(run, assignments)
367
+ _validated(new, repo)
368
+ records.write_json(run_dir, records.run_json_path(run_dir), new)
369
+ records.rebind(run_dir, records.bound_digest(new))
370
+ return new
371
+
372
+
373
+ def amend(run_dir, assignments, reason, scope=(), invalidates=(), repo=REPO):
374
+ """Append an amendment and apply it: `scope[]` names the stages licensed to read it
375
+ (default: every stage), `invalidates[]` the stages whose results it makes stale (the
376
+ ones `INVALIDATED_FROM` derives, plus those named), and the line binds the sha256 of the
377
+ run.json it produces to its seq. The line is written before run.json, so a crash between
378
+ the two leaves a declaration_seq behind the log, which `records.declaration_state` reports
379
+ as DECLARATION_DRIFT, never a silent edit. An amendment of a run.json that is not the
380
+ one the log authorized is refused the same way."""
381
+ if not _is_text(reason):
382
+ raise Refused("DECLARATION_INVALID reason: an amendment states why")
383
+ unknown = sorted((set(scope) | set(invalidates)) - set(records.STAGES))
384
+ if unknown:
385
+ raise Refused(f"DECLARATION_INVALID scope/invalidates: not stages: {unknown}")
386
+ with stagelock.hold(run_dir, "declaration"):
387
+ run, _digest, _amendments = records.declaration_state(run_dir)
388
+ new, diff = apply_assignments(run, assignments)
389
+ if not diff:
390
+ raise Refused("DECLARATION_INVALID amendment: it changes nothing")
391
+ new["declaration_seq"] = run["declaration_seq"] + 1
392
+ _validated(new, repo)
393
+ recorded = records.stage_records(run_dir)
394
+ derived = {stage for path in diff if path.split(".")[0] in INVALIDATED_FROM
395
+ for stage in records.STAGES[records.STAGES.index(INVALIDATED_FROM[path.split(".")[0]]):]
396
+ if stage in recorded}
397
+ amendment = {"seq": new["declaration_seq"], "at": records.now(), "reason": reason,
398
+ "scope": sorted(scope or records.STAGES, key=records.STAGES.index),
399
+ "invalidates": sorted(derived | set(invalidates), key=records.STAGES.index),
400
+ "diff": diff, "run_json_sha256": records.bound_digest(new)}
401
+ records.append_amendment(run_dir, amendment)
402
+ records.write_json(run_dir, records.run_json_path(run_dir), new)
403
+ return amendment
404
+
405
+
406
+ # --- self-test ------------------------------------------------------------------------------
407
+
408
+ def fixture():
409
+ """A valid declaration (golden): its seats are the ones the prompting guides cover today. Its S3 seat and
410
+ its Claude and Codex hosts are the ones seats.json pins, read from it, so a re-pin moves every suite built on this
411
+ declaration with it instead of leaving them on a host version the checkout no longer pins."""
412
+ digest = lambda name: records.sha256_bytes(name.encode()) # noqa: E731
413
+ pinned = gate.seats()
414
+ claude = pinned["hosts"]["claude"]["version"]
415
+ sonnet, opus = pinned["stage_seats"][VIEW_WINDOW_STAGE][0], "claude:claude-opus-5-5/high"
416
+ astra = "codex:gpt-6-astra/xhigh"
417
+ return {
418
+ "question": "Which repeated work patterns deserve a place in the library?",
419
+ "kind": "periodic",
420
+ "posture": "production",
421
+ "window": {"start": "2026-10-01T00:00:00", "end": "2026-10-08T00:00:00", "tz": "Asia/Seoul"},
422
+ "sources": [{"name": "claude_projects", "path": "/srv/fixture/claude/projects"},
423
+ {"name": "codex_sessions", "path": "/srv/fixture/codex/sessions"},
424
+ {"name": "zstd", "path": "/opt/homebrew/bin/zstd"}],
425
+ "checks": {"view_complete_share_min": 0.9},
426
+ "budget": {"per_stage": {"S3": 4000000, "S4": 1000000},
427
+ "per_episode": {"tokens": 200000, "compactions": 2, "max_budget_usd": 5.0, "max_turns": 40},
428
+ "reserve": 0.15},
429
+ # S6's sweeps as seats.json pins them for S6 (lead decision E1, WP-11 J3a)
430
+ "seats": {"S3": sonnet, "S4": opus, "S6.A": opus, "S6.B": astra, "S6.sweep_a": "claude:claude-sonnet-5-5/medium",
431
+ "S6.sweep_b": "codex:gpt-6-luna/medium", "S7b": astra},
432
+ "actor_seats": [{"stratum": "claude-main", "seat": sonnet, "provenance": "observed"},
433
+ {"stratum": "claude-subagent", "seat": opus, "provenance": "observed"},
434
+ {"stratum": "codex-main", "seat": astra, "provenance": "observed"},
435
+ {"stratum": "codex-subagent", "seat": "codex:gpt-6-luna/medium", "provenance": "fallback"}],
436
+ "config_manifest_B": {"global": digest("global")},
437
+ "starting_hashes": {"ledger": digest("ledger"), "coverage": digest("coverage"),
438
+ "layers": {"global": digest("global")}},
439
+ "account": {"extra_usage": "off", "declared_on": "2026-10-21"},
440
+ "hosts": {"claude": claude, "codex": pinned["hosts"]["codex"]["version"]},
441
+ "declaration_seq": 0,
442
+ "host_allowance": {sonnet: {"allowance_tokens": 3200, "host_version": claude,
443
+ "flag_set_sha256": digest("flags")}},
444
+ "output_caps": {VIEW_WINDOW_STAGE: 32000},
445
+ # COHERENT with the home below, because the writers derive their roots from it: a class
446
+ # root that does not contain what its writers compute from HOME is a declaration no run can
447
+ # satisfy, and the destination manifest says so by name. Each root here is where the real
448
+ # writers really write, with the fixture home in place of the owner's.
449
+ "destinations": {"checkout": "/srv/fixture/checkout",
450
+ # The HOME itself: a private installation writes in several places under
451
+ # it — the state root, both config homes, the corpus, the launcher's bin —
452
+ # so the class root that contains them all is the home. A run that wants a
453
+ # narrower one declares it, and then a writer whose suffix cannot be read
454
+ # is uncertified rather than assumed.
455
+ "install_roots": "/srv/fixture/home",
456
+ "personal_layers": "/srv/fixture/home",
457
+ "launcher_shell_integration": "/srv/fixture/home/.config/agent-bios/shell",
458
+ "runtime_state": "/srv/fixture/home/.local/state/agent-bios",
459
+ "nudge": "/srv/fixture/home/.local/state/agent-bios/nudge",
460
+ "recovery": "/srv/fixture/home/.local/state/agent-bios/recovery"},
461
+ # What the run HANDS its writers. The destination manifest computes every HOME-derived root
462
+ # from this one and compares the result with its class root, so a fixture without it cannot
463
+ # produce a manifest — which is the point: the alternative is guessing the owner's home.
464
+ "environment": {"home": "/srv/fixture/home"},
465
+ }
466
+
467
+
468
+ def self_test():
469
+ failures, ran = [], []
470
+
471
+ def control(name, errors, *needles):
472
+ """A named control: `errors` must carry every needle; with none it must be empty."""
473
+ ran.append(name)
474
+ if not needles and errors:
475
+ failures.append(f"{name}: expected no violation, got {errors}")
476
+ for needle in needles:
477
+ if not any(needle in line for line in errors):
478
+ failures.append(f"{name}: expected {needle!r} in {errors}")
479
+
480
+ # A control whose subject raises something other than a named refusal fails by its own name,
481
+ # with the exception in the message: a reverted check must not hide behind a traceback.
482
+ def checked(run):
483
+ try:
484
+ return check_declaration(run)
485
+ except Exception as exc:
486
+ return [f"RAISED {exc!r}"]
487
+
488
+ def mutated(edit):
489
+ run = fixture()
490
+ edit(run)
491
+ return checked(run)
492
+
493
+ def refusal(action, *args, **kwargs):
494
+ try:
495
+ action(*args, **kwargs)
496
+ except Refused as exc:
497
+ return str(exc).splitlines()
498
+ except Exception as exc:
499
+ return [f"RAISED {exc!r}"]
500
+ return []
501
+
502
+ # The declaration's fields, copied here once: design §4.1's contents plus what the plan adds
503
+ # (WP-01: declaration_seq, host_allowance, destinations; P3 / design §13.2: account, hosts) and
504
+ # `posture`, whose authority is design/session-distill/2026-10-21T0318--2d4fbd4--plan-addendum-wp01.md,
505
+ # and `output_caps` (WP-08: the cap's declared home, named in the schema's $comment).
506
+ # The schema is the authority for their shape; this pins which fields exist.
507
+ # `environment` is optional HERE and required by the destination manifest: what the run hands
508
+ # its writers (WP-21, `destinations.environment_for`), declared by a run written before the
509
+ # block existed or not at all, and refused at the manifest rather than at S0 so that no lane's
510
+ # fixture becomes invalid for a field only S11 needs.
511
+ # `density` and `retry` are the two optional fields (WP-08e: an earlier run's measured table; W r1 F4: the retries a
512
+ # call's claim holds), each named in the schema's $comment.
513
+ declared = {"question", "kind", "posture", "window", "sources", "checks", "budget", "seats",
514
+ "actor_seats", "config_manifest_B", "starting_hashes", "account", "hosts",
515
+ "declaration_seq", "host_allowance", "output_caps", "destinations"}
516
+ control("schema-requires-exactly-the-declared-fields",
517
+ [] if set(SCHEMA["required"]) == declared
518
+ and set(SCHEMA["properties"]) == declared | {"density", "retry", "retrieval", "judge",
519
+ "sweeps", "environment"}
520
+ and all(f"{name} (optional)" in SCHEMA["$comment"]
521
+ for name in ("density", "retry", "retrieval", "judge", "sweeps", "environment"))
522
+ else [f"schema requires {sorted(SCHEMA['required'])}, declares {sorted(SCHEMA['properties'])}"])
523
+ measured = {"bytes_per_token": 1.852, "measured_in": "c2-20261110", "samples": 8, "at": "2026-11-10T23:22:00+09:00"}
524
+ s3_seat = fixture()["seats"][VIEW_WINDOW_STAGE] # a name of its own: `sonnet` is assigned later in this function
525
+ control("WP-08e: a declared density with the run, the samples and the time that measured it is accepted",
526
+ mutated(lambda run: run.update(density={s3_seat: {"S3:window": dict(measured)}})))
527
+ control("WP-08e: a declared density without its provenance is refused at S0 by name (DENSITY_UNPROVENANCED)",
528
+ mutated(lambda run: run.update(density={s3_seat: {"S3:window": {"bytes_per_token": 1.852}}})),
529
+ f"DENSITY_UNPROVENANCED density.{s3_seat}.S3:window: a declared density carries the run that measured it")
530
+ control("WP-08e: a declared density with no samples or an unreadable time is refused at S0 by name",
531
+ mutated(lambda run: run.update(density={s3_seat: {"S3:window": {**measured, "samples": 0, "at": "yesterday"}}})),
532
+ f"DENSITY_UNPROVENANCED density.{s3_seat}.S3:window", "samples (at least one), at (ISO-8601)")
533
+ control("W r1 F4: a declared retry with its count and margin is accepted",
534
+ mutated(lambda run: run.update(retry={"count": 2, "margin": 4000})))
535
+ control("W r2 F9: a declared retry count that is an integral float is refused by name, before any arithmetic",
536
+ mutated(lambda run: run.update(retry={"count": 2.0})), "DECLARATION_INVALID retry.count: an integer, not 2.0")
537
+ control("W r2 F9: a declared density kind with a trailing newline is refused by name, so it is never read as nothing",
538
+ mutated(lambda run: run.update(density={s3_seat: {"S3:window\n": dict(measured)}})),
539
+ f"DECLARATION_INVALID density.{s3_seat}.'S3:window\\n': not a kind")
540
+ control("W r2 F9: a declared density that is not finite is refused by name",
541
+ mutated(lambda run: run.update(density={s3_seat: {"S3:window": {**measured, "bytes_per_token": math.inf}}})),
542
+ f"DECLARATION_INVALID density.{s3_seat}.S3:window.bytes_per_token: a finite number, not inf")
543
+ control("WP-11: declared retrieval counts and a judged scope with every formed candidate are accepted",
544
+ mutated(lambda run: run.update(retrieval={"per_layer": 5, "top_entries": 5},
545
+ judge={"candidate_kinds": {"formed": "all", "legacy": 10, "redundancy_hint": 0}})))
546
+ control("WP-11: a retrieval count that is an integral float is refused by name",
547
+ mutated(lambda run: run.update(retrieval={"per_layer": 5.0})), "DECLARATION_INVALID retrieval.per_layer: an integer")
548
+ control("WP-11 J3a: declared sweep sizes are accepted",
549
+ mutated(lambda run: run.update(sweeps={"shard_units": 50, "candidates_per_shard": 3, "output_cap": 16000})))
550
+ control("WP-11 J3a: a sweep size that is an integral float is refused by name",
551
+ mutated(lambda run: run.update(sweeps={"shard_units": 50.0})), "DECLARATION_INVALID sweeps.shard_units: an integer")
552
+ control("WP-11 J3a: a sweep size below one is refused by the schema",
553
+ mutated(lambda run: run.update(sweeps={"candidates_per_shard": 0})), "candidates_per_shard")
554
+ control("WP-11: a judged scope that is an integral float is refused by name",
555
+ mutated(lambda run: run.update(judge={"candidate_kinds": {"formed": "all", "legacy": 2.0}})),
556
+ "DECLARATION_INVALID judge.candidate_kinds.legacy: all or an integer")
557
+ control("WP-11: the formed candidates sampled is FORMED_SAMPLED (the planted controls take their shape)",
558
+ mutated(lambda run: run.update(judge={"candidate_kinds": {"formed": 3}})), "FORMED_SAMPLED judge.candidate_kinds.formed")
559
+ control("WP-11: the formed candidates left out of a declared map is FORMED_SAMPLED",
560
+ mutated(lambda run: run.update(judge={"candidate_kinds": {"legacy": "all"}})), "FORMED_SAMPLED")
561
+ control("WP-11: a judged scope naming a source S5 does not name is refused by the schema",
562
+ mutated(lambda run: run.update(judge={"candidate_kinds": {"formed": "all", "planted": "all"}})), "planted")
563
+ control("W r1 F4: a declared retry that names neither its count nor its margin is refused by name",
564
+ mutated(lambda run: run.update(retry={})), "DECLARATION_INVALID retry: a declared retry names its count")
565
+ control("WP-08e: a declared density is keyed by a seat the declaration names, as a reservation class is",
566
+ mutated(lambda run: run.update(density={"claude:claude-fable-5-2/high": {"S3:window": dict(measured)},
567
+ "claude": {"S3:window": dict(measured)}})),
568
+ "DECLARATION_INVALID density.claude:claude-fable-5-2/high: not a seat this declaration names",
569
+ "DECLARATION_INVALID density.claude: not a seat, expected provider:model/effort")
570
+ addendum = "design/session-distill/2026-10-21T0318--2d4fbd4--plan-addendum-wp01.md"
571
+ control("posture-is-authorized-by-a-named-addendum-that-exists",
572
+ [] if addendum in SCHEMA["$comment"] and (REPO / addendum).is_file()
573
+ else [f"run.schema.json cites {SCHEMA['$comment']!r}; {addendum} must be named and present"])
574
+ control("valid-declaration", checked(fixture())) # the positive control, first
575
+ # over the pinned set, not the schema's own list: a control that indexes a live list stops testing, silently, when
576
+ # an entry leaves it, so a requirement dropped from the schema still has its drop control here, and that fails
577
+ for name in sorted(declared):
578
+ code = "ACCOUNT_UNDECLARED" if name == "account" else "DECLARATION_INVALID"
579
+ control(f"drop-{name}", mutated(lambda run, name=name: run.pop(name)), f"{code} {name}: missing")
580
+ control("unknown-field", mutated(lambda run: run.update(extra=1)),
581
+ "DECLARATION_INVALID <root>: Additional properties", "'extra' was unexpected")
582
+ control("declaration-not-an-object", checked([]), "DECLARATION_INVALID <root>: [] is not of type 'object'")
583
+ control("account-not-an-object", mutated(lambda run: run.update(account="off")),
584
+ "ACCOUNT_UNDECLARED account: 'off' is not of type 'object'")
585
+ control("account-extra-usage-undecided", mutated(lambda run: run["account"].update(extra_usage="maybe")),
586
+ "ACCOUNT_UNDECLARED account.extra_usage")
587
+ control("account-without-date", mutated(lambda run: run["account"].pop("declared_on")),
588
+ "ACCOUNT_UNDECLARED account.declared_on: missing")
589
+ control("account-impossible-date", mutated(lambda run: run["account"].update(declared_on="2026-13-40")),
590
+ "ACCOUNT_UNDECLARED account.declared_on: not a calendar date")
591
+ control("kind-unknown", mutated(lambda run: run.update(kind="adhoc")), "DECLARATION_INVALID kind")
592
+ control("output-cap-zero", mutated(lambda run: run["output_caps"].update(S3=0)), "DECLARATION_INVALID output_caps.S3")
593
+ control("output-cap-not-an-integer", mutated(lambda run: run["output_caps"].update(S3=True)),
594
+ "DECLARATION_INVALID output_caps.S3")
595
+ control("output-cap-for-a-stage-nothing-reads", mutated(lambda run: run["output_caps"].update(S4=8000)),
596
+ "DECLARATION_INVALID output_caps: Additional properties")
597
+ control("posture-unknown", mutated(lambda run: run.update(posture="staging")), "DECLARATION_INVALID posture")
598
+ control("window-reversed", mutated(lambda run: run["window"].update(start="2026-10-09T00:00:00")),
599
+ "DECLARATION_INVALID window: the half-open window")
600
+ control("window-empty", mutated(lambda run: run["window"].update(end=run["window"]["start"])),
601
+ "DECLARATION_INVALID window: the half-open window")
602
+ control("window-unknown-zone", mutated(lambda run: run["window"].update(tz="Mars/Olympus")),
603
+ "DECLARATION_INVALID window: start and end")
604
+ control("sources-empty", mutated(lambda run: run.update(sources=[])), "DECLARATION_INVALID sources: [] should be non-empty")
605
+ control("sources-without-zstd", mutated(lambda run: run["sources"].pop()), "DECLARATION_INVALID sources: the absolute zstd")
606
+ control("sources-relative-path", mutated(lambda run: run["sources"][0].update(path="claude/projects")),
607
+ "DECLARATION_INVALID sources.0.path")
608
+ control("sources-repeated-name", mutated(lambda run: run["sources"][1].update(name="zstd")),
609
+ "DECLARATION_INVALID sources: source name 'zstd' repeats")
610
+ control("budget-negative-tokens", mutated(lambda run: run["budget"]["per_episode"].update(tokens=-1)),
611
+ "DECLARATION_INVALID budget.per_episode.tokens")
612
+ control("budget-stage-unknown", mutated(lambda run: run["budget"]["per_stage"].update(S99=1)),
613
+ "DECLARATION_INVALID budget.per_stage.S99: key is not a stage")
614
+ control("budget-stage-name-malformed", mutated(lambda run: run["budget"]["per_stage"].update(census=1)),
615
+ "DECLARATION_INVALID budget.per_stage: 'census' does not match any of the regexes")
616
+ control("budget-no-turn-cap", mutated(lambda run: run["budget"]["per_episode"].pop("max_turns")),
617
+ "DECLARATION_INVALID budget.per_episode.max_turns: missing")
618
+ control("seat-malformed", mutated(lambda run: run["seats"].update(S4="claude-opus-5-5")),
619
+ "DECLARATION_INVALID seats.S4: not a seat")
620
+ control("seats-without-the-view-window-stage", mutated(lambda run: run["seats"].pop("S3")),
621
+ "DECLARATION_INVALID seats.S3: missing")
622
+ control("seat-for-unknown-stage", mutated(lambda run: run["seats"].update(S99="claude:claude-sonnet-5-5/xhigh")),
623
+ "DECLARATION_INVALID seats.S99: key is not a stage")
624
+ control("actor-stratum-missing", mutated(lambda run: run["actor_seats"].pop()), "DECLARATION_INVALID actor_seats")
625
+ control("actor-stratum-repeated", mutated(lambda run: run["actor_seats"][3].update(stratum="codex-main")),
626
+ "DECLARATION_INVALID actor_seats: exactly one seat per stratum")
627
+ control("actor-seat-of-another-provider",
628
+ mutated(lambda run: run["actor_seats"][0].update(seat="codex:gpt-6-astra/xhigh")),
629
+ "the claude-main stratum names a seat of another provider")
630
+ control("starting-hash-not-sha256", mutated(lambda run: run["starting_hashes"].update(ledger="abc")),
631
+ "DECLARATION_INVALID starting_hashes.ledger")
632
+ control("manifest-entry-not-sha256", mutated(lambda run: run["config_manifest_B"].update(extra_layer="abc")),
633
+ "DECLARATION_INVALID config_manifest_B.extra_layer")
634
+ control("destination-class-missing", mutated(lambda run: run["destinations"].pop("recovery")),
635
+ "DECLARATION_INVALID destinations.recovery: missing")
636
+ control("destination-root-relative", mutated(lambda run: run["destinations"].update(nudge="state/nudge")),
637
+ "DECLARATION_INVALID destinations.nudge")
638
+ # the amendment to design §5.4: a declared allowance for the view-window seat, measured on the declared host
639
+ sonnet = fixture()["seats"]["S3"]
640
+ control("host-allowance-missing-for-the-view-window-seat", mutated(lambda run: run["host_allowance"].clear()),
641
+ f"ALLOWANCE_UNDECLARED seats.S3: {sonnet}")
642
+ control("host-allowance-only-for-another-seat",
643
+ mutated(lambda run: run.update(host_allowance={run["seats"]["S4"]: run["host_allowance"].popitem()[1]})),
644
+ "ALLOWANCE_UNDECLARED seats.S3")
645
+ control("host-allowance-measured-on-another-host-version",
646
+ mutated(lambda run: run["hosts"].update(claude="2.1.305")),
647
+ f"HOST_ALLOWANCE_STALE host_allowance.{sonnet}: measured on host {fixture()['hosts']['claude']}, "
648
+ f"the declaration names 2.1.305")
649
+ control("host-allowance-for-an-undeclared-seat",
650
+ mutated(lambda run: run["host_allowance"].update({"claude:claude-haiku-5-5/low": run["host_allowance"][sonnet]})),
651
+ "DECLARATION_INVALID host_allowance.claude:claude-haiku-5-5/low: not a seat this declaration names")
652
+ control("host-allowance-key-not-a-seat", mutated(lambda run: run["host_allowance"].update({"sonnet": run["host_allowance"][sonnet]})),
653
+ "DECLARATION_INVALID host_allowance.sonnet: not a seat")
654
+ control("host-allowance-without-its-flag-set", mutated(lambda run: run["host_allowance"][sonnet].pop("flag_set_sha256")),
655
+ f"DECLARATION_INVALID host_allowance.{sonnet}.flag_set_sha256: missing")
656
+ # seat coverage by the prompting-targets gate's own reader
657
+ control("stage-seat-uncovered",
658
+ mutated(lambda run: run["seats"].update(S4="claude:claude-opus-9-9/high")),
659
+ "SEAT_UNCOVERED claude:claude-opus-9-9/high")
660
+ control("codex-subagent-stratum-uncovered", # plan P6: the runtime half of the targets gate
661
+ mutated(lambda run: run["actor_seats"][3].update(seat="codex:gpt-4o-mini/medium")),
662
+ "SEAT_UNCOVERED codex:gpt-4o-mini/medium")
663
+ control("provider-without-a-guide", mutated(lambda run: run["seats"].update(S4="gemini:gemini-3/high")),
664
+ "SEAT_UNCOVERED gemini:gemini-3/high: no prompting guide owns provider 'gemini'")
665
+
666
+ # the reader is the gate's own: compiled from its script, and it follows the script when that changes
667
+ owners, targets = prompting_reader()
668
+ targets_gate = str(REPO / "launch" / "check-prompting-targets.sh")
669
+ ran.append("reader-is-compiled-from-the-gate-script")
670
+ if targets.__code__.co_filename != targets_gate or owners.get("claude") is None:
671
+ failures.append(f"reader-is-compiled-from-the-gate-script: {targets.__code__.co_filename}")
672
+ with tempfile.TemporaryDirectory() as td:
673
+ scratch = pathlib.Path(td)
674
+ (scratch / "launch").mkdir()
675
+ (scratch / "codex" / "guides").mkdir(parents=True)
676
+ text = pathlib.Path(targets_gate).read_text(encoding="utf-8")
677
+ for guide in ("claude-prompting", "gpt-prompting"):
678
+ (scratch / "codex" / "guides" / f"{guide}.md").write_bytes(
679
+ (REPO / "codex" / "guides" / f"{guide}.md").read_bytes())
680
+
681
+ def with_gate(edit):
682
+ (scratch / "launch" / "check-prompting-targets.sh").write_text(edit(text), encoding="utf-8")
683
+ return seat_coverage(fixture(), scratch)
684
+
685
+ control("scratch-copy-of-the-gate-agrees", with_gate(lambda t: t))
686
+ control("gate-edit-moves-the-verdict", # claude seats now read the gpt guide: the reader followed the script
687
+ with_gate(lambda t: t.replace('"claude": "claude-prompting"', '"claude": "gpt-prompting"')),
688
+ f"SEAT_UNCOVERED {sonnet}: gpt-prompting does not name {parse_seat(sonnet)[1]}")
689
+ control("gate-without-a-targets-function",
690
+ with_gate(lambda t: t.replace("def targets(", "def renamed(")), "SEAT_COVERAGE_UNREADABLE")
691
+ control("gate-without-a-python-body", with_gate(lambda t: t.replace("<<'PY'", "<<'EOF'")),
692
+ "SEAT_COVERAGE_UNREADABLE")
693
+ (scratch / "codex" / "guides" / "gpt-prompting.md").unlink()
694
+ control("guide-missing", with_gate(lambda t: t), "SEAT_COVERAGE_UNREADABLE FAIL: missing prompting guide")
695
+
696
+ # actions on a run directory. A step that must succeed for the controls after it to mean anything
697
+ # is run through `must`: if it is refused, the failure is named by the step and the rest is skipped.
698
+ class Abort(Exception):
699
+ pass
700
+
701
+ def must(step, action, *args, **kwargs):
702
+ try:
703
+ return action(*args, **kwargs)
704
+ except Exception as exc:
705
+ failures.append(f"{step}: refused unexpectedly ({exc}); the controls after it were not run")
706
+ raise Abort from exc
707
+
708
+ def stage_once(directory, name, output=None):
709
+ # S2 has parts (`records.STAGE_PARTS`), and a writer there names the part it produces; these
710
+ # controls are about the declaration a stage binds, not about parts.
711
+ part = "views" if name in records.STAGE_PARTS else None
712
+ with records.run_stage(directory, name, part=part) as stage_run:
713
+ if output:
714
+ (directory / output).write_text("{}\n", encoding="utf-8")
715
+ stage_run.output(output)
716
+
717
+ with tempfile.TemporaryDirectory() as td:
718
+ try:
719
+ run_dir = pathlib.Path(td) / "r1"
720
+ control("create", [] if must("create", create, run_dir, fixture())["declaration_seq"] == 0 else ["not at seq 0"])
721
+ control("create-twice", refusal(create, run_dir, fixture()), "RUN_EXISTS")
722
+ control("create-invalid", refusal(create, pathlib.Path(td) / "r2", {**fixture(), "kind": "x"}),
723
+ "DECLARATION_INVALID kind")
724
+ if records.run_json_path(pathlib.Path(td) / "r2").exists():
725
+ failures.append("create-invalid: an invalid declaration was written")
726
+ control("create-at-a-later-seq", refusal(create, pathlib.Path(td) / "r3", {**fixture(), "declaration_seq": 2}),
727
+ "DECLARATION_INVALID declaration_seq")
728
+ control("set-before-any-stage",
729
+ [] if must("set before any stage", set_fields, run_dir, [("checks.view_complete_share_min", 0.8)])
730
+ ["checks"]["view_complete_share_min"] == 0.8 else ["not applied"])
731
+ control("set-rebinds-the-declaration-at-seq-0", refusal(records.declaration_state, run_dir))
732
+ control("set-invalid-value", refusal(set_fields, run_dir, [("kind", "adhoc")]), "DECLARATION_INVALID kind")
733
+ control("set-seq", refusal(set_fields, run_dir, [("declaration_seq", 7)]), "DECLARATION_INVALID declaration_seq")
734
+ control("set-into-nothing", refusal(set_fields, run_dir, [("budget.nope.x", 1)]), "no such object")
735
+ control("amend-without-reason", refusal(amend, run_dir, [("budget.reserve", 0.2)], " "), "an amendment states why")
736
+ control("amend-unknown-stage", refusal(amend, run_dir, [("budget.reserve", 0.2)], "r", scope=["S99"]), "not stages")
737
+ control("amend-changing-nothing", refusal(amend, run_dir, [], "r"), "it changes nothing")
738
+ must("stage S1 starts under the bound declaration", stage_once, run_dir, "S1", "census.json")
739
+ control("set-after-a-stage-recorded",
740
+ refusal(set_fields, run_dir, [("checks.view_complete_share_min", 0.7)]), "AMEND_REQUIRED S1")
741
+ first = must("amend budget", amend, run_dir, [("budget.reserve", 0.2)], "raise the retry reserve", scope=["S2"])
742
+ control("amend-budget", [] if (first["seq"], first["scope"], first["invalidates"]) == (1, ["S2"], [])
743
+ else [f"unexpected amendment {first}"])
744
+ for stage in ("S2", "S3", "S4"):
745
+ must(f"stage {stage} starts under the bound declaration", stage_once, run_dir, stage)
746
+ second = must("amend checks", amend, run_dir, [("checks.view_complete_share_min", 0.95)],
747
+ "tighten the completeness criterion")
748
+ control("amend-checks-invalidates-s3-and-downstream",
749
+ [] if (second["seq"], second["invalidates"]) == (2, ["S3", "S4"]) else [f"unexpected {second}"])
750
+ third = must("amend hosts.codex", amend, run_dir, [("hosts.codex", "0.164.0")], "host upgrade", invalidates=["S1"])
751
+ control("amend-explicit-invalidation", [] if third["invalidates"] == ["S1"] else [f"unexpected {third}"])
752
+ logged = records.read_amendments(run_dir)
753
+ control("amendments-are-logged-in-order",
754
+ [] if [a["seq"] for a in logged] == [1, 2, 3] and logged[1]["diff"] == {
755
+ "checks.view_complete_share_min": {"old": 0.8, "new": 0.95}} else [f"log is {logged}"])
756
+ control("run-json-follows-the-log",
757
+ [] if records.read_json(records.run_json_path(run_dir))["declaration_seq"] == 3 else ["seq not advanced"])
758
+ control("amend-to-an-invalid-declaration", refusal(amend, run_dir, [("kind", "adhoc")], "r"), "DECLARATION_INVALID kind")
759
+ if len(records.read_amendments(run_dir)) != 3:
760
+ failures.append("amend-to-an-invalid-declaration: the refused amendment was logged")
761
+ # a host upgrade is re-measured in the same amendment: the version alone leaves the allowance stale
762
+ control("amend-host-upgrade-without-remeasuring", refusal(amend, run_dir, [("hosts.claude", "2.1.305")], "upgrade"),
763
+ f"HOST_ALLOWANCE_STALE host_allowance.{sonnet}")
764
+ remeasured = {sonnet: {**fixture()["host_allowance"][sonnet], "host_version": "2.1.305"}}
765
+ upgrade = must("amend the host upgrade with its allowance", amend, run_dir,
766
+ [("hosts.claude", "2.1.305"), ("host_allowance", remeasured)], "upgrade, re-measured")
767
+ control("amend-host-upgrade-with-the-new-allowance",
768
+ [] if upgrade["seq"] == 4 and records.read_json(records.run_json_path(run_dir))["host_allowance"] == remeasured
769
+ else [f"unexpected {upgrade}"])
770
+ # raising the cap is ACCEPTED, and every recorded stage from S2 on is stale: S2 cut the windows reserving
771
+ # the old cap, so a call reserving more may not send them
772
+ raised = must("amend output_caps", amend, run_dir, [("output_caps.S3", 48000)], "a longer answer")
773
+ control("amend-output-cap-invalidates-s2-and-downstream",
774
+ [] if (raised["seq"], raised["invalidates"]) == (5, ["S2", "S3", "S4"]) else [f"unexpected {raised}"])
775
+
776
+ # each declaration seq is bound to the run.json authorized at it: a hand edit, before any stage
777
+ # has read the new seq, is found by the next amendment, edit or stage
778
+ bound = pathlib.Path(td) / "r5"
779
+ must("create r5", create, bound, fixture())
780
+ log = records.read_log(bound)
781
+ control("create-binds-the-declaration-to-seq-0",
782
+ [] if len(log) == 1 and log[0]["seq"] == 0 and log[0]["run_json_sha256"] == records.sha256_file(records.run_json_path(bound))
783
+ else [f"unexpected log {log}"])
784
+ must("amend r5", amend, bound, [("budget.reserve", 0.2)], "raise the retry reserve")
785
+ control("an-amendment-binds-the-new-run-json-to-its-seq",
786
+ [] if records.read_log(bound)[-1]["run_json_sha256"] == records.sha256_file(records.run_json_path(bound))
787
+ and records.read_log(bound)[-1]["seq"] == 1 else [f"unexpected log {records.read_log(bound)}"])
788
+ control("set-after-an-amendment-is-refused", refusal(set_fields, bound, [("budget.reserve", 0.3)]),
789
+ "AMEND_REQUIRED declaration_seq 1")
790
+ authorized = records.run_json_path(bound).read_bytes()
791
+ edited = records.read_json(records.run_json_path(bound))
792
+ edited["checks"]["view_complete_share_min"] = 0.5
793
+ records.run_json_path(bound).write_text(records.json_text(edited), encoding="utf-8") # by hand: the seq stays 1
794
+ log_before = records.amendments_path(bound).read_bytes()
795
+ control("amend-after-a-hand-edit-of-checks-is-refused", refusal(amend, bound, [("budget.reserve", 0.4)], "r"),
796
+ "DECLARATION_DRIFT declare: run.json is not the declaration authorized at seq 1")
797
+ control("set-after-a-hand-edit-is-refused", refusal(set_fields, bound, [("budget.reserve", 0.4)]), "DECLARATION_DRIFT")
798
+ control("the-refused-amend-logged-nothing",
799
+ [] if records.amendments_path(bound).read_bytes() == log_before else ["the log changed"])
800
+ records.run_json_path(bound).write_bytes(authorized)
801
+ control("the-authorized-run-json-amends-again",
802
+ [] if must("amend the authorized run.json", amend, bound, [("budget.reserve", 0.4)], "r")["seq"] == 2
803
+ else ["not amended"])
804
+
805
+ # a link inside a new run directory cannot make `create` write outside it: nothing is created
806
+ # at the link's target, and nothing is logged inside before the refusal
807
+ def escape(action, *args):
808
+ try:
809
+ action(*args)
810
+ return []
811
+ except stagelock.Escaped as exc:
812
+ return [str(exc)]
813
+ except Exception as exc:
814
+ return [f"RAISED {exc!r}"]
815
+
816
+ for name, linked_file in (("r6", "run.json"), ("r7", "amendments.jsonl")):
817
+ linked, external = pathlib.Path(td) / name, pathlib.Path(td) / f"{name}-external"
818
+ linked.mkdir()
819
+ external.mkdir()
820
+ (linked / linked_file).symlink_to(external / linked_file) # dangling
821
+ control(f"create-through-a-dangling-{linked_file}-link", escape(create, linked, fixture()), "RUN_PATH_ESCAPE")
822
+ control(f"the-refused-create-touched-nothing-via-{linked_file}",
823
+ [] if not list(external.iterdir()) and sorted(p.name for p in linked.iterdir()) in (
824
+ [linked_file, "locks"], ["locks", linked_file]) else
825
+ [f"external {list(external.iterdir())}, run dir {sorted(p.name for p in linked.iterdir())}"])
826
+
827
+ # a link made after the declaration cannot make a later mutation half-happen: both files are confined
828
+ # before either is written, no byte changes, and the same call succeeds once the link is repaired
829
+ mutators = {"amend": lambda directory: amend(directory, [("budget.reserve", 0.4)], "raise the reserve"),
830
+ "set": lambda directory: set_fields(directory, [("budget.reserve", 0.4)])}
831
+ for mutator, mutate in mutators.items():
832
+ for linked_file, other_file in (("run.json", "amendments.jsonl"), ("amendments.jsonl", "run.json")):
833
+ name = f"{mutator}-with-{linked_file}-linked-out"
834
+ directory, external = pathlib.Path(td) / f"l-{mutator}-{linked_file}", pathlib.Path(td) / f"l-{mutator}-{linked_file}-x"
835
+ external.mkdir()
836
+ must(f"create {directory.name}", create, directory, fixture())
837
+ linked, other = directory / linked_file, directory / other_file
838
+ body, other_body = linked.read_bytes(), other.read_bytes()
839
+ (external / linked_file).write_bytes(body)
840
+ linked.unlink()
841
+ linked.symlink_to(external / linked_file)
842
+ control(name, escape(mutate, directory), "RUN_PATH_ESCAPE")
843
+ control(f"the-refused-{name}-changed-no-file",
844
+ [] if (external / linked_file).read_bytes() == body and linked.read_bytes() == body
845
+ and other.read_bytes() == other_body and sorted(q.name for q in external.iterdir()) == [linked_file]
846
+ else [f"{linked_file} or {other_file} or the link target changed"])
847
+ linked.unlink()
848
+ linked.write_bytes(body) # the link repaired
849
+ result = must(f"{name}, retried once the link is repaired", mutate, directory)
850
+ retried = records.read_json(records.run_json_path(directory))
851
+ control(f"{name}-succeeds-once-the-link-is-repaired",
852
+ [] if retried["budget"]["reserve"] == 0.4 and result
853
+ and retried["declaration_seq"] == (1 if mutator == "amend" else 0)
854
+ else [f"the retried {mutator} left {retried['budget']['reserve']} at seq {retried['declaration_seq']}"])
855
+
856
+ # done-when 3 on a run whose only record is S3: --set is refused naming S3, the same change
857
+ # through --amend is accepted, logged, and marks S3 invalidated
858
+ s3_dir = pathlib.Path(td) / "r4"
859
+ must("create r4", create, s3_dir, fixture())
860
+ must("stage S3 starts under the bound declaration", stage_once, s3_dir, "S3")
861
+ change = [("checks.view_complete_share_min", 0.99)]
862
+ control("set-checks-after-s3-is-refused", refusal(set_fields, s3_dir, change), "AMEND_REQUIRED S3 already read run.json")
863
+ control("the-refused-set-changed-nothing",
864
+ [] if records.read_json(records.run_json_path(s3_dir))["checks"]["view_complete_share_min"] == 0.9
865
+ else ["run.json was edited in place"])
866
+ accepted = must("amend the checks change", amend, s3_dir, change, "tighten the criterion")
867
+ control("the-same-checks-change-through-amend",
868
+ [] if (accepted["seq"], accepted["invalidates"]) == (1, ["S3"])
869
+ and records.read_amendments(s3_dir) == [accepted]
870
+ and records.read_json(records.run_json_path(s3_dir))["checks"]["view_complete_share_min"] == 0.99
871
+ else [f"unexpected {accepted}"])
872
+ except Abort:
873
+ pass
874
+
875
+ for failure in failures:
876
+ print(f"declare --self-test [FAIL] {failure}")
877
+ if failures:
878
+ return 1
879
+ for name in ran:
880
+ print(f" control {name}")
881
+ print(f"declare --self-test: OK ({len(ran)} controls)")
882
+ return 0
883
+
884
+
885
+ if __name__ == "__main__":
886
+ if "--self-test" not in sys.argv[1:]:
887
+ sys.exit("usage: declare.py --self-test")
888
+ sys.exit(self_test())