agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -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 +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,881 @@
1
+ #!/usr/bin/env python3
2
+ """The coverage state of design §5.2, and the range algebra it rests on.
3
+
4
+ `session-distill/coverage.json` records, per transcript, a list of versions `{sha,
5
+ record_count, prefix_sha}` and, per version, two kinds of range over its records (0-based
6
+ record index, half-open): **read** (seen in a view, for any reason) and **processed for
7
+ window w** (owned by w and extracted for it). Only processed ranges discharge work: a record
8
+ read as context for another window stays unprocessed for its own, and the run that owns it
9
+ reads it again. Records are the lines of the decompressed transcript, so record `i` is line
10
+ `i + 1`. A *version* is a continuity chain: an append updates it in place (`sha`,
11
+ `record_count`, `prefix_sha` move, the ranges before it stay true), a rewrite starts the next
12
+ one. Pending events, the backlog of unread ranges and the window flags live beside it.
13
+
14
+ This module owns the state and its transitions; it does not decide when to promote a run's
15
+ state to the tracked file. `write_atomic` is that last step (lock, base-hash check, temporary
16
+ file, fsync, rename), for S12. Targeted runs read but never advance periodic coverage:
17
+ `check_targeted` is the guard that says so.
18
+
19
+ A transcript is keyed by its identity, `<host>:<session id>` (`lineage.identity`). Work has the identity
20
+ (transcript, version, window): a record range is owed to one version of one transcript for one window, so
21
+ an S3 result names the version it read and may credit a range only to the current window's own records of
22
+ the latest version, or to a backlog entry of that same version and window, and only for records the same
23
+ result read: a record read earlier as context is read again by the run that owns it. A targeted run's
24
+ results are held to the same rules against the state it observed, and then discarded. One result answers a
25
+ unit, a root with its members (D-20261103-85f3e8): a member is a transcript of its own here, and the result's
26
+ readings credit it by name.
27
+
28
+ Failures are named by their first word: COVERAGE_INVALID, COVERAGE_BASE_STALE,
29
+ TARGETED_ADVANCED_COVERAGE, PROCESSED_OUTSIDE_OWNED, PROCESSED_UNREAD, VERSION_MISMATCH,
30
+ RESULT_INCONSISTENT, RESULT_STATUS_INVALID.
31
+
32
+ coverage.py --self-test
33
+ """
34
+ import bisect
35
+ import copy
36
+ import datetime
37
+ import itertools
38
+ import hashlib
39
+ import json
40
+ import os
41
+ import pathlib
42
+ import sys
43
+ import tempfile
44
+ import zoneinfo
45
+
46
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
47
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
48
+ from runlib import lineage, records, stagelock, validate
49
+ from runlib.records import Refused
50
+
51
+ SCHEMA_PATH = pathlib.Path(__file__).resolve().parents[1] / "schemas" / "coverage.schema.json"
52
+ TERMINAL = ("read_complete", "read_partial", "failed", "deferred", "nothing_new") # design §5.1
53
+ CARRIED = ("read_partial", "failed", "deferred") # the ones whose unread ranges wait in the backlog
54
+ # the backlog status of records S1 found appended to a version after the run of the window that owns them (review c0fix
55
+ # r1 #1): no result left them unread, they had not been written when that window was read
56
+ APPENDED = "appended"
57
+ _VALIDATOR = []
58
+
59
+
60
+ def validator():
61
+ if not _VALIDATOR:
62
+ _VALIDATOR.append(validate.compile_schema(json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))))
63
+ return _VALIDATOR[0]
64
+
65
+
66
+ # ---- ranges: sorted, merged, non-empty [start, end) pairs over record indexes -----------------
67
+
68
+ def normalize(ranges):
69
+ merged = []
70
+ for start, end in sorted(map(tuple, ranges)):
71
+ if end <= start:
72
+ continue
73
+ if merged and start <= merged[-1][1]:
74
+ merged[-1][1] = max(merged[-1][1], end)
75
+ else:
76
+ merged.append([start, end])
77
+ return merged
78
+
79
+
80
+ def union(a, b):
81
+ return normalize([*a, *b])
82
+
83
+
84
+ def subtract(a, b):
85
+ out, cuts = [], normalize(b)
86
+ for start, end in normalize(a):
87
+ for cut_start, cut_end in cuts:
88
+ if cut_end <= start or cut_start >= end:
89
+ continue
90
+ if cut_start > start:
91
+ out.append([start, cut_start])
92
+ start = max(start, cut_end)
93
+ if start >= end:
94
+ break
95
+ if start < end:
96
+ out.append([start, end])
97
+ return out
98
+
99
+
100
+ def window_bounds(window):
101
+ """(start, end, id) of a run's half-open window (design §4.1): aware instants and the key the
102
+ state files it under. A window without an offset is read in its own `tz`."""
103
+ zone = zoneinfo.ZoneInfo(window["tz"])
104
+ start, end = (datetime.datetime.fromisoformat(window[k]) for k in ("start", "end"))
105
+ start, end = (t if t.tzinfo else t.replace(tzinfo=zone) for t in (start, end))
106
+ return start, end, f"{window['start']}/{window['end']}@{window['tz']}"
107
+
108
+
109
+ def bounds_of(window_id):
110
+ """(start, end) of the window an id names, read back the way `window_bounds` wrote it (`<start>/<end>@<tz>`)."""
111
+ span, _at, tz = window_id.rpartition("@")
112
+ start, _slash, end = span.partition("/")
113
+ try:
114
+ return window_bounds({"start": start, "end": end, "tz": tz})[:2]
115
+ except (ValueError, zoneinfo.ZoneInfoNotFoundError) as exc:
116
+ raise Refused(f"COVERAGE_INVALID window {window_id!r}: {exc}") from exc
117
+
118
+
119
+ def instant(stamp):
120
+ """A record's timestamp as an aware instant (one without an offset is UTC), or None when it has none that parses."""
121
+ try:
122
+ when = datetime.datetime.fromisoformat(stamp)
123
+ except (TypeError, ValueError):
124
+ return None
125
+ return when if when.tzinfo else when.replace(tzinfo=datetime.timezone.utc)
126
+
127
+
128
+ class Ownership:
129
+ """Which records a window owns (design §5.2): a record belongs to the window when its timestamp
130
+ is in `[start, end)`. A record with no timestamp takes its predecessor's; leading ones take the
131
+ first that has one."""
132
+
133
+ def __init__(self, start, end):
134
+ self.start, self.end, self.runs, self.stamped = start, end, [], 0
135
+
136
+ def feed(self, index, stamp):
137
+ when = instant(stamp)
138
+ if when is None:
139
+ return
140
+ self.stamped += 1
141
+ side = -1 if when < self.start else 1 if when >= self.end else 0
142
+ if not self.runs:
143
+ self.runs.append([side, 0])
144
+ elif self.runs[-1][0] != side:
145
+ self.runs.append([side, index])
146
+
147
+ def finish(self, count):
148
+ """`{owned, before, after}`: the owned ranges and whether records lie before or after the window."""
149
+ bounds = [run[1] for run in self.runs[1:]] + [count]
150
+ owned = normalize([[run[1], end] for run, end in zip(self.runs, bounds) if run[0] == 0])
151
+ sides = {run[0] for run in self.runs}
152
+ return {"owned": owned, "before": -1 in sides, "after": 1 in sides}
153
+
154
+
155
+ class Owners:
156
+ """Which of several windows (`[(start, end, id)]`) own each record, by `Ownership`'s rule: a record belongs to every
157
+ window whose `[start, end)` holds its timestamp, one without a timestamp to its predecessor's windows, leading ones
158
+ to the first stamped record's. The windows are searched by their start, and the search goes back only while an
159
+ earlier window still reaches past the record, so windows that do not overlap cost a comparison or two a record."""
160
+
161
+ def __init__(self, windows):
162
+ self.windows = sorted(windows, key=lambda w: (w[0], w[1]))
163
+ self.starts = [w[0] for w in self.windows]
164
+ self.reach = list(itertools.accumulate((w[1] for w in self.windows), max))
165
+ self.runs = []
166
+
167
+ def feed(self, index, stamp):
168
+ when = instant(stamp)
169
+ if when is None:
170
+ return
171
+ found, k = [], bisect.bisect_right(self.starts, when) - 1
172
+ while k >= 0 and self.reach[k] > when:
173
+ if self.windows[k][1] > when:
174
+ found.append(self.windows[k][2])
175
+ k -= 1
176
+ owners = tuple(sorted(found))
177
+ if not self.runs:
178
+ self.runs.append([owners, 0])
179
+ elif self.runs[-1][0] != owners:
180
+ self.runs.append([owners, index])
181
+
182
+ def finish(self, count):
183
+ """`{window id: owned ranges}` for every window that owns a record."""
184
+ bounds = [run[1] for run in self.runs[1:]] + [count]
185
+ owned = {}
186
+ for (owners, start), end in zip(self.runs, bounds):
187
+ for window in owners:
188
+ owned.setdefault(window, []).append([start, end])
189
+ return {window: normalize(ranges) for window, ranges in owned.items()}
190
+
191
+
192
+ # ---- the state --------------------------------------------------------------------------------
193
+
194
+ def new_state():
195
+ return {"transcripts": {}, "pending_events": [], "backlog": [], "windows": {}}
196
+
197
+
198
+ def digest(state):
199
+ return records.bound_digest(state)
200
+
201
+
202
+ def check_state(state):
203
+ """Violations of the state's own invariants, beyond its schema; empty when it holds."""
204
+ errors = list(map(lambda e: f"COVERAGE_INVALID {e}", validate.validate_instance(validator(), state)))
205
+ if errors:
206
+ return errors
207
+ for tid, entry in state["transcripts"].items():
208
+ for number, version in enumerate(entry["versions"]):
209
+ where = f"{tid} version {number}"
210
+ sets = [("read", version["read"])] + [(f"processed[{w}]", r) for w, r in version["processed"].items()]
211
+ for label, ranges in sets:
212
+ if ranges != normalize(ranges):
213
+ errors.append(f"COVERAGE_INVALID {where} {label}: ranges are not sorted, merged and non-empty")
214
+ elif ranges and ranges[-1][1] > version["record_count"]:
215
+ errors.append(f"COVERAGE_INVALID {where} {label}: a range ends past record_count {version['record_count']}")
216
+ for w, ranges in version["processed"].items():
217
+ if subtract(ranges, version["read"]):
218
+ errors.append(f"COVERAGE_INVALID {where} processed[{w}]: records processed that were never read")
219
+ ids = [event["id"] for event in state["pending_events"]]
220
+ errors += [f"COVERAGE_INVALID pending event id {i!r} repeats" for i in sorted({i for i in ids if ids.count(i) > 1})]
221
+ for item in state["pending_events"] + state["backlog"]:
222
+ versions = state["transcripts"].get(item["transcript"], {}).get("versions", [])
223
+ if item["version"] >= len(versions):
224
+ errors.append(f"COVERAGE_INVALID {item.get('id') or 'backlog'} names version {item['version']} of {item['transcript']}, which is not in the state")
225
+ return errors
226
+
227
+
228
+ def load(path):
229
+ """(state, sha256 of the file's bytes). A file that is absent is the empty state, which hashes as
230
+ the committed initial file does; one that does not conform is refused by name."""
231
+ path = pathlib.Path(path)
232
+ try:
233
+ data = path.read_bytes()
234
+ except FileNotFoundError:
235
+ data = records.json_text(new_state()).encode("utf-8")
236
+ except OSError as exc:
237
+ raise Refused(f"COVERAGE_INVALID {path}: {exc.strerror or exc}") from exc
238
+ try:
239
+ state = json.loads(data)
240
+ except ValueError as exc:
241
+ raise Refused(f"COVERAGE_INVALID {path}: not JSON: {exc}") from exc
242
+ errors = check_state(state) if isinstance(state, dict) else ["COVERAGE_INVALID the state is not an object"]
243
+ if errors:
244
+ raise Refused("\n".join(errors))
245
+ return state, records.sha256_bytes(data)
246
+
247
+
248
+ def latest(state, tid):
249
+ versions = state["transcripts"].get(tid, {}).get("versions")
250
+ return versions[-1] if versions else None
251
+
252
+
253
+ def observe(state, tid, sha, record_count, prefix_sha, prefix_ok):
254
+ """Fold one reading of transcript `tid` into the state; returns `new`, `same`, `append` or `rewritten`.
255
+
256
+ `prefix_ok` is the append-only test (§5.2): did the first `record_count` records of the previous
257
+ latest version hash to its `prefix_sha` in what was just read. None when there was no previous."""
258
+ versions = state["transcripts"].setdefault(tid, {"versions": []})["versions"]
259
+ fresh = {"sha": sha, "record_count": record_count, "prefix_sha": prefix_sha, "read": [], "processed": {}}
260
+ if not versions:
261
+ versions.append(fresh)
262
+ return "new"
263
+ last = versions[-1]
264
+ if last["sha"] == sha:
265
+ return "same"
266
+ if prefix_ok and record_count >= last["record_count"]:
267
+ last.update(sha=sha, record_count=record_count, prefix_sha=prefix_sha)
268
+ return "append"
269
+ versions.append(fresh)
270
+ return "rewritten"
271
+
272
+
273
+ def carry_appended(state, tid, late):
274
+ """Hold in the backlog what S1 found appended to `tid`'s latest version and owned by a window already run: `late` maps
275
+ such a window's id to the records of the append it owns (review c0fix r1 #1). D-20261103-8facee gives what the host
276
+ appends after a census to the next run, and the next run reads another window: without this, a record stamped inside
277
+ a window that has been read - a line the host was still writing then, or one written late - is owned by no run. Each
278
+ is owed to its own window, under the status `appended`; what that window processed or the backlog already holds is
279
+ not owed again. Returns the entries added."""
280
+ versions = state["transcripts"][tid]["versions"]
281
+ number, version, added = len(versions) - 1, versions[-1], []
282
+ for window, ranges in sorted(late.items()):
283
+ held = normalize([r for b in state["backlog"] if (b["transcript"], b["version"], b["window"]) == (tid, number, window)
284
+ for r in b["unread"]])
285
+ unread = subtract(subtract(ranges, version["processed"].get(window, [])), held)
286
+ if unread:
287
+ added.append({"transcript": tid, "version": number, "window": window, "status": APPENDED, "unread": unread})
288
+ state["backlog"] += added
289
+ return added
290
+
291
+
292
+ def work_of(state, tid, owned, window_id):
293
+ """What a run owes one transcript: `version` (the latest, which `in_window` is about), `in_window` (owned
294
+ records not yet processed for the window) and `backlog` (unread ranges carried from earlier runs, each
295
+ naming the version and window it is owed to, read first)."""
296
+ version = latest(state, tid)
297
+ done = version["processed"].get(window_id, []) if version else []
298
+ carried = [{"window": b["window"], "version": b["version"], "unread": b["unread"]} for b in state["backlog"] if b["transcript"] == tid]
299
+ return {"version": len(state["transcripts"][tid]["versions"]) - 1 if version else None,
300
+ "in_window": subtract(owned, done), "backlog": carried}
301
+
302
+
303
+ def accounted(entries, state, window_id, units=None, owned=None):
304
+ """(accounted, fully_read) of a window over the census `entries` that are eligible (design §5.2).
305
+
306
+ Accounted: every eligible session has a terminal status, and a session whose reading did not finish has
307
+ what it still owes in the backlog: the unread records of this window it owns, and whatever it carries
308
+ from earlier windows, each under the window it belongs to. A session is its unit (D-20261103-85f3e8), and the
309
+ state names its files (D-20261103-a7128a): `units` maps a root's identity to `(its own files' keys, its members'
310
+ files' keys)`, `owned` a key to the records the window owns there, and every file's unread records are owed the
311
+ same way. Without them a session is one file under its identity and owns what its entry says. Fully read: every
312
+ one finished or had nothing to read."""
313
+ eligible = [e for e in entries if e["status"] == "eligible" or e["status"] in TERMINAL]
314
+ terminal = all(e["status"] in TERMINAL for e in eligible)
315
+ if owned is None:
316
+ owned = {lineage.identity(e["host"], e["id"]): e.get("owned", []) for e in entries}
317
+
318
+ def owes_nothing_unheld(entry):
319
+ root = lineage.identity(entry["host"], entry["id"])
320
+ own, members = (units or {}).get(root, ([root], []))
321
+ held_any = False
322
+ for tid in list(own) + list(members):
323
+ version = latest(state, tid)
324
+ remaining = subtract(owned.get(tid, []), version["processed"].get(window_id, []) if version else [])
325
+ held = [b for b in state["backlog"] if b["transcript"] == tid and b["unread"]]
326
+ held_any = held_any or bool(held)
327
+ if subtract(remaining, normalize([r for b in held if b["window"] == window_id for r in b["unread"]])):
328
+ return False
329
+ return held_any
330
+
331
+ carried = all(owes_nothing_unheld(e) for e in eligible if e["status"] in CARRIED)
332
+ return terminal and carried, all(e["status"] in ("read_complete", "nothing_new") for e in eligible)
333
+
334
+
335
+ def observed(state, files):
336
+ """A copy of `state` as the census observed it: each of the census's `files` (`census.segments_of`: a `key`, the
337
+ `versions` S1 recorded and its `work`) has those versions, an append moved in place and a rewrite added, with nothing
338
+ read or processed in a new one; and the backlog S1 added for records appended after their window was run
339
+ (`carry_appended`), which the work carries and the state does not."""
340
+ after = copy.deepcopy(state)
341
+ for file in files:
342
+ have = after["transcripts"].setdefault(file["key"], {"versions": []})["versions"]
343
+ for number, version in enumerate(file["versions"]):
344
+ if number < len(have):
345
+ have[number].update(version)
346
+ else:
347
+ have.append({**version, "read": [], "processed": {}})
348
+ for b in (file.get("work") or {}).get("backlog", []):
349
+ held = normalize([r for h in after["backlog"] if (h["transcript"], h["version"], h["window"]) == (file["key"], b["version"], b["window"])
350
+ for r in h["unread"]])
351
+ unread = subtract(b["unread"], held)
352
+ if unread:
353
+ after["backlog"].append({"transcript": file["key"], "version": b["version"], "window": b["window"], "status": APPENDED, "unread": unread})
354
+ return after
355
+
356
+
357
+ def apply_results(state, window_id, kind, results, owned, units=None):
358
+ """The state after S3's `results` (a copy; `state` is not touched).
359
+
360
+ A result is `{transcript, status, readings, pending_events, resolved_events}`, `readings` a list of
361
+ `{version, sha, read, processed}` with `processed` keyed by window id. Its status is one of the terminal
362
+ statuses whatever the run kind. A reading names the version it read and its sha; a range is credited to a
363
+ window only when that reading read it, and the window owns it in the latest version (`owned` maps a transcript
364
+ to the ranges the current window owns there) or a backlog entry of that same transcript, version and window
365
+ still holds it. A targeted run reads but never advances coverage: its results are held to the same rules and
366
+ the state it gets back is the one it gave.
367
+
368
+ One result answers a unit (D-20261103-85f3e8), and the state names its files (D-20261103-a7128a): `units` maps the
369
+ result's transcript to `(the keys of its own files, the keys of its members' files)`, by default its identity alone.
370
+ A reading names the file it read by `transcript`, which a session of one file may leave out; a reading naming a
371
+ file outside the unit is refused, and so is one that leaves it out of a session written across several files. A
372
+ `read_complete` or `nothing_new` result leaves nothing of the unit unprocessed, and a carried one keeps every
373
+ file's unread ranges in the backlog under that file. A pending event names its file the same way, by default the
374
+ session's last."""
375
+ folded = _fold(state, window_id, results, owned, units or {})
376
+ return folded if kind == "periodic" else copy.deepcopy(state)
377
+
378
+
379
+ def _fold(state, window_id, results, owned, units):
380
+ for result in results:
381
+ if result["status"] not in TERMINAL:
382
+ raise Refused(f"RESULT_STATUS_INVALID {result['transcript']}: {result['status']!r} is not a terminal status; S3 ends in one of {TERMINAL}")
383
+ after = copy.deepcopy(state)
384
+ for result in results:
385
+ root = result["transcript"]
386
+ own, members = units.get(root, ([root], []))
387
+ unit = list(own) + list(members)
388
+ newest, credited, seen = {}, {}, set()
389
+ for tid in unit:
390
+ versions = after["transcripts"].get(tid, {}).get("versions", [])
391
+ if tid in own and not versions:
392
+ raise Refused(f"VERSION_MISMATCH {tid}: the state has no version of it")
393
+ newest[tid] = len(versions) - 1
394
+ for reading in result["readings"]:
395
+ tid, n = reading.get("transcript", own[0] if len(own) == 1 else None), reading["version"]
396
+ if tid is None:
397
+ raise Refused(f"RESULT_INCONSISTENT {root}: a reading names no file, and the session is written across "
398
+ f"{len(own)} files ({own}); a reading names the one it read")
399
+ if tid not in newest:
400
+ raise Refused(f"RESULT_INCONSISTENT {root}: a reading names {tid}, which is not a member of its unit")
401
+ if (tid, n) in seen:
402
+ raise Refused(f"RESULT_INCONSISTENT {root}: version {n} of {tid} is read twice in one result")
403
+ seen.add((tid, n))
404
+ versions = after["transcripts"].get(tid, {}).get("versions", [])
405
+ if not 0 <= n < len(versions) or versions[n]["sha"] != reading["sha"]:
406
+ have = versions[n]["sha"][:12] if 0 <= n < len(versions) else "absent"
407
+ raise Refused(f"VERSION_MISMATCH {tid}: S3 read version {n} as {reading['sha'][:12]}, the state has {have}")
408
+ version = versions[n]
409
+ version["read"] = union(version["read"], reading["read"])
410
+ for w, ranges in reading["processed"].items():
411
+ if not ranges:
412
+ continue
413
+ if subtract(ranges, reading["read"]):
414
+ raise Refused(f"PROCESSED_UNREAD {tid}: version {n} processed {subtract(ranges, reading['read'])} for window {w}, which this result "
415
+ "did not read; a record read earlier as context is read again by the run that processes it")
416
+ allowed = normalize([r for b in after["backlog"] if (b["transcript"], b["version"], b["window"]) == (tid, n, w) for r in b["unread"]]
417
+ + (owned.get(tid, []) if w == window_id and n == newest[tid] else []))
418
+ if subtract(ranges, allowed):
419
+ raise Refused(f"PROCESSED_OUTSIDE_OWNED {tid}: version {n} processed {subtract(ranges, allowed)} for window {w}, which is owed "
420
+ f"{allowed}; a record is processed by the run whose window owns it or that reads its backlog, never in advance")
421
+ version["processed"][w] = union(version["processed"].get(w, []), ranges)
422
+ credited[(tid, n, w)] = union(credited.get((tid, n, w), []), ranges)
423
+ # the backlog of the unit: each entry loses what was credited to its own transcript, version and window; this window's,
424
+ # on each member's latest version, is recomputed
425
+ kept, remaining, carried_over = [], {}, False
426
+ for entry in after["backlog"]:
427
+ if entry["transcript"] not in newest:
428
+ kept.append(entry)
429
+ elif not (entry["window"] == window_id and entry["version"] == newest[entry["transcript"]]):
430
+ entry["unread"] = subtract(entry["unread"], credited.get((entry["transcript"], entry["version"], entry["window"]), []))
431
+ if entry["unread"]:
432
+ kept.append(entry)
433
+ carried_over = True
434
+ for tid in unit:
435
+ if newest[tid] < 0:
436
+ continue
437
+ left = subtract(owned.get(tid, []), after["transcripts"][tid]["versions"][newest[tid]]["processed"].get(window_id, []))
438
+ if left:
439
+ remaining[tid] = left
440
+ if result["status"] in ("read_complete", "nothing_new") and (remaining or carried_over):
441
+ where = next(iter(remaining.items()), None)
442
+ raise Refused(f"RESULT_INCONSISTENT {root}: {result['status']}, but "
443
+ f"{f'{where[1]} of {where[0]}' if where else 'earlier-window ranges'} are still unprocessed")
444
+ if result["status"] in CARRIED:
445
+ if not (remaining or carried_over):
446
+ raise Refused(f"RESULT_INCONSISTENT {root}: {result['status']}, but nothing is left unread")
447
+ kept += [{"transcript": tid, "version": newest[tid], "window": window_id, "status": result["status"], "unread": left}
448
+ for tid, left in remaining.items()]
449
+ after["backlog"] = kept
450
+ # a result resolves only the events of its own unit: one naming an event that is not pending, or that is pending
451
+ # on a file outside the unit, is refused before anything is removed (review c0fix r1 #5)
452
+ pending_on = {e["id"]: e["transcript"] for e in after["pending_events"]}
453
+ gone = set(result.get("resolved_events", []))
454
+ foreign = sorted(i for i in gone if pending_on.get(i) not in newest)
455
+ if foreign:
456
+ raise Refused(f"RESULT_INCONSISTENT {root}: it resolves {foreign}, which are not pending events of its unit "
457
+ f"({[pending_on.get(i) for i in foreign]})")
458
+ after["pending_events"] = [e for e in after["pending_events"] if e["id"] not in gone]
459
+ known = {e["id"] for e in after["pending_events"]}
460
+ for e in result.get("pending_events", []):
461
+ where = e.get("transcript", own[-1])
462
+ if where not in newest:
463
+ raise Refused(f"RESULT_INCONSISTENT {root}: a pending event names {where}, which is not a file of its unit")
464
+ if e["id"] not in known:
465
+ after["pending_events"].append({"version": newest[where], "window": window_id, **e, "transcript": where})
466
+ errors = check_state(after)
467
+ if errors:
468
+ raise Refused("\n".join(errors))
469
+ return after
470
+
471
+
472
+ def check_targeted(base, after):
473
+ """Violations when a targeted run's coverage is not the base it started from, byte for byte."""
474
+ if records.json_text(base) == records.json_text(after):
475
+ return []
476
+ return ["TARGETED_ADVANCED_COVERAGE: a targeted run reads but never advances periodic coverage; "
477
+ f"its state hashes {digest(after)[:12]}, the periodic base {digest(base)[:12]}"]
478
+
479
+
480
+ def write_atomic(state_dir, state, base_sha):
481
+ """Replace `<state_dir>/coverage.json` with `state`, only if the file on disk still hashes to
482
+ `base_sha` (what the run started from): under the coverage lock, the new bytes go to a temporary in
483
+ the same directory, are fsynced, and renamed over it. Returns the new sha256."""
484
+ errors = check_state(state)
485
+ if errors:
486
+ raise Refused("\n".join(errors))
487
+ state_dir = pathlib.Path(state_dir)
488
+ target = state_dir / "coverage.json"
489
+ with stagelock.hold(state_dir / "out", "coverage"):
490
+ _, on_disk = load(target)
491
+ if on_disk != base_sha:
492
+ raise Refused(f"COVERAGE_BASE_STALE {target}: the file hashes {on_disk[:12]}, the run started from {base_sha[:12]}; "
493
+ "another run advanced it, so this one must be redone from the new base")
494
+ text = records.json_text(state)
495
+ fd, tmp = tempfile.mkstemp(dir=state_dir, prefix=".coverage.json.")
496
+ try:
497
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
498
+ handle.write(text)
499
+ handle.flush()
500
+ os.fsync(handle.fileno())
501
+ os.replace(tmp, target)
502
+ except BaseException:
503
+ pathlib.Path(tmp).unlink(missing_ok=True)
504
+ raise
505
+ dir_fd = os.open(state_dir, os.O_RDONLY)
506
+ try:
507
+ os.fsync(dir_fd)
508
+ finally:
509
+ os.close(dir_fd)
510
+ return records.sha256_bytes(text.encode("utf-8"))
511
+
512
+
513
+ def contract_mismatch(schema, contract):
514
+ """Where the coverage schema departs from §5.2 (`contract` maps a place in the schema to
515
+ `(the fields the design names, the fields the schema adds to place the object)`): the required set must
516
+ be exactly their union, and every place must cite the section."""
517
+ errors = []
518
+ for place, (design, added) in contract.items():
519
+ node = schema["$defs"][place.split("/", 1)[1]] if place else schema
520
+ have, want = set(node.get("required", [])), set(design) | set(added)
521
+ missing, extra = sorted(want - have), sorted(have - want)
522
+ if missing or extra:
523
+ errors.append(f"CONTRACT_MISMATCH coverage (design §5.2) {place or 'state'}: required lacks {missing} adds {extra}")
524
+ if not str(node.get("$comment", "")).startswith("design §5.2"):
525
+ errors.append(f"CONTRACT_MISMATCH coverage (design §5.2) {place or 'state'}: $comment does not cite the section")
526
+ return errors
527
+
528
+
529
+ def self_test():
530
+ failures = []
531
+
532
+ def expect(label, got, want):
533
+ if got != want:
534
+ failures.append(f"{label}: expected {want!r}, got {got!r}")
535
+
536
+ def refused(label, fn, code):
537
+ try:
538
+ fn()
539
+ failures.append(f"{label}: nothing was refused")
540
+ except Refused as exc:
541
+ if code not in str(exc):
542
+ failures.append(f"{label}: expected {code}, got {exc}")
543
+
544
+ sha = lambda text: hashlib.sha256(text.encode()).hexdigest() # noqa: E731
545
+ W1, W2 = "w1", "w2"
546
+
547
+ # ranges: positive controls, then the cases an off-by-one would break
548
+ expect("normalize merges touching ranges and drops empty ones", normalize([[5, 8], [0, 2], [2, 4], [9, 9]]), [[0, 4], [5, 8]])
549
+ expect("subtract cuts the middle", subtract([[0, 10]], [[3, 5]]), [[0, 3], [5, 10]])
550
+ expect("subtract of a superset leaves nothing", subtract([[2, 4]], [[0, 10]]), [])
551
+ expect("subtract of a disjoint range leaves it", subtract([[2, 4]], [[4, 9]]), [[2, 4]])
552
+ expect("union", union([[0, 2]], [[2, 5], [7, 8]]), [[0, 5], [7, 8]])
553
+
554
+ # ownership: records before, inside and after the window; a record with no stamp follows its predecessor
555
+ zone = datetime.timezone.utc
556
+ start, end = datetime.datetime(2026, 10, 1, tzinfo=zone), datetime.datetime(2026, 10, 8, tzinfo=zone)
557
+ own = Ownership(start, end)
558
+ for index, stamp in enumerate(["2026-09-30T23:00:00Z", None, "2026-10-01T00:00:00Z", "2026-10-07T23:59:59.999Z", None,
559
+ "2026-10-08T00:00:00Z", "garbage"]):
560
+ own.feed(index, stamp)
561
+ expect("owned runs are [start, end) and stampless records follow", own.finish(7), {"owned": [[2, 5]], "before": True, "after": True})
562
+ lead = Ownership(start, end)
563
+ for index, stamp in enumerate([None, None, "2026-10-02T00:00:00Z"]):
564
+ lead.feed(index, stamp)
565
+ expect("leading records without a stamp take the first stamp", lead.finish(3), {"owned": [[0, 3]], "before": False, "after": False})
566
+ expect("a window id carries its zone", window_bounds({"start": "2026-10-01T00:00:00", "end": "2026-10-08T00:00:00", "tz": "Asia/Seoul"})[2],
567
+ "2026-10-01T00:00:00/2026-10-08T00:00:00@Asia/Seoul")
568
+ expect("a window without an offset is read in its zone", window_bounds({"start": "2026-10-01T09:00:00", "end": "2026-10-08T00:00:00", "tz": "Asia/Seoul"})[0],
569
+ datetime.datetime(2026, 10, 1, tzinfo=zone))
570
+
571
+ # r1 #1: several windows at once, as S1 judges records against the windows already run; c reaches past a
572
+ day = lambda d, m=10: datetime.datetime(2026, m, d, tzinfo=zone) # noqa: E731
573
+ owners = Owners([(day(1), day(8), "a"), (day(8), day(15), "b"), (day(1, 9), day(15), "c")])
574
+ for index, stamp in enumerate(["2026-08-30T00:00:00Z", None, "2026-10-02T00:00:00Z", "2026-10-09T00:00:00Z", None, "garbage"]):
575
+ owners.feed(index, stamp)
576
+ expect("r1 #1: each record belongs to every window that holds its stamp, stampless ones to their predecessor's",
577
+ owners.finish(6), {"a": [[2, 3]], "b": [[3, 6]], "c": [[2, 6]]})
578
+
579
+ # versions: new, same, append (continuity), rewritten (it fails)
580
+ state = new_state()
581
+ expect("first reading", observe(state, "t", sha("a"), 10, sha("a"), None), "new")
582
+ expect("the same bytes", observe(state, "t", sha("a"), 10, sha("a"), True), "same")
583
+ expect("appended records keep the version", observe(state, "t", sha("b"), 14, sha("b"), True), "append")
584
+ expect("the append moved the version in place", [(v["sha"], v["record_count"]) for v in state["transcripts"]["t"]["versions"]], [(sha("b"), 14)])
585
+ expect("a failed continuity starts the next version", observe(state, "t", sha("c"), 20, sha("c"), False), "rewritten")
586
+ expect("the prior version is still there for its evidence", [v["sha"] for v in state["transcripts"]["t"]["versions"]], [sha("b"), sha("c")])
587
+ short = new_state()
588
+ observe(short, "t", sha("a"), 10, sha("a"), None)
589
+ expect("fewer records than before is a rewrite whatever the prefix says", observe(short, "t", sha("b"), 6, sha("b"), True), "rewritten")
590
+
591
+ T = lineage.identity("claude", "t")
592
+
593
+ def row(status, ident="t"):
594
+ return {"host": "claude", "id": ident, "status": status}
595
+
596
+ def reading(text, read, processed, version=0):
597
+ return {"version": version, "sha": sha(text), "read": read, "processed": processed}
598
+
599
+ def answer(status, readings, **kw):
600
+ return {"transcript": T, "status": status, "readings": readings, "pending_events": [], "resolved_events": [], **kw}
601
+
602
+ # F04, two runs: the records past window w's end are read as context in run 1 and processed by run 2
603
+ state = new_state()
604
+ observe(state, T, sha("x"), 12, sha("x"), None)
605
+ run1 = answer("read_complete", [reading("x", [[0, 12]], {W1: [[0, 10]]})], pending_events=[{"id": "e1", "first_record": 9}])
606
+ after1 = apply_results(state, W1, "periodic", [run1], {T: [[0, 10]]})
607
+ v = latest(after1, T)
608
+ expect("run 1: context records are read and not processed for their own window", (v["read"], v["processed"]), ([[0, 12]], {W1: [[0, 10]]}))
609
+ expect("run 1: the pending event keeps its id", [e["id"] for e in after1["pending_events"]], ["e1"])
610
+ expect("run 2 still owes the records run 1 read as context", work_of(after1, T, [[10, 12]], W2)["in_window"], [[10, 12]])
611
+ run2 = answer("read_complete", [reading("x", [[0, 12]], {W2: [[10, 12]]})], resolved_events=["e1"])
612
+ after2 = apply_results(after1, W2, "periodic", [run2], {T: [[10, 12]]})
613
+ expect("run 2: the records are processed for the window that owns them", latest(after2, T)["processed"], {W1: [[0, 10]], W2: [[10, 12]]})
614
+ expect("run 2: the stitched event is resolved", after2["pending_events"], [])
615
+ expect("run 1's own record of the state is unchanged by run 2", [e["id"] for e in after1["pending_events"]], ["e1"])
616
+ own = {T: [[0, 10]]}
617
+ refused("processing a record the window does not own", lambda: apply_results(
618
+ state, W1, "periodic", [{**run1, "readings": [reading("x", [[0, 12]], {W1: [[0, 11]]})]}], own), f"PROCESSED_OUTSIDE_OWNED {T}")
619
+ refused("a result for another version of the transcript", lambda: apply_results(
620
+ state, W1, "periodic", [{**run1, "readings": [reading("other", [[0, 12]], {W1: [[0, 10]]})]}], own), f"VERSION_MISMATCH {T}")
621
+ refused("a result for a version the state does not have", lambda: apply_results(
622
+ state, W1, "periodic", [{**run1, "readings": [reading("x", [[0, 12]], {W1: [[0, 10]]}, version=3)]}], own), f"VERSION_MISMATCH {T}")
623
+ refused("a result for a transcript the state does not have", lambda: apply_results(
624
+ state, W1, "periodic", [{**run1, "transcript": "claude:ghost"}], own), "VERSION_MISMATCH claude:ghost")
625
+ refused("a deferred result for a transcript the state does not have", lambda: apply_results(
626
+ state, W1, "periodic", [answer("deferred", [], transcript="claude:ghost")], own), "VERSION_MISMATCH claude:ghost: the state has no version")
627
+ refused("one version read twice in a result", lambda: apply_results(
628
+ state, W1, "periodic", [{**run1, "readings": [run1["readings"][0]] * 2}], own), "RESULT_INCONSISTENT")
629
+ refused("read_complete with work left", lambda: apply_results(
630
+ state, W1, "periodic", [answer("read_complete", [reading("x", [[0, 12]], {W1: [[0, 5]]})])], own), f"RESULT_INCONSISTENT {T}")
631
+ refused("read_partial with nothing left", lambda: apply_results(
632
+ state, W1, "periodic", [{**run1, "status": "read_partial"}], own), f"RESULT_INCONSISTENT {T}")
633
+ refused("processing what was not read", lambda: apply_results(
634
+ state, W1, "periodic", [answer("read_complete", [reading("x", [[0, 4]], {W1: [[0, 10]]})])], own), f"PROCESSED_UNREAD {T}")
635
+ # F#1 (round 2): run 1 read [10, 12) as context; run 2 owns it and must read it again, however much earlier runs read
636
+ refused("the owning run processes records it did not read again, because an earlier run read them as context", lambda: apply_results(
637
+ after1, W2, "periodic", [answer("read_complete", [reading("x", [], {W2: [[10, 12]]})])], {T: [[10, 12]]}),
638
+ f"PROCESSED_UNREAD {T}: version 0 processed [[10, 12]] for window {W2}")
639
+ refused("the owning run reads only part of what it processes", lambda: apply_results(
640
+ after1, W2, "periodic", [answer("read_complete", [reading("x", [[10, 11]], {W2: [[10, 12]]})])], {T: [[10, 12]]}), f"PROCESSED_UNREAD {T}")
641
+ expect("the owning run that reads its records again is credited", latest(apply_results(
642
+ after1, W2, "periodic", [answer("read_complete", [reading("x", [[10, 12]], {W2: [[10, 12]]})])], {T: [[10, 12]]}), T)["processed"][W2], [[10, 12]])
643
+
644
+ # F#1: a window's records are never credited in advance. Run 1 read [10, 12) as context; it may not also process them for window 2
645
+ refused("a result crediting a later window's records in advance", lambda: apply_results(
646
+ state, W1, "periodic", [answer("read_complete", [reading("x", [[0, 12]], {W1: [[0, 10]], W2: [[10, 12]]})])], own),
647
+ f"PROCESSED_OUTSIDE_OWNED {T}: version 0 processed [[10, 12]] for window {W2}")
648
+ expect("the refused credit left run 2 its work", work_of(apply_results(state, W1, "periodic", [run1], own), T, [[10, 12]], W2)["in_window"], [[10, 12]])
649
+ refused("an earlier window's range that no backlog entry holds", lambda: apply_results(
650
+ after1, W2, "periodic", [answer("read_complete", [reading("x", [[0, 12]], {W1: [[10, 12]], W2: [[10, 12]]})])], {T: [[10, 12]]}),
651
+ f"PROCESSED_OUTSIDE_OWNED {T}: version 0 processed [[10, 12]] for window {W1}")
652
+
653
+ # F#2: every result ends in a terminal status, and nothing_new cannot make work vanish
654
+ for bad in ("eligible", "in_progress", "excluded", "known_absent", ""):
655
+ refused(f"a result with the status {bad!r}", lambda bad=bad: apply_results(state, W1, "periodic", [{**run1, "status": bad}], own), "RESULT_STATUS_INVALID")
656
+ refused("a targeted run's results carry a terminal status too", lambda: apply_results(state, W1, "targeted", [{**run1, "status": "eligible"}], own), "RESULT_STATUS_INVALID")
657
+ refused("nothing_new while the window still owns unprocessed records", lambda: apply_results(
658
+ state, W1, "periodic", [answer("nothing_new", [reading("x", [], {})])], own), f"RESULT_INCONSISTENT {T}: nothing_new")
659
+ refused("nothing_new while an earlier window's backlog remains", lambda: apply_results(
660
+ apply_results(state, W1, "periodic", [answer("read_partial", [reading("x", [[0, 6]], {W1: [[0, 6]]})])], own), W2, "periodic",
661
+ [answer("nothing_new", [reading("x", [], {})])], {T: []}), f"RESULT_INCONSISTENT {T}: nothing_new")
662
+ expect("nothing_new once everything is processed is allowed", apply_results(
663
+ state, W1, "periodic", [answer("nothing_new", [reading("x", [[0, 10]], {W1: [[0, 10]]})])], own)["backlog"], [])
664
+
665
+ # the backlog: a partial session carries its unread ranges, and the next run reads them first and clears them
666
+ part = answer("read_partial", [reading("x", [[0, 6]], {W1: [[0, 6]]})])
667
+ carried = apply_results(state, W1, "periodic", [part], own)
668
+ expect("a partial session's unread ranges are in the backlog", carried["backlog"], [
669
+ {"transcript": T, "version": 0, "window": W1, "status": "read_partial", "unread": [[6, 10]]}])
670
+ expect("the next run is told to read the backlog first, by version and window", work_of(carried, T, [], W2),
671
+ {"version": 0, "in_window": [], "backlog": [{"window": W1, "version": 0, "unread": [[6, 10]]}]})
672
+ cleared = apply_results(carried, W2, "periodic", [answer("read_complete", [reading("x", [[0, 10]], {W1: [[6, 10]]})])], {T: []})
673
+ expect("reading the backlog clears it and credits its own window", (cleared["backlog"], latest(cleared, T)["processed"]), ([], {W1: [[0, 10]]}))
674
+ failed = apply_results(state, W1, "periodic", [answer("failed", [])], own)
675
+ expect("a failed session carries all of its work", failed["backlog"][0]["unread"], [[0, 10]])
676
+
677
+ # F#3: work has a version. A rewrite starts version 1 with other bytes at the same offsets; the backlog still belongs to version 0
678
+ rewrite = copy.deepcopy(carried)
679
+ expect("a rewrite starts the next version", observe(rewrite, T, sha("y"), 12, sha("y"), False), "rewritten")
680
+ refused("a backlog range credited from a reading of the rewritten version", lambda: apply_results(
681
+ rewrite, W2, "periodic", [answer("read_complete", [reading("x", [], {}), reading("y", [[0, 12]], {W1: [[6, 10]], W2: [[10, 12]]}, version=1)])],
682
+ {T: [[10, 12]]}), f"PROCESSED_OUTSIDE_OWNED {T}: version 1 processed [[6, 10]] for window {W1}")
683
+ expect("the new version's work is its own, the old version's backlog is still owed", work_of(rewrite, T, [[0, 12]], W2),
684
+ {"version": 1, "in_window": [[0, 12]], "backlog": [{"window": W1, "version": 0, "unread": [[6, 10]]}]})
685
+ both = apply_results(rewrite, W2, "periodic", [answer("read_complete", [
686
+ reading("x", [[0, 10]], {W1: [[6, 10]]}, version=0), reading("y", [[0, 12]], {W2: [[0, 12]]}, version=1)])], {T: [[0, 12]]})
687
+ expect("each credit lands on the version it was read from", ([v["processed"] for v in both["transcripts"][T]["versions"]], both["backlog"]),
688
+ ([{W1: [[0, 10]]}, {W2: [[0, 12]]}], []))
689
+ expect("a backlog entry's version must exist", any("names version 4" in e for e in check_state(
690
+ {**carried, "backlog": [{**carried["backlog"][0], "version": 4}]})), True)
691
+
692
+ # F#2 (round 2): rerunning the window a backlog entry belongs to, after a rewrite, may read the old version for it
693
+ rerun = apply_results(rewrite, W1, "periodic", [answer("read_complete", [
694
+ reading("x", [[6, 10]], {W1: [[6, 10]]}, version=0), reading("y", [[0, 12]], {W1: [[0, 12]]}, version=1)])], {T: [[0, 12]]})
695
+ expect("the window that owns the backlog reads the old version for it and its own records of the new one",
696
+ ([v["processed"] for v in rerun["transcripts"][T]["versions"]], rerun["backlog"]), ([{W1: [[0, 10]]}, {W1: [[0, 12]]}], []))
697
+ refused("the same window, a rewritten version, and offsets that only the old version's backlog held", lambda: apply_results(
698
+ rewrite, W1, "periodic", [answer("read_complete", [reading("y", [[0, 12]], {W1: [[6, 10]]}, version=1)])], {T: [[10, 12]]}),
699
+ f"PROCESSED_OUTSIDE_OWNED {T}: version 1 processed [[6, 10]] for window {W1}")
700
+
701
+ # F#3 (round 2): a session still carrying an earlier window's backlog is accounted for the current one, which keeps the original windows
702
+ deferred = apply_results(carried, W2, "periodic", [answer("deferred", [])], {T: []})
703
+ expect("deferring earlier-window work again keeps its window", deferred["backlog"], carried["backlog"])
704
+ expect("the current window owes nothing and the earlier backlog is held: accounted, not fully read",
705
+ accounted([{**row("deferred"), "owned": []}], deferred, W2), (True, False))
706
+ mixed = apply_results(carried, W2, "periodic", [answer("deferred", [reading("x", [], {})])], {T: [[10, 12]]})
707
+ expect("both windows' obligations are held, each under its own window", sorted((b["window"], b["unread"]) for b in mixed["backlog"]),
708
+ [(W1, [[6, 10]]), (W2, [[10, 12]])])
709
+ expect("the current window's own unread records and the carried ones are held: accounted",
710
+ accounted([{**row("deferred"), "owned": [[10, 12]]}], mixed, W2), (True, False))
711
+ expect("the current window owns records that no backlog entry of its own holds: not accounted",
712
+ accounted([{**row("deferred"), "owned": [[10, 12]]}], deferred, W2), (False, False))
713
+ expect("the session carries nothing and is deferred without a backlog: not accounted",
714
+ accounted([{**row("deferred"), "owned": []}], new_state(), W2), (False, False))
715
+
716
+ # a window is accounted when every eligible session is terminal and its unread ranges are held; fully read is separate
717
+ entries = [row("read_partial"), row("read_complete", "u"), row("excluded", "x")]
718
+ expect("partial with its backlog: accounted, not fully read", accounted(entries, carried, W1), (True, False))
719
+ expect("partial without its backlog: not accounted", accounted(entries, new_state(), W1), (False, False))
720
+ expect("one session left non-terminal: not accounted", accounted([*entries[1:], row("eligible", "n")], new_state(), W1), (False, False))
721
+ expect("all complete or nothing to read: both", accounted([entries[1], row("nothing_new", "n")], new_state(), W1), (True, True))
722
+ expect("no eligible session at all", accounted([entries[2]], new_state(), W1), (True, True))
723
+ expect("a backlog held for another host's session of the same id does not account for this one",
724
+ accounted([{**row("read_partial"), "host": "codex"}], carried, W1), (False, False))
725
+
726
+ # F#0 (round 2): a targeted run's results are held to the periodic rules, then discarded
727
+ refused("a targeted run's false nothing_new", lambda: apply_results(
728
+ state, W1, "targeted", [answer("nothing_new", [reading("x", [], {})])], own), f"RESULT_INCONSISTENT {T}: nothing_new")
729
+ refused("a targeted run's reading of a version the state does not have", lambda: apply_results(
730
+ state, W1, "targeted", [{**run1, "readings": [reading("other", [[0, 12]], {W1: [[0, 10]]})]}], own), f"VERSION_MISMATCH {T}")
731
+ refused("a targeted run processing what it did not read", lambda: apply_results(
732
+ state, W1, "targeted", [answer("read_complete", [reading("x", [[0, 4]], {W1: [[0, 10]]})])], own), f"PROCESSED_UNREAD {T}")
733
+ refused("a targeted run crediting a later window", lambda: apply_results(
734
+ state, W1, "targeted", [answer("read_complete", [reading("x", [[0, 12]], {W1: [[0, 10]], W2: [[10, 12]]})])], own), "PROCESSED_OUTSIDE_OWNED")
735
+
736
+ # a targeted run reads but never advances periodic coverage
737
+ expect("a targeted run returns the base", records.json_text(apply_results(state, W1, "targeted", [run1], own)), records.json_text(state))
738
+ expect("the targeted guard passes the unchanged state", check_targeted(state, apply_results(state, W1, "targeted", [run1], own)), [])
739
+ expect("the targeted guard names a processed range that advanced", [e.split(":")[0] for e in check_targeted(
740
+ state, apply_results(state, W1, "periodic", [run1], own))], ["TARGETED_ADVANCED_COVERAGE"])
741
+
742
+ # observed(): the versions a census saw laid over a state that has not seen them
743
+ seen_at = [{"key": T, "versions": [{"sha": sha("x2"), "record_count": 14, "prefix_sha": sha("x2")}]},
744
+ {"key": "codex:n", "versions": [{"sha": sha("n"), "record_count": 3, "prefix_sha": sha("n")}]}]
745
+ watched = observed(after1, seen_at)
746
+ expect("an append moves the version in place and keeps what was read", [(v["sha"], v["record_count"], v["read"]) for v in watched["transcripts"][T]["versions"]],
747
+ [(sha("x2"), 14, [[0, 12]])])
748
+ expect("a transcript the state never saw gets a version with nothing read", watched["transcripts"]["codex:n"]["versions"][0]["read"], [])
749
+ expect("observing leaves the state it was given alone", records.json_text(after1) == records.json_text(apply_results(state, W1, "periodic", [run1], own)), True)
750
+
751
+ # review c0fix r1 #1: records appended after the run of the window that owns them are owed to that window
752
+ week = {"start": "2026-10-01T00:00:00", "end": "2026-10-08T00:00:00", "tz": "Asia/Seoul"}
753
+ expect("r1 #1: a window id is read back to the bounds it was made from", bounds_of(window_bounds(week)[2]), window_bounds(week)[:2])
754
+ refused("r1 #1: a window id that is not <start>/<end>@<tz> is refused by name", lambda: bounds_of("w1"), "COVERAGE_INVALID window 'w1'")
755
+ late = copy.deepcopy(after1) # version 0 of T: 12 records, window 1 processed [0, 10)
756
+ expect("r1 #1: the append moves version 0 in place", observe(late, T, sha("x3"), 14, sha("x3"), True), "append")
757
+ expect("r1 #1: the appended records a window already run owns are held for it, under the status appended",
758
+ carry_appended(late, T, {W1: [[12, 14]]}), [{"transcript": T, "version": 0, "window": W1, "status": APPENDED, "unread": [[12, 14]]}])
759
+ # each on a copy: a reverted check must fail its own label, not leave an entry that makes a later control raise
760
+ expect("r1 #1: what the backlog already holds is not held again", carry_appended(copy.deepcopy(late), T, {W1: [[12, 14]]}), [])
761
+ expect("r1 #1: what the window processed is not owed again", carry_appended(copy.deepcopy(late), T, {W1: [[8, 10]]}), [])
762
+ expect("r1 #1: the next run is told to read them, under their window", work_of(late, T, [], W2)["backlog"],
763
+ [{"window": W1, "version": 0, "unread": [[12, 14]]}])
764
+ try:
765
+ credited_late = apply_results(late, W2, "periodic", [answer("read_complete", [
766
+ {"version": 0, "sha": sha("x3"), "read": [[0, 14]], "processed": {W1: [[12, 14]]}}])], {T: []})
767
+ credited_late = (latest(credited_late, T)["processed"], credited_late["backlog"])
768
+ except Refused as exc: # a control reads the refusal, never a traceback
769
+ credited_late = str(exc)
770
+ expect("r1 #1: the next run that reads them is credited under their window, and they leave the backlog", credited_late,
771
+ ({W1: [[0, 10], [12, 14]]}, []))
772
+ seen_late = observed(after1, [{"key": T, "versions": [{"sha": sha("x3"), "record_count": 14, "prefix_sha": sha("x3")}],
773
+ "work": {"version": 0, "in_window": [], "backlog": [{"window": W1, "version": 0, "unread": [[12, 14]]}]}}])
774
+ expect("r1 #1: the state a targeted census observed holds the backlog it added for appended records", seen_late["backlog"],
775
+ [{"transcript": T, "version": 0, "window": W1, "status": APPENDED, "unread": [[12, 14]]}])
776
+
777
+ # review c0fix r1 #5: a result resolves only the pending events of its own unit
778
+ pair = new_state()
779
+ RA, RB = lineage.identity("claude", "ra"), lineage.identity("claude", "rb")
780
+ for tid, text in ((RA, "ra"), (RB, "rb")):
781
+ observe(pair, tid, sha(text), 4, sha(text), None)
782
+ pair["pending_events"] = [{"id": "event-b", "transcript": RB, "version": 0, "window": W1, "first_record": 2}]
783
+
784
+ def whole(tid, text, resolved=()):
785
+ return {**answer("read_complete", [reading(text, [[0, 4]], {W1: [[0, 4]]})]), "transcript": tid, "resolved_events": list(resolved)}
786
+
787
+ both_owned = {RA: [[0, 4]], RB: [[0, 4]]}
788
+ refused("r1 #5: a result resolving another unit's pending event is refused, naming the event", lambda: apply_results(
789
+ pair, W1, "periodic", [whole(RA, "ra", ["event-b"]), whole(RB, "rb")], both_owned), f"RESULT_INCONSISTENT {RA}: it resolves ['event-b']")
790
+ refused("r1 #5: a result resolving an event that is not pending is refused", lambda: apply_results(
791
+ pair, W1, "periodic", [whole(RA, "ra", ["ghost"]), whole(RB, "rb")], both_owned), f"RESULT_INCONSISTENT {RA}: it resolves ['ghost']")
792
+ expect("r1 #5: the unit an event is pending on resolves it", apply_results(
793
+ pair, W1, "periodic", [whole(RA, "ra"), whole(RB, "rb", ["event-b"])], both_owned)["pending_events"], [])
794
+
795
+ # the state on disk: it validates, and writes are atomic against a base hash
796
+ with tempfile.TemporaryDirectory() as td:
797
+ directory = pathlib.Path(td)
798
+ _, base = load(directory / "coverage.json")
799
+ expect("an absent file hashes as the empty state", base, digest(new_state()))
800
+ new = write_atomic(directory, after1, base)
801
+ expect("the write lands with the hash it reports", load(directory / "coverage.json")[1], new)
802
+ refused("a write from a stale base", lambda: write_atomic(directory, after2, base), "COVERAGE_BASE_STALE")
803
+ expect("a refused write left the file as it was", load(directory / "coverage.json")[1], new)
804
+ write_atomic(directory, after2, new)
805
+ expect("a write from the current base lands", [e["id"] for e in load(directory / "coverage.json")[0]["pending_events"]], [])
806
+ expect("no temporary file is left behind", sorted(p.name for p in directory.iterdir() if p.name != "out"), ["coverage.json"])
807
+ with stagelock.hold(directory / "out", "coverage"):
808
+ try:
809
+ write_atomic(directory, after1, load(directory / "coverage.json")[1])
810
+ failures.append("a write went ahead while another writer held the lock")
811
+ except stagelock.Locked as exc:
812
+ if "STAGE_LOCKED coverage" not in str(exc):
813
+ failures.append(f"a held lock was refused unnamed: {exc}")
814
+ (directory / "bad.json").write_text('{"transcripts": {}}')
815
+ refused("a state that does not conform", lambda: load(directory / "bad.json"), "COVERAGE_INVALID")
816
+ (directory / "bad.json").write_text("{")
817
+ refused("a state that is not JSON", lambda: load(directory / "bad.json"), "COVERAGE_INVALID")
818
+ broken = copy.deepcopy(after2)
819
+ broken["transcripts"][T]["versions"][0]["processed"]["w9"] = [[0, 99]]
820
+ with tempfile.TemporaryDirectory() as refused_into:
821
+ refused("a range past record_count", lambda: write_atomic(pathlib.Path(refused_into), broken, digest(new_state())),
822
+ "COVERAGE_INVALID")
823
+ for label, edit, fragment in (
824
+ ("ranges out of order", lambda st: st["transcripts"][T]["versions"][0]["read"].__setitem__(slice(None), [[5, 8], [0, 2]]), "ranges are not sorted"),
825
+ ("a read range past record_count", lambda st: st["transcripts"][T]["versions"][0]["read"].__setitem__(slice(None), [[0, 99]]), "ends past record_count 12"),
826
+ ("processed records never read", lambda st: st["transcripts"][T]["versions"][0]["read"].__setitem__(slice(None), [[0, 4]]), "never read"),
827
+ ("an event naming a version the state lacks", lambda st: st["pending_events"].append(
828
+ {"id": "ghost", "transcript": T, "version": 5, "window": W1, "first_record": 0}), "names version 5")):
829
+ mutated = copy.deepcopy(after2)
830
+ edit(mutated)
831
+ if not any(fragment in line for line in check_state(mutated)):
832
+ failures.append(f"state invariant not named: {label} -> {check_state(mutated)}")
833
+ refused("a state path that cannot be read", lambda: load(tempfile.gettempdir()), "COVERAGE_INVALID")
834
+ again = copy.deepcopy(after2)
835
+ again["pending_events"] = [{"id": "e", "transcript": T, "version": 0, "window": W1, "first_record": 1}] * 2
836
+ expect("a pending event id that repeats is named", [e for e in check_state(again) if "repeats" in e] != [], True)
837
+
838
+ # the tracked state conforms to its own schema and invariants
839
+ expect("the tracked session-distill/coverage.json is a valid coverage state", check_state(load(SCHEMA_PATH.parent.parent / "coverage.json")[0]), [])
840
+
841
+ # contract fidelity (done-when 7): the lists below are the field lists of design §5.2, copied once and cited. The first
842
+ # list of each pair is what the design names; the second is what the schema adds to say whose an object is
843
+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
844
+ contract = {"": (["transcripts", "pending_events", "backlog", "windows"], []),
845
+ "$defs/version": (["sha", "record_count", "prefix_sha", "read", "processed"], []),
846
+ "$defs/window_flags": (["accounted", "fully_read"], []),
847
+ "$defs/pending_event": (["id"], ["transcript", "version", "window", "first_record"]),
848
+ "$defs/backlog_entry": (["unread"], ["transcript", "version", "window", "status"])}
849
+ expect("the schema matches design §5.2", contract_mismatch(schema, contract), [])
850
+ for place in contract:
851
+ node_of = lambda doc, place=place: doc["$defs"][place.split("/", 1)[1]] if place else doc # noqa: E731
852
+ for field in node_of(schema)["required"]:
853
+ mutated = copy.deepcopy(schema)
854
+ node_of(mutated)["required"].remove(field)
855
+ found = contract_mismatch(mutated, contract)
856
+ if not any(f"(design §5.2) {place or 'state'}: required lacks ['{field}']" in line for line in found):
857
+ failures.append(f"contract control not named: {place or 'state'} lacking {field} -> {found}")
858
+ mutated = copy.deepcopy(schema)
859
+ node_of(mutated)["required"].append("extra")
860
+ found = contract_mismatch(mutated, contract)
861
+ if not any(f"(design §5.2) {place or 'state'}: required lacks [] adds ['extra']" in line for line in found):
862
+ failures.append(f"contract control not named: {place or 'state'} adding a required field -> {found}")
863
+ uncited = copy.deepcopy(schema)
864
+ node_of(uncited)["$comment"] = "design §0.0"
865
+ if not any(f"{place or 'state'}: $comment does not cite" in line for line in contract_mismatch(uncited, contract)):
866
+ failures.append(f"a {place or 'state'} definition that cites another section was not named")
867
+ for failure in failures:
868
+ print(f"coverage --self-test [FAIL] {failure}")
869
+ if failures:
870
+ return 1
871
+ print("coverage --self-test: OK (range algebra; window ownership; versions new/same/append/rewritten; two-run range ownership "
872
+ "with a pending event stitched across the boundary and no credit in advance; terminal result statuses only and no false "
873
+ "nothing_new; backlog carried and cleared by version and window; accounted vs fully read; a targeted run leaves the base "
874
+ "byte-identical; atomic write refuses a stale base and a held lock; every required set of the schema equals design §5.2's)")
875
+ return 0
876
+
877
+
878
+ if __name__ == "__main__":
879
+ if "--self-test" not in sys.argv[1:]:
880
+ sys.exit("usage: coverage.py --self-test")
881
+ sys.exit(self_test())