agent-bios 0.19.4 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/DEPENDENCIES.md +20 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +8 -7
  6. package/claude/guides/gpt-prompting.md +319 -144
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/agents/frontier.toml +1 -1
  10. package/codex/agents/reviewer.toml +1 -1
  11. package/codex/agents/workhorse.toml +1 -1
  12. package/codex/guides/claude-prompting.md +475 -234
  13. package/codex/guides/cli-multi-model-workflow.md +8 -7
  14. package/codex/guides/gpt-prompting.md +319 -144
  15. package/codex/guides/session-distill-workflow.md +93 -43
  16. package/codex/guides/tooling-gotchas.md +3 -1
  17. package/compose/assemble.py +4 -1
  18. package/compose/canary.sh +8 -6
  19. package/compose/host_platform.py +158 -15
  20. package/compose/instructions-state.py +183 -41
  21. package/compose/instructions_install.py +222 -27
  22. package/compose/instructions_session.py +250 -75
  23. package/compose/instructions_setup_cli.py +2 -36
  24. package/compose/instructions_store.py +160 -3
  25. package/compose/instructions_transaction.py +29 -5
  26. package/docs/advanced-launch.md +5 -1
  27. package/docs/releases/0.20.0.md +102 -0
  28. package/docs/releases/0.20.1.md +76 -0
  29. package/install.sh +42 -14
  30. package/launch/agent-launch.py +152 -18
  31. package/launch/agent-launch.toml +28 -16
  32. package/launch/agent-launch.zsh +104 -13
  33. package/launch/claude_subcommands.py +179 -0
  34. package/launch/shell_integration.py +7 -1
  35. package/learn/collect-learning.py +60 -9
  36. package/learn/migrate-learnings.py +70 -4
  37. package/learn/redact.py +2 -1
  38. package/package.json +36 -3
  39. package/provenance.json +1 -1
  40. package/session-cost.py +80 -9
  41. package/session-distill/coverage.json +6 -0
  42. package/session-distill/distill.py +2575 -0
  43. package/session-distill/grammar/__init__.py +0 -0
  44. package/session-distill/grammar/owner_lines.py +874 -0
  45. package/session-distill/originators.json +9 -0
  46. package/session-distill/packets/cross_review.md +31 -0
  47. package/session-distill/packets/form.md +86 -0
  48. package/session-distill/packets/judge.md +81 -0
  49. package/session-distill/packets/placement_contract.md +90 -0
  50. package/session-distill/packets/propose.md +124 -0
  51. package/session-distill/packets/read.md +57 -0
  52. package/session-distill/packets/reconsider.md +53 -0
  53. package/session-distill/packets/s7b.md +65 -0
  54. package/session-distill/packets/s9b.md +39 -0
  55. package/session-distill/packets/stitch.md +35 -0
  56. package/session-distill/packets/sweep.md +33 -0
  57. package/session-distill/runlib/__init__.py +0 -0
  58. package/session-distill/runlib/bound.py +1102 -0
  59. package/session-distill/runlib/breaker.py +467 -0
  60. package/session-distill/runlib/census.py +2347 -0
  61. package/session-distill/runlib/claims.py +420 -0
  62. package/session-distill/runlib/controls.py +902 -0
  63. package/session-distill/runlib/coverage.py +881 -0
  64. package/session-distill/runlib/declare.py +888 -0
  65. package/session-distill/runlib/delivery_evidence.py +1145 -0
  66. package/session-distill/runlib/derive.py +812 -0
  67. package/session-distill/runlib/destinations.py +3072 -0
  68. package/session-distill/runlib/dispatch.py +7940 -0
  69. package/session-distill/runlib/drift.py +1077 -0
  70. package/session-distill/runlib/entry.py +401 -0
  71. package/session-distill/runlib/evidence.py +890 -0
  72. package/session-distill/runlib/exposure.py +1162 -0
  73. package/session-distill/runlib/gate.py +2727 -0
  74. package/session-distill/runlib/gitread.py +79 -0
  75. package/session-distill/runlib/inventory.py +19624 -0
  76. package/session-distill/runlib/journal.py +1919 -0
  77. package/session-distill/runlib/ledger.py +3210 -0
  78. package/session-distill/runlib/ledger_compat.py +101 -0
  79. package/session-distill/runlib/ledger_migration.py +190 -0
  80. package/session-distill/runlib/lifecycle_intake.py +693 -0
  81. package/session-distill/runlib/lineage.py +454 -0
  82. package/session-distill/runlib/measures.py +249 -0
  83. package/session-distill/runlib/monitor.py +1180 -0
  84. package/session-distill/runlib/operations.py +522 -0
  85. package/session-distill/runlib/packet.py +838 -0
  86. package/session-distill/runlib/placement.py +1769 -0
  87. package/session-distill/runlib/projection.py +4090 -0
  88. package/session-distill/runlib/ranking.py +740 -0
  89. package/session-distill/runlib/receipts.py +200 -0
  90. package/session-distill/runlib/records.py +1965 -0
  91. package/session-distill/runlib/search.py +249 -0
  92. package/session-distill/runlib/sequencing.py +829 -0
  93. package/session-distill/runlib/sources.py +641 -0
  94. package/session-distill/runlib/stage_adjudicate.py +845 -0
  95. package/session-distill/runlib/stage_apply.py +1378 -0
  96. package/session-distill/runlib/stage_approvals.py +758 -0
  97. package/session-distill/runlib/stage_close.py +1220 -0
  98. package/session-distill/runlib/stage_confirm.py +929 -0
  99. package/session-distill/runlib/stage_delivery.py +3080 -0
  100. package/session-distill/runlib/stage_form.py +2576 -0
  101. package/session-distill/runlib/stage_judge.py +4248 -0
  102. package/session-distill/runlib/stage_propose.py +3307 -0
  103. package/session-distill/runlib/stage_read.py +5179 -0
  104. package/session-distill/runlib/stage_render.py +2739 -0
  105. package/session-distill/runlib/stage_retrieve.py +924 -0
  106. package/session-distill/runlib/stage_review_korean.py +1002 -0
  107. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  108. package/session-distill/runlib/stagelock.py +412 -0
  109. package/session-distill/runlib/stop.py +1061 -0
  110. package/session-distill/runlib/targets.py +809 -0
  111. package/session-distill/runlib/usage.py +280 -0
  112. package/session-distill/runlib/validate.py +319 -0
  113. package/session-distill/runlib/views.py +4327 -0
  114. package/session-distill/schemas/adjudication.schema.json +35 -0
  115. package/session-distill/schemas/approval.schema.json +35 -0
  116. package/session-distill/schemas/census.schema.json +128 -0
  117. package/session-distill/schemas/checks.schema.json +207 -0
  118. package/session-distill/schemas/claim.schema.json +16 -0
  119. package/session-distill/schemas/confirmation.schema.json +24 -0
  120. package/session-distill/schemas/coverage.schema.json +66 -0
  121. package/session-distill/schemas/cross_review.schema.json +24 -0
  122. package/session-distill/schemas/event.schema.json +20 -0
  123. package/session-distill/schemas/evidence.schema.json +20 -0
  124. package/session-distill/schemas/expected_observation.schema.json +18 -0
  125. package/session-distill/schemas/form.schema.json +103 -0
  126. package/session-distill/schemas/intake.schema.json +71 -0
  127. package/session-distill/schemas/inventory.schema.json +872 -0
  128. package/session-distill/schemas/judge.schema.json +77 -0
  129. package/session-distill/schemas/ledger.schema.json +313 -0
  130. package/session-distill/schemas/observation.schema.json +16 -0
  131. package/session-distill/schemas/propose.schema.json +555 -0
  132. package/session-distill/schemas/read.schema.json +76 -0
  133. package/session-distill/schemas/reconsider.schema.json +122 -0
  134. package/session-distill/schemas/run.schema.json +150 -0
  135. package/session-distill/schemas/s7b.schema.json +200 -0
  136. package/session-distill/schemas/s9b.schema.json +28 -0
  137. package/session-distill/schemas/stitch.schema.json +25 -0
  138. package/session-distill/schemas/sweep.schema.json +25 -0
  139. package/session-distill/seats.json +149 -0
  140. package/session-distill/tables/allowed_pairs.json +257 -0
  141. package/session-distill/tables/controls.json +30 -0
  142. package/session-distill/tables/delivery_evidence.json +36 -0
  143. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  144. package/session-distill/tables/destinations.json +684 -0
  145. package/session-distill/tables/drift_layers.json +68 -0
  146. package/session-distill/tables/exposure_rules.json +192 -0
  147. package/session-distill/tables/placement_rules.json +148 -0
  148. package/session-distill/tables/propose_fixtures.json +154 -0
  149. package/session-distill/tables/ranking.json +194 -0
  150. package/session-distill/tables/redundancy.json +10 -0
  151. package/session-distill/tables/structural_rules.json +44 -0
  152. package/session-distill/tables/transition_fixtures.json +398 -0
  153. package/session-distill/tables/transitions.json +69 -0
  154. package/session-distill/tables/unit_outcome.json +67 -0
  155. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  156. package/wrappers/claude-run.sh +481 -33
  157. package/wrappers/claude_hermetic_evidence.py +1423 -0
  158. package/wrappers/codex-helm.sh +46 -15
  159. package/wrappers/codex-run.sh +183 -20
  160. package/wrappers/codex_frame_filter.py +1199 -0
  161. package/wrappers/codex_protocol.py +737 -0
  162. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,3210 @@
1
+ #!/usr/bin/env python3
2
+ """The ledger of the session distill: schema 2, transitions, events, the id-set check, the atomic write.
3
+
4
+ `design/session-distill/ledger.json` moves to schema 2 at the cutover (design §12.1-§12.4); until
5
+ then it is schema 1 and every function here reads both. The pieces:
6
+
7
+ validate_ledger schema 1: the structure the legacy merge keeps (entries with unique ids and
8
+ a status). Schema 2: `schemas/ledger.schema.json` through `validate.py`, then
9
+ the rules a schema cannot say: unique ids and decision runs, an approval row
10
+ on every run decision, the §7.2 vocabulary and none of §12.2's metadata on
11
+ every decision a run made, the structural rules of §7.3 (an incubate with its observation,
12
+ a keep or a drop with its reason), resolutions on the decision they resolve,
13
+ relations that resolve, exactly one evidence form per evidence item, and a
14
+ history that replays through the table to the status the entry holds.
15
+ check_pair the id-set check of design §12.4 over a frozen base and a head ledger: no id
16
+ lost, new ids exactly those allocated (a schema 2 run that writes at all needs
17
+ the allocation it froze; only a schema 1 ledger may continue its numbering),
18
+ every changed row bound to an applied decision whose disposition licenses that
19
+ field, every new row bound to the
20
+ decision that created it, decisions append-only. Schema 1 to schema 2 is
21
+ judged by equality with the migration.
22
+ transition, events design §12.3, read from `tables/transitions.json`. `render_cell` writes the
23
+ design's cell wording back from the data, and the self-test holds that wording
24
+ and the event rows against the design's tables. `apply_decision` and
25
+ `create_entry` append one decisions[] element, move the status by the table and
26
+ check the effects the cell requires; `record_event` carries the five events. A
27
+ revert restores the status derived from the entry's own history (`replays`); a
28
+ migrated entry's history starts at the status its `legacy_migration` element records.
29
+ write_atomic lock, expected base hash, temporary file, fsync, rename, all confined beneath
30
+ the ledger's directory.
31
+
32
+ ledger.py --check [--ledger FILE] [--base REV] [--worktree] [--allocated ID,ID]
33
+ ledger.py --generate-transition-fixtures
34
+ ledger.py --self-test
35
+
36
+ `--check` compares the ledger in the index (`--worktree`: on disk) with its content at REV (HEAD by
37
+ default). Exit 0 holds; 1 a violation; 2 a side git could not read, because a gate that judged
38
+ nothing has not passed (design/session-distill/2026-10-21T0455--9410a1d--plan-addendum-wp14.md).
39
+ Failures are named by their first word.
40
+ """
41
+ import argparse
42
+ import contextlib
43
+ import copy
44
+ import hashlib
45
+ import importlib.util
46
+ import io
47
+ import json
48
+ import os
49
+ import pathlib
50
+ import re
51
+ import subprocess
52
+ import sys
53
+ import tempfile
54
+
55
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
56
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
57
+ from runlib import gitread, stagelock, validate
58
+
59
+ HERE = pathlib.Path(__file__).resolve().parents[1] # session-distill/
60
+ REPO = HERE.parent
61
+ # The ledger of an INSTALLED driver, under the private installation's state root — the root that
62
+ # also holds the pins and the receipts. It is the only ledger location shipped code names: the
63
+ # owner's checkout keeps its own under `design/`, which the author-side caller passes with `--ledger`
64
+ # (`gates/check-ledger.py`, the runbook, the preset). A packaged user has no `design/`, so a default
65
+ # pointing there was a path that could not exist on the machine the code ran on.
66
+ STATE_LEDGER_REL = "distill/ledger.json"
67
+ SCHEMA_PATH = HERE / "schemas" / "ledger.schema.json"
68
+ EO_SCHEMA_PATH = HERE / "schemas" / "expected_observation.schema.json"
69
+ TRANSITIONS_PATH = HERE / "tables" / "transitions.json"
70
+ FIXTURES_PATH = HERE / "tables" / "transition_fixtures.json"
71
+ LOCK_ROOT = HERE / "out" / "ledger-lock" # untracked: `session-distill/out/*/` is ignored
72
+
73
+ SUPPORTED = (1, 2)
74
+ ID_SERIES = re.compile(r"^([A-Z]+[0-9]*)-([0-9]+)$")
75
+ # Fields whose growth needs no decision: design §12.3's recurrence event ("evidence and lineages
76
+ # appended"). A list among them only ever grows at its end.
77
+ EVENT_FIELDS = ("recurrence", "evidence", "independent_lineages", "coverage")
78
+ APPEND_ONLY = ("recurrence", "evidence")
79
+ TEXT_FIELDS = ("lesson", "principle", "rationale") # what "text revised" revises
80
+ # What each disposition of design §7.2 licenses on its entry, besides the status the table moves and
81
+ # the disposition the entry takes from it (ADDENDUM §3). A disposition that changes nothing installed
82
+ # — `none`, and design §12.3's incubated or dropped intervention — licenses neither the entry's text
83
+ # nor its destination. The identity and the provenance of an entry (id, learning_id, source,
84
+ # surfaced, window, baseline_ref) are licensed by no disposition at all.
85
+ CLASSIFYING_FIELDS = ("kind", "diagnosis", "classification", "note", "domain")
86
+ DISPOSITION_FIELDS = {
87
+ "place": TEXT_FIELDS + ("destination", "relations") + CLASSIFYING_FIELDS,
88
+ "correct": TEXT_FIELDS + ("destination",) + CLASSIFYING_FIELDS,
89
+ "re-deliver": ("destination",) + CLASSIFYING_FIELDS,
90
+ "keep": ("keep",) + CLASSIFYING_FIELDS,
91
+ "reduce": ("absorbed_by", "relations", "retired", "retire_reason") + CLASSIFYING_FIELDS,
92
+ "incubate": CLASSIFYING_FIELDS,
93
+ "drop": ("retired", "retire_reason") + CLASSIFYING_FIELDS,
94
+ "none": (),
95
+ }
96
+ # What a cell's effect needs the entry to gain or lose, over what its disposition licenses.
97
+ EFFECT_FIELDS = {"keep_record": ("keep",), "absorbed_by": ("absorbed_by",), "allocate_destination_entry": ("absorbed_by",),
98
+ "text_revised": TEXT_FIELDS, "never_placed": ("destination",),
99
+ "revival": ("retired", "retire_reason", "absorbed_by")}
100
+ # A revert restores what the application it undoes recorded: design §12.1's `applied` carries `before`,
101
+ # the values the row held for every field that application changed (the owner's decision of 2026-10-21,
102
+ # in RECORD below). Six review rounds of inferring those values from the history each found a case the
103
+ # inference got wrong, so nothing is inferred here: an application that changes a row records what it
104
+ # replaced, and a revert with no such record to read is refused by name.
105
+ REVERTIBLE = tuple(sorted({f for fields in DISPOSITION_FIELDS.values() for f in fields}))
106
+ NULLABLE = ("destination", "keep", "classification") # design §12.1 keeps these on every entry, null when it has none
107
+ EMPTY_BEFORE = {"fields": {}, "absent": []}
108
+ LEGACY_KINDS = ("legacy_application", "legacy_retirement", "legacy_migration")
109
+ # Design §12.2's metadata: what an element the migration produced carries and a decision of a run
110
+ # never does (ADDENDUM §1-§2). `contract_problems` holds this list against the schema's own marks.
111
+ LEGACY_PROPERTIES = ("at", "field", "legacy_text", "legacy_placed", "legacy_status", "status_note")
112
+ LEGACY_MARK = "design §12.2, a migrated element only" # what marks one of them in the schema
113
+ LEGACY_REQUIRED = ("at", "field", "legacy_text") # design §12.2: what every migrated element carries
114
+ UNAPPROVED = ("legacy", "unavailable") # approval_id values that record no approval row
115
+ EMPTY_SHA = hashlib.sha256(b"").hexdigest()
116
+ # What schema 2 carries beyond design §12.1, with each property's reader and its reason: the record
117
+ # the plan's one-authority rule asks for. `addendum_problems` holds it against this module.
118
+ ADDENDUM = "design/session-distill/2026-10-21T0820--9b42df2--plan-addendum-wp13.md"
119
+ # The owner's decision on how a revert knows what to put back, with the rules that hold a recorded
120
+ # value complete — no missing record read as an empty one, no field recorded as both held and
121
+ # absent, no migrated element carrying one — and how the two rows of a merge are paired: by the
122
+ # entry, the run and the operation, and by replaying what each appended revert actually undoes. It
123
+ # also owns where that contract is held: the writer, against the bytes it would replace.
124
+ RECORD = "design/session-distill/2026-10-21T1545--b324de5--writer-holds-the-transaction.md"
125
+ # A property schema 2 gained after ADDENDUM, each contracted by a dated record of its own: a dated record is
126
+ # written once, so a later property is not added to ADDENDUM's text. `field_record_problems` holds each
127
+ # against this module the way `addendum_problems` holds ADDENDUM.
128
+ FIELD_RECORDS = {"resolves": "design/session-distill/2026-11-06T0558--01eaddf--a-decision-names-the-incubate-it-resolves.md"}
129
+ SUPERSEDED = "design/session-distill/2026-10-21T1420--428724d--merge-pair-identity.md"
130
+
131
+
132
+ class LedgerError(Exception):
133
+ """A refusal; the message starts with the named code."""
134
+
135
+
136
+ def sha256_bytes(data):
137
+ return hashlib.sha256(data).hexdigest()
138
+
139
+
140
+ def render(ledger):
141
+ """The bytes a ledger file holds: the legacy layout (indent 1, insertion order, UTF-8)."""
142
+ return json.dumps(ledger, ensure_ascii=False, indent=1) + "\n"
143
+
144
+
145
+ def parse(raw, where="ledger"):
146
+ try:
147
+ ledger = json.loads(raw)
148
+ except ValueError as exc:
149
+ raise LedgerError(f"LEDGER_UNREADABLE {where}: {exc}") from exc
150
+ if not isinstance(ledger, dict):
151
+ raise LedgerError(f"LEDGER_UNREADABLE {where}: the top level is not an object")
152
+ return ledger
153
+
154
+
155
+ def version(ledger):
156
+ found = ledger.get("schema")
157
+ if found not in SUPPORTED:
158
+ raise LedgerError(f"LEDGER_SCHEMA_UNSUPPORTED schema {found!r}; supported {list(SUPPORTED)}")
159
+ return found
160
+
161
+
162
+ def schema():
163
+ """The schema-2 document, `schemas/ledger.schema.json`."""
164
+ return json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
165
+
166
+
167
+ _VALIDATOR = {}
168
+
169
+
170
+ def validator():
171
+ if "v" not in _VALIDATOR:
172
+ _VALIDATOR["v"] = validate.compile_schema(schema())
173
+ return _VALIDATOR["v"]
174
+
175
+
176
+ def vocabulary(name):
177
+ """An enumeration of the schema: `disposition`, `legacy_disposition`, or an entry property."""
178
+ defs = schema()["$defs"]
179
+ return list(defs[name]["enum"]) if name in defs else list(defs["entry"]["properties"][name]["enum"])
180
+
181
+
182
+ # ---------------------------------------------------------------- validation
183
+
184
+ def is_legacy(element):
185
+ """A legacy element: one design §12.2 migrates from a schema 1 field, not a run's decision."""
186
+ return element["run"].startswith("legacy-") or element.get("kind") in LEGACY_KINDS
187
+
188
+
189
+ def entry_row(entry):
190
+ """The table row of an entry no decision has made yet: a gap is a new learning, every other kind
191
+ (and an unclassified legacy one) comes from a unit of the library or from the intake."""
192
+ return "no_entry_new_learning" if entry["kind"] in ("gap", "unclassified") else "no_entry_existing_unit"
193
+
194
+
195
+ def element_problems(eid, n, element):
196
+ """The rules of one decisions[] element that the schema cannot say."""
197
+ tag, problems = f"{eid} decisions[{n}]", []
198
+ if is_legacy(element):
199
+ problems += [f"LEGACY_ELEMENT_INCOMPLETE {tag}: a legacy element carries {k} (design §12.2)" for k in LEGACY_REQUIRED if k not in element]
200
+ if element.get("kind") == "legacy_migration" and "legacy_status" not in element:
201
+ problems.append(f"LEGACY_ELEMENT_INCOMPLETE {tag}: a legacy_migration element carries legacy_status, the status the entry had when it was migrated")
202
+ if "legacy_status" in element and element.get("kind") != "legacy_migration":
203
+ problems.append(f"LEGACY_STATUS_MISPLACED {tag}: legacy_status belongs to an element of kind legacy_migration")
204
+ if element.get("kind") == "revert":
205
+ problems.append(f"LEGACY_KIND_ON_REVERT {tag}: a revert is a decision a run made, not an element the migration produced")
206
+ if "legacy_placed" in element and (element["applied"] is None or element.get("kind") in ("legacy_retirement", "legacy_migration")):
207
+ problems.append(f"LEGACY_PLACED_MISPLACED {tag}: legacy_placed is the date of the application the element itself carries "
208
+ f"(design §12.2), and this element carries none")
209
+ if before_of(element) is not None:
210
+ problems.append(f"LEGACY_BEFORE {tag}: applied.before is what a run's application records about the row it changed; the "
211
+ f"migration replaced nothing (RECORD)")
212
+ if "resolves" in element:
213
+ problems.append(f"RESOLVES_ON_LEGACY {tag}: resolves is what a run's decision names; the migration resolved nothing "
214
+ f"(design §7.1, {FIELD_RECORDS['resolves']})")
215
+ return problems
216
+ run, disposition = element["run"], element["disposition"]
217
+ if element["approval_id"] in UNAPPROVED:
218
+ problems.append(f"DECISION_UNAPPROVED {tag}: run {run!r} carries approval_id {element['approval_id']!r}, which is no approval row")
219
+ if disposition not in vocabulary("disposition"):
220
+ problems.append(f"DISPOSITION_NOT_CURRENT {tag}: {disposition!r} is outside design §7.2's vocabulary, which only a legacy element may leave")
221
+ problems += [f"LEGACY_FIELD_ON_MODERN {tag}: {k} belongs to a legacy element" for k in LEGACY_PROPERTIES if k in element]
222
+ if disposition == "incubate" and element["expected_observation"] is None:
223
+ problems.append(f"INCUBATE_WITHOUT_OBSERVATION {tag}: an incubate carries its observation and expiry (design §7.3)")
224
+ if disposition in ("keep", "drop") and not element.get("reason"):
225
+ problems.append(f"REASON_REQUIRED {tag}: a {disposition} carries its reason (design §7.3)")
226
+ if element.get("kind") == "revert" and (disposition != "none" or element["applied"] is None):
227
+ problems.append(f"REVERT_MALFORMED {tag}: a revert is an applied decision with disposition none")
228
+ problems += before_overlap(tag, before_of(element))
229
+ return problems
230
+
231
+
232
+ def resolves_problems(entry):
233
+ """Design §7.1's `resolves` over one entry: a run's decision names an incubate decision an earlier run made on the
234
+ same entry, as `<entry id>@<run>`, and no incubate is resolved twice. Each break by name."""
235
+ problems, eid, resolved = [], entry["id"], {}
236
+ runs = {d["run"]: n for n, d in enumerate(entry["decisions"]) if not is_legacy(d)}
237
+ for n, element in enumerate(entry["decisions"]):
238
+ target = element.get("resolves")
239
+ if target is None or is_legacy(element):
240
+ continue
241
+ tag = f"{eid} decisions[{n}]"
242
+ owner, _, run = target.partition("@")
243
+ if owner != eid:
244
+ problems.append(f"RESOLVES_OTHER_ENTRY {tag}: it resolves {target!r}, a decision of another entry; a decision resolves "
245
+ "the incubate of its own entry")
246
+ continue
247
+ at = runs.get(run)
248
+ if at is None:
249
+ problems.append(f"RESOLVES_DANGLING {tag}: no decision of run {run!r} on {eid} is there to resolve")
250
+ continue
251
+ if at >= n:
252
+ problems.append(f"RESOLVES_NOT_EARLIER {tag}: it resolves {target!r} at decisions[{at}], which is not an earlier decision")
253
+ continue
254
+ if entry["decisions"][at]["disposition"] != "incubate":
255
+ problems.append(f"RESOLVES_NOT_INCUBATE {tag}: {target!r} is a {entry['decisions'][at]['disposition']}, and only an "
256
+ "incubate is pending")
257
+ continue
258
+ if target in resolved:
259
+ problems.append(f"RESOLVES_TWICE {tag}: {target!r} was resolved at decisions[{resolved[target]}] already")
260
+ continue
261
+ resolved[target] = n
262
+ return problems
263
+
264
+
265
+ def unresolved_incubates(ledger):
266
+ """Design §7.1's pending incubate decisions: every incubate a run decided (an incubating entry, or a pending
267
+ intervention on a placed one, §12.3) that no later decision of its entry resolves, by id `<entry>@<run>`, with its
268
+ expiry and its entry's status, in id order. Asked of a ledger `validate_ledger` passed."""
269
+ out = []
270
+ for entry in ledger["entries"]:
271
+ resolved = {d["resolves"] for d in entry["decisions"] if not is_legacy(d) and d.get("resolves")}
272
+ for element in entry["decisions"]:
273
+ if is_legacy(element) or element["disposition"] != "incubate":
274
+ continue
275
+ ident = f"{entry['id']}@{element['run']}"
276
+ if ident not in resolved:
277
+ out.append({"decision_id": ident, "entry": entry["id"], "run": element["run"], "status": entry["status"],
278
+ "expiry": element["expected_observation"]["expiry"]})
279
+ return sorted(out, key=lambda d: d["decision_id"])
280
+
281
+
282
+ def semantic_v2(ledger):
283
+ """What `schemas/ledger.schema.json` cannot say about a schema 2 ledger."""
284
+ problems, seen_ids, seen_runs = [], set(), set()
285
+ ids = {e["id"] for e in ledger["entries"]}
286
+ for window in ledger["windows"]:
287
+ if window["run_id"] in seen_runs:
288
+ problems.append(f"WINDOW_DUPLICATE {window['run_id']}")
289
+ seen_runs.add(window["run_id"])
290
+ for entry in ledger["entries"]:
291
+ eid = entry["id"]
292
+ if eid in seen_ids:
293
+ problems.append(f"ID_DUPLICATE {eid}")
294
+ seen_ids.add(eid)
295
+ runs = set()
296
+ for n, element in enumerate(entry["decisions"]):
297
+ problems += element_problems(eid, n, element)
298
+ if not is_legacy(element):
299
+ if element["run"] in runs:
300
+ problems.append(f"DECISION_RUN_DUPLICATE {eid} decisions[{n}]: run {element['run']!r} decided this entry twice")
301
+ runs.add(element["run"])
302
+ for resolution in (element["expected_observation"] or {}).get("resolutions", []):
303
+ if resolution["run"] != element["run"]:
304
+ problems.append(f"RESOLUTION_MISPLACED {eid} decisions[{n}]: a resolution of run "
305
+ f"{resolution['run']!r} sits under run {element['run']!r}")
306
+ problems += resolves_problems(entry)
307
+ for field, target in (("absorbed_by", entry.get("absorbed_by")), ("instance_of", entry["relations"].get("instance_of"))):
308
+ if target is not None and target not in ids:
309
+ problems.append(f"RELATION_DANGLING {eid} {field}: {target!r} is no entry of this ledger")
310
+ migrations = [n for n, d in enumerate(entry["decisions"]) if d.get("kind") == "legacy_migration"]
311
+ if len(migrations) > 1:
312
+ problems.append(f"LEGACY_MIGRATION_DUPLICATE {eid}: {len(migrations)} legacy_migration elements; an entry is migrated once")
313
+ modern_at = [n for n, d in enumerate(entry["decisions"]) if not is_legacy(d)]
314
+ if migrations and modern_at and migrations[0] > modern_at[0]:
315
+ problems.append(f"LEGACY_MIGRATION_LATE {eid} decisions[{migrations[0]}]: the migration element follows the run decision at decisions[{modern_at[0]}]")
316
+ for n, item in enumerate(entry["evidence"]):
317
+ if ("claim_id" in item) == ("locator" in item):
318
+ problems.append(f"EVIDENCE_FORM {eid} evidence[{n}]: exactly one of a claim id with its evidence id, or the unavailable form")
319
+ if not replays(entry, entry["status"]):
320
+ problems.append(f"HISTORY_INCONSISTENT {eid}: the entry's decisions do not replay through design §12.3 to its status {entry['status']!r}")
321
+ return problems
322
+
323
+
324
+ def validate_ledger(ledger):
325
+ """Every violation of `ledger` as a list of strings, each starting with its code."""
326
+ try:
327
+ found = version(ledger)
328
+ except LedgerError as exc:
329
+ return [str(exc)]
330
+ if found == 1:
331
+ entries = ledger.get("entries")
332
+ if not isinstance(entries, list):
333
+ return ["LEDGER_INVALID entries: schema 1 holds a list of entries"]
334
+ problems, seen = [], set()
335
+ for n, entry in enumerate(entries):
336
+ if not (isinstance(entry, dict) and isinstance(entry.get("id"), str) and isinstance(entry.get("status"), str)):
337
+ problems.append(f"LEDGER_INVALID entries[{n}]: an entry needs a string id and status")
338
+ elif entry["id"] in seen:
339
+ problems.append(f"ID_DUPLICATE {entry['id']}")
340
+ else:
341
+ seen.add(entry["id"])
342
+ return problems
343
+ problems = [f"LEDGER_INVALID {line}" for line in validate.validate_instance(validator(), ledger)]
344
+ return problems or semantic_v2(ledger)
345
+
346
+
347
+ def entry_ids(ledger):
348
+ return [e["id"] for e in ledger["entries"]]
349
+
350
+
351
+ # ---------------------------------------------------------------- the id-set check
352
+
353
+ def id_set_violations(base_ids, head_ids, allocated=None, numbered=False, transaction=False):
354
+ """Design §12.4: no id lost, and the new ids exactly the allocated ones.
355
+
356
+ `allocated` is the id list the run froze before it began. A schema 2 run that writes the ledger
357
+ at all (`transaction`) needs it, whether or not the ids it added turn out to be none: an
358
+ allocation that produced no row is a violation the check can see (`ID_ALLOCATED_MISSING`), and
359
+ an absent allocation says nothing at all. An explicit empty list is an allocation; `None` is the
360
+ absence of one (`ALLOCATION_REQUIRED`). Validating a ledger against nothing — a head with no
361
+ base — is not a transaction and asks for none. Only a schema 1 ledger (`numbered`) may add ids
362
+ without an allocation: the legacy merge has no record, so a series (`S3`, `G`, `L`) continues at
363
+ the base's highest number, none skipped. A duplicate id is the validator's finding."""
364
+ problems = [f"ID_LOST {i}: present in the base, absent from the ledger" for i in sorted(set(base_ids) - set(head_ids))]
365
+ new = sorted(set(head_ids) - set(base_ids))
366
+ if allocated is not None:
367
+ problems += [f"ID_UNALLOCATED {i}: not among the allocated ids" for i in new if i not in allocated]
368
+ problems += [f"ID_ALLOCATED_EXISTING {i}: allocated as new, and the base already holds it" for i in sorted(set(allocated) & set(base_ids))]
369
+ problems += [f"ID_ALLOCATED_MISSING {i}: allocated, absent from the ledger" for i in sorted(set(allocated) - set(base_ids) - set(new))]
370
+ return problems
371
+ if not numbered:
372
+ return problems + ([f"ALLOCATION_REQUIRED {new or '[]'}: a schema 2 run writes the ledger only against the allocation it froze"]
373
+ if new or transaction else [])
374
+ top = {}
375
+ for i in base_ids:
376
+ found = ID_SERIES.match(i)
377
+ if found:
378
+ top[found.group(1)] = max(top.get(found.group(1), 0), int(found.group(2)))
379
+ by_series = {}
380
+ for i in new:
381
+ found = ID_SERIES.match(i)
382
+ by_series.setdefault(found.group(1) if found else None, []).append((int(found.group(2)) if found else 0, i))
383
+ for series, members in by_series.items():
384
+ if series is None:
385
+ problems += [f"ID_UNALLOCATED {i}: not an id of the form <series>-<number>" for _, i in members]
386
+ continue
387
+ want = set(range(top.get(series, 0) + 1, top.get(series, 0) + 1 + len(members)))
388
+ problems += [f"ID_UNALLOCATED {i}: series {series} continues at {top.get(series, 0) + 1} with no number skipped"
389
+ for number, i in members if number not in want]
390
+ return problems
391
+
392
+
393
+ # ---------------------------------------------------------------- transitions
394
+
395
+ _TABLES = {}
396
+
397
+
398
+ def transitions():
399
+ if "t" not in _TABLES:
400
+ _TABLES["t"] = json.loads(TRANSITIONS_PATH.read_text(encoding="utf-8"))
401
+ return _TABLES["t"]
402
+
403
+
404
+ EFFECT_WORDING = {
405
+ "never_placed": " (never placed)", "text_revised": " (text revised)", "expiry_renewed": " (expiry renewed)",
406
+ "revival": " (revival)", "keep_record": ", keep record", "pending_intervention": ", pending intervention",
407
+ "dropped_intervention": ", dropped intervention",
408
+ "allocate_destination_entry": "; destination entry allocated (placed) if it has none",
409
+ "absorbed_by": " (`absorbed_by`)", "receiver_merge_decision": "; the receiving entry gets a merge decision",
410
+ }
411
+
412
+
413
+ def render_cell(cell):
414
+ """The wording design §12.3 gives a table cell, written from the cell's record."""
415
+ if cell is None:
416
+ return "—"
417
+ if cell["status"] is None:
418
+ return "no entry"
419
+ unknown = [e for e in cell["effects"] if e not in EFFECT_WORDING]
420
+ if unknown:
421
+ raise LedgerError(f"TRANSITION_EFFECT_UNKNOWN {unknown}: no wording for it in the design's table")
422
+ return ("new entry, " if cell["new_entry"] else "") + cell["status"] + "".join(EFFECT_WORDING[e] for e in cell["effects"])
423
+
424
+
425
+ def disposition_key(element):
426
+ """The table column of a decision: `reduce` is a merge when an operation of it merges."""
427
+ if element["disposition"] != "reduce":
428
+ return element["disposition"]
429
+ merged = any(op["type"] == "merge" for op in (element["applied"] or {"operations": []})["operations"])
430
+ return "reduce_merge" if merged else "reduce_delete"
431
+
432
+
433
+ def transition(row, key):
434
+ """The cell for `row` and column `key`; `TRANSITION_DISALLOWED` for a pair the design marks —."""
435
+ table = transitions()
436
+ if key not in table["dispositions"] or row not in table["cells"]:
437
+ raise LedgerError(f"TRANSITION_DISALLOWED {row} + {key}: the table has no such row or column")
438
+ cell = table["cells"][row][key]
439
+ if cell is None:
440
+ raise LedgerError(f"TRANSITION_DISALLOWED {row} + {key}: design §12.3 allows no such pair")
441
+ return cell
442
+
443
+
444
+ def row_of(status):
445
+ return transitions()["state_rows"][status]
446
+
447
+
448
+ def status_after(status, cell):
449
+ return status if cell["status"] in (None, "unchanged") else cell["status"]
450
+
451
+
452
+ def takes_effect(element):
453
+ """An applied decision: its operations completed, so it moves the status and licenses its row's
454
+ changes, whatever its delivery check then found. Design §10.6 records an application whose
455
+ delivery failed or did not run as applied, "not lost", and leaves the owner to keep, revert or
456
+ revise it; design §12.3's delivery row leaves that application unchanged —
457
+ `decisions[].applied.delivery` records the outcome and moves nothing further (ADDENDUM §3)."""
458
+ return element["applied"] is not None
459
+
460
+
461
+ def revive(entry):
462
+ """A revived entry (placed or incubating again) no longer holds the retirement or the absorption."""
463
+ for field in ("retired", "retire_reason", "absorbed_by"):
464
+ entry.pop(field, None)
465
+
466
+
467
+ def effect_problems(cell, element, before, after, rows):
468
+ """What a cell's effects require of the result of `element`. `before` is the entry as it was (None
469
+ for an entry the decision creates), `after` as it is now, `rows` every entry of the ledger by id."""
470
+ eid, problems = after["id"], []
471
+ receiver = rows.get(after.get("absorbed_by"))
472
+ observation = element["expected_observation"]
473
+ for token in cell["effects"]:
474
+ if token == "keep_record":
475
+ missing = after["keep"] is None or not element.get("reason")
476
+ what = "the entry's keep record and the decision's reason"
477
+ elif token == "absorbed_by":
478
+ missing, what = receiver is None, "the receiving entry's id, an entry of the ledger"
479
+ elif token == "receiver_merge_decision":
480
+ missing = receiver is None or receiver["status"] != "placed" or not any(
481
+ d["run"] == element["run"] and any(op["type"] == "merge" for op in (d["applied"] or {"operations": []})["operations"])
482
+ for d in receiver["decisions"])
483
+ what = "a decision of this run on a placed receiving entry that carries the merge"
484
+ elif token == "allocate_destination_entry":
485
+ missing, what = receiver is None or receiver["status"] != "placed", "a placed receiving entry"
486
+ elif token == "pending_intervention":
487
+ missing, what = element["disposition"] != "incubate" or observation is None, "an incubate with its observation and expiry"
488
+ elif token == "dropped_intervention":
489
+ missing, what = element["disposition"] != "drop" or not element.get("reason"), "a drop with its reason"
490
+ elif token == "never_placed":
491
+ missing, what = after["destination"] is not None, "an entry with no destination"
492
+ elif token == "text_revised":
493
+ missing, what = before is None or all(before.get(k) == after.get(k) for k in TEXT_FIELDS), "a revised lesson, principle or rationale"
494
+ elif token == "expiry_renewed":
495
+ earlier = [d["expected_observation"]["expiry"] for d in (before or after)["decisions"] if d["expected_observation"] and d is not element]
496
+ missing = observation is None or (bool(earlier) and observation["expiry"] <= max(earlier))
497
+ what = "an observation whose expiry is later than every earlier one"
498
+ elif token == "revival":
499
+ missing, what = any(k in after for k in ("retired", "retire_reason", "absorbed_by")), "an entry that is no longer retired or absorbed"
500
+ else:
501
+ raise LedgerError(f"TRANSITION_EFFECT_UNKNOWN [{token!r}]: no check for it")
502
+ if missing:
503
+ problems.append(f"EFFECT_MISSING {eid}: {token} needs {what}")
504
+ return problems
505
+
506
+
507
+ def licensed_fields(element, cell):
508
+ """The entry fields `element` licenses besides its status and its disposition: what design §7.2's
509
+ disposition changes, widened by exactly what the cell's own effects need (ADDENDUM §3)."""
510
+ fields = set(DISPOSITION_FIELDS.get(element["disposition"], ()))
511
+ for token in cell["effects"]:
512
+ fields |= set(EFFECT_FIELDS.get(token, ()))
513
+ return fields
514
+
515
+
516
+ def reverted(entry, status):
517
+ """The decision a revert of `entry` undoes and the status it restores: the latest decision that took
518
+ effect and is not already reverted, and the status the entry held before it, both derived from the
519
+ entry's own decisions[] through design §12.3's table (`replays`). `entry` holds the decisions before
520
+ the revert and `status` the status it has now. A history that leaves the status open is refused
521
+ rather than guessed, and one that does not replay to `status` at all is refused too."""
522
+ fits = replays(entry, status)
523
+ if not fits:
524
+ raise LedgerError(f"REPLAY_INCONSISTENT {entry['id']}: the decisions do not replay to {status!r}")
525
+ # Which decision is the one to revert does not depend on where the history started: every fit
526
+ # pushes the same applied decisions and pops on the same reverts, so the stacks are equal. What
527
+ # the start does decide is the status before that decision, which is why only that is open below.
528
+ if not fits[0]["stack"]:
529
+ raise LedgerError(f"REVERT_NOTHING {entry['id']}: no applied decision is left to revert")
530
+ stack = fits[0]["stack"]
531
+ index = stack[-1]
532
+ priors = sorted({str(fit["before"][index]) for fit in fits})
533
+ if len(priors) > 1:
534
+ raise LedgerError(f"REVERT_PRIOR_STATUS_AMBIGUOUS {entry['id']}: the history leaves {priors} open for the status before that decision")
535
+ if priors == ["None"]:
536
+ raise LedgerError(f"REVERT_PRIOR_STATUS_NONE {entry['id']}: the decision created the entry; there is no status before it to restore")
537
+ return entry["decisions"][index], priors[0]
538
+
539
+
540
+ def before_record(was, now):
541
+ """The values `was` held for every field `now` changed: design §12.1's `applied.before` (RECORD).
542
+ `fields` carries what was there and `absent` names the fields the row had none of, which is not the
543
+ same answer — a row that held no destination and one whose destination this application replaced
544
+ are undone differently."""
545
+ fields, absent = {}, []
546
+ for field in REVERTIBLE:
547
+ if was.get(field) == now.get(field):
548
+ continue
549
+ (absent.append(field) if was.get(field) is None else fields.update({field: copy.deepcopy(was[field])}))
550
+ return {"fields": fields, "absent": sorted(absent)}
551
+
552
+
553
+ def before_of(element):
554
+ """The `before` record of an applied decision, or None when it carries none."""
555
+ return (element["applied"] or {}).get("before")
556
+
557
+
558
+ def restore(entry, before):
559
+ """Put `before` back on `entry`: its values where the row had them, and nothing where it had none."""
560
+ entry.update(copy.deepcopy(before["fields"]))
561
+ for field in before["absent"]:
562
+ if field in NULLABLE:
563
+ entry[field] = None
564
+ else:
565
+ entry.pop(field, None)
566
+
567
+
568
+ def revert_restored(was, now, recorded):
569
+ """What a revert left undone: a field the application recorded as replaced that the row does not
570
+ hold again, and one the row had none of that it still holds."""
571
+ problems = [f"REVERT_NOT_RESTORED {now['id']} {field}: the application recorded {value!r} as what it replaced, the row holds {now.get(field)!r}"
572
+ for field, value in recorded["fields"].items() if now.get(field) != value]
573
+ return problems + [f"REVERT_NOT_RESTORED {now['id']} {field}: the row held none before the application and holds {now.get(field)!r}"
574
+ for field in recorded["absent"] if now.get(field) is not None]
575
+
576
+
577
+ def before_overlap(tag, recorded):
578
+ """A field in both parts of a before record: the row held a value there or it did not, never both,
579
+ and `restore` would put the value back and clear it in one pass (RECORD)."""
580
+ both = sorted(set((recorded or EMPTY_BEFORE)["fields"]) & set((recorded or EMPTY_BEFORE)["absent"]))
581
+ return [f"BEFORE_FIELD_OVERLAP {tag} {both}: its applied.before records a value there and records that the row held none"] if both else []
582
+
583
+
584
+ def before_required(tag, element):
585
+ """Every application records what it replaced, an empty record when that was nothing (RECORD).
586
+ A missing record is the one case a revert cannot read, so it is refused where it is appended
587
+ rather than where it is read."""
588
+ return [] if before_of(element) is not None else [
589
+ f"BEFORE_MISSING {tag}: an applied decision records what it replaced in applied.before, an empty record when it replaced nothing"]
590
+
591
+
592
+ def before_problems(tag, recorded, want):
593
+ """`recorded` against the row change it claims to describe (RECORD): a field the application changed
594
+ and the record does not name, one it names and the application did not change, and one whose value
595
+ is not what the row held."""
596
+ recorded = recorded or EMPTY_BEFORE
597
+ held, wanted = dict(recorded["fields"]), dict(want["fields"])
598
+ missing = (set(wanted) | set(want["absent"])) - (set(held) | set(recorded["absent"]))
599
+ extra = (set(held) | set(recorded["absent"])) - (set(wanted) | set(want["absent"]))
600
+ problems = [f"BEFORE_FIELD_MISSING {tag} {f}: the application changed it and its applied.before does not say what it replaced"
601
+ for f in sorted(missing)]
602
+ problems += [f"BEFORE_FIELD_EXTRA {tag} {f}: its applied.before says what it replaced there and the application did not change it"
603
+ for f in sorted(extra)]
604
+ problems += [f"BEFORE_FIELD_WRONG {tag} {f}: its applied.before says {held.get(f, 'absent')!r}, the row held {wanted.get(f, 'absent')!r}"
605
+ for f in sorted((set(held) | set(recorded["absent"])) & (set(wanted) | set(want["absent"])))
606
+ if held.get(f, "\0absent") != wanted.get(f, "\0absent")]
607
+ return problems
608
+
609
+
610
+ def reverted_before(entry, status):
611
+ """The decision a revert of `entry` undoes, the status it restores, and the row values it puts back.
612
+
613
+ The values are the ones that application recorded (`applied.before`); nothing is inferred from the
614
+ history (RECORD). A decision that recorded none — an element design §12.2 migrated carries no
615
+ `before`, and so does a row written by hand — can have its status reverted and its fields not, so
616
+ unless it changed nothing the revert is refused by name."""
617
+ undone, prior = reverted(entry, status)
618
+ recorded = before_of(undone)
619
+ if recorded is None:
620
+ raise LedgerError(f"REVERT_INVERSE_UNPROVABLE {entry['id']} applied.before: the application of run {undone['run']!r} did not "
621
+ f"record the values it replaced, so what its fields were before it is not in the ledger")
622
+ # No decision still standing can have changed the same field after this one: a revert undoes the
623
+ # latest standing decision and each earlier one is still covered by the value this record holds,
624
+ # so the order is last in, first out. Two rows are the one place where that does not hold by
625
+ # itself, and `merge_receiver` is where it is checked (RECORD).
626
+ return undone, prior, recorded
627
+
628
+
629
+ def merge_receiver_element(element, absorbed_id, before=None):
630
+ """The decision the receiving entry of a merge gets: its unit is revised by the merge, so the
631
+ decision carries the merge's own operations and what it replaced on this row (RECORD)."""
632
+ receiver = copy.deepcopy(element)
633
+ receiver.update(disposition="correct", reason=f"receives the merge of {absorbed_id}", expected_observation=None)
634
+ receiver["applied"] = {**receiver["applied"], "before": copy.deepcopy(before or EMPTY_BEFORE)}
635
+ return receiver
636
+
637
+
638
+ def merge_receiver_revert(element, absorbed_id, before=None):
639
+ """The decision the receiving entry gets when the merge it received is reverted: the merge revised
640
+ its unit, so reverting the merge reverts that application too (design §12.3's revert row)."""
641
+ receiver = copy.deepcopy(element)
642
+ receiver.update(reason=f"releases the merge of {absorbed_id}", expected_observation=None)
643
+ receiver["applied"] = {**receiver["applied"], "before": copy.deepcopy(before or EMPTY_BEFORE)}
644
+ return receiver
645
+
646
+
647
+ def is_merge(element):
648
+ """This application merged its entry into another: design §12.3's reduce (merge) column."""
649
+ return disposition_key(element) == "reduce_merge"
650
+
651
+
652
+ def merge_operations(element):
653
+ """The merge operations of an application, by their own operation ids (design §7.3)."""
654
+ return {op["operation_id"] for op in (element["applied"] or {"operations": []})["operations"] if op["type"] == "merge"}
655
+
656
+
657
+ def receiving_side(element):
658
+ """This application received a merge rather than making one: it carries the merge's own operation
659
+ and is not design §12.3's reduce (merge) that performed it."""
660
+ return bool(merge_operations(element)) and not is_merge(element)
661
+
662
+
663
+ def standing_decision(entry):
664
+ """The application still standing over `entry`, through the same replay a revert of that row uses
665
+ (`reverted`): a reverted application is not standing, and a revert is never itself standing."""
666
+ fits = replays(entry, entry["status"])
667
+ if not fits:
668
+ raise LedgerError(f"REPLAY_INCONSISTENT {entry['id']}: the decisions do not replay to {entry['status']!r}")
669
+ if not fits[0]["stack"]:
670
+ return None
671
+ return entry["decisions"][fits[0]["stack"][-1]]
672
+
673
+
674
+ def merge_receiver(ledger, entry, undone):
675
+ """The entry the reverted merge wrote its decision on, and that decision — the one carrying the
676
+ merge's own operation, not merely one of the same run. It has to be the application still standing
677
+ over the receiver: a row whose own history moved on after the merge cannot be put back by this
678
+ revert alone, and what came after it is reverted first (Q#3, RECORD)."""
679
+ # The id is there: a dangling absorbed_by never validated in the first place (RELATION_DANGLING)
680
+ # and an id of the base is never lost (ID_LOST), so this reads the row the merge named.
681
+ receiver, ops = _rows(ledger)[entry["absorbed_by"]], merge_operations(undone)
682
+ carried = [d for d in receiver["decisions"] if d["run"] == undone["run"] and receiving_side(d) and merge_operations(d) & ops]
683
+ if not carried:
684
+ raise LedgerError(f"REVERT_INVERSE_UNPROVABLE {receiver['id']} decisions: no decision of this entry carries the merge operation "
685
+ f"{sorted(ops)} of run {undone['run']!r}, so there is none of it to put back")
686
+ standing = standing_decision(receiver)
687
+ if standing is None or standing is not carried[-1]:
688
+ raise LedgerError(f"REVERT_INVERSE_UNPROVABLE {receiver['id']} decisions: the application standing over this entry is "
689
+ f"{'none' if standing is None else repr(standing['run'])}, not the one that received the merge "
690
+ f"{sorted(ops)} of run {undone['run']!r}, so that one is reverted first")
691
+ return receiver, carried[-1]
692
+
693
+
694
+ def receiver_revert(ledger, entry, undone, element):
695
+ """Revert the merge on the receiving entry too: its own decision recorded what the merge replaced
696
+ there, so the same record puts that row back (`merge_receiver` says what stops it)."""
697
+ receiver, given = merge_receiver(ledger, entry, undone)
698
+ recorded = before_of(given)
699
+ if recorded is None:
700
+ raise LedgerError(f"REVERT_INVERSE_UNPROVABLE {receiver['id']} applied.before: the merge's decision on this entry did not record "
701
+ f"the values it replaced here")
702
+ was = copy.deepcopy(receiver)
703
+ restore(receiver, recorded)
704
+ receiver["decisions"].append(merge_receiver_revert(element, entry["id"], before_record(was, receiver)))
705
+ receiver["disposition"] = element["disposition"]
706
+
707
+
708
+ def _rows(ledger):
709
+ return {e["id"]: e for e in ledger["entries"]}
710
+
711
+
712
+ def apply_decision(ledger, entry_id, element, updates=None):
713
+ """A copy of `ledger` with `element` appended to the entry and the status moved by design §12.3.
714
+
715
+ A decision that was not applied changes nothing but its own record, so it brings no `updates`
716
+ (`UPDATES_WITHOUT_DECISION`). `updates` are the entry fields its disposition and its cell license
717
+ (`licensed_fields`, `UPDATES_UNLICENSED`), and the appended decision records what they replaced
718
+ (`applied.before`, RECORD). A revert carries no value of its own: it puts back exactly what the
719
+ application it undoes recorded, and is refused by name where that record is missing. The effects
720
+ the cell requires are checked on the result, which is then validated."""
721
+ result = copy.deepcopy(ledger)
722
+ entry = _rows(result).get(entry_id)
723
+ if entry is None:
724
+ raise LedgerError(f"ENTRY_UNKNOWN {entry_id}")
725
+ updates = copy.deepcopy(updates or {})
726
+ was = copy.deepcopy(entry)
727
+ cell, reverting, plan = None, element.get("kind") == "revert", None
728
+ if takes_effect(element):
729
+ cell = {"effects": []} if reverting else transition(row_of(was["status"]), disposition_key(element))
730
+ if reverting:
731
+ if updates:
732
+ raise LedgerError(f"REVERT_VALUE_SUPPLIED {entry_id}: {sorted(updates)} were handed to a revert, which carries no value: "
733
+ f"it puts back what the application it undoes recorded")
734
+ plan = reverted_before(was, was["status"])
735
+ if receiving_side(plan[0]):
736
+ makers = merge_makers(result["entries"], entry_id, plan[0])
737
+ raise LedgerError(f"REVERT_MERGE_SIDE {entry_id}: this decision received the merge "
738
+ f"{sorted(merge_operations(plan[0]))} of run {plan[0]['run']!r}; a merge is put back on both rows at "
739
+ f"once, and the owner reverts it on "
740
+ f"{'the entry it absorbed, which no row of this ledger is' if not makers else ', '.join(row['id'] for row in makers)}")
741
+ else:
742
+ unlicensed = sorted(set(updates) - licensed_fields(element, cell))
743
+ if unlicensed:
744
+ raise LedgerError(f"UPDATES_UNLICENSED {entry_id}: {unlicensed} are not fields a {element['disposition']} decision licenses")
745
+ elif updates:
746
+ raise LedgerError(f"UPDATES_WITHOUT_DECISION {entry_id}: {sorted(updates)} change an entry only through an applied decision")
747
+ entry["decisions"].append(copy.deepcopy(element))
748
+ if cell is not None:
749
+ if reverting:
750
+ undone, prior, recorded = plan
751
+ entry["status"] = prior
752
+ restore(entry, recorded)
753
+ else:
754
+ entry["status"] = status_after(was["status"], cell)
755
+ entry.update(updates)
756
+ entry["disposition"] = element["disposition"]
757
+ if "revival" in cell["effects"]:
758
+ revive(entry)
759
+ rows = _rows(result)
760
+ receiver = rows.get((was if reverting else entry).get("absorbed_by"))
761
+ if "receiver_merge_decision" in cell["effects"] and receiver is not None:
762
+ receiver["decisions"].append(merge_receiver_element(element, entry_id, before_record(receiver, receiver)))
763
+ receiver["disposition"] = "correct"
764
+ problems = effect_problems(cell, element, was, entry, rows)
765
+ if reverting:
766
+ problems += revert_restored(was, entry, recorded)
767
+ # The merge wrote a decision on the receiving entry too, and that decision recorded what
768
+ # it replaced there, so the revert reaches that row by the same record.
769
+ if is_merge(undone):
770
+ receiver_revert(result, was, undone, element)
771
+ if problems:
772
+ raise LedgerError("; ".join(problems))
773
+ # What this application replaced, recorded on the decision itself: the row as it was against
774
+ # the row as it is now, so a later revert reads values rather than inferring them (RECORD).
775
+ entry["decisions"][-1]["applied"]["before"] = before_record(was, entry)
776
+ problems = validate_ledger(result)
777
+ if problems:
778
+ raise LedgerError("LEDGER_INVALID after the decision: " + "; ".join(problems))
779
+ return result
780
+
781
+
782
+ def create_entry(ledger, entry, element):
783
+ """A copy of `ledger` with `entry` created by `element`, its first decision (design §12.3's rows
784
+ for an entry no one has made yet). A cell that says "no entry" creates none. A decision whose
785
+ delivery failed or went unverified still created the entry: its operations completed, and the
786
+ delivery outcome is what `applied.delivery` records (design §10.6, ADDENDUM §3)."""
787
+ result = copy.deepcopy(ledger)
788
+ new = copy.deepcopy(entry)
789
+ if not takes_effect(element):
790
+ raise LedgerError(f"NEW_ROW_UNAPPLIED {new['id']}: an entry is created by an applied decision")
791
+ cell = transition(entry_row(new), disposition_key(element))
792
+ if cell["status"] is None:
793
+ return result
794
+ new["decisions"] = [copy.deepcopy(element)]
795
+ # A row that did not exist replaced nothing, and recording that is not the same as recording
796
+ # nothing: the empty record is what says this application had no earlier value to put back (RECORD).
797
+ new["decisions"][0]["applied"] = {**new["decisions"][0]["applied"], "before": copy.deepcopy(EMPTY_BEFORE)}
798
+ new.update(status=cell["status"], disposition=element["disposition"])
799
+ result["entries"].append(new)
800
+ problems = effect_problems(cell, element, None, new, _rows(result))
801
+ if problems:
802
+ raise LedgerError("; ".join(problems))
803
+ problems = validate_ledger(result)
804
+ if problems:
805
+ raise LedgerError("LEDGER_INVALID after the new entry: " + "; ".join(problems))
806
+ return result
807
+
808
+
809
+ def append_resolution(ledger, entry_id, run, resolution):
810
+ """A copy of `ledger` with `resolution` appended to the observation of the entry's decision of
811
+ `run`. The status never moves: a resolution records what a window observed."""
812
+ result = copy.deepcopy(ledger)
813
+ entry = _rows(result).get(entry_id)
814
+ element = next((d for d in (entry or {"decisions": []})["decisions"] if d["run"] == run), None)
815
+ if element is None or element["expected_observation"] is None:
816
+ raise LedgerError(f"RESOLUTION_TARGET_MISSING {entry_id} run {run!r}: no decision of that run holds an expected observation")
817
+ element["expected_observation"]["resolutions"].append(copy.deepcopy(resolution))
818
+ problems = validate_ledger(result)
819
+ if problems:
820
+ raise LedgerError("LEDGER_INVALID after the resolution: " + "; ".join(problems))
821
+ return result
822
+
823
+
824
+ # ---------------------------------------------------------------- history: replays and reverts
825
+
826
+ def replays(entry, final_status):
827
+ """Every way the entry's decisions replay through design §12.3 to `final_status`.
828
+
829
+ An entry the migration produced records its status at migration in its `legacy_migration` element
830
+ (design §12.2), and that is its one start. Any other entry did not record where it started, so each
831
+ start that fits is tried: no entry at all when the first decision is a run's (it may have created the
832
+ entry), or any status. A fit is
833
+ `{start, before, stack}`: the status before every applied decision (by index), and the decisions that
834
+ took effect and are not yet reverted. A revert pops the latest of them and restores the status it
835
+ had before it. Legacy elements move nothing here: design §12.2 migrates the status itself."""
836
+ modern = [(i, d) for i, d in enumerate(entry["decisions"]) if not is_legacy(d) and d["applied"] is not None]
837
+ first = entry["decisions"][0] if entry["decisions"] else None
838
+ migration = next((d for d in entry["decisions"] if d.get("kind") == "legacy_migration" and "legacy_status" in d), None)
839
+ if migration is not None:
840
+ starts = [migration["legacy_status"]]
841
+ else:
842
+ starts = ([None] if first is not None and not is_legacy(first) else []) + vocabulary("status")
843
+ fits = []
844
+ for start in starts:
845
+ status, before, stack, fits_here = start, {}, [], True
846
+ for i, d in modern:
847
+ before[i] = status
848
+ if not takes_effect(d):
849
+ continue
850
+ if d.get("kind") == "revert":
851
+ if not stack: # nothing left to revert
852
+ fits_here = False
853
+ break
854
+ status = before[stack.pop()]
855
+ continue
856
+ try:
857
+ cell = transition(entry_row(entry) if status is None else row_of(status), disposition_key(d))
858
+ except LedgerError: # a pair the table rejects
859
+ fits_here = False
860
+ break
861
+ if status is None and cell["status"] is None: # a decision recorded on an entry that does not exist
862
+ fits_here = False
863
+ break
864
+ status = cell["status"] if status is None else status_after(status, cell)
865
+ stack.append(i)
866
+ if fits_here and status == final_status:
867
+ fits.append({"start": start, "before": before, "stack": stack})
868
+ return fits
869
+
870
+
871
+ def revert_target(entry, status):
872
+ """The status a revert of the entry's latest applied decision restores (design §12.3's revert row):
873
+ what the latest earlier decision that set one left, or the status the history started from."""
874
+ return reverted(entry, status)[1]
875
+
876
+
877
+ # ---------------------------------------------------------------- events (design §12.3)
878
+
879
+ def _entry_copy(ledger, entry_id):
880
+ result = copy.deepcopy(ledger)
881
+ entry = _rows(result).get(entry_id)
882
+ if entry is None:
883
+ raise LedgerError(f"ENTRY_UNKNOWN {entry_id}")
884
+ return result, entry
885
+
886
+
887
+ def _malformed(entry_id, event, why):
888
+ return LedgerError(f"EVENT_MALFORMED {entry_id} {event}: {why}")
889
+
890
+
891
+ def _awaiting_r(ledger, entry_id, element):
892
+ """An admitted item waits for R: an incubating entry keeps its status; an unapplied decision records why."""
893
+ result, entry = _entry_copy(ledger, entry_id)
894
+ if entry["status"] != "incubating":
895
+ raise LedgerError(f"EVENT_NOT_APPLICABLE {entry_id} awaiting_R: the entry is {entry['status']}; awaiting R is an incubating entry's")
896
+ if element["applied"] is not None or not element.get("reason"):
897
+ raise _malformed(entry_id, "awaiting_R", "an unapplied decision that records its reason")
898
+ entry["decisions"].append(copy.deepcopy(element))
899
+ return result
900
+
901
+
902
+ def _recurrence(ledger, entry_id, evidence=(), lineages=None, record=None):
903
+ """New evidence for the same learning: evidence and lineages are appended, the status stays."""
904
+ result, entry = _entry_copy(ledger, entry_id)
905
+ if not evidence:
906
+ raise _malformed(entry_id, "recurrence", "a recurrence appends evidence")
907
+ held = [json.dumps(item, sort_keys=True) for item in entry["evidence"]]
908
+ if any(json.dumps(item, sort_keys=True) in held for item in evidence):
909
+ raise _malformed(entry_id, "recurrence", "evidence the entry already holds is not new")
910
+ entry["evidence"] += copy.deepcopy(list(evidence))
911
+ if lineages is not None:
912
+ entry["independent_lineages"] = lineages
913
+ if record is not None:
914
+ entry.setdefault("recurrence", []).append(copy.deepcopy(record))
915
+ return result
916
+
917
+
918
+ def _contradiction(ledger, entry_id, element):
919
+ """Admitted evidence against an entry: nothing changes until the candidate's disposition is applied."""
920
+ result, entry = _entry_copy(ledger, entry_id)
921
+ if element["applied"] is not None or element["disposition"] not in ("correct", "reduce", "drop"):
922
+ raise _malformed(entry_id, "contradiction", "an unapplied correct, reduce or drop")
923
+ entry["decisions"].append(copy.deepcopy(element))
924
+ return result
925
+
926
+
927
+ def _delivery(ledger, entry_id, run, outcome):
928
+ """What the delivery check of an already applied decision found (design §12.3's delivery row).
929
+
930
+ The application itself was recorded when its operations completed and took effect then; this
931
+ writes the outcome into that decision's `applied.delivery` and moves nothing else — no transition
932
+ is replayed and no second decision is appended for the same run (ADDENDUM §3, the correction)."""
933
+ result, entry = _entry_copy(ledger, entry_id)
934
+ if outcome not in ("failed", "unverified"):
935
+ raise _malformed(entry_id, "delivery", f"an outcome of failed or unverified, not {outcome!r}; design §12.3's row has no other")
936
+ element = next((d for d in entry["decisions"] if d["run"] == run), None)
937
+ if element is None:
938
+ raise _malformed(entry_id, "delivery", f"no decision of run {run!r} is on this entry")
939
+ if is_legacy(element):
940
+ raise _malformed(entry_id, "delivery", f"run {run!r} is an element of the migration, whose delivery design §12.2 already recorded")
941
+ if element["applied"] is None:
942
+ raise _malformed(entry_id, "delivery", f"the decision of run {run!r} records no application for a delivery check to have found")
943
+ element["applied"]["delivery"] = outcome
944
+ return result
945
+
946
+
947
+ def _revert(ledger, entry_id, element):
948
+ """The owner reverts an application: a revert decision is appended, the status goes back, and the
949
+ row takes the values that application recorded as replaced. It carries no value of its own, and
950
+ where the application recorded none the revert is refused (`reverted_before`, RECORD)."""
951
+ if element.get("kind") != "revert":
952
+ raise _malformed(entry_id, "revert", "a decision of kind revert")
953
+ return apply_decision(ledger, entry_id, element)
954
+
955
+
956
+ EVENTS = {"awaiting_R": _awaiting_r, "recurrence": _recurrence, "contradiction": _contradiction, "delivery": _delivery, "revert": _revert}
957
+
958
+
959
+ def record_event(ledger, entry_id, event, **kwargs):
960
+ """A copy of `ledger` with the event recorded as design §12.3 gives it; the result is validated."""
961
+ if event not in EVENTS:
962
+ raise LedgerError(f"EVENT_UNKNOWN {event!r}: design §12.3 has {sorted(EVENTS)}")
963
+ result = EVENTS[event](ledger, entry_id, **kwargs)
964
+ problems = validate_ledger(result)
965
+ if problems:
966
+ raise LedgerError(f"LEDGER_INVALID after {event}: " + "; ".join(problems))
967
+ return result
968
+
969
+
970
+ # ---------------------------------------------------------------- changed rows
971
+
972
+ def _written_once(element):
973
+ """The element without the two things a later window still writes into it: the resolutions of its
974
+ expected observation (design §11) and the outcome its delivery check found (design §12.3's
975
+ delivery row). Everything else of a decision is written once and never overwritten (design §12.1)."""
976
+ element = copy.deepcopy(element)
977
+ if element["expected_observation"] is not None:
978
+ element["expected_observation"]["resolutions"] = []
979
+ if element["applied"] is not None:
980
+ element["applied"]["delivery"] = None
981
+ return element
982
+
983
+
984
+ def _grew(old, new):
985
+ return isinstance(old, list) and isinstance(new, list) and new[:len(old)] == old
986
+
987
+
988
+ def delivery_problems(eid, n, before, after):
989
+ """A delivery outcome written into a recorded decision by a transaction, by the same rules the
990
+ delivery event applies (`_delivery`, K#4): design §12.3's row has only failed and unverified, and a
991
+ legacy element's delivery is the one design §12.2 recorded when it migrated the entry."""
992
+ was, now = (before["applied"] or {}).get("delivery"), (after["applied"] or {}).get("delivery")
993
+ if was == now:
994
+ return []
995
+ tag = f"{eid} decisions[{n}] ({after['run']})"
996
+ if is_legacy(after):
997
+ return [f"DELIVERY_ON_MIGRATED {tag}: the delivery of an element design §12.2 migrated is the one the migration recorded"]
998
+ if now not in ("failed", "unverified"):
999
+ return [f"DELIVERY_OUTCOME_INVALID {tag}: a delivery check records failed or unverified, not {now!r}; design §12.3's row has no other"]
1000
+ return []
1001
+
1002
+
1003
+ def legacy_appended(eid, elements, offset=0):
1004
+ """An element of the migration a transaction introduced. It is not a decision a run made: it
1005
+ carries no approval row and design §12.2 is its only author, so it enters a ledger through the
1006
+ migration of the schema 1 file (MIGRATION_MISMATCH holds that) and never through a transaction
1007
+ between two schema 2 ledgers — on a row that was already there or on one the run allocated."""
1008
+ return [f"LEGACY_ELEMENT_APPENDED {eid} decisions[{offset + n}]: an element of the migration is written by the "
1009
+ f"migration of the schema 1 ledger, not appended by a run" for n, e in enumerate(elements) if is_legacy(e)]
1010
+
1011
+
1012
+ def new_row_problems(entry, rows):
1013
+ """A new row is bound to the applied decision that created it (design §12.3's rows for no entry)."""
1014
+ eid, decisions = entry["id"], entry["decisions"]
1015
+ if not decisions or is_legacy(decisions[0]):
1016
+ return [f"NEW_ROW_WITHOUT_DECISION {eid}: a new entry is created by a decision of a run"]
1017
+ first = decisions[0]
1018
+ if not takes_effect(first):
1019
+ return [f"NEW_ROW_UNAPPLIED {eid}: the decision that creates an entry is applied"]
1020
+ try:
1021
+ cell = transition(entry_row(entry), disposition_key(first))
1022
+ except LedgerError as exc:
1023
+ return [str(exc).replace("TRANSITION_DISALLOWED", f"TRANSITION_DISALLOWED {eid}:", 1)]
1024
+ if cell["status"] is None:
1025
+ return [f"NEW_ENTRY_FOR_NO_ENTRY {eid}: design §12.3 creates no entry for this decision"]
1026
+ # One decision per row a transaction allocates. A second one would have to be judged from the
1027
+ # state the first left, which is the work `row_violations` does between two recorded rows and
1028
+ # which this side has no base for: the row did not exist at the base (K#3, correction 3). A run
1029
+ # that decides such an entry again does it in the next close, against the row it can now read.
1030
+ problems = legacy_appended(eid, decisions)
1031
+ if len(decisions) > 1:
1032
+ return problems + [f"NEW_ROW_MULTIPLE_DECISIONS {eid}: {len(decisions)} decisions on a row this transaction allocated; the decision "
1033
+ f"that creates an entry is the only one it carries, and a later one is judged against the row the close recorded"]
1034
+ problems += effect_problems(cell, first, None, entry, rows)
1035
+ problems += before_required(f"{eid} decisions[0] ({first['run']})", first)
1036
+ problems += before_problems(f"{eid} decisions[0] ({first['run']})", before_of(first), EMPTY_BEFORE)
1037
+ if entry["status"] != cell["status"]:
1038
+ problems.append(f"STATUS_UNEXPLAINED {eid}: created as {entry['status']}, but its first decision leads to {cell['status']}")
1039
+ if entry["disposition"] != first["disposition"]:
1040
+ problems.append(f"DISPOSITION_UNBOUND {eid}: the entry says {entry['disposition']!r}, its first decision {first['disposition']!r}")
1041
+ return problems
1042
+
1043
+
1044
+ def merge_makers(rows, eid, undone):
1045
+ """Every entry whose merge this decision received: a row absorbed into `eid` carrying a reduce
1046
+ (merge) of the same run and the same operation. All of it is identity — the row the merge named,
1047
+ the run that decided it, the operation it recorded (RECORD) — and the row is the half that was
1048
+ missing: two rows can carry a merge of one run and one operation id, and only one of them merged
1049
+ into this entry (T#0). More than one leaves which row this revert puts back undecidable, and the
1050
+ caller refuses rather than taking the first."""
1051
+ ops = merge_operations(undone)
1052
+ return [row for row in rows if row["id"] != eid and row.get("absorbed_by") == eid and any(
1053
+ is_merge(d) and d["run"] == undone["run"] and merge_operations(d) & ops for d in row["decisions"])]
1054
+
1055
+
1056
+ def at(decisions, element):
1057
+ """Where `element` sits in `decisions`, by identity: its position is what identifies a decision
1058
+ across the base and the head of one transaction, because decisions are only ever appended
1059
+ (`DECISION_REWRITTEN`). Comparing the elements themselves would read a delivery outcome or a
1060
+ resolution written into the recorded decision as a different decision (T#1)."""
1061
+ return next((n for n, d in enumerate(decisions) if d is element), None)
1062
+
1063
+
1064
+ def undoes(partner_base, partner_head, revert_at, target_at):
1065
+ """The replay says the revert this transaction appended at `revert_at` undoes the decision at
1066
+ `target_at`.
1067
+
1068
+ Asking what a revert undoes is the only way to know: a revert carries no reference to its own
1069
+ target, so a same-run revert sitting on the right row can be undoing something else entirely
1070
+ (RECORD). The row holds at most one appended application (`TRANSACTION_MULTIPLE_APPLICATIONS`),
1071
+ so the status before this revert is the base's."""
1072
+ was = {**partner_base, "decisions": partner_head["decisions"][:revert_at]}
1073
+ try:
1074
+ undone, _prior = reverted(was, partner_base["status"])
1075
+ except LedgerError:
1076
+ return False
1077
+ return at(was["decisions"], undone) == target_at
1078
+
1079
+
1080
+ def merge_pair_problems(side, partner_base, partner_head, target_at, run, ops, role):
1081
+ """A merge is put back on both rows or on neither (RECORD): the partner row carries a revert this
1082
+ transaction appended, and the replay says that revert undoes the merge's application there."""
1083
+ first = len(partner_base["decisions"])
1084
+ revert_at = next((n for n, d in enumerate(partner_head["decisions"][first:], first)
1085
+ if d.get("kind") == "revert" and d["run"] == run), None)
1086
+ if revert_at is None:
1087
+ return [f"REVERT_MERGE_SIDE {side}: the merge {sorted(ops)} is put back here and {partner_base['id']}, the entry that "
1088
+ f"{role} it, is left holding it; this transaction appends no revert of run {run!r} there"]
1089
+ if not undoes(partner_base, partner_head, revert_at, target_at):
1090
+ return [f"REVERT_MERGE_UNPAIRED {side}: the revert of run {run!r} appended to {partner_base['id']} undoes another decision of "
1091
+ f"that row, not the application that {role} the merge {sorted(ops)}"]
1092
+ return []
1093
+
1094
+
1095
+ def row_violations(base, head, rows, base_rows=None):
1096
+ """Design §12.4, "every changed row matching a validated decision", between two schema 2 rows.
1097
+
1098
+ A change is licensed by what was appended. Without an applied decision only the recurrence event's
1099
+ fields may change; with one, its status (by the table, or by the history for a revert), its
1100
+ disposition (the decision's own) and the fields that decision's own disposition and cell license
1101
+ (`licensed_fields`), and the effects its cell requires are checked on the result."""
1102
+ if base == head:
1103
+ return []
1104
+ eid, problems = head["id"], []
1105
+ old, new = base["decisions"], head["decisions"]
1106
+ if len(new) < len(old):
1107
+ problems.append(f"DECISION_REWRITTEN {eid}: {len(old) - len(new)} decision(s) removed; a decision is never overwritten")
1108
+ for n, (before, after) in enumerate(zip(old, new)):
1109
+ if before != after and (_written_once(before) != _written_once(after) or not _grew(
1110
+ (before["expected_observation"] or {}).get("resolutions") or [], (after["expected_observation"] or {}).get("resolutions") or [])):
1111
+ problems.append(f"DECISION_REWRITTEN {eid} decisions[{n}] ({before['run']}): only a resolution and the delivery outcome are written later")
1112
+ problems += delivery_problems(eid, n, before, after)
1113
+ appended = new[len(old):]
1114
+ problems += legacy_appended(eid, appended, len(old))
1115
+ appended = [e for e in appended if not is_legacy(e)]
1116
+ applied = [e for e in appended if takes_effect(e)]
1117
+ changed = sorted(k for k in set(base) | set(head) if k != "decisions" and base.get(k) != head.get(k))
1118
+ for field in (f for f in APPEND_ONLY if f in changed):
1119
+ if not _grew(base.get(field, []), head.get(field, [])):
1120
+ problems.append(f"EVENT_REWRITTEN {eid} {field}: a recurrence only appends")
1121
+ # One applied decision per row per transaction. A second would have to be judged from the row the
1122
+ # first left, and this side holds the row as the base recorded it and as the close wrote it, never
1123
+ # the state in between: a transaction that applied a decision and reverted it in one close would
1124
+ # be judged against neither (RECORD). A run decides an entry once (DECISION_RUN_DUPLICATE), so
1125
+ # the case this refuses is a close carrying two runs' applications for one row.
1126
+ if len(applied) > 1:
1127
+ problems.append(f"TRANSACTION_MULTIPLE_APPLICATIONS {eid}: {len(applied)} applied decisions appended in one transaction "
1128
+ f"({', '.join(e['run'] for e in applied)}); the row in between them is not recorded anywhere")
1129
+ return problems
1130
+ reached, so_far, licensed = base["status"], list(old), set()
1131
+ for element in appended:
1132
+ so_far.append(element)
1133
+ if not takes_effect(element):
1134
+ continue
1135
+ restored, undone = None, None
1136
+ try:
1137
+ if element.get("kind") == "revert":
1138
+ was = {**base, "decisions": so_far[:-1]}
1139
+ undone, reached, restored = reverted_before(was, reached)
1140
+ cell, licensed = {"effects": []}, licensed | set(restored["fields"]) | set(restored["absent"])
1141
+ else:
1142
+ cell = transition(row_of(reached), disposition_key(element))
1143
+ reached = status_after(reached, cell)
1144
+ except LedgerError as exc:
1145
+ problems.append(str(exc).replace("TRANSITION_DISALLOWED", f"TRANSITION_DISALLOWED {eid}:", 1))
1146
+ continue
1147
+ licensed |= licensed_fields(element, cell)
1148
+ problems += effect_problems(cell, element, base, head, rows)
1149
+ # What the application says it replaced, against what the row says it replaced.
1150
+ tag = f"{eid} decisions[{len(old) + appended.index(element)}] ({element['run']})"
1151
+ problems += before_required(tag, element)
1152
+ problems += before_problems(tag, before_of(element), before_record(base, head))
1153
+ if restored is not None: # a revert puts the row back, and the result is held against the record
1154
+ problems += revert_restored(base, head, restored)
1155
+ if receiving_side(undone): # the receiving side of a merge: the row it absorbed is put back with it
1156
+ makers = merge_makers((base_rows or rows).values(), eid, undone)
1157
+ if not makers:
1158
+ problems.append(f"REVERT_MERGE_SIDE {eid}: this decision received the merge {sorted(merge_operations(undone))} of run "
1159
+ f"{undone['run']!r} and no entry of the base merged into this one with it, so there is no row to "
1160
+ f"put back with it")
1161
+ elif len(makers) > 1:
1162
+ problems.append(f"REVERT_MERGE_SIDE {eid}: {[row['id'] for row in makers]} each recorded the merge "
1163
+ f"{sorted(merge_operations(undone))} of run {undone['run']!r} into this entry, so which row this "
1164
+ f"revert puts back is not decidable")
1165
+ else:
1166
+ source = makers[0]
1167
+ made = next(d for d in source["decisions"] if is_merge(d) and d["run"] == undone["run"])
1168
+ problems += merge_pair_problems(eid, source, rows[source["id"]], at(source["decisions"], made),
1169
+ element["run"], merge_operations(undone), "made")
1170
+ if is_merge(undone): # and the receiving entry of a merge is part of that row's inverse
1171
+ try:
1172
+ # the receiver as the base recorded it: its own revert is what this transaction
1173
+ # appends, so the row to read the merge's standing from is the one before that
1174
+ receiver, given = merge_receiver({"entries": list((base_rows or rows).values())}, base, undone)
1175
+ now = rows[receiver["id"]]
1176
+ appended_there = now["decisions"][len(receiver["decisions"]):]
1177
+ if not any(d.get("kind") == "revert" and d["run"] == element["run"] for d in appended_there):
1178
+ problems.append(f"RECEIVER_REVERT_MISSING {receiver['id']}: the merge of run {undone['run']!r} is reverted on {eid} "
1179
+ f"and this transaction appends no revert of it on this entry, where its decision still stands")
1180
+ else:
1181
+ problems += merge_pair_problems(eid, receiver, now, at(receiver["decisions"], given),
1182
+ element["run"], merge_operations(undone), "received")
1183
+ problems += revert_restored(receiver, now, before_of(given) or EMPTY_BEFORE)
1184
+ except LedgerError as exc:
1185
+ problems.append(str(exc))
1186
+ allowed = set(EVENT_FIELDS) | ({"status", "disposition"} | licensed if applied else set())
1187
+ problems += [f"ROW_FIELD_UNLICENSED {eid} {k}: changed with {'no applied decision' if not applied else 'a decision whose disposition does not license it'}"
1188
+ for k in changed if k not in allowed]
1189
+ if applied and head["disposition"] != applied[-1]["disposition"]:
1190
+ problems.append(f"DISPOSITION_UNBOUND {eid}: the entry says {head['disposition']!r}, the latest decision that took effect {applied[-1]['disposition']!r}")
1191
+ if reached != head["status"]:
1192
+ problems.append(f"STATUS_UNEXPLAINED {eid}: {base['status']} → {head['status']}, but the decisions that took effect lead to {reached}")
1193
+ return problems
1194
+
1195
+
1196
+ def ledger_path(state_root=None, override=None):
1197
+ """The ledger to read: `override` when the caller named one, else the state root's own.
1198
+
1199
+ A caller that has neither names nothing, and gets None rather than a guess — a path this module
1200
+ invented would be read, created and written somewhere nobody asked for.
1201
+ """
1202
+ if override:
1203
+ return pathlib.Path(override).expanduser()
1204
+ if state_root:
1205
+ return pathlib.Path(state_root).expanduser() / STATE_LEDGER_REL
1206
+ return None
1207
+
1208
+
1209
+ def check_pair(base, head, allocated=None, migrate=None):
1210
+ """Every violation of design §12.4 between a frozen `base` ledger and a `head` ledger.
1211
+
1212
+ `migrate` is the schema 1 to schema 2 migration, INJECTED: it lives in an author-side script
1213
+ (`session-distill/migrate-ledger.py`, run through `gates/check-ledger.py`) that a packaged user
1214
+ does not have, and loading it from here made shipped code name a file outside the payload. A
1215
+ comparison that needs it without being given it says so by name and migrates nothing — an
1216
+ installed ledger is schema 2 from its first write, so the case belongs to the checkout.
1217
+ """
1218
+ problems = validate_ledger(head)
1219
+ if problems:
1220
+ return problems
1221
+ before, after = version(base), version(head)
1222
+ problems = id_set_violations(entry_ids(base), entry_ids(head), allocated, numbered=before == 1 and after == 1,
1223
+ transaction=before == 2 and after == 2 and base != head)
1224
+ held = base.get("windows", [])
1225
+ if after == 2 and held != head["windows"][:len(held)]:
1226
+ problems.append("WINDOWS_REWRITTEN: a window record of the base was changed or removed")
1227
+ if before == 1 and after == 2:
1228
+ if migrate is None:
1229
+ problems.append("MIGRATOR_UNAVAILABLE: a schema 1 base against a schema 2 head is judged by equality "
1230
+ "with the migration, and no migration was given to this comparison")
1231
+ else:
1232
+ migrated, _removed = migrate(base)
1233
+ if migrated != head:
1234
+ problems.append("MIGRATION_MISMATCH: the schema 2 head is not the migration of the schema 1 base")
1235
+ elif before == 2 and after == 1:
1236
+ problems.append("LEDGER_SCHEMA_REGRESSED: the head is schema 1 and the base schema 2")
1237
+ elif before == 2:
1238
+ base_rows, rows = _rows(base), _rows(head)
1239
+ for entry in head["entries"]:
1240
+ if entry["id"] in base_rows:
1241
+ problems += row_violations(base_rows[entry["id"]], entry, rows, base_rows)
1242
+ else:
1243
+ problems += new_row_problems(entry, rows)
1244
+ return problems
1245
+
1246
+
1247
+ # ---------------------------------------------------------------- atomic writes
1248
+
1249
+ def read_current(path):
1250
+ try:
1251
+ return pathlib.Path(path).read_bytes()
1252
+ except FileNotFoundError:
1253
+ return b""
1254
+
1255
+
1256
+ def write_atomic(path, ledger, base_sha, lock_root=LOCK_ROOT, before_rename=None, allocated=()):
1257
+ """Replace the ledger at `path` with `ledger` if it still hashes to `base_sha`.
1258
+
1259
+ The ledger is validated first, the lock taken (`STAGE_LOCKED` when another writer holds it), the
1260
+ file's hash compared with the one the caller read (`BASE_STALE`), and the file it would replace
1261
+ held against the ledger that replaces it (`check_pair`, with the allocation the caller froze):
1262
+ the bytes on disk are the base of a transaction, and a writer that erases or reorders a decision
1263
+ is refused here rather than caught later by a gate (U#0). Only then are the new bytes written to
1264
+ a temporary file beside it, fsynced, and renamed over it. Every path is confined beneath the
1265
+ ledger's directory (`RUN_PATH_ESCAPE`). `before_rename` is the seam a crash is injected through:
1266
+ a reader sees the old file or the complete new one, never a part."""
1267
+ problems = validate_ledger(ledger)
1268
+ if problems:
1269
+ raise LedgerError("LEDGER_INVALID, nothing written: " + "; ".join(problems))
1270
+ path = pathlib.Path(path)
1271
+ root = path.parent
1272
+ target = stagelock.confine(root, path)
1273
+ with stagelock.hold(lock_root, "ledger"):
1274
+ bytes_there = read_current(target)
1275
+ current = sha256_bytes(bytes_there)
1276
+ if current != base_sha:
1277
+ raise LedgerError(f"BASE_STALE {path}: the file hashes to {current[:12]}, the writer read {base_sha[:12]}")
1278
+ if bytes_there: # a first write replaces no transaction; every later one does
1279
+ # the base is read as a ledger before it is read as a transaction's base: `check_pair`
1280
+ # validates the head it is given and takes the base as one, so a base that is not a
1281
+ # ledger reaches the comparison as whatever it is — a list, a null, a row set with two
1282
+ # rows of one id — and is read through as if it said something (X#0).
1283
+ try:
1284
+ was = json.loads(bytes_there.decode("utf-8"))
1285
+ unsound = validate_ledger(was) if isinstance(was, dict) else [f"it holds {type(was).__name__}, not an object"]
1286
+ except (UnicodeDecodeError, json.JSONDecodeError, AttributeError, TypeError, KeyError) as exc:
1287
+ unsound = [f"reading it raised {type(exc).__name__}: {exc}"]
1288
+ if unsound:
1289
+ raise LedgerError(f"BASE_UNREADABLE {path}, nothing written: the file this writer would replace is not a ledger: "
1290
+ + "; ".join(unsound))
1291
+ problems = check_pair(was, ledger, allocated)
1292
+ if problems:
1293
+ raise LedgerError("TRANSACTION_INVALID, nothing written: " + "; ".join(problems))
1294
+ fd, temporary = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.")
1295
+ try:
1296
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
1297
+ handle.write(render(ledger))
1298
+ handle.flush()
1299
+ os.fsync(handle.fileno())
1300
+ if before_rename is not None:
1301
+ before_rename()
1302
+ os.replace(temporary, target)
1303
+ except BaseException:
1304
+ pathlib.Path(temporary).unlink(missing_ok=True)
1305
+ raise
1306
+ directory = os.open(target.parent, os.O_RDONLY)
1307
+ try:
1308
+ os.fsync(directory)
1309
+ finally:
1310
+ os.close(directory)
1311
+
1312
+
1313
+ # ---------------------------------------------------------------- the check command
1314
+
1315
+ def allocation(argument):
1316
+ """`--allocated` as an allocation: an omitted flag is no allocation at all (`None`), and the flag
1317
+ passed empty is the allocation of a run that froze no new id (`[]`) — a correction or a resolution
1318
+ writes the ledger without adding a row, and the two cases are not the same answer (`ALLOCATION_REQUIRED`)."""
1319
+ return None if argument is None else [i for i in (part.strip() for part in argument.split(",")) if i]
1320
+
1321
+
1322
+ def check_command(repo, rel, base, worktree, allocated, migrate=None):
1323
+ """(exit code, lines). 0 holds, 1 a violation, 2 a side that could not be read.
1324
+
1325
+ `migrate` is passed through to `check_pair`: comparing a schema 1 base with a schema 2 head needs
1326
+ the author-side migration, which `gates/check-ledger.py` supplies.
1327
+ """
1328
+ old, old_absent = gitread.base_blob(repo, base, rel)
1329
+ new, new_absent = gitread.current_blob(repo, rel, worktree)
1330
+ where = "worktree" if worktree else "index"
1331
+ if old is None:
1332
+ return 2, [f"CANNOT JUDGE LEDGER_BASE_UNREADABLE {base}:{rel}"]
1333
+ if new is None:
1334
+ return 2, [f"CANNOT JUDGE LEDGER_FILE_UNREADABLE {rel} ({where})"]
1335
+ if new_absent:
1336
+ return 1, [f"LEDGER_ABSENT {rel}: the {where} holds no ledger"]
1337
+ try:
1338
+ head = parse(new, f"{where}:{rel}")
1339
+ if old_absent:
1340
+ problems = validate_ledger(head)
1341
+ note = f"no ledger at {base}: validated alone"
1342
+ else:
1343
+ problems = check_pair(parse(old, f"{base}:{rel}"), head, allocated, migrate=migrate)
1344
+ note = f"against {base}"
1345
+ except LedgerError as exc:
1346
+ return 1, [str(exc)]
1347
+ if problems:
1348
+ return 1, problems
1349
+ return 0, [f"ledger --check: OK (schema {version(head)}, {len(head['entries'])} entries, {note}, {where})"]
1350
+
1351
+
1352
+ # ---------------------------------------------------------------- samples and transition fixtures
1353
+
1354
+ def sample_entry(eid, status="placed", **fields):
1355
+ entry = {"id": eid, "lesson": f"lesson of {eid}", "status": status, "classification": None, "window": "unknown",
1356
+ "kind": "unclassified", "diagnosis": "unknown", "disposition": "none", "destination": None, "evidence": [],
1357
+ "independent_lineages": "unavailable", "consequence": {"kinds": []}, "coverage": {"basis": "unavailable"},
1358
+ "keep": None, "relations": {}, "decisions": []}
1359
+ entry.update(fields)
1360
+ return entry
1361
+
1362
+
1363
+ def sample_ledger(*entries, windows=()):
1364
+ return {"schema": 2, "framework": "design/session-distill/PLACEMENT-FRAMEWORK.md", "windows": list(windows), "entries": list(entries)}
1365
+
1366
+
1367
+ def sample_element(run, disposition, applied=True, observation=None, approval="ap-1", operations=(), delivery="not_applicable", **extra):
1368
+ """A decision of a run: design §12.1's eight keys, and nothing design §12.2 gives a migrated one."""
1369
+ return {"run": run, "disposition": disposition, "approval_id": approval, "adjudication_id": None, "confirmation": None,
1370
+ "applied": ({"commit": None, "paths": [], "operations": list(operations), "delivery": delivery,
1371
+ "before": copy.deepcopy(EMPTY_BEFORE)} if applied else None),
1372
+ "tests": None, "expected_observation": observation, **extra}
1373
+
1374
+
1375
+ def sample_observation(expiry="2026-12-31"):
1376
+ return {"occasion_criteria": "the owner asks again", "exposure_rule": "the unit was delivered first",
1377
+ "expected_behavior": "no second ask", "retrieval_terms": ["ask again"], "expiry": expiry, "resolutions": []}
1378
+
1379
+
1380
+ def sample_resolution(run, window="2026-11-20", resolution="observed"):
1381
+ return {"run": run, "window": window, "resolution": resolution, "basis": "source",
1382
+ "counts": {"eligible": 2, "observed": 2, "not_observed": 0, "exposure_unknown": 0}, "occasions": ["occ-1", "occ-2"]}
1383
+
1384
+
1385
+ MERGE = {"operation_id": "op-1", "type": "merge", "target": "claude/CLAUDE.md#x"}
1386
+ ROW_STATUS = {"incubating": "incubating", "placed": "placed", "absorbed_retired": "retired"}
1387
+
1388
+
1389
+ def cell_ids():
1390
+ """`<row>/<disposition>` of every cell the table allows."""
1391
+ return sorted(f"{row}/{key}" for row, cells in transitions()["cells"].items() for key, cell in cells.items() if cell is not None)
1392
+
1393
+
1394
+ # What an entry has to gain for a cell's effect: the footprints the fixtures pass as `updates`. The other
1395
+ # footprints belong to the decision (a reason, an observation) or to the receiving entry, and are built
1396
+ # by `scenario`.
1397
+ UPDATES = {"keep_record": {"keep": {"units": ["unit-1"]}}, "absorbed_by": {"absorbed_by": "G-0"},
1398
+ "allocate_destination_entry": {"absorbed_by": "G-0"}, "text_revised": {"lesson": "a revised lesson"}}
1399
+
1400
+
1401
+ def updates_for(cell):
1402
+ return {k: v for e in cell["effects"] for k, v in UPDATES.get(e, {}).items()}
1403
+
1404
+
1405
+ def scenario(row, key, updates):
1406
+ """What one cell's fixture runs through the production code: the entry (a candidate when the row is
1407
+ no entry yet), the entries around it, the decision, and the updates."""
1408
+ status = ROW_STATUS.get(row)
1409
+ if status is None: # no entry yet: a new learning is a gap, anything else comes from a unit of the library
1410
+ entry = sample_entry("S9-01", "placed", kind="gap" if row == "no_entry_new_learning" else "misfire")
1411
+ else:
1412
+ entry = sample_entry("S9-01", status, kind="gap")
1413
+ if row == "incubating": # an incubating entry was incubated by an earlier run, whose expiry a renewal has to pass
1414
+ entry["decisions"].append(sample_element("run-0", "incubate", observation=sample_observation("2026-12-31")))
1415
+ disposition = "reduce" if key.startswith("reduce") else key
1416
+ extra = {"reason": "the reason"} if disposition in ("keep", "drop") else {}
1417
+ observation = sample_observation("2027-06-30") if disposition == "incubate" else None
1418
+ element = sample_element("run-1", disposition, observation=observation, operations=[MERGE] if key == "reduce_merge" else (), **extra)
1419
+ return {"entry": entry, "others": [sample_entry("G-0")], "element": element, "updates": updates}
1420
+
1421
+
1422
+ def fixture_for(row, key):
1423
+ return scenario(row, key, updates_for(transition(row, key)))
1424
+
1425
+
1426
+ def generate_fixtures(path=FIXTURES_PATH):
1427
+ """Write one fixture per allowed cell, once. The fixtures are committed, and a second call refuses:
1428
+ a fixture regenerated from the table it is meant to hold would hold nothing."""
1429
+ path = pathlib.Path(path)
1430
+ if path.exists():
1431
+ raise LedgerError(f"FIXTURES_FROZEN {path}: generated once and committed; delete it by hand to regenerate")
1432
+ fixtures = []
1433
+ for cid in cell_ids():
1434
+ row, key = cid.split("/")
1435
+ cell = transitions()["cells"][row][key]
1436
+ fixtures.append({"id": cid, "row": row, "disposition": key, "before": ROW_STATUS.get(row),
1437
+ "updates": updates_for(cell), "after": cell})
1438
+ doc = {"$comment": "design §12.3: one frozen fixture per allowed cell of tables/transitions.json, written once by "
1439
+ "`runlib/ledger.py --generate-transition-fixtures`; the self-test never regenerates them.",
1440
+ "fixtures": fixtures}
1441
+ path.write_text(json.dumps(doc, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
1442
+ return len(fixtures)
1443
+
1444
+
1445
+ def fixture_problems(fixture):
1446
+ """Run one frozen fixture through the real code path and compare it with what it froze: an entry
1447
+ that exists moves by `apply_decision`, a row with no entry yet creates it (or none) by `create_entry`."""
1448
+ fid, row, key, before, after = fixture["id"], fixture["row"], fixture["disposition"], fixture["before"], fixture["after"]
1449
+ cell = transition(row, key) # the table as it stands now
1450
+ if cell != after:
1451
+ return [f"{fid}: the table now says {cell}, frozen {after}"]
1452
+ run = scenario(row, key, fixture["updates"])
1453
+ ledger = sample_ledger(*run["others"])
1454
+ try:
1455
+ if before is None:
1456
+ made = [e for e in create_entry(ledger, {**run["entry"], **run["updates"]}, run["element"])["entries"] if e["id"] == "S9-01"]
1457
+ if len(made) != (1 if after["status"] is not None else 0):
1458
+ return [f"{fid}: {len(made)} entries created, frozen {after['status']}"]
1459
+ return [] if not made or made[0]["status"] == after["status"] else [f"{fid}: created {made[0]['status']}, frozen {after['status']}"]
1460
+ ledger["entries"].append(run["entry"])
1461
+ moved = apply_decision(ledger, "S9-01", run["element"], run["updates"])["entries"][-1]["status"]
1462
+ except LedgerError as exc:
1463
+ return [f"{fid}: {exc}"]
1464
+ want = after["status"] if after["status"] not in (None, "unchanged") else before
1465
+ return [] if moved == want else [f"{fid}: the status moved {before} → {moved}, frozen {want}"]
1466
+
1467
+
1468
+ def coverage_problems(cells, frozen, executed):
1469
+ """The three-set comparison of the table's cells, the frozen fixtures' ids and the case ids a run
1470
+ executed (the `check_bijection` pattern of benchmarks/manifest.py): any difference, by id."""
1471
+ return ([f"CELL_UNFIXTURED {i}: a cell of the table with no frozen fixture" for i in sorted(set(cells) - set(frozen))]
1472
+ + [f"FIXTURE_ORPHAN {i}: a frozen fixture for no cell of the table" for i in sorted(set(frozen) - set(cells))]
1473
+ + [f"CASE_NOT_EXECUTED {i}: a frozen fixture the run never executed" for i in sorted(set(frozen) - set(executed))]
1474
+ + [f"CASE_UNFROZEN {i}: a case the run executed with no frozen fixture" for i in sorted(set(executed) - set(frozen))])
1475
+
1476
+
1477
+ # ---------------------------------------------------------------- the self-test
1478
+
1479
+ # The design's table of §12.3, copied here once (WP-13 done-when 4). The cross-provider review of
1480
+ # this module compares it with the design text. Each row is the cell wording in the column order of
1481
+ # `transitions()["dispositions"]`; "—" is a pair code rejects.
1482
+ DESIGN_12_3 = {
1483
+ "no_entry_new_learning": ["new entry, placed", "—", "—", "—", "—", "—", "new entry, incubating",
1484
+ "new entry, retired (never placed)", "no entry"],
1485
+ "no_entry_existing_unit": ["—", "new entry, placed", "new entry, placed", "new entry, placed, keep record",
1486
+ "new entry, retired", "new entry, absorbed; destination entry allocated (placed) if it has none",
1487
+ "new entry, placed, pending intervention", "new entry, placed, dropped intervention", "no entry"],
1488
+ "incubating": ["placed", "incubating (text revised)", "—", "—", "—", "—", "incubating (expiry renewed)", "retired", "unchanged"],
1489
+ "placed": ["—", "unchanged", "unchanged", "unchanged, keep record", "retired",
1490
+ "absorbed (`absorbed_by`); the receiving entry gets a merge decision", "unchanged, pending intervention",
1491
+ "unchanged, dropped intervention", "unchanged"],
1492
+ "absorbed_retired": ["placed (revival)", "—", "—", "—", "—", "—", "incubating (revival)", "unchanged", "unchanged"],
1493
+ }
1494
+ # design §12.3, "Events other than dispositions": (from, event, to), copied once. Its branch set is the
1495
+ # five events; `EVENTS` holds one handler for each.
1496
+ DESIGN_12_3_EVENTS = (
1497
+ ("incubating", "awaiting R (§10.2)", "incubating, reason recorded"),
1498
+ ("any", "recurrence (new evidence for the same learning)", "unchanged; evidence and lineages appended"),
1499
+ ("any", "contradiction (admitted evidence against it)", "unchanged until its candidate's disposition (correct, reduce, or drop) is applied"),
1500
+ ("any applied decision", "delivery failed or unverified", "unchanged; `decisions[].applied.delivery` records it"),
1501
+ ("any applied decision", "application reverted by the owner", "the status before that decision; a revert decision appended"),
1502
+ )
1503
+ # design §7.2's closed vocabularies, copied once. A current entry and every decision of a run use them;
1504
+ # design §12.2 adds `unknown` and `revival` to the elements it migrates, and nowhere else.
1505
+ DESIGN_7_2 = {
1506
+ "kind": ["misfire", "gap", "not delivered", "confirmed", "obsolete", "already resolved", "unclassified"],
1507
+ "diagnosis": ["covered", "wrong or insufficient", "trigger problem", "gap", "redundant", "unknown"],
1508
+ "disposition": ["place", "correct", "re-deliver", "keep", "reduce", "incubate", "drop", "none"],
1509
+ "legacy_only": ["unknown", "revival"],
1510
+ }
1511
+ # The field lists of design §12.1 and §12.2, copied once. `entry_required` are the fields §12.1 adds and
1512
+ # the kept fields every entry carries, `element_required` the eight keys of a decisions[] element in §12.1
1513
+ # and nothing else. Every property beyond those lists is optional, and each is contracted — with the code
1514
+ # that reads it and the reason it exists — by ADDENDUM, which `addendum_problems` holds against this
1515
+ # module: §12.2's metadata of a migrated element (`element_legacy_only`, which a decision of a run may
1516
+ # not carry), the legacy and revert kinds, and the `reason` §7.3 and §12.3 ask of a keep, a drop and an
1517
+ # awaiting-R record.
1518
+ DESIGN_12_1 = {
1519
+ "entry_required": {"id", "lesson", "status", "classification", "window"} | {
1520
+ "kind", "diagnosis", "disposition", "destination", "evidence", "independent_lineages", "consequence",
1521
+ "coverage", "keep", "relations", "decisions"},
1522
+ "entry_optional": {"principle", "rationale", "surfaced", "domain", "source", "note", "learning_id", "baseline_ref",
1523
+ "recurrence", "absorbed_by", "retired", "retire_reason"},
1524
+ "element_required": {"run", "disposition", "approval_id", "adjudication_id", "confirmation", "applied", "tests",
1525
+ "expected_observation"},
1526
+ "element_optional": {"at", "field", "legacy_text", "legacy_placed", "legacy_status", "kind", "status_note", "reason",
1527
+ "resolves"},
1528
+ "element_legacy_only": set(LEGACY_PROPERTIES),
1529
+ "applied": {"commit", "paths", "operations", "delivery"},
1530
+ "applied_optional": {"before"}, # the owner's decision of 2026-10-21, contracted in RECORD
1531
+ "tests": {"results_sha", "summary", "attribution"},
1532
+ "window": {"start", "end", "run_id", "kind", "commit", "accounted", "fully_read"},
1533
+ "evidence": {"claim_id", "evidence_id", "locator", "session"},
1534
+ }
1535
+
1536
+
1537
+ def contract_problems(doc):
1538
+ """Where the schema departs from the field lists of design §12.1, §12.2, §12.4 and the vocabularies of §7.2."""
1539
+ problems = []
1540
+ if not str(doc.get("$comment", "")).startswith("design §12.1"):
1541
+ problems.append("CONTRACT_MISMATCH ledger: $comment does not cite design §12.1")
1542
+ defs = doc["$defs"]
1543
+ shapes = {"entry": (defs["entry"], DESIGN_12_1["entry_required"], DESIGN_12_1["entry_optional"]),
1544
+ "decision": (defs["decision"], DESIGN_12_1["element_required"], DESIGN_12_1["element_optional"]),
1545
+ "applied": (defs["applied"], DESIGN_12_1["applied"], DESIGN_12_1["applied_optional"]),
1546
+ "tests": (defs["tests"], DESIGN_12_1["tests"], set()),
1547
+ "window": (defs["window"], DESIGN_12_1["window"], set()),
1548
+ "evidence_item": (defs["evidence_item"], set(), DESIGN_12_1["evidence"])}
1549
+ for name, (shape, required, optional) in shapes.items():
1550
+ for verb, fields in (("lacks", required - set(shape["required"] if "required" in shape else ())), ("adds", set(shape.get("required", ())) - required)):
1551
+ if fields:
1552
+ problems.append(f"CONTRACT_MISMATCH {name} (design §12.1): required {verb} {sorted(fields)}")
1553
+ for verb, fields in (("lacks", (required | optional) - set(shape["properties"])), ("adds", set(shape["properties"]) - required - optional)):
1554
+ if fields:
1555
+ problems.append(f"CONTRACT_MISMATCH {name} (design §12.1): properties {verb} {sorted(fields)}")
1556
+ entry = defs["entry"]["properties"]
1557
+ legacy_only = set(defs["legacy_disposition"]["enum"]) - set(defs["disposition"]["enum"])
1558
+ for name, have, want in (("entry kind", defs["entry_kind"]["enum"], DESIGN_7_2["kind"]),
1559
+ ("entry diagnosis", defs["entry_diagnosis"]["enum"], DESIGN_7_2["diagnosis"]),
1560
+ ("disposition", defs["disposition"]["enum"], DESIGN_7_2["disposition"]),
1561
+ ("legacy-only dispositions", sorted(legacy_only), sorted(DESIGN_7_2["legacy_only"]))):
1562
+ if have != want:
1563
+ problems.append(f"CONTRACT_MISMATCH {name} (design §7.2): {have} differs from {want}")
1564
+ before = defs["before_row"]
1565
+ named = set(before["properties"]["fields"]["properties"]) | set(before["properties"]["absent"]["items"]["enum"])
1566
+ if named != set(REVERTIBLE) or set(before["properties"]["fields"]["properties"]) != set(before["properties"]["absent"]["items"]["enum"]):
1567
+ problems.append(f"CONTRACT_MISMATCH before_row (RECORD): it names {sorted(named)}, the fields a decision may change are {sorted(REVERTIBLE)}")
1568
+ if not str(before.get("$comment", "")).startswith("the owner's decision of 2026-10-21"):
1569
+ problems.append("CONTRACT_MISMATCH before_row (RECORD): its comment does not cite the decision that added it")
1570
+ if defs["decision"]["properties"].get("legacy_status", {}).get("enum") != entry["status"]["enum"]:
1571
+ problems.append("CONTRACT_MISMATCH legacy_status (design §12.2): its values differ from the entry status vocabulary")
1572
+ if entry["disposition"] != {"$ref": "#/$defs/disposition"}:
1573
+ problems.append("CONTRACT_MISMATCH entry disposition (design §7.2): an entry takes the current vocabulary only")
1574
+ if defs["decision"]["properties"]["disposition"] != {"$ref": "#/$defs/legacy_disposition"}:
1575
+ problems.append("CONTRACT_MISMATCH decision disposition (design §12.2): a decision takes the vocabulary with the two legacy values")
1576
+ # The two shapes of a decisions[] element (ADDENDUM §1): the schema marks each property design §12.2
1577
+ # gives a migrated element, and this module rejects exactly those on a decision a run made.
1578
+ marked = {k for k, v in defs["decision"]["properties"].items() if str(v.get("$comment", "")).startswith(LEGACY_MARK)}
1579
+ if marked != DESIGN_12_1["element_legacy_only"]:
1580
+ problems.append(f"CONTRACT_MISMATCH decision (ADDENDUM §1): the schema marks {sorted(marked)} as a migrated element's, "
1581
+ f"the record names {sorted(DESIGN_12_1['element_legacy_only'])}")
1582
+ return problems
1583
+
1584
+
1585
+ def addendum_problems(text=None, rel=ADDENDUM):
1586
+ """ADDENDUM against this module: it exists, and it names a contract for every property schema 2
1587
+ carries beyond design §12.1's lists. A property added to the schema without one is then a named
1588
+ failure here, not a comment in the file that added it."""
1589
+ if text is None:
1590
+ path = REPO / rel
1591
+ if not path.is_file():
1592
+ return [f"ADDENDUM_MISSING {rel}: what schema 2 carries beyond design §12.1 has no contract"]
1593
+ text = path.read_text(encoding="utf-8")
1594
+ named = {f"`{p}`" for p in DESIGN_12_1["element_optional"] - {"kind"} - set(FIELD_RECORDS)} | {
1595
+ f"`kind: {k}`" for k in (*LEGACY_KINDS, "revert")}
1596
+ return [f"ADDENDUM_SILENT {rel}: it contracts no {token}" for token in sorted(named) if token not in text]
1597
+
1598
+
1599
+ def field_record_problems(texts=None, field_records=None):
1600
+ """Each property FIELD_RECORDS names against its record: the property is one schema 2 carries beyond design §12.1,
1601
+ and the record exists and names it. `texts` maps a property to the text to read instead of its file;
1602
+ `field_records` replaces FIELD_RECORDS (the self-test's way to name a record that is not there)."""
1603
+ problems = []
1604
+ for prop, rel in sorted((FIELD_RECORDS if field_records is None else field_records).items()):
1605
+ if prop not in DESIGN_12_1["element_optional"]:
1606
+ problems.append(f"FIELD_RECORD_STALE {rel}: {prop} is no optional property of a decision")
1607
+ if texts is not None and prop in texts:
1608
+ text = texts[prop]
1609
+ elif (REPO / rel).is_file():
1610
+ text = (REPO / rel).read_text(encoding="utf-8")
1611
+ else:
1612
+ problems.append(f"FIELD_RECORD_MISSING {rel}: schema 2's `{prop}` has no contract")
1613
+ continue
1614
+ if f"`{prop}`" not in text:
1615
+ problems.append(f"FIELD_RECORD_SILENT {rel}: it contracts no `{prop}`")
1616
+ return problems
1617
+
1618
+
1619
+ def record_problems(text=None, rel=RECORD):
1620
+ """The owner's decision on what a revert puts back: the record exists, it says which reading it
1621
+ supersedes, and it names the rules the code now holds. A rule decided in the code and not here
1622
+ would leave an earlier dated record standing as the contract, which is how the first one went wrong."""
1623
+ if text is None:
1624
+ path = REPO / rel
1625
+ if not path.is_file():
1626
+ return [f"RECORD_MISSING {rel}: the decision this module implements has no record"]
1627
+ text = path.read_text(encoding="utf-8")
1628
+ older = SUPERSEDED.rsplit("/", 1)[1]
1629
+ problems = [] if f"supersedes: {older}" in text else [f"RECORD_UNANCHORED {rel}: its frontmatter does not supersede {older}"]
1630
+ return problems + [f"RECORD_SILENT {rel}: it carries no {code}" for code in
1631
+ ("applied.before", "REVERT_INVERSE_UNPROVABLE", "BEFORE_FIELD_WRONG", "TRANSACTION_MULTIPLE_APPLICATIONS",
1632
+ "BEFORE_MISSING", "BEFORE_FIELD_OVERLAP", "REVERT_MERGE_SIDE", "standing_decision",
1633
+ "REVERT_MERGE_UNPAIRED", "TRANSACTION_INVALID", "BASE_UNREADABLE")
1634
+ if code not in text]
1635
+
1636
+
1637
+ def eo_mismatch(doc):
1638
+ """The ledger's expected_observation against schemas/expected_observation.schema.json (design §7.3)."""
1639
+ mine = doc["$defs"]["expected_observation"]
1640
+ other = json.loads(EO_SCHEMA_PATH.read_text(encoding="utf-8"))
1641
+ problems = []
1642
+ if set(mine["properties"]) - {"resolutions"} != set(other["properties"]):
1643
+ problems.append("CONTRACT_MISMATCH expected_observation (design §7.3): properties differ from schemas/expected_observation.schema.json")
1644
+ if set(mine["required"]) - {"resolutions"} != set(other["required"]):
1645
+ problems.append("CONTRACT_MISMATCH expected_observation (design §7.3): required differs from schemas/expected_observation.schema.json")
1646
+ return problems
1647
+
1648
+
1649
+ def event_problems(table):
1650
+ """The event rows of the table against the design's, and the handlers against the rows."""
1651
+ rows = table.get("events", [])
1652
+ problems = [f"CONTRACT_MISMATCH events (design §12.3): row {n} is {(r['from'], r['event'], r['to'])}, the design says {want}"
1653
+ for n, (r, want) in enumerate(zip(rows, DESIGN_12_3_EVENTS)) if (r["from"], r["event"], r["to"]) != want]
1654
+ if len(rows) != len(DESIGN_12_3_EVENTS):
1655
+ problems.append(f"CONTRACT_MISMATCH events (design §12.3): {len(rows)} rows, the design has {len(DESIGN_12_3_EVENTS)}")
1656
+ if [r["id"] for r in rows] != list(EVENTS):
1657
+ problems.append(f"CONTRACT_MISMATCH events (design §12.3): the handlers {list(EVENTS)} differ from the rows' ids {[r['id'] for r in rows]}")
1658
+ return problems
1659
+
1660
+
1661
+ @contextlib.contextmanager
1662
+ def scratch_git():
1663
+ """A scratch repository with every GIT_* variable scrubbed: the pre-commit hook exports them, and
1664
+ a repository initialised under them would rewrite the real one (AGENTS.md traps)."""
1665
+ saved = {k: os.environ.pop(k) for k in list(os.environ) if k.startswith("GIT_")}
1666
+ try:
1667
+ with tempfile.TemporaryDirectory() as td:
1668
+ def git(*args, check=True):
1669
+ done = subprocess.run(["git", "-C", td, "-c", "user.email=t@t", "-c", "user.name=t", *args],
1670
+ capture_output=True, text=True)
1671
+ assert not check or done.returncode == 0, f"git {args}: {done.stderr}"
1672
+ return done
1673
+ git("init", "-q")
1674
+ yield pathlib.Path(td), git
1675
+ finally:
1676
+ os.environ.update(saved)
1677
+
1678
+
1679
+ def legacy_element(field="decision", disposition="unknown", **extra):
1680
+ """A decisions[] element design §12.2 migrates from a schema 1 field."""
1681
+ element = sample_element("legacy-2026-08-25", disposition, applied=False, approval="legacy",
1682
+ **{"at": "2026-08-25", "field": field, "legacy_text": "user-approved-default 2026-08-25", **extra})
1683
+ if element["applied"] is not None: # a legacy application carries one, and it records nothing
1684
+ element["applied"].pop("before", None)
1685
+ return element
1686
+
1687
+
1688
+ def migration_element(status, **extra):
1689
+ """The element a migrated entry ends its legacy decisions with: its status when it was migrated."""
1690
+ return legacy_element("status", "unknown", kind="legacy_migration", legacy_status=status, legacy_text=status, **extra)
1691
+
1692
+
1693
+ # The hard-kill fixture this module's self-test runs: a real process that proposes a successor and
1694
+ # dies before the rename, so bytes that are still the base afterwards say the rename had not
1695
+ # happened (X#1). An inline `python -c` program is admitted by DECLARATION
1696
+ # (`runlib/dispatch.py` `INLINE_PROGRAMS`, which pins its sha256), so its text is FIXED and the four
1697
+ # values it used to interpolate arrive as its own argv (r3 S3). A test fixture; nothing in this
1698
+ # module's behaviour reads it.
1699
+ HARD_KILL = (
1700
+ "import json, os, sys, pathlib\n"
1701
+ "here, target, current, lock_root = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]\n"
1702
+ "sys.path.insert(0, here)\n"
1703
+ "from runlib import ledger\n"
1704
+ "doc = json.loads(pathlib.Path(target).read_text())\n"
1705
+ "proposed = ledger.apply_decision(doc, 'S3-2', ledger.sample_element('r2', 'correct'))\n"
1706
+ "ledger.write_atomic(target, proposed, current, lock_root, before_rename=lambda: os._exit(9))\n")
1707
+
1708
+
1709
+ def self_test(migrate=None, checkout_ledger=None, tiny=None):
1710
+ """The contract legs, plus the two that need a CHECKOUT: the schema 1 migration (an author-side
1711
+ script) and the committed ledger itself. Both are passed in by `gates/check-ledger.py`; without
1712
+ them those legs are reported as skipped BY NAME rather than quietly dropped, which is also what an
1713
+ installed tree gets (WP-24's installed-self-test rule)."""
1714
+ skipped = []
1715
+ failures = []
1716
+ ran = {"events": {}, "effects": set()}
1717
+
1718
+ def expect(label, problems, *needles):
1719
+ """`problems` must name every needle; an empty list for a case that must fail is a failure."""
1720
+ text = "\n".join(problems)
1721
+ for needle in needles:
1722
+ if needle not in text:
1723
+ failures.append(f"{label}: expected {needle!r} among {problems or 'no violation'}")
1724
+
1725
+ def clean(label, problems):
1726
+ if problems:
1727
+ failures.append(f"{label}: expected no violation, got {problems}")
1728
+
1729
+ def refuses(label, call, *needles):
1730
+ try:
1731
+ call()
1732
+ except LedgerError as exc:
1733
+ expect(label, [str(exc)], *needles)
1734
+ except Exception as exc: # a refusal carries its code; a bare exception is reported, not raised
1735
+ failures.append(f"{label}: raised {type(exc).__name__} ({exc}) instead of a refusal naming {needles}")
1736
+ else:
1737
+ failures.append(f"{label}: accepted although {needles} was due")
1738
+
1739
+ def accepts(label, call):
1740
+ try:
1741
+ return call()
1742
+ except LedgerError as exc:
1743
+ failures.append(f"{label}: refused: {exc}")
1744
+
1745
+ def event_case(event, outcome):
1746
+ ran["events"].setdefault(event, set()).add(outcome)
1747
+
1748
+ placed = sample_entry("S3-1")
1749
+ base = sample_ledger(placed, sample_entry("S3-2", "incubating"), sample_entry("S3-3", "incubating"))
1750
+
1751
+ # contract fidelity: the schema holds the design's field lists and vocabularies, and the checker can tell
1752
+ doc = schema()
1753
+ clean("schema against design §12.1/§12.2/§12.4/§7.2", contract_problems(doc))
1754
+ clean("expected_observation against §7.3", eo_mismatch(doc))
1755
+ clean("the record contracting what schema 2 carries beyond design §12.1", addendum_problems())
1756
+ clean("the record of the owner's decision on what a revert puts back", record_problems())
1757
+ record_text = (REPO / RECORD).read_text(encoding="utf-8") if (REPO / RECORD).is_file() else ""
1758
+ for token in ("applied.before", "REVERT_INVERSE_UNPROVABLE", "TRANSACTION_MULTIPLE_APPLICATIONS",
1759
+ "BEFORE_MISSING", "BEFORE_FIELD_OVERLAP", "REVERT_MERGE_SIDE", "standing_decision",
1760
+ "REVERT_MERGE_UNPAIRED", "TRANSACTION_INVALID", "BASE_UNREADABLE"):
1761
+ expect(f"the record silent about {token}", record_problems(record_text.replace(token, "it")), f"RECORD_SILENT {RECORD}", token)
1762
+ expect("a record that supersedes nothing", record_problems(record_text.replace("supersedes: 2026", "supersedes: null # 2026")),
1763
+ f"RECORD_UNANCHORED {RECORD}")
1764
+ expect("no record at all of that decision", record_problems(rel="design/session-distill/no-such-record.md"), "RECORD_MISSING")
1765
+ addendum_text = (REPO / ADDENDUM).read_text(encoding="utf-8") if (REPO / ADDENDUM).is_file() else ""
1766
+ for token in ("`legacy_placed`", "`kind: legacy_migration`", "`reason`"):
1767
+ expect(f"the record silent about {token}", addendum_problems(addendum_text.replace(token, "it")), f"ADDENDUM_SILENT {ADDENDUM}", token)
1768
+ expect("no record at all", addendum_problems(rel="design/session-distill/no-such-addendum.md"), "ADDENDUM_MISSING")
1769
+ # a property contracted by a record of its own (WP-09 commit 3): ADDENDUM is not asked for it, its record is
1770
+ clean("each property a record of its own contracts", field_record_problems())
1771
+ expect("the record of resolves silent about it", field_record_problems({"resolves": "a decision names what it settles"}),
1772
+ f"FIELD_RECORD_SILENT {FIELD_RECORDS['resolves']}")
1773
+ expect("no record of resolves at all", field_record_problems(field_records={"resolves": "design/session-distill/no-such-record.md"}),
1774
+ "FIELD_RECORD_MISSING design/session-distill/no-such-record.md")
1775
+ expect("a record contracting a property a decision does not carry", field_record_problems(
1776
+ texts={"surfaced": "`surfaced`"}, field_records={"surfaced": FIELD_RECORDS["resolves"]}), "FIELD_RECORD_STALE")
1777
+ clean("ADDENDUM is not asked for a property a record of its own contracts", addendum_problems(addendum_text.replace("`resolves`", "")))
1778
+ # design §7.1's resolves (WP-09 commit 3): a run's decision names the earlier incubate of its own entry it resolves.
1779
+ # A subject that raises is reported under its control's name, never as a traceback ending the suite.
1780
+ def run_rules(call):
1781
+ try:
1782
+ return call()
1783
+ except Exception as exc: # noqa: BLE001 - reported by the control that reads it
1784
+ return [f"RAISED {exc!r}"]
1785
+ incubate = sample_element("r1", "incubate", observation=sample_observation("2026-11-30"))
1786
+ later = sample_element("r2", "drop", reason="expired and not seen", resolves="S3-1@r1")
1787
+ clean("a drop resolving the incubate an earlier run made on the entry", run_rules(lambda: validate_ledger(sample_ledger(
1788
+ sample_entry("S3-1", "retired", decisions=[incubate, later])))))
1789
+ intervention = sample_element("r1", "incubate", observation=sample_observation("2026-11-30"))
1790
+ pending_placed = sample_ledger(sample_entry("P-1", "placed", decisions=[sample_element("r0", "place"), intervention]))
1791
+ clean("a pending intervention on a placed entry", validate_ledger(pending_placed))
1792
+ clean("unresolved_incubates lists the pending intervention on a placed entry by <entry>@<run>",
1793
+ [] if [(d["decision_id"], d["status"], d["expiry"]) for d in unresolved_incubates(pending_placed)]
1794
+ == [("P-1@r1", "placed", "2026-11-30")] else [f"listed {unresolved_incubates(pending_placed)}"])
1795
+ resolved_ledger = sample_ledger(sample_entry("S3-1", "retired", decisions=[incubate, later]))
1796
+ clean("unresolved_incubates leaves out an incubate a later decision resolves",
1797
+ [] if unresolved_incubates(resolved_ledger) == [] else [f"listed {unresolved_incubates(resolved_ledger)}"])
1798
+ open_ledger = sample_ledger(sample_entry("S3-1", "incubating", decisions=[incubate]))
1799
+ clean("unresolved_incubates lists an incubate nothing resolves",
1800
+ [] if [d["decision_id"] for d in unresolved_incubates(open_ledger)] == ["S3-1@r1"] else [f"{unresolved_incubates(open_ledger)}"])
1801
+ for label, decisions, needle in (
1802
+ ("a decision resolving another entry's incubate", [incubate, {**later, "resolves": "S3-9@r1"}], "RESOLVES_OTHER_ENTRY S3-1 decisions[1]"),
1803
+ ("a decision resolving a run that decided nothing here", [incubate, {**later, "resolves": "S3-1@r7"}], "RESOLVES_DANGLING S3-1 decisions[1]"),
1804
+ ("a decision resolving itself", [incubate, {**later, "resolves": "S3-1@r2"}], "RESOLVES_NOT_EARLIER S3-1 decisions[1]"),
1805
+ ("a decision resolving one that is not an incubate",
1806
+ [sample_element("r1", "place"), {**later, "resolves": "S3-1@r1"}], "RESOLVES_NOT_INCUBATE S3-1 decisions[1]"),
1807
+ ("two decisions resolving one incubate",
1808
+ [incubate, sample_element("r2", "incubate", observation=sample_observation(), resolves="S3-1@r1"),
1809
+ {**later, "run": "r3", "resolves": "S3-1@r1"}], "RESOLVES_TWICE S3-1 decisions[2]")):
1810
+ expect(label, run_rules(lambda decisions=decisions: resolves_problems(sample_entry("S3-1", "incubating", decisions=decisions))), needle)
1811
+ expect("validate_ledger holds the resolves rules", run_rules(lambda: validate_ledger(sample_ledger(sample_entry("S3-1", "retired", decisions=[
1812
+ incubate, {**later, "resolves": "S3-1@r7"}])))), "RESOLVES_DANGLING S3-1 decisions[1]")
1813
+ expect("a migrated element naming what it resolves", run_rules(lambda: validate_ledger(sample_ledger(sample_entry("M-1", "incubating", decisions=[
1814
+ {**legacy_element(), "resolves": "M-1@r1"}, migration_element("incubating")])))), "RESOLVES_ON_LEGACY M-1 decisions[0]")
1815
+ expect("a resolves that is no <entry>@<run>", run_rules(lambda: validate_ledger(sample_ledger(sample_entry("S3-1", "retired", decisions=[
1816
+ incubate, {**later, "resolves": "r1"}])))), "does not match '^[A-Z]+[0-9]*-[0-9]+@.+$'")
1817
+ for label, mutate, needle in (
1818
+ ("a field dropped from the entry's required set", lambda d: d["$defs"]["entry"]["required"].remove("keep"), "required lacks ['keep']"),
1819
+ ("a ninth key in the element's required set", lambda d: d["$defs"]["decision"]["required"].append("at"), "required adds ['at']"),
1820
+ ("a key dropped from the element's required set", lambda d: d["$defs"]["decision"]["required"].remove("tests"), "required lacks ['tests']"),
1821
+ ("a property dropped from applied", lambda d: d["$defs"]["applied"]["properties"].pop("delivery"), "properties lacks ['delivery']"),
1822
+ ("legacy_status dropped from the element", lambda d: d["$defs"]["decision"]["properties"].pop("legacy_status"), "properties lacks ['legacy_status']"),
1823
+ ("legacy_status values differing from the entry's", lambda d: d["$defs"]["decision"]["properties"]["legacy_status"]["enum"].append("done"),
1824
+ "CONTRACT_MISMATCH legacy_status"),
1825
+ ("a property dropped from the evidence item", lambda d: d["$defs"]["evidence_item"]["properties"].pop("evidence_id"), "properties lacks ['evidence_id']"),
1826
+ ("a legacy value leaking into the current vocabulary", lambda d: d["$defs"]["disposition"]["enum"].append("unknown"), "CONTRACT_MISMATCH disposition (design §7.2)"),
1827
+ ("a current value dropped from the vocabulary", lambda d: d["$defs"]["disposition"]["enum"].remove("drop"), "CONTRACT_MISMATCH disposition (design §7.2)"),
1828
+ ("an entry taking the legacy vocabulary", lambda d: d["$defs"]["entry"]["properties"].update(disposition={"$ref": "#/$defs/legacy_disposition"}),
1829
+ "an entry takes the current vocabulary only"),
1830
+ ("a decision taking the current vocabulary", lambda d: d["$defs"]["decision"]["properties"].update(disposition={"$ref": "#/$defs/disposition"}),
1831
+ "a decision takes the vocabulary with the two legacy values"),
1832
+ ("a legacy-only property the schema does not mark", lambda d: d["$defs"]["decision"]["properties"]["at"].pop("$comment"),
1833
+ "CONTRACT_MISMATCH decision (ADDENDUM §1)"),
1834
+ ("a property of both shapes marked as a migrated element's",
1835
+ lambda d: d["$defs"]["decision"]["properties"]["reason"].update({"$comment": LEGACY_MARK}), "CONTRACT_MISMATCH decision (ADDENDUM §1)"),
1836
+ ("the comment citing another section", lambda d: d.update({"$comment": "design §9"}), "does not cite design §12.1"),
1837
+ ("a field a disposition licenses that the before record cannot name",
1838
+ lambda d: d["$defs"]["before_row"]["properties"]["fields"]["properties"].pop("keep"), "CONTRACT_MISMATCH before_row (RECORD)"),
1839
+ ("a before record naming a field no disposition licenses",
1840
+ lambda d: (d["$defs"]["before_row"]["properties"]["fields"]["properties"].update(surfaced={"type": "string"}),
1841
+ d["$defs"]["before_row"]["properties"]["absent"]["items"]["enum"].append("surfaced")), "CONTRACT_MISMATCH before_row (RECORD)"),
1842
+ ("a before record whose two parts name different fields",
1843
+ lambda d: d["$defs"]["before_row"]["properties"]["absent"]["items"]["enum"].remove("keep"), "CONTRACT_MISMATCH before_row (RECORD)"),
1844
+ ("the before record not citing the decision that added it",
1845
+ lambda d: d["$defs"]["before_row"].update({"$comment": "what a revert puts back"}), "its comment does not cite the decision")):
1846
+ broken = copy.deepcopy(doc)
1847
+ mutate(broken)
1848
+ expect(label, contract_problems(broken), needle)
1849
+ mutated = copy.deepcopy(doc)
1850
+ mutated["$defs"]["expected_observation"]["properties"].pop("expiry")
1851
+ expect("expected_observation losing a §7.3 field", eo_mismatch(mutated), "properties differ")
1852
+ mutated = copy.deepcopy(doc)
1853
+ mutated["$defs"]["expected_observation"]["required"].remove("expiry")
1854
+ expect("expected_observation losing a §7.3 requirement", eo_mismatch(mutated), "required differs")
1855
+
1856
+ # validation: a conforming ledger first, then one rejection per rule
1857
+ clean("a conforming schema 2 ledger", validate_ledger(base))
1858
+ clean("a conforming schema 1 ledger", validate_ledger({"schema": 1, "entries": [{"id": "S3-1", "status": "placed"}]}))
1859
+ eight = sample_element("r1", "none")
1860
+ clean("an element with exactly design §12.1's eight keys", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[eight]))))
1861
+ expect("an element lacking one of the eight keys", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1862
+ {k: v for k, v in eight.items() if k != "tests"}]))), "'tests' is a required property")
1863
+ dropped = copy.deepcopy(base)
1864
+ del dropped["entries"][0]["keep"]
1865
+ expect("an entry missing a required field", validate_ledger(dropped), "LEDGER_INVALID", "'keep' is a required property")
1866
+ extra = copy.deepcopy(base)
1867
+ extra["entries"][0]["strength"] = 3
1868
+ expect("a legacy field left on an entry", validate_ledger(extra), "Additional properties", "strength")
1869
+ expect("an unsupported schema", validate_ledger({"schema": 3, "entries": []}), "LEDGER_SCHEMA_UNSUPPORTED")
1870
+ expect("schema 1 entries not a list", validate_ledger({"schema": 1, "entries": {}}), "LEDGER_INVALID entries")
1871
+ expect("a schema 1 entry without a status", validate_ledger({"schema": 1, "entries": [{"id": "S3-1"}]}), "LEDGER_INVALID entries[0]")
1872
+ expect("a duplicate id in schema 1", validate_ledger({"schema": 1, "entries": [{"id": "S3-1", "status": "p"}, {"id": "S3-1", "status": "p"}]}), "ID_DUPLICATE S3-1")
1873
+ expect("a duplicate id in schema 2", validate_ledger(sample_ledger(sample_entry("S3-1"), sample_entry("S3-1"))), "ID_DUPLICATE S3-1")
1874
+ expect("one run deciding an entry twice", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1875
+ sample_element("r1", "none"), sample_element("r1", "none")]))), "DECISION_RUN_DUPLICATE S3-1 decisions[1]")
1876
+ clean("legacy runs repeating", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1877
+ legacy_element("decision"), legacy_element("decision1", approval_id="unavailable")]))))
1878
+ expect("a run decision without an approval row", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1879
+ sample_element("r1", "none", approval="legacy")]))), "DECISION_UNAPPROVED S3-1 decisions[0]")
1880
+ expect("a relation to no entry", validate_ledger(sample_ledger(sample_entry("S3-1", relations={"instance_of": "G-9"}))), "RELATION_DANGLING S3-1 instance_of")
1881
+ expect("an absorption by no entry", validate_ledger(sample_ledger(sample_entry("S3-1", absorbed_by="G-9"))), "RELATION_DANGLING S3-1 absorbed_by")
1882
+ expect("a window run id twice", validate_ledger(sample_ledger(windows=[
1883
+ {"start": None, "end": "2026-09-01", "run_id": "w", "kind": "periodic", "commit": None, "accounted": None, "fully_read": None}] * 2)), "WINDOW_DUPLICATE w")
1884
+ misplaced = sample_ledger(sample_entry("S3-1", decisions=[sample_element("r1", "incubate", observation={
1885
+ **sample_observation(), "resolutions": [sample_resolution("r2")]})]))
1886
+ expect("a resolution under another run's decision", validate_ledger(misplaced), "RESOLUTION_MISPLACED S3-1 decisions[0]")
1887
+
1888
+ # the two vocabularies (F#2): design §7.2's for everything current, the legacy values only in legacy elements
1889
+ clean("a legacy element with disposition unknown and a null date", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1890
+ legacy_element(disposition="unknown", at=None), legacy_element("decision3", disposition="revival")]))))
1891
+ for value in ("unknown", "revival"):
1892
+ expect(f"a run's decision with the legacy value {value}", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1893
+ sample_element("r1", value)]))), "DISPOSITION_NOT_CURRENT S3-1 decisions[0]")
1894
+ expect(f"an entry with the legacy value {value}", validate_ledger(sample_ledger(sample_entry("S3-1", disposition=value))), "LEDGER_INVALID", "is not one of")
1895
+ expect("a value outside both vocabularies", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1896
+ legacy_element(disposition="adopt")]))), "LEDGER_INVALID", "'adopt' is not one of")
1897
+ expect("a legacy element without the date design §12.2 gives it", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1898
+ {k: v for k, v in legacy_element().items() if k != "at"}]))), "LEGACY_ELEMENT_INCOMPLETE S3-1 decisions[0]", "at")
1899
+ expect("a legacy element without its field name", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1900
+ {k: v for k, v in legacy_element().items() if k != "field"}]))), "LEGACY_ELEMENT_INCOMPLETE S3-1 decisions[0]", "field")
1901
+ # the two shapes (ADDENDUM §1): design §12.2's metadata belongs to a migrated element, the kind
1902
+ # revert to a decision a run made, and neither crosses
1903
+ legacy_values = {"at": "2026-08-25", "field": "decision", "legacy_text": "user-approved-default 2026-08-25",
1904
+ "legacy_placed": "2026-07-19", "legacy_status": "incubating", "status_note": "set without a recorded revival"}
1905
+ for legacy_property in LEGACY_PROPERTIES: # a value the schema itself accepts, so the refusal is this rule's
1906
+ expect(f"a run's decision carrying {legacy_property}", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1907
+ sample_element("r1", "none", **{legacy_property: legacy_values[legacy_property]})]))),
1908
+ "LEGACY_FIELD_ON_MODERN S3-1 decisions[0]", legacy_property)
1909
+ expect("a migrated element marked a revert", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1910
+ legacy_element(kind="revert")]))), "LEGACY_KIND_ON_REVERT S3-1 decisions[0]")
1911
+ # legacy_placed is the date of the application its own element carries (F#4): design §12.2 attaches
1912
+ # `placed` to the latest place decision, or to a legacy_application when the entry has no place decision
1913
+ applied_record = {"commit": None, "paths": [], "operations": [], "delivery": "unverified"}
1914
+ for label, element in (("a migrated place decision", {**legacy_element("decision1"), "applied": applied_record, "legacy_placed": "2026-09-01"}),
1915
+ ("a legacy application", {**legacy_element("placed", kind="legacy_application"), "applied": applied_record, "legacy_placed": "2026-09-01"})):
1916
+ clean(f"{label} carrying the date its application happened", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[element]))))
1917
+ for label, element in (
1918
+ ("a migrated element that records no application", legacy_element("decision1", legacy_placed="2026-09-01")),
1919
+ ("a historical retirement", {**legacy_element("retired", kind="legacy_retirement"), "applied": applied_record, "legacy_placed": "2026-09-01"}),
1920
+ ("the migration element", {**migration_element("placed"), "applied": applied_record, "legacy_placed": "2026-09-01"})):
1921
+ expect(f"legacy_placed on {label}", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[element]))),
1922
+ "LEGACY_PLACED_MISPLACED S3-1 decisions[0]")
1923
+ expect("an incubate without its observation", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1924
+ sample_element("r1", "incubate")]))), "INCUBATE_WITHOUT_OBSERVATION S3-1 decisions[0]")
1925
+ for disposition in ("keep", "drop"):
1926
+ expect(f"a {disposition} without its reason", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1927
+ sample_element("r1", disposition)]))), f"REASON_REQUIRED S3-1 decisions[0]")
1928
+ expect("a revert that is not an applied none", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1929
+ sample_element("r1", "place", kind="revert")]))), "REVERT_MALFORMED S3-1 decisions[0]")
1930
+ expect("a status its decisions do not reach", validate_ledger(sample_ledger(sample_entry("S3-1", "retired", decisions=[
1931
+ sample_element("r1", "place")]))), "HISTORY_INCONSISTENT S3-1")
1932
+ expect("a revert with nothing before it to revert", validate_ledger(sample_ledger(sample_entry("S3-1", decisions=[
1933
+ sample_element("r1", "none", kind="revert")]))), "HISTORY_INCONSISTENT S3-1")
1934
+ refuses("a revert over a history that does not replay", lambda: revert_target(
1935
+ sample_entry("S3-1", "retired", decisions=[sample_element("r1", "place")]), "retired"), "REPLAY_INCONSISTENT S3-1")
1936
+ # the status an entry was migrated at: exactly one element, before any run decision, in the status vocabulary
1937
+ clean("a migrated entry with its migration element", validate_ledger(sample_ledger(sample_entry("M-1", "incubating", decisions=[
1938
+ legacy_element(), migration_element("incubating")]))))
1939
+ expect("a migration element without its status", validate_ledger(sample_ledger(sample_entry("M-1", "incubating", decisions=[
1940
+ {k: v for k, v in migration_element("incubating").items() if k != "legacy_status"}]))), "LEGACY_ELEMENT_INCOMPLETE M-1 decisions[0]", "legacy_status")
1941
+ expect("legacy_status on another legacy kind", validate_ledger(sample_ledger(sample_entry("M-1", decisions=[
1942
+ legacy_element(kind="legacy_application", legacy_status="placed")]))), "LEGACY_STATUS_MISPLACED M-1 decisions[0]")
1943
+ expect("legacy_status on a run decision", validate_ledger(sample_ledger(sample_entry("M-1", decisions=[
1944
+ sample_element("r1", "none", legacy_status="placed")]))), "LEGACY_FIELD_ON_MODERN M-1 decisions[0]")
1945
+ expect("a migration status outside the vocabulary", validate_ledger(sample_ledger(sample_entry("M-1", decisions=[
1946
+ migration_element("done")]))), "LEDGER_INVALID", "'done' is not one of")
1947
+ expect("two migration elements", validate_ledger(sample_ledger(sample_entry("M-1", "incubating", decisions=[
1948
+ migration_element("incubating"), migration_element("incubating")]))), "LEGACY_MIGRATION_DUPLICATE M-1")
1949
+ expect("a migration element after a run decision", validate_ledger(sample_ledger(sample_entry("M-1", decisions=[
1950
+ sample_element("r1", "correct"), migration_element("placed")]))), "LEGACY_MIGRATION_LATE M-1 decisions[1]")
1951
+ expect("an entry whose status is not the one it was migrated at and no decision moved it", validate_ledger(sample_ledger(sample_entry(
1952
+ "M-1", "placed", decisions=[migration_element("incubating")]))), "HISTORY_INCONSISTENT M-1")
1953
+
1954
+ # evidence references (F#3): claim and evidence ids together, or the explicit unavailable form, never a part
1955
+ for label, item in (("a claim id with its evidence id", {"claim_id": "c-1", "evidence_id": "e-1"}),
1956
+ ("the unavailable form of a legacy supporting session", {"locator": "unavailable", "session": "claude:1"})):
1957
+ clean(label, validate_ledger(sample_ledger(sample_entry("S3-1", evidence=[item]))))
1958
+ for label, item, needles in (
1959
+ ("a claim id with no evidence id", {"claim_id": "c-1"}, ("LEDGER_INVALID", "evidence_id")),
1960
+ ("an evidence id with no claim id", {"evidence_id": "e-1"}, ("LEDGER_INVALID", "claim_id")),
1961
+ ("an unavailable locator with no session", {"locator": "unavailable"}, ("LEDGER_INVALID", "session")),
1962
+ ("both forms in one item", {"claim_id": "c-1", "evidence_id": "e-1", "locator": "unavailable", "session": "claude:1"}, ("EVIDENCE_FORM S3-1 evidence[0]",)),
1963
+ ("an empty item", {}, ("LEDGER_INVALID",)),
1964
+ ("a locator other than unavailable", {"locator": "somewhere", "session": "claude:1"}, ("LEDGER_INVALID",)),
1965
+ ("an unknown key", {"claim_id": "c-1", "evidence_id": "e-1", "note": "x"}, ("LEDGER_INVALID", "Additional properties"))):
1966
+ expect(label, validate_ledger(sample_ledger(sample_entry("S3-1", evidence=[item]))), *needles)
1967
+
1968
+ for label, raw in (("a list at the top", "[1]"), ("text that is not JSON", "{ nope")):
1969
+ refuses(label, lambda raw=raw: parse(raw), "LEDGER_UNREADABLE")
1970
+
1971
+ # A schema 1 base against a schema 2 head is judged by equality with the migration, which this
1972
+ # module no longer loads: the legs that need a real migration live with it, in
1973
+ # gates/check-ledger.py --self-test. What belongs here is the answer when none was given.
1974
+ # The path is a parameter, and a caller that names neither a root nor an override gets None
1975
+ # rather than a path this module invented (WP-24).
1976
+ clean("no state root and no override names no ledger", [] if ledger_path() is None else ["it named one"])
1977
+ clean("a state root names the ledger under it",
1978
+ [] if str(ledger_path(state_root="/s")) == "/s/distill/ledger.json" else [str(ledger_path(state_root="/s"))])
1979
+ clean("an override is the ledger, whatever the root",
1980
+ [] if str(ledger_path(state_root="/s", override="/elsewhere/l.json")) == "/elsewhere/l.json"
1981
+ else [str(ledger_path(state_root="/s", override="/elsewhere/l.json"))])
1982
+ expect("a comparison that needs the migration and was given none",
1983
+ check_pair({"schema": 1, "framework": "f", "window": "w", "entries": []},
1984
+ sample_ledger(sample_entry("S3-1", "placed"))),
1985
+ "MIGRATOR_UNAVAILABLE")
1986
+ if migrate is None or tiny is None:
1987
+ skipped.append("a schema 2 head judged by equality with the migration of its schema 1 base "
1988
+ "(needs the author-side migrator and its schema 1 sample)")
1989
+ else:
1990
+ legacy_one = tiny()
1991
+ migrated_one, _ = migrate(legacy_one)
1992
+ clean("a schema 2 head that is the migration of its schema 1 base",
1993
+ check_pair(legacy_one, migrated_one, migrate=migrate))
1994
+ tampered_one = copy.deepcopy(migrated_one)
1995
+ tampered_one["entries"][0]["lesson"] = "tampered"
1996
+ expect("a schema 2 head that is not the migration of its base",
1997
+ check_pair(legacy_one, tampered_one, migrate=migrate), "MIGRATION_MISMATCH")
1998
+
1999
+ # the id-set check (design §12.4, O10): schema 1 continues a series; schema 2 needs the frozen allocation
2000
+ ids = ["S3-1", "S3-2", "S3-3"]
2001
+ clean("identical id sets", id_set_violations(ids, ids))
2002
+ clean("a schema 1 series continuing at the next number", id_set_violations(ids, ids + ["S3-4", "G-1"], numbered=True))
2003
+ expect("a schema 1 equal-count deletion plus insertion", id_set_violations(ids, ["S3-1", "S3-2", "S3-4"], numbered=True), "ID_LOST S3-3")
2004
+ expect("a schema 1 id past the next number", id_set_violations(ids, ids + ["S3-9"], numbered=True), "ID_UNALLOCATED S3-9")
2005
+ expect("a schema 1 id reusing a gap", id_set_violations(["S3-1", "S3-3"], ["S3-1", "S3-2", "S3-3"], numbered=True), "ID_UNALLOCATED S3-2")
2006
+ expect("a schema 1 id outside every series", id_set_violations(ids, ids + ["new"], numbered=True), "ID_UNALLOCATED new")
2007
+ expect("a schema 2 id continuing a series with no allocation", id_set_violations(ids, ids + ["S3-4"]), "ALLOCATION_REQUIRED")
2008
+ clean("a schema 2 ledger validated against no base needs no allocation", id_set_violations(ids, ids))
2009
+ expect("a schema 2 transaction that added no id and froze no allocation", id_set_violations(ids, ids, transaction=True), "ALLOCATION_REQUIRED")
2010
+ clean("a schema 2 transaction whose frozen allocation is explicitly empty", id_set_violations(ids, ids, allocated=[], transaction=True))
2011
+ expect("a frozen allocation that produced no row", id_set_violations(ids, ids, allocated=["S3-7"], transaction=True), "ID_ALLOCATED_MISSING S3-7")
2012
+ clean("exactly the allocated ids", id_set_violations(ids, ids + ["S3-7"], allocated=["S3-7"]))
2013
+ clean("an allocation that skips numbers", id_set_violations(ids, ids + ["S3-7", "N-1"], allocated=["N-1", "S3-7"]))
2014
+ expect("an id outside the allocation", id_set_violations(ids, ids + ["S3-4"], allocated=["S3-7"]), "ID_UNALLOCATED S3-4", "ID_ALLOCATED_MISSING S3-7")
2015
+ expect("an allocated id the ledger never gained", id_set_violations(ids, ids, allocated=["S3-7"]), "ID_ALLOCATED_MISSING S3-7")
2016
+ expect("an allocated id the base already holds", id_set_violations(ids, ids + ["S3-4"], allocated=["S3-4", "S3-2"]), "ID_ALLOCATED_EXISTING S3-2")
2017
+ expect("an equal-count deletion plus insertion under an allocation", id_set_violations(ids, ["S3-1", "S3-2", "S3-4"], allocated=["S3-4"]), "ID_LOST S3-3")
2018
+ expect("a duplicate id", check_pair(base, sample_ledger(*base["entries"], sample_entry("S3-2"))), "ID_DUPLICATE S3-2")
2019
+
2020
+ # changed rows between schema 2 ledgers (F#1): what was appended licenses a change, and only that change
2021
+ def changed(label, mutate, *needles, expect_clean=False, over=None, allocated=()):
2022
+ """A transaction over `over`: the run froze an allocation, empty unless the case says otherwise."""
2023
+ start = over or base
2024
+ head = copy.deepcopy(start)
2025
+ mutate(head)
2026
+ found = check_pair(start, head, None if allocated is None else list(allocated))
2027
+ (clean if expect_clean else lambda lab, p: expect(lab, p, *needles))(label, found)
2028
+
2029
+ def bound(h, i, element, **fields):
2030
+ """Append `element` to entry i the way apply_decision does: the entry says what the decision
2031
+ says, and the decision records what its own change replaced (`applied.before`)."""
2032
+ was = copy.deepcopy(h["entries"][i])
2033
+ h["entries"][i].update(fields)
2034
+ element = copy.deepcopy(element)
2035
+ if element["applied"] is not None and not is_legacy(element):
2036
+ element["applied"]["before"] = before_record(was, h["entries"][i])
2037
+ h["entries"][i]["decisions"].append(element)
2038
+
2039
+ changed("an unchanged ledger", lambda h: None, expect_clean=True)
2040
+ changed("a field edited with no decision", lambda h: h["entries"][0].update(lesson="edited"), "ROW_FIELD_UNLICENSED S3-1 lesson")
2041
+ changed("a status moved with no decision", lambda h: h["entries"][1].update(status="placed"),
2042
+ "ROW_FIELD_UNLICENSED S3-2 status", "STATUS_UNEXPLAINED S3-2")
2043
+ changed("an applied correct that moves nothing", lambda h: bound(h, 0, sample_element("r1", "correct"), disposition="correct"), expect_clean=True)
2044
+ # the frozen allocation (C#4): a schema 2 run that writes at all carries one, empty or not
2045
+ changed("that same transaction with no allocation frozen", lambda h: bound(
2046
+ h, 0, sample_element("r1", "correct"), disposition="correct"), "ALLOCATION_REQUIRED", allocated=None)
2047
+ changed("that same transaction under an allocation that produced no row", lambda h: bound(
2048
+ h, 0, sample_element("r1", "correct"), disposition="correct"), "ID_ALLOCATED_MISSING S3-7", allocated=["S3-7"])
2049
+ changed("an applied decision the entry does not say it holds", lambda h: bound(h, 0, sample_element("r1", "correct")), "DISPOSITION_UNBOUND S3-1")
2050
+ changed("an unapplied decision alone", lambda h: bound(h, 0, sample_element("r1", "place", applied=False)), expect_clean=True)
2051
+ changed("an unapplied decision licensing an unrelated edit", lambda h: bound(
2052
+ h, 0, sample_element("r1", "place", applied=False), lesson="edited"), "ROW_FIELD_UNLICENSED S3-1 lesson")
2053
+ changed("an unapplied decision licensing a status change", lambda h: bound(
2054
+ h, 1, sample_element("r1", "place", applied=False), status="placed"), "ROW_FIELD_UNLICENSED S3-2 status", "STATUS_UNEXPLAINED S3-2")
2055
+ # an application stands whatever its delivery check found (design §10.6, ADDENDUM §3): it moves the
2056
+ # status and licenses what its disposition licenses, exactly as a verified one does
2057
+ changed("a correct whose delivery failed revising the text it corrected", lambda h: bound(
2058
+ h, 0, sample_element("r1", "correct", delivery="failed"), disposition="correct", lesson="edited"), expect_clean=True)
2059
+ changed("a place whose delivery went unverified moving the status", lambda h: bound(
2060
+ h, 1, sample_element("r1", "place", delivery="unverified"), status="placed", disposition="place"), expect_clean=True)
2061
+ changed("a decision whose delivery failed licensing a field its disposition does not", lambda h: bound(
2062
+ h, 0, sample_element("r1", "correct", delivery="failed"), disposition="correct", window="2026-09-01"), "ROW_FIELD_UNLICENSED S3-1 window")
2063
+ changed("an applied decision licensing an unrelated field", lambda h: bound(
2064
+ h, 1, sample_element("r1", "place"), status="placed", disposition="place", window="2026-09-01"), "ROW_FIELD_UNLICENSED S3-2 window")
2065
+ changed("an applied decision licensing its own status and fields", lambda h: bound(
2066
+ h, 1, sample_element("r1", "place"), status="placed", disposition="place"), expect_clean=True)
2067
+ # the licence is the decision's own disposition (C#3, ADDENDUM §3): positive first, then the edit it
2068
+ # does not carry. An applied `none` changes nothing; an incubated or dropped intervention on a placed
2069
+ # entry leaves what is installed alone.
2070
+ changed("an applied none on a placed entry", lambda h: bound(h, 0, sample_element("r1", "none"), disposition="none"), expect_clean=True)
2071
+ changed("an applied none rewriting the installed text", lambda h: bound(
2072
+ h, 0, sample_element("r1", "none"), disposition="none", lesson="edited"), "ROW_FIELD_UNLICENSED S3-1 lesson")
2073
+ changed("an applied none rewriting the destination", lambda h: bound(
2074
+ h, 0, sample_element("r1", "none"), disposition="none", destination={"implementation": "x", "anchor": None, "package_id": None}),
2075
+ "ROW_FIELD_UNLICENSED S3-1 destination")
2076
+ pending = sample_element("r1", "incubate", observation=sample_observation())
2077
+ changed("a pending intervention on a placed entry", lambda h: bound(h, 0, pending, disposition="incubate"), expect_clean=True)
2078
+ changed("a pending intervention rewriting the destination", lambda h: bound(
2079
+ h, 0, pending, disposition="incubate", destination={"implementation": "x", "anchor": None, "package_id": None}),
2080
+ "ROW_FIELD_UNLICENSED S3-1 destination")
2081
+ changed("a pending intervention rewriting the installed text", lambda h: bound(
2082
+ h, 0, pending, disposition="incubate", lesson="edited"), "ROW_FIELD_UNLICENSED S3-1 lesson")
2083
+ dropped_intervention = sample_element("r1", "drop", reason="the miss is acceptable: the unit is still right")
2084
+ changed("a dropped intervention on a placed entry", lambda h: bound(h, 0, dropped_intervention, disposition="drop"), expect_clean=True)
2085
+ changed("a dropped intervention rewriting the destination", lambda h: bound(
2086
+ h, 0, dropped_intervention, disposition="drop", destination={"implementation": "x", "anchor": None, "package_id": None}),
2087
+ "ROW_FIELD_UNLICENSED S3-1 destination")
2088
+ changed("a correct revising the text it corrected", lambda h: bound(
2089
+ h, 0, sample_element("r1", "correct"), disposition="correct", lesson="edited"), expect_clean=True)
2090
+ refuses("an applied none carrying an edit of the installed text", lambda: apply_decision(
2091
+ base, "S3-1", sample_element("r1", "none"), {"lesson": "edited"}), "UPDATES_UNLICENSED S3-1", "none")
2092
+ refuses("a pending intervention carrying a new destination", lambda: apply_decision(
2093
+ base, "S3-1", pending, {"destination": {"implementation": "x", "anchor": None, "package_id": None}}),
2094
+ "UPDATES_UNLICENSED S3-1", "incubate")
2095
+ refuses("a dropped intervention carrying a new destination", lambda: apply_decision(
2096
+ base, "S3-1", dropped_intervention, {"destination": {"implementation": "x", "anchor": None, "package_id": None}}),
2097
+ "UPDATES_UNLICENSED S3-1", "drop")
2098
+ accepts("a correct carrying the text it revised", lambda: apply_decision(base, "S3-1", sample_element("r1", "correct"), {"lesson": "edited"}))
2099
+ # an element of the migration licenses nothing in a transaction (F#0): it carries no approval row,
2100
+ # and design §12.2 writes it only when the schema 1 ledger is migrated
2101
+ # the fabrication wears a disposition the table accepts, so without the rule above its edit is
2102
+ # licensed and the ledger holds a correction no approval row stands behind
2103
+ fabricated = {**legacy_element("decision1", "correct"), "applied": {"commit": None, "paths": [], "operations": [], "delivery": "unverified"}}
2104
+ changed("a run's decision licensing the same edit", lambda h: bound(
2105
+ h, 0, sample_element("r1", "correct"), disposition="correct", lesson="edited"), expect_clean=True)
2106
+ changed("a fabricated legacy element licensing a lesson edit", lambda h: bound(
2107
+ h, 0, fabricated, disposition="correct", lesson="edited"), "LEGACY_ELEMENT_APPENDED S3-1 decisions[0]", "ROW_FIELD_UNLICENSED S3-1 lesson")
2108
+ changed("a fabricated legacy element appended alone", lambda h: bound(h, 0, fabricated), "LEGACY_ELEMENT_APPENDED S3-1 decisions[0]")
2109
+ # A revert puts back what the application it undoes recorded (RECORD): one round trip per
2110
+ # disposition that changes a row, over entries whose migrated status gives the history one start,
2111
+ # each application run through production code so the record it writes is the one a revert reads.
2112
+ HOME = {"implementation": "claude/CLAUDE.md §x", "anchor": "claude/CLAUDE.md#x", "package_id": None}
2113
+ ROUTE = {"implementation": "claude/guides/x.md §y", "anchor": "claude/guides/x.md#y", "package_id": "@d1/x"}
2114
+ revert_of = sample_element("r3", "none", kind="revert")
2115
+
2116
+ def migrated(eid, status, **fields):
2117
+ return sample_entry(eid, status, decisions=[migration_element(status)], **fields)
2118
+
2119
+ def undo(ledger, eid="M-1", run="r3"):
2120
+ return apply_decision(ledger, eid, sample_element(run, "none", kind="revert"))
2121
+
2122
+ for label, start_entry, element, updates, want in (
2123
+ ("a place", migrated("M-1", "incubating", kind="gap"), sample_element("r2", "place"),
2124
+ {"destination": HOME}, {"status": "incubating", "destination": None}),
2125
+ ("a place that also sets a relation", migrated("M-1", "incubating", kind="gap"), sample_element("r2", "place"),
2126
+ {"destination": HOME, "relations": {"instance_of": "G-0"}},
2127
+ {"status": "incubating", "destination": None, "relations": {}}),
2128
+ ("a correction design §12.3 requires to revise the text",
2129
+ migrated("M-1", "incubating", kind="gap", lesson="the first lesson"), sample_element("r2", "correct"),
2130
+ {"lesson": "the corrected lesson"}, {"status": "incubating", "lesson": "the first lesson"}),
2131
+ ("a correction with no operations recorded",
2132
+ migrated("M-1", "placed", kind="misfire", destination=HOME, lesson="the first lesson"), sample_element("r2", "correct"),
2133
+ {"lesson": "the corrected lesson"}, {"status": "placed", "lesson": "the first lesson"}),
2134
+ ("a re-delivery", migrated("M-1", "placed", kind="not delivered", destination=HOME), sample_element("r2", "re-deliver"),
2135
+ {"destination": ROUTE}, {"status": "placed", "destination": HOME}),
2136
+ ("a keep", migrated("M-1", "placed", kind="confirmed"), sample_element("r2", "keep", reason="the unit still works"),
2137
+ {"keep": {"units": ["u"]}}, {"status": "placed", "keep": None}),
2138
+ ("a deletion", migrated("M-1", "placed", kind="obsolete", destination=HOME), sample_element("r2", "reduce"),
2139
+ {"retired": "2026-11-01", "retire_reason": "obsolete"}, {"status": "placed", "retired": None, "retire_reason": None}),
2140
+ ("a deletion over a retirement design §12.2 migrated",
2141
+ sample_entry("M-1", "placed", kind="obsolete", destination=HOME, retired="2026-08-09", retire_reason="superseded",
2142
+ decisions=[legacy_element("retired", kind="legacy_retirement"), migration_element("placed")]),
2143
+ sample_element("r2", "reduce"), {"retired": "2026-11-01", "retire_reason": "obsolete"},
2144
+ {"status": "placed", "retired": "2026-08-09", "retire_reason": "superseded"}),
2145
+ ("a merge", migrated("M-1", "placed", kind="misfire", destination=HOME), sample_element("r2", "reduce", operations=[MERGE]),
2146
+ {"absorbed_by": "G-0"}, {"status": "placed", "absorbed_by": None})):
2147
+ ledger = sample_ledger(start_entry, sample_entry("G-0"))
2148
+ done = accepts(f"{label} applied to a migrated entry", lambda ledger=ledger, element=element, updates=updates:
2149
+ apply_decision(ledger, "M-1", element, updates))
2150
+ if done is None:
2151
+ continue
2152
+ recorded = before_of(_rows(done)["M-1"]["decisions"][-1])
2153
+ if recorded != before_record(_rows(ledger)["M-1"], _rows(done)["M-1"]):
2154
+ failures.append(f"{label}: the decision recorded {recorded}, not what the row held before it")
2155
+ undone = accepts(f"a revert of {label}", lambda done=done: undo(done))
2156
+ if undone is None:
2157
+ continue
2158
+ row = _rows(undone)["M-1"]
2159
+ left = {field: row.get(field) for field in want}
2160
+ if left != want:
2161
+ failures.append(f"revert of {label}: the row is {left}, the record says {want}")
2162
+ if label == "a merge": # the merge wrote a decision on the receiver, so the revert reaches it too
2163
+ receiver = _rows(undone)["G-0"]
2164
+ if len(receiver["decisions"]) != 2 or receiver["decisions"][-1].get("kind") != "revert" or receiver["disposition"] != "none":
2165
+ failures.append(f"revert of a merge: the receiving entry still holds the merge it was given: {receiver['decisions']}")
2166
+ clean(f"a revert of {label}, as a transaction", check_pair(done, undone, []))
2167
+ refuses(f"a revert of {label} handed the value to put back", lambda done=done, updates=updates: apply_decision(
2168
+ done, "M-1", revert_of, updates), "REVERT_VALUE_SUPPLIED M-1", "it puts back what the application it undoes recorded")
2169
+ cheated = copy.deepcopy(done)
2170
+ cheated["entries"][0]["decisions"].append(revert_of)
2171
+ cheated["entries"][0]["disposition"] = "none"
2172
+ cheated["entries"][0]["status"] = want["status"]
2173
+ expect(f"a revert of {label} recorded without putting the row back", check_pair(done, cheated, []), "REVERT_NOT_RESTORED M-1")
2174
+ # a keep reaffirmed with the same record, and one that changes it: the earlier record comes back,
2175
+ # which is what clearing it to null used to destroy (K#0, L#4)
2176
+ for label, second in (("the same record", {"keep": {"units": ["u"]}}), ("a wider record", {"keep": {"units": ["u", "v"]}})):
2177
+ twice = accepts(f"a keep reaffirmed with {label}", lambda second=second: apply_decision(apply_decision(
2178
+ sample_ledger(migrated("M-1", "placed", kind="confirmed"), sample_entry("G-0")), "M-1",
2179
+ sample_element("r2", "keep", reason="the unit works"), {"keep": {"units": ["u"]}}),
2180
+ "M-1", sample_element("r3", "keep", reason="it still works"), second))
2181
+ if twice is None:
2182
+ continue
2183
+ back = accepts(f"a revert of the keep reaffirmed with {label}", lambda twice=twice: undo(twice, run="r4"))
2184
+ if back is not None:
2185
+ if _rows(back)["M-1"]["keep"] != {"units": ["u"]}:
2186
+ failures.append(f"revert of a keep reaffirmed with {label}: the earlier keep record is {_rows(back)['M-1']['keep']}, "
2187
+ f"not the {{'units': ['u']}} the second keep replaced")
2188
+ clean(f"a revert of the keep reaffirmed with {label}, as a transaction", check_pair(twice, back, []))
2189
+ # an application that recorded nothing: its status can be reverted and its fields cannot (RECORD)
2190
+ silent = accepts("an application recorded by hand with no before", lambda: apply_decision(
2191
+ sample_ledger(migrated("M-1", "incubating", kind="gap"), sample_entry("G-0")), "M-1", sample_element("r2", "incubate", observation=sample_observation())))
2192
+ if silent is not None:
2193
+ stripped = copy.deepcopy(silent)
2194
+ _rows(stripped)["M-1"]["decisions"][-1]["applied"].pop("before")
2195
+ refuses("a revert of an application that recorded nothing", lambda: undo(stripped),
2196
+ "REVERT_INVERSE_UNPROVABLE M-1 applied.before", "r2")
2197
+ # the record against the row change it claims to describe
2198
+ for label, mutate, needle in (
2199
+ ("a field the application changed and its record does not name", lambda b: b["fields"].pop("lesson"), "BEFORE_FIELD_MISSING"),
2200
+ ("a field its record names and the application did not change", lambda b: b["fields"].update(domain="elsewhere"), "BEFORE_FIELD_EXTRA"),
2201
+ ("a value its record gets wrong", lambda b: b["fields"].update(lesson="never there"), "BEFORE_FIELD_WRONG"),
2202
+ ("a field recorded as absent that held a value", lambda b: (b["fields"].pop("lesson"), b["absent"].append("lesson")), "BEFORE_FIELD_WRONG")):
2203
+ changed(f"a transaction whose applied.before names {label}", lambda h, mutate=mutate: mutate(
2204
+ bound(h, 0, sample_element("r1", "correct"), disposition="correct", lesson="edited") or h["entries"][0]["decisions"][-1]["applied"]["before"]),
2205
+ needle, over=sample_ledger(sample_entry("S3-1", lesson="the first lesson")))
2206
+ # an application and its revert batched into one close: the row between them is recorded nowhere
2207
+ changed("a transaction appending one applied decision", lambda h: bound(
2208
+ h, 0, sample_element("r1", "keep", reason="kept"), disposition="keep", keep={"units": ["u"]}), expect_clean=True)
2209
+ changed("a transaction appending an applied keep and its revert", lambda h: (
2210
+ bound(h, 0, sample_element("r1", "keep", reason="kept"), disposition="keep", keep={"units": ["u"]}),
2211
+ bound(h, 0, sample_element("r2", "none", kind="revert"), disposition="none")), "TRANSACTION_MULTIPLE_APPLICATIONS S3-1")
2212
+ # the receiving entry of a merge (K#2, L#3): bound to the merge's own operation, and its row put
2213
+ # back by the record that decision carries
2214
+ pre_merge = sample_ledger(migrated("M-1", "placed", kind="misfire", destination=HOME), sample_entry("G-0"))
2215
+ merged = accepts("a merge into a receiving entry", lambda: apply_decision(
2216
+ pre_merge, "M-1", sample_element("r2", "reduce", operations=[MERGE]), {"absorbed_by": "G-0"}))
2217
+ if merged is not None:
2218
+ alone = copy.deepcopy(merged)
2219
+ alone["entries"][0]["decisions"].append(revert_of)
2220
+ alone["entries"][0]["disposition"] = "none"
2221
+ alone["entries"][0].update(status="placed")
2222
+ alone["entries"][0].pop("absorbed_by", None)
2223
+ expect("the absorbed row put back and its receiver left holding the merge", check_pair(merged, alone, []),
2224
+ "RECEIVER_REVERT_MISSING G-0")
2225
+ moved_on = accepts("a correction of the receiving entry after the merge", lambda: apply_decision(
2226
+ merged, "G-0", sample_element("r3", "correct")))
2227
+ if moved_on is not None:
2228
+ refuses("a revert of the merge once the receiver has moved on", lambda: undo(moved_on, run="r4"),
2229
+ "REVERT_INVERSE_UNPROVABLE G-0 decisions", "r3")
2230
+ reverted_anyway = copy.deepcopy(moved_on)
2231
+ late = sample_element("r4", "none", kind="revert")
2232
+ absorbed_row, receiving_row = _rows(reverted_anyway)["M-1"], _rows(reverted_anyway)["G-0"]
2233
+ absorbed_row["decisions"].append(late)
2234
+ absorbed_row.update(status="placed", disposition="none")
2235
+ absorbed_row.pop("absorbed_by", None)
2236
+ receiving_row["decisions"].append(merge_receiver_revert(late, "M-1"))
2237
+ receiving_row["disposition"] = "none"
2238
+ expect("a transaction reverting a merge the receiver has moved on from", check_pair(moved_on, reverted_anyway, []),
2239
+ "REVERT_INVERSE_UNPROVABLE G-0 decisions")
2240
+ unrecorded = copy.deepcopy(merged)
2241
+ _rows(unrecorded)["G-0"]["decisions"][-1]["applied"].pop("before")
2242
+ refuses("a revert of a merge whose decision on the receiver recorded nothing", lambda: undo(unrecorded),
2243
+ "REVERT_INVERSE_UNPROVABLE G-0 applied.before", "replaced here")
2244
+ mismatched = copy.deepcopy(merged)
2245
+ _rows(mismatched)["G-0"]["decisions"][-1]["applied"]["operations"] = [{**MERGE, "operation_id": "op-9"}]
2246
+ refuses("a revert of a merge the receiver recorded under another operation", lambda: undo(mismatched),
2247
+ "REVERT_INVERSE_UNPROVABLE G-0 decisions", "op-1")
2248
+ orphaned = copy.deepcopy(merged)
2249
+ _rows(orphaned)["G-0"].update(decisions=[], disposition="none")
2250
+ refuses("a revert of a merge the receiving entry never recorded", lambda: undo(orphaned),
2251
+ "REVERT_INVERSE_UNPROVABLE G-0 decisions", "none of it to put back")
2252
+ # the receiver's own history moves on and comes back: the merge is reverted once its own
2253
+ # revert leaves the merge's decision standing again, which is the stack and not the list (Q#3)
2254
+ if moved_on is not None:
2255
+ settled = accepts("the correction of the receiver reverted", lambda: apply_decision(
2256
+ moved_on, "G-0", sample_element("r4", "none", kind="revert")))
2257
+ if settled is not None:
2258
+ back = accepts("a revert of the merge once the receiver's own revert put it back", lambda: undo(settled, run="r5"))
2259
+ if back is not None and _rows(back)["M-1"].get("absorbed_by") is not None:
2260
+ failures.append("the merge was not released although the receiver's standing decision was the merge's again")
2261
+ # the merge is put back on both rows or neither, from either side (Q#2)
2262
+ refuses("a revert of the merge from the entry that received it", lambda: record_event(
2263
+ merged, "G-0", "revert", element=sample_element("r3", "none", kind="revert")), "REVERT_MERGE_SIDE G-0",
2264
+ "reverts it on M-1") # the refusal names the entry the merge absorbed (S#3)
2265
+ one_side = copy.deepcopy(merged)
2266
+ receiving_row = _rows(one_side)["G-0"]
2267
+ receiving_row["decisions"].append(merge_receiver_revert(sample_element("r3", "none", kind="revert"), "M-1"))
2268
+ receiving_row["disposition"] = "none"
2269
+ expect("a transaction putting the receiver back and leaving the row it absorbed", check_pair(merged, one_side, []),
2270
+ "REVERT_MERGE_SIDE G-0", "M-1, the entry that made it")
2271
+ # and the merge is no longer the receiver's standing application once that revert is in its
2272
+ # history, so the source cannot put it back on its own either (Q#3)
2273
+ refuses("a revert of a merge the receiver has already released", lambda: undo(one_side),
2274
+ "REVERT_INVERSE_UNPROVABLE G-0 decisions", "is none")
2275
+ adrift = copy.deepcopy(merged)
2276
+ _rows(adrift)["G-0"]["status"] = "retired"
2277
+ refuses("a revert of a merge whose receiving entry's own decisions do not replay to its status",
2278
+ lambda: undo(adrift), "REPLAY_INCONSISTENT G-0")
2279
+ # a receiver put back where no row of the base made the merge it says it received: there is no
2280
+ # second row to revert with it, so the pair cannot be closed either way (Q#2)
2281
+ received = {**merge_receiver_element(sample_element("r2", "reduce", operations=[MERGE]), "M-1"), "disposition": "correct"}
2282
+ stranded = sample_ledger(sample_entry("G-0", "placed", disposition="correct",
2283
+ decisions=[migration_element("placed"), received]))
2284
+ clean("a receiving decision whose merge no row of this ledger made", validate_ledger(stranded))
2285
+ on_its_own = copy.deepcopy(stranded)
2286
+ _rows(on_its_own)["G-0"]["decisions"].append(merge_receiver_revert(sample_element("r3", "none", kind="revert"), "M-1"))
2287
+ _rows(on_its_own)["G-0"]["disposition"] = "none"
2288
+ expect("a transaction putting that receiver back with no row to put back beside it",
2289
+ check_pair(stranded, on_its_own, []), "REVERT_MERGE_SIDE G-0", "no entry of the base merged into this one")
2290
+
2291
+ # a pair is two reverts that each undo the merge, and a same-run revert on the right row is
2292
+ # not that by itself: the replay says what a revert undoes, because a revert names no target
2293
+ # (S#0). The source's own later decision is the counterexample — its revert undoes that one.
2294
+ after_drop = accepts("a field-neutral drop on the absorbed row", lambda: apply_decision(
2295
+ merged, "M-1", sample_element("r3", "drop", reason="the unit is gone")))
2296
+ if after_drop is not None:
2297
+ drop_back = accepts("that drop reverted on the absorbed row alone", lambda: undo(after_drop, run="r4"))
2298
+ if drop_back is not None:
2299
+ clean("a revert of a decision that is not the merge, as a transaction", check_pair(after_drop, drop_back, []))
2300
+ unpaired = copy.deepcopy(drop_back)
2301
+ late = sample_element("r4", "none", kind="revert")
2302
+ receiving_row = _rows(unpaired)["G-0"]
2303
+ receiving_row["decisions"].append(merge_receiver_revert(late, "M-1"))
2304
+ receiving_row["disposition"] = "none"
2305
+ expect("a transaction releasing the receiver beside a revert that undoes the source's later drop",
2306
+ check_pair(after_drop, unpaired, []), "REVERT_MERGE_UNPAIRED G-0", "undoes another decision of that row")
2307
+ # and the receiver's revert is the one this transaction appends: an older revert of the same
2308
+ # run, sitting in the receiver's history for another reason, closes no pair (S#0)
2309
+ settled_first = accepts("a correction of the receiving entry reverted before any merge", lambda: apply_decision(
2310
+ apply_decision(pre_merge, "G-0", sample_element("r0", "correct")), "G-0", sample_element("r1", "none", kind="revert")))
2311
+ if settled_first is not None:
2312
+ merged_after = accepts("a merge into a receiving entry whose history already holds a revert", lambda: apply_decision(
2313
+ settled_first, "M-1", sample_element("r2", "reduce", operations=[MERGE]), {"absorbed_by": "G-0"}))
2314
+ if merged_after is not None:
2315
+ source_only = copy.deepcopy(merged_after)
2316
+ absorbed_row = _rows(source_only)["M-1"]
2317
+ reopened = sample_element("r1", "none", kind="revert")
2318
+ reopened["applied"]["before"] = {"fields": {"absorbed_by": "G-0"}, "absent": []}
2319
+ absorbed_row["decisions"].append(reopened)
2320
+ absorbed_row.update(status="placed", disposition="none")
2321
+ absorbed_row.pop("absorbed_by", None)
2322
+ expect("a transaction reverting the merge on the source and reading the receiver's older revert of that run",
2323
+ check_pair(merged_after, source_only, []), "RECEIVER_REVERT_MISSING G-0", "appends no revert of it on this entry")
2324
+ # a close may write a delivery outcome and append a resolution to a decision already recorded
2325
+ # (ADDENDUM §3), and a pair is judged by which decision the replay says each revert undoes,
2326
+ # not by comparing the decisions themselves — which would read either of those as a different
2327
+ # decision and refuse a sound pair (T#1)
2328
+ paired = accepts("a merge reverted on both rows", lambda: undo(merged))
2329
+ if paired is not None:
2330
+ clean("that pair, as a transaction", check_pair(merged, paired, []))
2331
+ with_delivery = copy.deepcopy(paired)
2332
+ _rows(with_delivery)["M-1"]["decisions"][1]["applied"]["delivery"] = "failed"
2333
+ clean("a pair in a close that also records the merge's delivery as failed", check_pair(merged, with_delivery, []))
2334
+ observed = accepts("a merge whose decision carries an observation", lambda: apply_decision(
2335
+ pre_merge, "M-1", sample_element("r2", "reduce", operations=[MERGE], observation=sample_observation()),
2336
+ {"absorbed_by": "G-0"}))
2337
+ if observed is not None:
2338
+ watched = accepts("that merge reverted on both rows", lambda: undo(observed))
2339
+ if watched is not None:
2340
+ with_resolution = copy.deepcopy(watched)
2341
+ _rows(with_resolution)["M-1"]["decisions"][1]["expected_observation"]["resolutions"].append(sample_resolution("r2"))
2342
+ clean("a pair in a close that also appends a resolution to the merge's observation",
2343
+ check_pair(observed, with_resolution, []))
2344
+ # the row the merge named is part of its identity: two rows can carry a merge of one run and
2345
+ # one operation id, and the one that merged into this entry is the one this revert pairs with
2346
+ # (T#0). Each of these holds a receiver whose own decision says no more than the merge does.
2347
+ def absorbed_into(eid, receiver_id, run="r2"):
2348
+ made = sample_element(run, "reduce", operations=[MERGE])
2349
+ made["applied"]["before"] = {"fields": {}, "absent": ["absorbed_by"]} # the row held none before the merge
2350
+ return sample_entry(eid, "absorbed", kind="misfire", disposition="reduce", absorbed_by=receiver_id, decisions=[
2351
+ migration_element("placed"), made])
2352
+
2353
+ def released(ledger, source_id, receiver_ids, run="r9"):
2354
+ """The transaction that puts the merge back: a revert appended to the source and to each
2355
+ entry named, the way the owner's revert of the source writes them."""
2356
+ head, late = copy.deepcopy(ledger), sample_element(run, "none", kind="revert")
2357
+ for receiver_id in receiver_ids:
2358
+ row = _rows(head)[receiver_id]
2359
+ row["decisions"].append(merge_receiver_revert(late, source_id))
2360
+ row["disposition"] = "none"
2361
+ row = _rows(head)[source_id]
2362
+ reopened = copy.deepcopy(late)
2363
+ reopened["applied"]["before"] = {"fields": {"absorbed_by": row["absorbed_by"]}, "absent": []}
2364
+ row["decisions"].append(reopened)
2365
+ row.update(status="placed", disposition="none")
2366
+ row.pop("absorbed_by", None)
2367
+ return head
2368
+
2369
+ received_merge = merge_receiver_element(sample_element("r2", "reduce", operations=[MERGE]), "M-1")
2370
+ one_maker = sample_ledger(absorbed_into("M-1", "G-0"), sample_entry(
2371
+ "G-0", "placed", disposition="correct", decisions=[migration_element("placed"), received_merge]))
2372
+ clean("a merge of one run and one operation recorded on both of its rows", validate_ledger(one_maker))
2373
+ clean("that merge put back on both of its rows", check_pair(one_maker, released(one_maker, "M-1", ["G-0"]), []))
2374
+ two_makers = sample_ledger(absorbed_into("M-1", "G-0"), absorbed_into("M-2", "G-0"), sample_entry(
2375
+ "G-0", "placed", disposition="correct", decisions=[migration_element("placed"), copy.deepcopy(received_merge)]))
2376
+ clean("two entries absorbed into one by a merge of the same run and operation", validate_ledger(two_makers))
2377
+ expect("a receiver put back where two entries recorded that merge into it",
2378
+ check_pair(two_makers, released(two_makers, "M-1", ["G-0"]), []), "REVERT_MERGE_SIDE G-0", "not decidable")
2379
+ elsewhere = sample_ledger(absorbed_into("M-1", "G-1"), sample_entry(
2380
+ "G-1", "placed", disposition="correct", decisions=[migration_element("placed"), copy.deepcopy(received_merge)]), sample_entry(
2381
+ "G-0", "placed", disposition="correct", decisions=[migration_element("placed"), copy.deepcopy(received_merge)]))
2382
+ clean("a merge into one entry beside another holding a decision of the same run and operation", validate_ledger(elsewhere))
2383
+ beside = check_pair(elsewhere, released(elsewhere, "M-1", ["G-0", "G-1"]), [])
2384
+ expect("a receiver put back beside the pair of a merge that was never into it", beside,
2385
+ "REVERT_MERGE_SIDE G-0", "no entry of the base merged into this one")
2386
+ if [problem for problem in beside if "G-1" in problem]:
2387
+ failures.append(f"the merge into G-1 was put back on both its rows and still drew {[p for p in beside if 'G-1' in p]}")
2388
+ # a revert of the receiver's own, carrying the merge's run and operation: it looks like the
2389
+ # application that received the merge and is not one, because a revert never stands (S#2)
2390
+ masked_receiver = sample_entry("G-0", "placed", disposition="none", decisions=[
2391
+ migration_element("placed"), sample_element("r0", "correct"),
2392
+ sample_element("r2", "none", kind="revert", operations=[MERGE])])
2393
+ masked = sample_ledger(sample_entry("M-1", "absorbed", kind="misfire", disposition="reduce", absorbed_by="G-0", decisions=[
2394
+ migration_element("placed"), sample_element("r2", "reduce", operations=[MERGE])]), masked_receiver)
2395
+ clean("a receiver whose own revert carries the merge's run and operation", validate_ledger(masked))
2396
+ refuses("a revert of a merge whose receiver recorded a revert carrying that run and operation",
2397
+ lambda: undo(masked), "REVERT_INVERSE_UNPROVABLE G-0 decisions", "is none")
2398
+ # a merge whose receiver's own row the merge changed: the record on the receiver's decision is
2399
+ # what puts that row back, through the transaction side and through the event API (Q#4)
2400
+ routed = copy.deepcopy(merged)
2401
+ receiving_row = _rows(routed)["G-0"]
2402
+ receiving_row["decisions"][-1]["applied"]["before"] = {"fields": {"lesson": receiving_row["lesson"]}, "absent": ["destination"]}
2403
+ receiving_row["decisions"][-1]["applied"]["operations"] = [MERGE, {"operation_id": "op-2", "type": "route",
2404
+ "target": "claude/guides/x.md"}]
2405
+ receiving_row.update(lesson="the merged lesson", destination=ROUTE)
2406
+ clean("a merge that revised the receiving entry's own text and route", check_pair(pre_merge, routed, []))
2407
+ released = accepts("the owner's revert of a merge that revised the receiver", lambda: undo(routed))
2408
+ if released is not None:
2409
+ receiver = _rows(released)["G-0"]
2410
+ if receiver["lesson"] != _rows(merged)["G-0"]["lesson"] or receiver["destination"] is not None:
2411
+ failures.append(f"the revert of a merge that revised the receiver left {receiver['lesson']!r} and "
2412
+ f"{receiver['destination']!r}, not the values its decision recorded")
2413
+ clean("that revert, as a transaction", check_pair(routed, released, []))
2414
+ for label, mutate, needle in (
2415
+ ("the receiver's text", lambda r: r.update(lesson="never there"), "REVERT_NOT_RESTORED G-0 lesson"),
2416
+ ("the receiver's route", lambda r: r.update(destination=ROUTE), "REVERT_NOT_RESTORED G-0 destination")):
2417
+ planted = copy.deepcopy(released)
2418
+ mutate(_rows(planted)["G-0"])
2419
+ expect(f"a revert of that merge leaving {label} as the merge wrote it", check_pair(routed, planted, []), needle)
2420
+ overlap = copy.deepcopy(routed)
2421
+ _rows(overlap)["G-0"]["decisions"][-1]["applied"]["before"]["absent"].append("lesson")
2422
+ expect("a merge whose receiver's record says the row both held a value and held none",
2423
+ check_pair(pre_merge, overlap, []), "BEFORE_FIELD_OVERLAP G-0")
2424
+ # every application records what it replaced, and a row that did not exist replaced nothing (Q#0)
2425
+ # the creating decision carries design §12.1's four keys and no record of its own, so what the
2426
+ # created row holds is what create_entry wrote there, not what the caller handed in (S#1)
2427
+ bare = sample_element("r1", "place")
2428
+ bare["applied"].pop("before")
2429
+ anchored = sample_ledger(sample_entry("G-0"))
2430
+ created = accepts("an entry created by a place that records nothing of its own", lambda: create_entry(
2431
+ anchored, sample_entry("N-1", kind="gap"), bare))
2432
+ if created is not None:
2433
+ if before_of(_rows(created)["N-1"]["decisions"][0]) != EMPTY_BEFORE:
2434
+ failures.append(f"the decision that created an entry recorded {before_of(_rows(created)['N-1']['decisions'][0])}, "
2435
+ f"and create_entry is what writes the empty record there")
2436
+ clean("that created row, as a transaction", check_pair(anchored, created, ["N-1"]))
2437
+ for label, mutate, needle in (
2438
+ ("no record at all", lambda d: d["applied"].pop("before", None), "BEFORE_MISSING N-1 decisions[0]"),
2439
+ ("a value it claims to have replaced", lambda d: d["applied"]["before"]["fields"].update(lesson="never there"),
2440
+ "BEFORE_FIELD_EXTRA N-1 decisions[0]"),
2441
+ ("a field it claims the row held none of", lambda d: d["applied"]["before"]["absent"].append("destination"),
2442
+ "BEFORE_FIELD_EXTRA N-1 decisions[0]"),
2443
+ ("both parts naming one field", lambda d: (d["applied"]["before"]["fields"].update(keep={"units": ["u"]}),
2444
+ d["applied"]["before"]["absent"].append("keep")), "BEFORE_FIELD_OVERLAP N-1")):
2445
+ planted = copy.deepcopy(created)
2446
+ # each plant is written against a record it seeds itself, so that the control above is
2447
+ # the only one reading what create_entry generated
2448
+ decision = _rows(planted)["N-1"]["decisions"][0]
2449
+ decision["applied"].setdefault("before", copy.deepcopy(EMPTY_BEFORE))
2450
+ mutate(decision)
2451
+ expect(f"a row this transaction allocated whose creating decision records {label}",
2452
+ check_pair(anchored, planted, ["N-1"]), needle)
2453
+ changed("a transaction appending an application that records nothing at all", lambda h: (
2454
+ bound(h, 0, sample_element("r1", "none"), disposition="none"),
2455
+ h["entries"][0]["decisions"][-1]["applied"].pop("before")), "BEFORE_MISSING S3-1 decisions[0]")
2456
+ changed("a transaction whose applied.before says the row both held a value and held none", lambda h: (
2457
+ bound(h, 0, sample_element("r1", "correct"), disposition="correct", lesson="edited"),
2458
+ h["entries"][0]["decisions"][-1]["applied"]["before"]["absent"].append("lesson")), "BEFORE_FIELD_OVERLAP S3-1",
2459
+ over=sample_ledger(sample_entry("S3-1", lesson="the first lesson")))
2460
+ changed("a migrated element carrying a record of what it replaced", lambda h: h["entries"][0]["decisions"][0]["applied"].update(
2461
+ before=copy.deepcopy(EMPTY_BEFORE)), "LEGACY_BEFORE S3-1 decisions[0]", over=sample_ledger(sample_entry(
2462
+ "S3-1", "placed", decisions=[{**legacy_element("placed", kind="legacy_application"), "applied": {
2463
+ "commit": None, "paths": [], "operations": [], "delivery": "unverified"}}])))
2464
+ # the entry design §12.2 migrated with its retirement on the row and no element of its own: a
2465
+ # decision that changes nothing records nothing, so its revert restores the status and leaves the
2466
+ # retirement where the migration put it (Q#4, over the real migrated ledger)
2467
+ real_migrated = None
2468
+ if migrate is None or checkout_ledger is None:
2469
+ skipped.append("the migrated-retirement legs over the real ledger (needs the checkout's ledger "
2470
+ "and the author-side migrator)")
2471
+ else:
2472
+ real_migrated, _removed = migrate(json.loads(pathlib.Path(checkout_ledger).read_text(encoding="utf-8")))
2473
+ drop_done = None if real_migrated is None else accepts("an approved drop over a migrated retirement", lambda: apply_decision(
2474
+ real_migrated, "S2-19", sample_element("r1", "drop", reason="the unit is covered elsewhere")))
2475
+ if drop_done is not None:
2476
+ if before_of(_rows(drop_done)["S2-19"]["decisions"][-1]) != EMPTY_BEFORE:
2477
+ failures.append(f"the drop over S2-19 recorded {before_of(_rows(drop_done)['S2-19']['decisions'][-1])}, "
2478
+ f"and it changed no field of the row")
2479
+ drop_back = accepts("the owner's revert of that drop", lambda: record_event(
2480
+ drop_done, "S2-19", "revert", element=sample_element("r2", "none", kind="revert")))
2481
+ if drop_back is not None:
2482
+ row, was = _rows(drop_back)["S2-19"], _rows(real_migrated)["S2-19"]
2483
+ if row["retired"] != was["retired"] or row["retire_reason"] != was["retire_reason"] or row["status"] != was["status"]:
2484
+ failures.append(f"the revert of a drop over S2-19 left retired={row.get('retired')!r} and status={row['status']!r}, "
2485
+ f"not the {was['retired']!r} and {was['status']!r} the migration put on the row")
2486
+ clean("that revert of a drop, as a transaction", check_pair(drop_done, drop_back, []))
2487
+ drop_cleared = copy.deepcopy(drop_back)
2488
+ _rows(drop_cleared)["S2-19"].pop("retired"), _rows(drop_cleared)["S2-19"].pop("retire_reason")
2489
+ expect("a revert of that drop clearing the retirement the migration kept on the row",
2490
+ check_pair(drop_done, drop_cleared, []), "ROW_FIELD_UNLICENSED S2-19")
2491
+ changed("a status moved to a state the table does not reach", lambda h: bound(
2492
+ h, 1, sample_element("r1", "place"), status="retired", disposition="place"), "HISTORY_INCONSISTENT S3-2")
2493
+ changed("a pair the table rejects", lambda h: bound(h, 0, sample_element("r1", "place"), disposition="place"),
2494
+ "TRANSITION_DISALLOWED S3-1: placed + place: design §12.3 allows no such pair")
2495
+ changed("an applied keep without its record", lambda h: bound(h, 0, sample_element("r1", "keep", reason="kept"), disposition="keep"), "EFFECT_MISSING S3-1")
2496
+ changed("an applied keep with its record", lambda h: bound(
2497
+ h, 0, sample_element("r1", "keep", reason="kept"), disposition="keep", keep={"units": ["u"]}), expect_clean=True)
2498
+ changed("a recurrence appended", lambda h: h["entries"][0].update(recurrence=[{"window": "2026-09-01"}]), expect_clean=True)
2499
+ changed("evidence appended", lambda h: h["entries"][0].update(evidence=[{"locator": "unavailable", "session": "claude:1"}]), expect_clean=True)
2500
+ withrecurrence = sample_ledger(sample_entry("S3-1", recurrence=[{"window": "2026-09-01"}], evidence=[{"claim_id": "c-1", "evidence_id": "e-1"}]))
2501
+ changed("a recurrence rewritten", lambda h: h["entries"][0].update(recurrence=[{"window": "2026-09-02"}]), "EVENT_REWRITTEN S3-1 recurrence", over=withrecurrence)
2502
+ changed("evidence rewritten", lambda h: h["entries"][0].update(evidence=[{"claim_id": "c-2", "evidence_id": "e-2"}]), "EVENT_REWRITTEN S3-1 evidence", over=withrecurrence)
2503
+ withdecision = sample_ledger(sample_entry("S3-1", decisions=[sample_element("r1", "none")]))
2504
+ changed("a decision overwritten", lambda h: h["entries"][0]["decisions"][0].update(disposition="correct"),
2505
+ "DECISION_REWRITTEN S3-1 decisions[0] (r1)", over=withdecision)
2506
+ changed("a decision removed", lambda h: h["entries"][0].update(decisions=[]), "DECISION_REWRITTEN S3-1", "removed", over=withdecision)
2507
+ windowed = sample_ledger(windows=[{"start": None, "end": "2026-09-01", "run_id": "w1", "kind": "periodic", "commit": None, "accounted": True, "fully_read": True}])
2508
+ changed("a window record rewritten", lambda h: h["windows"][0].update(accounted=False), "WINDOWS_REWRITTEN", over=windowed)
2509
+ expect("a head that does not validate", check_pair(base, dropped), "LEDGER_INVALID")
2510
+ expect("schema 2 returning to schema 1", check_pair(base, {"schema": 1, "entries": []}), "LEDGER_SCHEMA_REGRESSED")
2511
+ legacy_base = {"schema": 1, "entries": [{"id": "S3-1", "status": "placed", "strength": 3}]}
2512
+ legacy_head = {"schema": 1, "entries": [{"id": "S3-1", "status": "placed", "strength": 4}, {"id": "S3-2", "status": "candidate"}]}
2513
+ clean("a schema 1 merge changing a row and adding the next id", check_pair(legacy_base, legacy_head))
2514
+ expect("a schema 1 equal-count deletion plus insertion", check_pair(legacy_base, {"schema": 1, "entries": [{"id": "S3-2", "status": "p"}]}), "ID_LOST S3-1")
2515
+
2516
+ # new rows (F#1): each is bound to the applied decision that created it, and a ledger without one is refused
2517
+ anchor = sample_ledger(sample_entry("G-0"))
2518
+ created = accepts("an entry created by its first decision", lambda: create_entry(
2519
+ anchor, sample_entry("N-1", kind="misfire"), sample_element("r1", "correct")))
2520
+ if created is not None:
2521
+ clean("a new row bound to the decision that created it", check_pair(anchor, created, ["N-1"]))
2522
+ expect("a new row with no allocation", check_pair(anchor, created), "ALLOCATION_REQUIRED")
2523
+
2524
+ def new_row(label, entry, *needles):
2525
+ head = sample_ledger(*anchor["entries"], entry)
2526
+ expect(label, check_pair(anchor, head, ["N-1"]), *needles)
2527
+
2528
+ new_row("a new row with no decision", sample_entry("N-1"), "NEW_ROW_WITHOUT_DECISION N-1")
2529
+ new_row("a new row created by a legacy element", sample_entry("N-1", decisions=[legacy_element()]), "NEW_ROW_WITHOUT_DECISION N-1")
2530
+ new_row("a new row whose first decision is not applied", sample_entry("N-1", decisions=[sample_element("r1", "place", applied=False)]), "NEW_ROW_UNAPPLIED N-1")
2531
+ # an application whose delivery failed still created its entry (design §10.6, ADDENDUM §3)
2532
+ created_failed = accepts("an entry created by a place whose delivery failed", lambda: create_entry(
2533
+ anchor, sample_entry("N-1", kind="gap"), sample_element("r1", "place", delivery="failed")))
2534
+ if created_failed is not None:
2535
+ if [e["id"] for e in created_failed["entries"]] != ["G-0", "N-1"] or created_failed["entries"][1]["status"] != "placed":
2536
+ failures.append(f"delivery: a place whose delivery failed did not create the placed entry: {created_failed['entries'][1:]}")
2537
+ clean("that entry bound to the decision that created it", check_pair(anchor, created_failed, ["N-1"]))
2538
+ new_row("a new row from a pair the table rejects", sample_entry("N-1", kind="gap", disposition="keep", decisions=[
2539
+ sample_element("r1", "keep", reason="kept")]), "TRANSITION_DISALLOWED N-1")
2540
+ new_row("a new row for a decision the table gives no entry", sample_entry("N-1", kind="misfire", decisions=[sample_element("r1", "none")]),
2541
+ "NEW_ENTRY_FOR_NO_ENTRY N-1")
2542
+ new_row("a new row created in a state its decision does not lead to", sample_entry(
2543
+ "N-1", "incubating", kind="misfire", disposition="incubate", decisions=[sample_element("r1", "incubate", observation=sample_observation())]),
2544
+ "STATUS_UNEXPLAINED N-1")
2545
+ new_row("a new row saying another disposition than its decision", sample_entry(
2546
+ "N-1", "placed", kind="gap", disposition="none", decisions=[sample_element("r1", "place")]), "DISPOSITION_UNBOUND N-1")
2547
+ new_row("a new row that gained its decision without its keep record", sample_entry(
2548
+ "N-1", "placed", kind="misfire", disposition="keep", decisions=[sample_element("r1", "keep", reason="kept")]), "EFFECT_MISSING N-1")
2549
+ # a row the run allocated is no way in for an element of the migration either (H#1): the clean
2550
+ # transaction first, then the same row with a complete legacy application behind its first decision
2551
+ allocated = sample_entry("N-1", "placed", kind="gap", disposition="place", decisions=[sample_element("r1", "place")])
2552
+ clean("a new row bound to its first decision", check_pair(anchor, sample_ledger(*anchor["entries"], allocated), ["N-1"]))
2553
+ new_row("a new row carrying a legacy application behind its first decision", {
2554
+ **allocated, "decisions": [*allocated["decisions"], legacy_element("placed", kind="legacy_application", legacy_text="placed 2026-07-19")]},
2555
+ "LEGACY_ELEMENT_APPENDED N-1 decisions[1]")
2556
+ # A row the transaction allocated carries the one decision that created it (K#3). A second
2557
+ # decision would have to be judged from the state the first left, and this side has no base for
2558
+ # that row at all, so the whole class is refused by name rather than half-checked: the tail that
2559
+ # looks valid, the one missing the keep record its cell requires, and the one whose entry ends on
2560
+ # another disposition than its latest decision are all the same refusal.
2561
+ for label, tail, fields in (
2562
+ ("a keep with the record its cell requires", sample_element("r2", "keep", reason="still works"), {"keep": {"units": ["u"]}, "disposition": "keep"}),
2563
+ ("a keep without that record", sample_element("r2", "keep", reason="still works"), {"disposition": "keep"}),
2564
+ ("a keep the entry does not say it holds", sample_element("r2", "keep", reason="still works"), {"keep": {"units": ["u"]}})):
2565
+ new_row(f"a new row whose second decision is {label}", {
2566
+ **allocated, **fields, "decisions": [*allocated["decisions"], tail]}, "NEW_ROW_MULTIPLE_DECISIONS N-1")
2567
+
2568
+ # events (F#6): design §12.3's five rows, each with the entry it accepts and the ones it refuses
2569
+ table = transitions()
2570
+ clean("the event rows against the design's", event_problems(table))
2571
+ for label, mutate, needle in (
2572
+ ("an event row reworded", lambda t: t["events"][4].update(to="unchanged"), "row 4 is"),
2573
+ ("an event row dropped", lambda t: t["events"].pop(), "4 rows, the design has 5"),
2574
+ ("an event row renamed", lambda t: t["events"][0].update(id="waiting"), "the handlers")):
2575
+ changed_events = copy.deepcopy(table)
2576
+ mutate(changed_events)
2577
+ expect(label, event_problems(changed_events), needle)
2578
+ inc = sample_ledger(sample_entry("S3-2", "incubating"), sample_entry("S3-1"))
2579
+ waiting = sample_element("r1", "none", applied=False, reason="awaiting R: the core item needs a second window")
2580
+ held = accepts("awaiting R on an incubating entry", lambda: record_event(inc, "S3-2", "awaiting_R", element=waiting))
2581
+ if held is not None:
2582
+ event_case("awaiting_R", "accept")
2583
+ if held["entries"][0]["status"] != "incubating" or held["entries"][0]["decisions"] != [waiting]:
2584
+ failures.append("awaiting R: the status moved or the reason was not recorded")
2585
+ clean("awaiting R recorded", check_pair(inc, held, []))
2586
+ for label, call, needles in (
2587
+ ("awaiting R on a placed entry", lambda: record_event(inc, "S3-1", "awaiting_R", element=waiting), ("EVENT_NOT_APPLICABLE S3-1",)),
2588
+ ("awaiting R recorded as an applied decision", lambda: record_event(inc, "S3-2", "awaiting_R", element=sample_element("r1", "none", reason="x")), ("EVENT_MALFORMED S3-2 awaiting_R",)),
2589
+ ("awaiting R with no reason", lambda: record_event(inc, "S3-2", "awaiting_R", element=sample_element("r1", "none", applied=False)), ("EVENT_MALFORMED S3-2 awaiting_R",))):
2590
+ refuses(label, call, *needles)
2591
+ event_case("awaiting_R", "refuse")
2592
+ changed("awaiting R moving the status", lambda h: bound(h, 0, waiting, status="placed"), "STATUS_UNEXPLAINED S3-2", over=inc)
2593
+
2594
+ reference = {"claim_id": "c-1", "evidence_id": "e-1"}
2595
+ recurred = accepts("recurrence on an incubating entry", lambda: record_event(
2596
+ inc, "S3-2", "recurrence", evidence=[reference], lineages=2, record={"window": "2026-11-01"}))
2597
+ if recurred is not None:
2598
+ event_case("recurrence", "accept")
2599
+ entry = recurred["entries"][0]
2600
+ if (entry["status"], entry["evidence"], entry["independent_lineages"], entry["decisions"]) != ("incubating", [reference], 2, []):
2601
+ failures.append(f"recurrence: expected the evidence and lineages appended, status and decisions unchanged, got {entry}")
2602
+ clean("a recurrence licensed with no decision", check_pair(inc, recurred, []))
2603
+ refuses("evidence the entry already holds", lambda: record_event(recurred, "S3-2", "recurrence", evidence=[reference]), "EVENT_MALFORMED S3-2 recurrence")
2604
+ for label, call, needles in (
2605
+ ("a recurrence with no evidence", lambda: record_event(inc, "S3-2", "recurrence", evidence=[]), ("EVENT_MALFORMED S3-2 recurrence",)),
2606
+ ("a recurrence with an incomplete reference", lambda: record_event(inc, "S3-2", "recurrence", evidence=[{"claim_id": "c-1"}]), ("LEDGER_INVALID after recurrence",)),
2607
+ ("an event nobody defined", lambda: record_event(inc, "S3-2", "resurrection", evidence=[reference]), ("EVENT_UNKNOWN",)),
2608
+ ("an event for no entry", lambda: record_event(inc, "S9-9", "recurrence", evidence=[reference]), ("ENTRY_UNKNOWN S9-9",))):
2609
+ refuses(label, call, *needles)
2610
+ event_case("recurrence", "refuse")
2611
+
2612
+ candidate = sample_element("r2", "drop", applied=False, reason="the contradicting session shows the rule is wrong")
2613
+ contradicted = accepts("a contradiction of an incubating entry", lambda: record_event(inc, "S3-2", "contradiction", element=candidate))
2614
+ if contradicted is not None:
2615
+ event_case("contradiction", "accept")
2616
+ if contradicted["entries"][0]["status"] != "incubating":
2617
+ failures.append("contradiction: the status moved before the candidate's disposition was applied")
2618
+ clean("a contradiction recorded", check_pair(inc, contradicted, []))
2619
+ later = accepts("the candidate applied by a later run", lambda: apply_decision(
2620
+ contradicted, "S3-2", sample_element("r3", "drop", reason="the contradicting session shows the rule is wrong")))
2621
+ if later is not None and later["entries"][0]["status"] != "retired":
2622
+ failures.append("contradiction: the candidate's disposition, applied, did not retire the entry")
2623
+ for label, call, needles in (
2624
+ ("a contradiction recorded as an applied decision", lambda: record_event(inc, "S3-2", "contradiction", element=sample_element("r2", "drop", reason="x")), ("EVENT_MALFORMED S3-2 contradiction",)),
2625
+ ("a contradiction whose candidate is a place", lambda: record_event(inc, "S3-2", "contradiction", element=sample_element("r2", "place", applied=False)), ("EVENT_MALFORMED S3-2 contradiction",))):
2626
+ refuses(label, call, *needles)
2627
+ event_case("contradiction", "refuse")
2628
+ changed("a contradiction moving the status", lambda h: bound(h, 0, candidate, status="retired"), "STATUS_UNEXPLAINED S3-2", over=inc)
2629
+
2630
+ # design §10.6: an application whose delivery check failed or did not run is applied, not lost. Its
2631
+ # effects stand, `applied.delivery` records the outcome, and the owner may revert it (ADDENDUM §3).
2632
+ verified = accepts("a place with its delivery verified", lambda: apply_decision(inc, "S3-2", sample_element("r1", "place", delivery="verified")))
2633
+ if verified is not None and verified["entries"][0]["status"] != "placed":
2634
+ failures.append("delivery: a verified place did not place the entry, so the unverified cases prove nothing")
2635
+ # the event records what the check found on the decision already applied: no transition is
2636
+ # replayed, no second decision of that run is appended, and the entry stands as the application
2637
+ # left it (F#1). Each case starts from a real application made by production code.
2638
+ # Each entry records the status it was migrated at, so the revert of its one application has an answer.
2639
+ marked = sample_ledger(sample_entry("S3-2", "incubating", decisions=[migration_element("incubating")]),
2640
+ sample_entry("S3-1", "placed", decisions=[migration_element("placed")]), sample_entry("G-0"))
2641
+ for applied_label, entry_id, element, updates, want_status, want_before in (
2642
+ ("a place", "S3-2", sample_element("r1", "place"), None, "placed", "incubating"),
2643
+ ("a correct", "S3-2", sample_element("r1", "correct"), {"lesson": "a revised lesson"}, "incubating", "incubating"),
2644
+ ("a reduction", "S3-1", sample_element("r1", "reduce", operations=[MERGE]), {"absorbed_by": "G-0"}, "absorbed", "placed")):
2645
+ done = accepts(f"{applied_label} applied, its delivery not yet checked", lambda entry_id=entry_id,
2646
+ element=element, updates=updates: apply_decision(marked, entry_id, element, updates))
2647
+ if done is None:
2648
+ continue
2649
+ for state in ("failed", "unverified"):
2650
+ late = accepts(f"the delivery of {applied_label} recorded {state}", lambda done=done, entry_id=entry_id, state=state:
2651
+ record_event(done, entry_id, "delivery", run="r1", outcome=state))
2652
+ if late is None:
2653
+ continue
2654
+ event_case("delivery", "accept")
2655
+ was, now = _rows(done)[entry_id], _rows(late)[entry_id]
2656
+ if now["status"] != want_status or now["status"] != was["status"]:
2657
+ failures.append(f"delivery {state}: recording the outcome of {applied_label} moved the status to {now['status']!r}")
2658
+ if len(now["decisions"]) != len(was["decisions"]) or now["decisions"][-1]["applied"]["delivery"] != state:
2659
+ failures.append(f"delivery {state}: the outcome of {applied_label} was not written into the decision already there: {now['decisions']}")
2660
+ if {k: v for k, v in now.items() if k != "decisions"} != {k: v for k, v in was.items() if k != "decisions"}:
2661
+ failures.append(f"delivery {state}: recording the outcome of {applied_label} changed the entry besides its decisions")
2662
+ if _written_once(now["decisions"][-1]) != _written_once(was["decisions"][-1]):
2663
+ failures.append(f"delivery {state}: recording the outcome of {applied_label} rewrote the decision")
2664
+ clean(f"the delivery of {applied_label} recorded {state}, as a transaction", check_pair(done, late, []))
2665
+ # a revert reads the application and the values it recorded, not the outcome of its
2666
+ # delivery check: an application stands whatever its delivery did, so the row it put back
2667
+ # is the same one a verified delivery would have put back (ADDENDUM §3, RECORD)
2668
+ back = accepts(f"the owner's revert of {applied_label} whose delivery {state}", lambda late=late, entry_id=entry_id: record_event(
2669
+ late, entry_id, "revert", element=sample_element("r2", "none", kind="revert")))
2670
+ if back is not None:
2671
+ row = _rows(back)[entry_id]
2672
+ if row["status"] != want_before:
2673
+ failures.append(f"delivery {state}: the owner's revert of {applied_label} left {row['status']!r}, "
2674
+ f"not the {want_before!r} before it")
2675
+ for field, value in (before_of(_rows(late)[entry_id]["decisions"][-1]) or EMPTY_BEFORE)["fields"].items():
2676
+ if row.get(field) != value:
2677
+ failures.append(f"delivery {state}: the owner's revert of {applied_label} left {field} at {row.get(field)!r}, "
2678
+ f"not the {value!r} the application recorded")
2679
+ for label, call, needles in (
2680
+ ("a delivery outcome for a run that decided nothing", lambda: record_event(inc, "S3-2", "delivery", run="r9", outcome="failed"),
2681
+ ("EVENT_MALFORMED S3-2 delivery", "no decision of run 'r9'")),
2682
+ ("a delivery outcome for a decision that was not applied", lambda: record_event(sample_ledger(sample_entry(
2683
+ "S3-2", "incubating", decisions=[sample_element("r1", "place", applied=False)])), "S3-2", "delivery", run="r1", outcome="failed"),
2684
+ ("EVENT_MALFORMED S3-2 delivery", "records no application"))):
2685
+ refuses(label, call, *needles)
2686
+ event_case("delivery", "refuse")
2687
+ # each guard against the ledger the other guards accept (H#2), so what refuses is the guard named.
2688
+ # The outcome: a real applied decision of run r1, recorded failed first and then with a verdict
2689
+ # design §12.3's row does not have. The legacy exclusion: a legacy element that carries an
2690
+ # application of its own, which only the exclusion stands between and the write.
2691
+ outcome_ready = apply_decision(inc, "S3-2", sample_element("r1", "place"))
2692
+ accepts("a delivery outcome of failed on that applied decision", lambda: record_event(outcome_ready, "S3-2", "delivery", run="r1", outcome="failed"))
2693
+ refuses("a delivery outcome of verified on the same decision", lambda: record_event(outcome_ready, "S3-2", "delivery", run="r1", outcome="verified"),
2694
+ "EVENT_MALFORMED S3-2 delivery", "not 'verified'", "design §12.3's row has no other")
2695
+ event_case("delivery", "refuse")
2696
+ legacy_applied = sample_ledger(sample_entry("S3-2", "placed", decisions=[
2697
+ {**legacy_element("placed", kind="legacy_application"), "applied": {"commit": None, "paths": [], "operations": [], "delivery": "unverified"}}]))
2698
+ clean("a ledger whose migrated application records its own delivery", validate_ledger(legacy_applied))
2699
+ refuses("a delivery outcome for the run of that migrated application", lambda: record_event(
2700
+ legacy_applied, "S3-2", "delivery", run="legacy-2026-08-25", outcome="failed"),
2701
+ "EVENT_MALFORMED S3-2 delivery", "is an element of the migration")
2702
+ event_case("delivery", "refuse")
2703
+ changed("a decision rewritten past its delivery outcome", lambda h: h["entries"][0]["decisions"][0].update(approval_id="ap-9"),
2704
+ "DECISION_REWRITTEN S3-1 decisions[0]", over=sample_ledger(sample_entry("S3-1", decisions=[sample_element("r1", "none")])))
2705
+ # a transaction writes a delivery outcome by the same rules as the event (K#4): the positive case
2706
+ # first, then the two the event refuses, each written straight into a recorded decision
2707
+ recorded = sample_ledger(sample_entry("S3-1", decisions=[sample_element("r1", "none")]),
2708
+ sample_entry("S3-2", decisions=[{**legacy_element("placed", kind="legacy_application"),
2709
+ "applied": {"commit": None, "paths": [], "operations": [], "delivery": "unverified"}}]))
2710
+ for state in ("failed", "unverified"):
2711
+ changed(f"a transaction recording a delivery of {state}", lambda h, state=state: h["entries"][0]["decisions"][0]["applied"].update(delivery=state),
2712
+ expect_clean=True, over=recorded)
2713
+ changed("a transaction recording a delivery of verified", lambda h: h["entries"][0]["decisions"][0]["applied"].update(delivery="verified"),
2714
+ "DELIVERY_OUTCOME_INVALID S3-1 decisions[0] (r1)", over=recorded)
2715
+ changed("a transaction recording a delivery on an element the migration wrote",
2716
+ lambda h: h["entries"][1]["decisions"][0]["applied"].update(delivery="failed"),
2717
+ "DELIVERY_ON_MIGRATED S3-2 decisions[0]", over=recorded)
2718
+
2719
+ two_back = accepts("a placed entry corrected and then reduced", lambda: apply_decision(apply_decision(
2720
+ accepts("an entry created by place", lambda: create_entry(sample_ledger(sample_entry("G-0")), sample_entry("N-1", kind="gap"), sample_element("r1", "place"))),
2721
+ "N-1", sample_element("r2", "correct")), "N-1", sample_element("r3", "reduce")))
2722
+ revert = sample_element("r4", "none", kind="revert")
2723
+ if two_back is not None:
2724
+ if two_back["entries"][1]["status"] != "retired":
2725
+ failures.append("revert: the setup did not retire the entry")
2726
+ undone = accepts("a revert of the latest decision", lambda: record_event(two_back, "N-1", "revert", element=revert))
2727
+ if undone is not None:
2728
+ event_case("revert", "accept")
2729
+ # r3 retired it, r2 changed nothing, r1 placed it: the status before r3 comes from r1, two decisions back
2730
+ appended = {k: v for k, v in undone["entries"][1]["decisions"][-1].items() if k != "applied"}
2731
+ if undone["entries"][1]["status"] != "placed" or appended != {k: v for k, v in revert.items() if k != "applied"}:
2732
+ failures.append(f"revert: expected placed (set by the decision two steps back) with the revert appended, got {undone['entries'][1]['status']}")
2733
+ clean("a revert recorded", check_pair(two_back, undone, []))
2734
+ again = accepts("a second revert", lambda: record_event(undone, "N-1", "revert", element=sample_element("r5", "none", kind="revert")))
2735
+ if again is not None and again["entries"][1]["status"] != "placed":
2736
+ failures.append("revert: reverting the correct, which changed nothing, did not leave the status placed")
2737
+ refuses("a third revert, of the decision that created the entry", lambda: record_event(again, "N-1", "revert", element=sample_element("r6", "none", kind="revert")),
2738
+ "REVERT_PRIOR_STATUS_AMBIGUOUS N-1")
2739
+ changed("a revert that restores a status the history does not give", lambda h: bound(
2740
+ h, 1, revert, status="incubating", disposition="none"), "HISTORY_INCONSISTENT N-1", over=two_back)
2741
+ changed("a status restored with no revert decision", lambda h: h["entries"][1].update(status="placed"), "HISTORY_INCONSISTENT N-1", over=two_back)
2742
+ step = accepts("an entry created by incubate and then placed", lambda: apply_decision(
2743
+ accepts("an entry created by incubate", lambda: create_entry(
2744
+ sample_ledger(sample_entry("G-0")), sample_entry("N-1", kind="gap"), sample_element("r1", "incubate", observation=sample_observation()))),
2745
+ "N-1", sample_element("r2", "place")))
2746
+ if step is not None:
2747
+ back = accepts("a revert of the place", lambda: record_event(step, "N-1", "revert", element=revert))
2748
+ if back is not None and back["entries"][1]["status"] != "incubating":
2749
+ failures.append(f"revert: the status before the place was incubating, got {back['entries'][1]['status']}")
2750
+ merged = accepts("an entry created by place and then merged", lambda: apply_decision(
2751
+ accepts("a placed entry", lambda: create_entry(sample_ledger(sample_entry("G-0")), sample_entry("N-1", kind="gap"), sample_element("r1", "place"))),
2752
+ "N-1", sample_element("r2", "reduce", operations=[MERGE]), {"absorbed_by": "G-0"}))
2753
+ if merged is not None:
2754
+ released = accepts("a revert of a merge", lambda: record_event(merged, "N-1", "revert", element=sample_element("r3", "none", kind="revert")))
2755
+ if released is not None and (released["entries"][1]["status"], "absorbed_by" in released["entries"][1]) != ("placed", False):
2756
+ failures.append(f"revert of a merge: expected placed with the absorption gone, got {released['entries'][1]['status']}")
2757
+ migrated_like = accepts("a migrated entry placed by a run", lambda: apply_decision(
2758
+ sample_ledger(sample_entry("M-1", "incubating", decisions=[legacy_element()])), "M-1", sample_element("r1", "place")))
2759
+ if migrated_like is not None:
2760
+ refuses("a revert where the history leaves the earlier status open", lambda: record_event(
2761
+ migrated_like, "M-1", "revert", element=revert), "REVERT_PRIOR_STATUS_AMBIGUOUS M-1", "incubating")
2762
+ event_case("revert", "refuse")
2763
+ for start in ("incubating", "retired"): # the element is the one start the history has, so the revert has its answer
2764
+ marked = accepts(f"a migrated {start} entry placed by a run", lambda start=start: apply_decision(sample_ledger(sample_entry(
2765
+ "M-1", start, decisions=[legacy_element(), migration_element(start)])), "M-1", sample_element("r1", "place")))
2766
+ if marked is not None:
2767
+ returned = accepts(f"a revert of the first run decision on a migrated {start} entry", lambda marked=marked: record_event(marked, "M-1", "revert", element=revert))
2768
+ if returned is not None:
2769
+ event_case("revert", "accept")
2770
+ if returned["entries"][0]["status"] != start:
2771
+ failures.append(f"revert: the entry was migrated {start} and the revert of its first run decision restored {returned['entries'][0]['status']}")
2772
+ clean(f"a revert to the status {start} recorded", check_pair(marked, returned, []))
2773
+ for label, call, needles in (
2774
+ ("a revert with no application to revert", lambda: record_event(sample_ledger(sample_entry("S3-1")), "S3-1", "revert", element=revert), ("REVERT_NOTHING S3-1",)),
2775
+ ("a revert that is not a revert decision", lambda: record_event(inc, "S3-2", "revert", element=sample_element("r4", "none")), ("EVENT_MALFORMED S3-2 revert",))):
2776
+ refuses(label, call, *needles)
2777
+ event_case("revert", "refuse")
2778
+ only_created = accepts("an entry created by place", lambda: create_entry(
2779
+ sample_ledger(sample_entry("G-0")), sample_entry("N-1", kind="gap"), sample_element("r1", "place")))
2780
+ if only_created is not None: # no status can start the history, so only creation does: the guard has to speak
2781
+ saved_vocabulary, globals()["vocabulary"] = vocabulary, lambda name: [] if name == "status" else saved_vocabulary(name)
2782
+ try:
2783
+ refuses("a revert of the decision that created the entry, with no status left to restore",
2784
+ lambda: revert_target(only_created["entries"][1], "placed"), "REVERT_PRIOR_STATUS_NONE")
2785
+ finally:
2786
+ globals()["vocabulary"] = saved_vocabulary
2787
+ for event in DESIGN_12_3_EVENTS:
2788
+ name = next((r["id"] for r in table["events"] if (r["from"], r["event"], r["to"]) == event), None)
2789
+ if name is None or ran["events"].get(name) != {"accept", "refuse"}:
2790
+ failures.append(f"events: design §12.3's {event[1]!r} has no accepting and refusing control (ran {ran['events'].get(name)})")
2791
+
2792
+ # decisions applied to entries (F#5): the effects each cell requires, checked on the resulting entry
2793
+ def fx(row, key):
2794
+ f = fixture_for(row, key)
2795
+ entries = [copy.deepcopy(f["entry"])] if ROW_STATUS.get(row) else []
2796
+ return f, sample_ledger(*f["others"], *entries)
2797
+
2798
+ def effect_case(token, row, key, *, element=None, updates=None, entry=None, others=None, rows=None):
2799
+ """Run the fixture of `row`/`key` with one footprint taken away; the production path must name the effect."""
2800
+ f, ledger = fx(row, key)
2801
+ if others is not None:
2802
+ ledger = sample_ledger(*others, *ledger["entries"][len(f["others"]):])
2803
+ element = element if element is not None else f["element"]
2804
+ updates = f["updates"] if updates is None else updates
2805
+ if ROW_STATUS.get(row) is None:
2806
+ refuses(f"{token} missing on {row}/{key}", lambda: create_entry(ledger, {**(entry or f["entry"]), **updates}, element), f"EFFECT_MISSING", token)
2807
+ else:
2808
+ refuses(f"{token} missing on {row}/{key}", lambda: apply_decision(ledger, f["entry"]["id"], element, updates), "EFFECT_MISSING", token)
2809
+ ran["effects"].add(token)
2810
+
2811
+ f, _ = fx("placed", "keep")
2812
+ effect_case("keep_record", "placed", "keep", updates={})
2813
+ effect_case("keep_record", "placed", "keep", element={k: v for k, v in f["element"].items() if k != "reason"})
2814
+ effect_case("keep_record", "no_entry_existing_unit", "keep", updates={})
2815
+ effect_case("absorbed_by", "placed", "reduce_merge", updates={})
2816
+ effect_case("absorbed_by", "placed", "reduce_merge", updates={"absorbed_by": "G-404"})
2817
+ effect_case("allocate_destination_entry", "no_entry_existing_unit", "reduce_merge", others=[sample_entry("G-0", "incubating")])
2818
+ f, _ = fx("placed", "incubate")
2819
+ effect_case("pending_intervention", "placed", "incubate", element={**f["element"], "expected_observation": None})
2820
+ f, _ = fx("placed", "drop")
2821
+ effect_case("dropped_intervention", "placed", "drop", element={k: v for k, v in f["element"].items() if k != "reason"})
2822
+ effect_case("never_placed", "no_entry_new_learning", "drop", entry={**fx("no_entry_new_learning", "drop")[0]["entry"], "destination": {
2823
+ "implementation": "x", "anchor": None, "package_id": None}})
2824
+ effect_case("text_revised", "incubating", "correct", updates={})
2825
+ f, _ = fx("incubating", "incubate")
2826
+ effect_case("expiry_renewed", "incubating", "incubate", element={**f["element"], "expected_observation": sample_observation("2026-06-30")})
2827
+ # the effects that a second row carries are held at the row check: the merge decision on the receiver, the revival of the entry
2828
+ f, ledger = fx("placed", "reduce_merge")
2829
+ absorbed = apply_decision(ledger, "S9-01", f["element"], f["updates"])
2830
+ clean("a merge with its receiving decision", check_pair(ledger, absorbed, []))
2831
+ stripped = copy.deepcopy(absorbed)
2832
+ stripped["entries"][0]["decisions"] = []
2833
+ stripped["entries"][0]["disposition"] = "none"
2834
+ expect("a merge whose receiver has no merge decision", check_pair(ledger, stripped, []), "EFFECT_MISSING S9-01", "receiver_merge_decision")
2835
+ ran["effects"].add("receiver_merge_decision")
2836
+ f, ledger = fx("absorbed_retired", "place")
2837
+ revived = apply_decision(ledger, "S9-01", f["element"], f["updates"])
2838
+ clean("a revival that drops the retirement", check_pair(ledger, revived, []))
2839
+ holding = copy.deepcopy(revived)
2840
+ holding["entries"][-1]["retired"] = "2026-08-09"
2841
+ expect("a revival that keeps the retirement", check_pair(ledger, holding, []), "EFFECT_MISSING S9-01", "revival")
2842
+ ran["effects"].add("revival")
2843
+ all_effects = {e for cells in table["cells"].values() for cell in cells.values() if cell for e in cell["effects"]}
2844
+ if all_effects != ran["effects"]:
2845
+ failures.append(f"effects: the table's {sorted(all_effects - ran['effects'])} have no refusing control, and the controls name {sorted(ran['effects'] - all_effects)} the table lacks")
2846
+ f, ledger = fx("no_entry_existing_unit", "none")
2847
+ if create_entry(ledger, f["entry"], f["element"]) != ledger:
2848
+ failures.append("a decision the table gives no entry created one")
2849
+ refuses("an entry created by an unapplied decision", lambda: create_entry(ledger, f["entry"], sample_element("r1", "correct", applied=False)), "NEW_ROW_UNAPPLIED")
2850
+ f, ledger = fx("no_entry_existing_unit", "correct")
2851
+ made = accepts("an entry created by a correct whose delivery failed", lambda: create_entry(
2852
+ ledger, f["entry"], sample_element("r1", "correct", delivery="failed")))
2853
+ if made is not None and [e["id"] for e in made["entries"]] != [e["id"] for e in ledger["entries"]] + ["S9-01"]:
2854
+ failures.append("a decision whose delivery failed did not create the entry its completed operations made")
2855
+ refuses("updates to an entry through an unapplied decision", lambda: apply_decision(
2856
+ base, "S3-1", sample_element("r1", "correct", applied=False), {"lesson": "edited"}), "UPDATES_WITHOUT_DECISION S3-1")
2857
+ refuses("updates outside the fields a decision changes", lambda: apply_decision(
2858
+ base, "S3-1", sample_element("r1", "correct"), {"id": "S3-9"}), "UPDATES_UNLICENSED S3-1")
2859
+
2860
+ # history: two decisions, each resolved on its own, and the status stays
2861
+ ledger = sample_ledger(sample_entry("S3-1", decisions=[]))
2862
+ ledger = apply_decision(ledger, "S3-1", sample_element("r1", "correct", observation=sample_observation("2026-12-31")))
2863
+ ledger = apply_decision(ledger, "S3-1", sample_element("r2", "incubate", observation=sample_observation("2027-02-28")))
2864
+ ledger = append_resolution(ledger, "S3-1", "r1", sample_resolution("r1", resolution="observed"))
2865
+ ledger = append_resolution(ledger, "S3-1", "r2", sample_resolution("r2", window="2027-03-01", resolution="pending"))
2866
+ decisions = ledger["entries"][0]["decisions"]
2867
+ if [len(d["expected_observation"]["resolutions"]) for d in decisions] != [1, 1] or ledger["entries"][0]["status"] != "placed":
2868
+ failures.append(f"history: two decisions with one resolution each, status unchanged, expected; got {decisions}")
2869
+ if [d["expected_observation"]["resolutions"][0]["resolution"] for d in decisions] != ["observed", "pending"]:
2870
+ failures.append("history: each decision keeps its own resolution")
2871
+ clean("the history ledger", validate_ledger(ledger))
2872
+ wrong = copy.deepcopy(ledger)
2873
+ wrong["entries"][0]["decisions"][1]["expected_observation"]["resolutions"].append(sample_resolution("r1", window="2027-04-01"))
2874
+ expect("a resolution appended to the wrong decision", validate_ledger(wrong), "RESOLUTION_MISPLACED S3-1 decisions[1]")
2875
+ refuses("a resolution for a run that decided nothing", lambda: append_resolution(ledger, "S3-1", "r9", sample_resolution("r9")), "RESOLUTION_TARGET_MISSING")
2876
+ refuses("a resolution outside the vocabulary", lambda: append_resolution(ledger, "S3-1", "r1", {**sample_resolution("r1"), "resolution": "later"}), "LEDGER_INVALID")
2877
+ pre = sample_ledger(sample_entry("S3-1", decisions=[sample_element("r1", "correct", observation=sample_observation())]))
2878
+ clean("a resolution appended to an existing decision", check_pair(pre, append_resolution(pre, "S3-1", "r1", sample_resolution("r1")), []))
2879
+ refuses("a decision for no entry", lambda: apply_decision(pre, "S9-9", sample_element("r2", "none")), "ENTRY_UNKNOWN S9-9")
2880
+ refuses("a rejected pair applied", lambda: apply_decision(pre, "S3-1", sample_element("r2", "place")), "TRANSITION_DISALLOWED")
2881
+ refuses("a keep applied without its record", lambda: apply_decision(pre, "S3-1", sample_element("r2", "keep", reason="kept")), "EFFECT_MISSING")
2882
+ kept = apply_decision(pre, "S3-1", sample_element("r2", "keep", reason="kept"), {"keep": {"units": ["u"]}})
2883
+ if kept["entries"][0]["keep"] != {"units": ["u"]} or kept["entries"][0]["status"] != "placed" or kept["entries"][0]["disposition"] != "keep":
2884
+ failures.append("a keep with its record did not keep the entry placed and say so")
2885
+ unapplied = apply_decision(sample_ledger(sample_entry("S3-1", "incubating")), "S3-1", sample_element("r2", "place", applied=False))
2886
+ if unapplied["entries"][0]["status"] != "incubating" or unapplied["entries"][0]["disposition"] != "none":
2887
+ failures.append("an unapplied place moved the status or the disposition")
2888
+
2889
+ # transitions: the data renders to the design's wording, every allowed cell has a frozen fixture that runs
2890
+ if list(table["cells"]) != list(DESIGN_12_3):
2891
+ failures.append(f"transitions: rows {list(table['cells'])} differ from the design's {list(DESIGN_12_3)}")
2892
+ for row, wording in DESIGN_12_3.items():
2893
+ for key, text in zip(table["dispositions"], wording):
2894
+ rendered = render_cell(table["cells"][row][key])
2895
+ if not rendered.startswith("—") if text.startswith("—") else rendered != text:
2896
+ failures.append(f"transitions: {row}/{key} renders {rendered!r}, the design says {text!r}")
2897
+ if len(table["dispositions"]) != len(next(iter(DESIGN_12_3.values()))):
2898
+ failures.append("transitions: the table's columns are not the design's nine")
2899
+ mutated = copy.deepcopy(table)
2900
+ mutated["cells"]["placed"]["keep"]["effects"] = []
2901
+ _TABLES["t"] = mutated
2902
+ try:
2903
+ if render_cell(mutated["cells"]["placed"]["keep"]) == DESIGN_12_3["placed"][3]:
2904
+ failures.append("transitions: a cell losing its effect still rendered the design's wording")
2905
+ finally:
2906
+ _TABLES["t"] = table
2907
+ refuses("an effect with no wording", lambda: render_cell({"new_entry": False, "status": "placed", "effects": ["invented"]}), "TRANSITION_EFFECT_UNKNOWN")
2908
+ refuses("an effect no check exists for", lambda: effect_problems(
2909
+ {"effects": ["invented"]}, sample_element("r1", "none"), None, sample_entry("S3-1"), {}), "TRANSITION_EFFECT_UNKNOWN")
2910
+ if len(cell_ids()) != 29:
2911
+ failures.append(f"transitions: {len(cell_ids())} allowed cells, the design's table has 29")
2912
+ fixtures = json.loads(FIXTURES_PATH.read_text(encoding="utf-8"))["fixtures"]
2913
+ executed = set()
2914
+ for fixture in fixtures:
2915
+ failures += [f"transitions: {line}" for line in fixture_problems(fixture)]
2916
+ executed.add(fixture["id"]) # recorded after the case ran through the real code path
2917
+ frozen = {f["id"] for f in fixtures}
2918
+ clean("table cells, frozen fixtures and executed cases", coverage_problems(cell_ids(), frozen, executed))
2919
+ scratch_cells = copy.deepcopy(table)
2920
+ scratch_cells["cells"]["incubating"]["re-deliver"] = scratch_cells["cells"]["incubating"]["correct"]
2921
+ _TABLES["t"] = scratch_cells
2922
+ try:
2923
+ expect("a cell added to the table, the fixtures unchanged", coverage_problems(cell_ids(), frozen, executed), "CELL_UNFIXTURED incubating/re-deliver")
2924
+ finally:
2925
+ _TABLES["t"] = table
2926
+ expect("a frozen fixture deleted", coverage_problems(cell_ids(), frozen - {"placed/keep"}, executed), "CELL_UNFIXTURED placed/keep")
2927
+ expect("a cell removed with its fixture left", coverage_problems(set(cell_ids()) - {"placed/keep"}, frozen, executed), "FIXTURE_ORPHAN placed/keep")
2928
+ expect("an executed case removed from the run's record", coverage_problems(cell_ids(), frozen, executed - {"placed/keep"}), "CASE_NOT_EXECUTED placed/keep")
2929
+ expect("a case executed with no fixture", coverage_problems(cell_ids(), frozen, executed | {"placed/place"}), "CASE_UNFROZEN placed/place")
2930
+ by_id = {f["id"]: f for f in fixtures}
2931
+ for cid, mutate, needle in (("no_entry_new_learning/place", lambda t: t["cells"]["no_entry_new_learning"]["place"].update(status="incubating"), "the table now says"),
2932
+ ("placed/keep", lambda t: t["cells"]["placed"]["keep"].update(effects=[]), "effects"),
2933
+ ("incubating/place", lambda t: t["cells"]["incubating"]["place"].update(status="retired"), "the table now says")):
2934
+ changed_table = copy.deepcopy(table)
2935
+ mutate(changed_table)
2936
+ _TABLES["t"] = changed_table
2937
+ try:
2938
+ expect(f"fixture {cid} against a changed table", fixture_problems(by_id[cid]), needle)
2939
+ finally:
2940
+ _TABLES["t"] = table
2941
+ saved_status_after, globals()["status_after"] = status_after, lambda status, cell: "retired"
2942
+ try: # the fixtures run the production code: when it moves the status somewhere else than the table does, they say so
2943
+ expect("a production status_after that disagrees with the table", fixture_problems(by_id["incubating/place"]), "the status moved")
2944
+ finally:
2945
+ globals()["status_after"] = saved_status_after
2946
+ saved_takes_effect, globals()["takes_effect"] = takes_effect, lambda element: False
2947
+ try:
2948
+ expect("a production creation that refuses the decision", fixture_problems(by_id["no_entry_new_learning/place"]),
2949
+ "no_entry_new_learning/place:", "NEW_ROW_UNAPPLIED")
2950
+ finally:
2951
+ globals()["takes_effect"] = saved_takes_effect
2952
+ saved_create, globals()["create_entry"] = create_entry, lambda ledger, entry, element: copy.deepcopy(ledger)
2953
+ try:
2954
+ expect("a production creation that creates nothing", fixture_problems(by_id["no_entry_new_learning/place"]), "0 entries created")
2955
+ finally:
2956
+ globals()["create_entry"] = saved_create
2957
+ saved_entry_row, globals()["entry_row"] = entry_row, lambda entry: "no_entry_existing_unit"
2958
+ try:
2959
+ expect("a production creation that reads the wrong row", fixture_problems(by_id["no_entry_new_learning/place"]), "no_entry_new_learning/place:", "TRANSITION_DISALLOWED")
2960
+ finally:
2961
+ globals()["entry_row"] = saved_entry_row
2962
+ for row, key in (("no_entry_new_learning", "keep"), ("placed", "place"), ("absorbed_retired", "reduce_merge")):
2963
+ refuses(f"{row}/{key}", lambda row=row, key=key: transition(row, key), "TRANSITION_DISALLOWED")
2964
+ refuses("an unknown row", lambda: transition("nowhere", "place"), "TRANSITION_DISALLOWED nowhere + place")
2965
+ with tempfile.TemporaryDirectory() as td:
2966
+ target = pathlib.Path(td) / "fixtures.json"
2967
+ if generate_fixtures(target) != 29:
2968
+ failures.append("transitions: the generator did not write 29 fixtures")
2969
+ if json.loads(target.read_text(encoding="utf-8"))["fixtures"] != fixtures:
2970
+ failures.append("transitions: the generator's fixtures differ from the frozen ones")
2971
+ refuses("a second generation", lambda: generate_fixtures(target), "FIXTURES_FROZEN")
2972
+
2973
+ # atomic writes: a stale base, a held lock, a crash before the rename, an escape, an invalid ledger
2974
+ with tempfile.TemporaryDirectory() as td:
2975
+ root = pathlib.Path(td)
2976
+ target, lock_root = root / "ledger" / "ledger.json", root / "lock"
2977
+ target.parent.mkdir()
2978
+ write_atomic(target, base, EMPTY_SHA, lock_root)
2979
+ if json.loads(target.read_text(encoding="utf-8")) != base or target.read_text(encoding="utf-8") != render(base):
2980
+ failures.append("write: a first write did not leave the ledger's bytes")
2981
+ first = sha256_bytes(target.read_bytes())
2982
+ newer = apply_decision(base, "S3-2", sample_element("r1", "place"))
2983
+ write_atomic(target, newer, first, lock_root)
2984
+ refuses("a stale base", lambda: write_atomic(target, base, first, lock_root), "BASE_STALE")
2985
+ if json.loads(target.read_text(encoding="utf-8")) != newer:
2986
+ failures.append("write: a refused stale writer changed the file")
2987
+ current = sha256_bytes(target.read_bytes())
2988
+ # the bytes on disk are the base of a transaction, so what this writer would replace them
2989
+ # with is held against them, and a writer that erases or reorders a decision is refused
2990
+ # before anything is written (U#0). Every write below is a transaction over the one before it.
2991
+ # The plants run against a file of their own, so a write that slipped through would be read
2992
+ # here rather than disturbing the chain the crash controls depend on.
2993
+ later = apply_decision(newer, "S3-2", sample_element("r2", "correct"))
2994
+ probe = root / "ledger" / "probe.json"
2995
+ write_atomic(probe, newer, EMPTY_SHA, lock_root)
2996
+ reordered = {**later, "entries": [{**row, "decisions": list(reversed(row["decisions"]))} if row["id"] == "S3-2" else row
2997
+ for row in later["entries"]]}
2998
+ for label, proposed, successor, needle in (
2999
+ ("a decision removed", base, later, "DECISION_REWRITTEN S3-2: 1 decision(s) removed"),
3000
+ ("the decisions reordered", reordered, None, "DECISION_REWRITTEN S3-2 decisions[0]")):
3001
+ held = sha256_bytes(probe.read_bytes())
3002
+ refuses(f"a writer with {label}", lambda proposed=proposed, held=held: write_atomic(probe, proposed, held, lock_root),
3003
+ "TRANSACTION_INVALID, nothing written", needle)
3004
+ if sha256_bytes(probe.read_bytes()) != held:
3005
+ failures.append(f"write: a writer with {label} was refused and the file changed anyway")
3006
+ if successor is not None: # the next plant needs a row with two decisions to reorder
3007
+ write_atomic(probe, successor, sha256_bytes(probe.read_bytes()), lock_root)
3008
+ with stagelock.hold(lock_root, "ledger"):
3009
+ try:
3010
+ write_atomic(target, later, current, lock_root)
3011
+ failures.append("write: a second writer took a held lock")
3012
+ except stagelock.Locked as exc:
3013
+ expect("a held lock", [str(exc)], "STAGE_LOCKED ledger")
3014
+ before = target.read_bytes()
3015
+
3016
+ class Crash(Exception):
3017
+ pass
3018
+
3019
+ def crash():
3020
+ raise Crash("injected between the temporary write and the rename")
3021
+ try:
3022
+ write_atomic(target, later, current, lock_root, before_rename=crash)
3023
+ failures.append("write: the injected crash did not surface")
3024
+ except Crash:
3025
+ pass
3026
+ if target.read_bytes() != before or sorted(p.name for p in target.parent.iterdir()) != ["ledger.json", "probe.json"]:
3027
+ failures.append("write: a crash before the rename changed the file or left a temporary behind")
3028
+ hard = subprocess.run([sys.executable, "-c", HARD_KILL, str(HERE), str(target), current,
3029
+ str(lock_root)], capture_output=True, text=True)
3030
+ if hard.returncode != 9 or target.read_bytes() != before:
3031
+ failures.append(f"write: a process killed before the rename left the file changed (exit {hard.returncode})")
3032
+ # the same successor the killed child proposed, written now: it lands, so what the child
3033
+ # proposed was a transaction this writer accepts and the unchanged bytes above say the
3034
+ # rename had not happened rather than that nothing was proposed (X#1)
3035
+ write_atomic(target, later, current, lock_root)
3036
+ if target.read_text(encoding="utf-8") != render(later):
3037
+ failures.append("write: a write after a killed writer did not land")
3038
+ landed = sha256_bytes(target.read_bytes())
3039
+ # a base is read as a ledger before it is read as a transaction's base (X#0): a file of its
3040
+ # own takes an append first, then each shape that is not a ledger is refused over it and the
3041
+ # bytes stay. A valid empty-looking ledger is the one worth planting — nothing in a row or
3042
+ # window comparison would have reported it.
3043
+ scratch = root / "ledger" / "scratch.json"
3044
+ write_atomic(scratch, newer, EMPTY_SHA, lock_root)
3045
+ write_atomic(scratch, later, sha256_bytes(scratch.read_bytes()), lock_root)
3046
+ if scratch.read_text(encoding="utf-8") != render(later):
3047
+ failures.append("write: an append over a sound base of its own did not land")
3048
+ for label, text in ( # the shapes a reader reports on come first, the one it raises on last
3049
+ ("bytes that are not a ledger", "not a ledger at all"),
3050
+ ("a ledger without the framework design §12.1 requires", json.dumps({"schema": 2, "windows": [], "entries": []})),
3051
+ ("a base holding two rows of one id", render({**base, "entries": [base["entries"][0], copy.deepcopy(base["entries"][0])]})),
3052
+ ("JSON that is not an object", "[]")):
3053
+ scratch.write_text(text, encoding="utf-8")
3054
+ refuses(f"a writer over {label}", lambda text=text: write_atomic(
3055
+ scratch, later, sha256_bytes(text.encode("utf-8")), lock_root), "BASE_UNREADABLE", "nothing written")
3056
+ if scratch.read_text(encoding="utf-8") != text:
3057
+ failures.append(f"write: a writer over {label} was refused and the file changed anyway")
3058
+ elsewhere = root / "elsewhere"
3059
+ elsewhere.mkdir()
3060
+ (elsewhere / "ledger.json").write_text("{}", encoding="utf-8")
3061
+ (root / "linked").mkdir()
3062
+ (root / "linked" / "ledger.json").symlink_to(elsewhere / "ledger.json")
3063
+ try:
3064
+ write_atomic(root / "linked" / "ledger.json", base, sha256_bytes(b"{}"), lock_root)
3065
+ failures.append("write: a ledger linked to a file outside its directory was replaced")
3066
+ except stagelock.Escaped as exc:
3067
+ expect("a linked ledger", [str(exc)], "RUN_PATH_ESCAPE")
3068
+ if (elsewhere / "ledger.json").read_text(encoding="utf-8") != "{}":
3069
+ failures.append("write: a linked ledger's target was changed")
3070
+ refuses("an invalid ledger", lambda: write_atomic(target, dropped, landed, lock_root), "LEDGER_INVALID, nothing written")
3071
+
3072
+ # the check command, end to end over scratch repositories: index against HEAD, then exit codes
3073
+ with scratch_git() as (repo, git):
3074
+ path = repo / STATE_LEDGER_REL
3075
+ path.parent.mkdir(parents=True)
3076
+ path.write_text(render(base), encoding="utf-8")
3077
+ git("add", "-A")
3078
+ git("commit", "-q", "-m", "base")
3079
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", False, None)
3080
+ if code != 0 or "OK" not in lines[0]:
3081
+ failures.append(f"check: an unchanged ledger was not accepted: {code} {lines}")
3082
+ swapped = copy.deepcopy(base)
3083
+ swapped["entries"][2] = sample_entry("S3-4", "incubating")
3084
+ path.write_text(render(swapped), encoding="utf-8")
3085
+ git("add", STATE_LEDGER_REL)
3086
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", False, None)
3087
+ if code != 1 or "ID_LOST S3-3" not in "\n".join(lines) or "ALLOCATION_REQUIRED" not in "\n".join(lines):
3088
+ failures.append(f"check: a staged equal-count deletion plus insertion was not refused naming the lost id and the missing allocation: {code} {lines}")
3089
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", False, ["S3-4"])
3090
+ if code != 1 or "ID_LOST S3-3" not in "\n".join(lines) or "NEW_ROW_WITHOUT_DECISION S3-4" not in "\n".join(lines):
3091
+ failures.append(f"check: under its allocation, the swap was not refused naming the lost id and the row with no decision: {code} {lines}")
3092
+ path.write_text(render(base), encoding="utf-8") # restored on disk; the index keeps the swap
3093
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", False, None)
3094
+ if code != 1:
3095
+ failures.append(f"check: the index was not judged when the disk was restored: {code} {lines}")
3096
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", True, None)
3097
+ if code != 0:
3098
+ failures.append(f"check: --worktree did not read the disk: {code} {lines}")
3099
+ code, lines = check_command(repo, STATE_LEDGER_REL, "no-such-revision", False, None)
3100
+ if code != 2 or "CANNOT JUDGE" not in lines[0]:
3101
+ failures.append(f"check: an unresolvable base did not exit 2 naming it: {code} {lines}")
3102
+ git("rm", "-q", "-f", "--cached", STATE_LEDGER_REL)
3103
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", False, None)
3104
+ if code != 1 or "LEDGER_ABSENT" not in lines[0]:
3105
+ failures.append(f"check: a ledger removed from the index was not refused: {code} {lines}")
3106
+ git("add", STATE_LEDGER_REL)
3107
+ path.unlink()
3108
+ path.mkdir() # a directory where the file should be: the disk cannot answer
3109
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", True, None)
3110
+ if code != 2 or "LEDGER_FILE_UNREADABLE" not in lines[0]:
3111
+ failures.append(f"check: a side the disk could not read did not exit 2 naming it: {code} {lines}")
3112
+ path.rmdir()
3113
+ path.write_text("{ not json", encoding="utf-8")
3114
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", True, None)
3115
+ if code != 1 or "LEDGER_UNREADABLE" not in lines[0]:
3116
+ failures.append(f"check: an unparsable ledger was not refused: {code} {lines}")
3117
+ with scratch_git() as (repo, git):
3118
+ (repo / "README").write_text("x", encoding="utf-8")
3119
+ git("add", "-A")
3120
+ git("commit", "-q", "-m", "no ledger")
3121
+ (repo / STATE_LEDGER_REL).parent.mkdir(parents=True)
3122
+ (repo / STATE_LEDGER_REL).write_text(render(base), encoding="utf-8")
3123
+ git("add", "-A")
3124
+ code, lines = check_command(repo, STATE_LEDGER_REL, "HEAD", False, None)
3125
+ if code != 0 or "validated alone" not in lines[0]:
3126
+ failures.append(f"check: a ledger new in the index was not validated alone: {code} {lines}")
3127
+
3128
+ # the command line, end to end (F#3): a run that allocated no id says so, and that is not the
3129
+ # same argument as no run at all. A correction writes the ledger and adds no row.
3130
+ for label, argument, want in (("an omitted flag", None, None), ("the flag passed empty", "", []),
3131
+ ("one id", "N-1", ["N-1"]), ("two ids and a space", "N-1, N-2", ["N-1", "N-2"])):
3132
+ if allocation(argument) != want:
3133
+ failures.append(f"allocation: {label} read as {allocation(argument)!r}, expected {want!r}")
3134
+ with scratch_git() as (repo, git):
3135
+ path = repo / STATE_LEDGER_REL
3136
+ path.parent.mkdir(parents=True)
3137
+ path.write_text(render(base), encoding="utf-8")
3138
+ git("add", "-A")
3139
+ git("commit", "-q", "-m", "base")
3140
+ path.write_text(render(apply_decision(base, "S3-1", sample_element("r1", "correct"), {"lesson": "a corrected lesson"})), encoding="utf-8")
3141
+ git("add", STATE_LEDGER_REL)
3142
+ kept_repo, globals()["REPO"] = REPO, repo
3143
+ try:
3144
+ for label, argv, want_code, needle in (
3145
+ ("a correction under the empty allocation it froze", ["--check", "--allocated", ""], 0, "OK"),
3146
+ ("the same correction with no allocation at all", ["--check"], 1, "ALLOCATION_REQUIRED"),
3147
+ ("an allocated id no row of the result carries", ["--check", "--allocated", "N-9"], 1, "ID_ALLOCATED_MISSING N-9")):
3148
+ out, err = io.StringIO(), io.StringIO()
3149
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
3150
+ code = main(argv)
3151
+ said = (out.getvalue() + err.getvalue()).strip()
3152
+ if code != want_code or needle not in said:
3153
+ failures.append(f"check CLI, {label}: expected exit {want_code} naming {needle}, got {code}: {said[:160]}")
3154
+ finally:
3155
+ globals()["REPO"] = kept_repo
3156
+
3157
+ for failure in failures:
3158
+ print(f"ledger --self-test [FAIL] {failure}")
3159
+ if failures:
3160
+ return 1
3161
+ for name in skipped:
3162
+ print(f"ledger --self-test SKIPPED: {name}")
3163
+ print("ledger --self-test: OK (contract fidelity against design §12.1/§12.2/§12.4/§7.2/§7.3 and the record contracting what "
3164
+ "schema 2 carries beyond them, validation with the two disposition vocabularies, the two element shapes and the evidence "
3165
+ "forms, the id-set check against the frozen allocation a schema 2 transaction carries whether or not it adds a row, changed "
3166
+ "rows and new rows bound to the decision whose disposition licenses them, an application standing with its delivery failed or "
3167
+ "unverified and its delivery outcome written into the decision already there, the five events with accepting and refusing controls, "
3168
+ "a migrated element refused when a run appends it on an existing or a new row, one decision per row a transaction allocates, a "
3169
+ "revert that restores the status design §12.3 derives and the values the application it undoes recorded — one round trip per "
3170
+ "disposition that changes a row, a keep reaffirmed, a merge with its receiver, and a named refusal where an application recorded "
3171
+ "nothing, where its record disagrees with the row change, where the receiver has moved on, and where an application and its "
3172
+ "revert are batched into one close — the revert to the migrated status, "
3173
+ "every effect of the table refused "
3174
+ "when missing, 29 transitions rendered to the design's wording and run from frozen fixtures, atomic writes with an "
3175
+ "injected crash, --check over scratch repositories)")
3176
+ return 0
3177
+
3178
+
3179
+ def main(argv=None):
3180
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
3181
+ parser.add_argument("--check", action="store_true")
3182
+ parser.add_argument("--ledger", default=STATE_LEDGER_REL,
3183
+ help="path of the ledger, relative to the repository for --check; the default is the "
3184
+ "state-root location an installed driver uses, and a checkout passes its own "
3185
+ "(gates/check-ledger.py does)")
3186
+ parser.add_argument("--base", default="HEAD")
3187
+ parser.add_argument("--worktree", action="store_true", help="read the file on disk instead of the index")
3188
+ parser.add_argument("--allocated", help="comma-separated ids the run allocated; pass it empty for a "
3189
+ "transaction that allocated none, omit it only when there is no run")
3190
+ parser.add_argument("--generate-transition-fixtures", action="store_true")
3191
+ parser.add_argument("--self-test", action="store_true")
3192
+ args = parser.parse_args(argv)
3193
+ if args.self_test:
3194
+ return self_test()
3195
+ if args.generate_transition_fixtures:
3196
+ try:
3197
+ print(f"wrote {generate_fixtures()} fixtures to {FIXTURES_PATH}")
3198
+ except LedgerError as exc:
3199
+ sys.exit(str(exc))
3200
+ return 0
3201
+ if args.check:
3202
+ code, lines = check_command(REPO, args.ledger, args.base, args.worktree, allocation(args.allocated))
3203
+ print("\n".join(lines), file=sys.stdout if code == 0 else sys.stderr)
3204
+ return code
3205
+ parser.print_usage()
3206
+ return 2
3207
+
3208
+
3209
+ if __name__ == "__main__":
3210
+ sys.exit(main())