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,4327 @@
1
+ #!/usr/bin/env python3
2
+ """S2, the reading views (design §5.4, §13.4; the amendment of its input bound, 2026-10-21).
3
+
4
+ For every eligible transcript, and the child transcripts linked to it, `run` leaves in the run directory:
5
+
6
+ * `sources/<version_sha>.jsonl` - the immutable copy of the version (decompressed if the host compressed it,
7
+ mode 0444, named by its own sha256). It is raw, and no model reads it: the owner's openable locator points here.
8
+ * `redacted/<version_sha>.<redaction_version>.jsonl` - the projection of every content block of the version
9
+ (`projection.project`); the only text a window, a search hit or a quote is built from.
10
+ * `views/<transcript>/<n>.json` - the windows, `views/<transcript>/sequence.json` - the order they were cut from,
11
+ `index/bm25/<transcript>.json` - the full-source search index, and `views.json` - the manifest of all of it.
12
+ The manifest also carries, per transcript, the shape counts this module keeps (`hints_of`, the v1 digest's
13
+ own six signals): they rank what to
14
+ read, and no claim rests on one, because evidence is a locator into a copy (design §5.5), never a count.
15
+
16
+ **What is viewed.** The content blocks of a record are the human, assistant and delegated text, the tool calls with
17
+ their arguments and the tool results (Claude: `user`/`assistant` records and the `queued_command` attachment a human
18
+ typed while the assistant worked; Codex: `response_item` messages of the `user` and `assistant` roles, calls and
19
+ outputs). Thinking, developer text, system and bookkeeping records are not blocks. A tool result longer than
20
+ `CLIP_OVER` characters is **clipped**: its head, its tail, and every line of the middle that reads as an error, kept
21
+ whole; the rest is a gap named in the omission manifest with its size, its span and the sha256 of the omitted
22
+ characters (so two results that look alike from outside, and differ inside, are told apart). A record is viewed when
23
+ the census says this run owes it: the records the window owns and has not processed, and the backlog on the latest
24
+ version. Anything else is shown only as the overlap (five entries each side of a window, each cut to
25
+ `OVERLAP_ITEM_BYTES`) and is `context`. A file of a unit that owes the window nothing and holds an event an earlier run
26
+ left pending is viewed with no window (`carried_only`), so the unit's stitch can show that event from this run's copy.
27
+
28
+ **Windows.** Entries are cut greedily into windows in record order. Every viewed entry is owned by exactly one window;
29
+ an entry too large for a window is split into **spans**, each a slice of the entry's view text with the mapping of
30
+ every shown stretch to the block's characters (`segments`), so the spans' union is the entry. A window never joins
31
+ two viewed runs that have unviewed records between them. A window names each entry it shows by a label of its own, e1,
32
+ e2, ... in the order it renders them (`entry_labels`), never by the entry: a reader writes the label, and S3 turns it
33
+ back into the entry (WP-08b). The labels are not stored; they follow from the window, so the bytes S2 measures are the
34
+ bytes a packet carries.
35
+
36
+ **The bound** (design §5.4 as amended, view-window calls only). The driver's part of a call - the window as
37
+ `render_window` writes it, plus the packet template, schema and instructions (`overhead`) - is at most
38
+ `bound.INPUT_BOUND` minus the seat's declared host allowance, in bytes (a token covers at least one byte), and, with the
39
+ allowance and the output reservation (`run.json`'s `output_caps.S3`, the cap every S3 call declares), within the seat's
40
+ context capacity. A window failing either is cut smaller.
41
+ `bound.check_observed` compares what a call really consumed with `bound.INPUT_BOUND`; above it is a host change
42
+ (`INPUT_BOUND_EXCEEDED`) and the dispatcher refuses every dispatch until an amendment of `host_allowance` follows.
43
+ No guarantee about the complete request is claimed.
44
+
45
+ **Expansion** (`expand`, `record_decision`): a clipped record is expanded into windows under the same bound and the
46
+ same span mapping, or skipped with a reason; `forced_records` names the records that may not be skipped (those
47
+ between a pending event and the next human turn) and `forced_by_search` those a claim's retrieval terms match in
48
+ the full redacted text, clipped spans included. A session is *view complete* when
49
+ every window passed the gate and every clipped record has an executed expansion or a recorded skip, *source
50
+ complete* when no span was skipped that a gather did not read (`completeness`); `coverage_basis` is the order of
51
+ design §5.4's coverage basis. A **gather** (`gather_windows`, `gather`, WP-08e) is the middles one window's reading
52
+ skipped, re-read as an expansion's middle is (`omitted_middle`) and cut into windows of their own under the same bound.
53
+
54
+ Failures are named by their first word: ALLOWANCE_UNDECLARED, WINDOW_UNBOUNDED, WINDOW_BOUND_EXCEEDED,
55
+ WINDOW_CAPACITY_EXCEEDED, INPUT_BOUND_EXCEEDED, SOURCE_CHANGED, SOURCE_TAMPERED, SOURCE_UNREADABLE,
56
+ VIEW_NAME_COLLISION, SET_MISMATCH, OVERLAP_MISSING, SPAN_UNION_MISMATCH, ERROR_LINE_DROPPED, EXPANSION_SKIPPED,
57
+ EXPANSION_DECISION_INVALID, EXPANSION_DECISION_CONFLICT, EXPANSION_SOURCE_DRIFT, EXPANSION_UNKNOWN. Under the production posture a transcript
58
+ whose work raises is quarantined under that name and the run goes on (design §4, `records.run_items`).
59
+
60
+ views.py --self-test
61
+ """
62
+ import bisect
63
+ import collections
64
+ import contextlib
65
+ import copy
66
+ import datetime
67
+ import hashlib
68
+ import json
69
+ import os
70
+ import pathlib
71
+ import re
72
+ import shutil
73
+ import subprocess
74
+ import sys
75
+ import tempfile
76
+
77
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
78
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
79
+ from runlib import bound, census, claims, coverage, declare, gate, ledger, lineage, projection, records, search, sources, stagelock, validate
80
+ from runlib.records import Refused
81
+
82
+ OVERLAP_TURNS = 5
83
+ OVERLAP_ITEM_BYTES = 700
84
+ OVERLAP_SLACK = 260 # header and cut marker of an overlap entry, beyond its text
85
+ # What one side's overlap may cost a window. The same reservation as before, but now it is filled from a
86
+ # slice counted in TURNS rather than in entries, and whatever does not fit is accounted rather than dropped.
87
+ OVERLAP_SIDE_BYTES = OVERLAP_TURNS * (OVERLAP_ITEM_BYTES + OVERLAP_SLACK)
88
+ HEADER_SLACK = 700 # the window's own heading lines
89
+ LABEL_BOUND = "e99999" # wider than any label a window renders: a window of the bound holds far fewer entries
90
+ MIN_ENTRY_BYTES = 2048 # a window that cannot hold an entry this large is unbounded
91
+ CLIP_OVER, HEAD_CHARS, TAIL_CHARS = 4_000, 1_200, 800
92
+ ERROR_LINE = re.compile(r"(?i)\b(error|exception|traceback|fatal|failed|failure|denied|not found|no such file|cannot|"
93
+ r"can't|unable to|timed out|timeout|panic|segmentation fault)\b")
94
+ FORCED_BY = ("pending_event", "search_match", "none")
95
+ DECISIONS = ("expand", "skip")
96
+ ROLE_BACKLOG = re.compile(r"^backlog\(.+\)$")
97
+
98
+
99
+ # ---- the bound -------------------------------------------------------------------------------
100
+
101
+ def limits_of(run, overhead=bound.PACKET_OVERHEAD, seats_path=None):
102
+ """The bound a view-window call keeps, from the declaration: the S3 seat's declared allowance, and the output cap
103
+ the declaration gives S3's calls.
104
+
105
+ Where the allowance comes from is this module's business; what the bound then IS belongs to
106
+ `runlib/bound.py`, which both this side and the dispatcher import (the seam record of 2026-10-22).
107
+
108
+ There is no capacity argument. It was one, and a caller could then cut a window against a number no
109
+ declaration carried; the capacity now comes from the shared reader on every path, and a test that needs
110
+ another one declares it in a `seats.json` fixture and names it with `seats_path` - the reader is the
111
+ same, and so is what it requires of a declaration (BB#5). There is no reservation argument either, for the same
112
+ reason: the cap is `run.json`'s `output_caps`, the number S3's calls declare (WP-08)."""
113
+ seat = (run.get("seats") or {}).get("S3")
114
+ entry = (run.get("host_allowance") or {}).get(seat)
115
+ if not seat or not entry:
116
+ raise Refused(f"ALLOWANCE_UNDECLARED seats.S3: {seat!r} has no host_allowance entry, so no view window can be cut "
117
+ "against a bound (measure it in preflight and declare it)")
118
+ # BA#1: the seat's context size is host-reported evidence seats.json declares, and cutting a window
119
+ # reads the SAME declaration the dispatcher admits against. There is no default: a window cut against
120
+ # an invented capacity is a window cut against nothing.
121
+ capacity, basis = gate.seat_capacity(seat, (run.get("host_versions") or {}).get(seat.partition(":")[0])
122
+ or (entry.get("host_version")),
123
+ **({"path": seats_path} if seats_path else {}))
124
+ if capacity is None:
125
+ raise Refused(f"CAPACITY_UNDECLARED seats.S3: {basis}; no window is cut against a capacity nobody "
126
+ "measured (the seat's context window is host-reported)")
127
+ # The output reservation is the cap the S3 call will declare for its answer - the same number the
128
+ # dispatcher admits that call against. There is no constant: a window cut against a reservation nobody
129
+ # chose reserves nothing (the ruling of 2026-10-22), and the declaration is where it is chosen (WP-08).
130
+ reservation = (run.get("output_caps") or {}).get(declare.VIEW_WINDOW_STAGE)
131
+ if not (isinstance(reservation, int) and not isinstance(reservation, bool) and reservation > 0):
132
+ raise Refused(f"CAP_UNDECLARED output_caps.S3: output-token cap {reservation!r}; a window is cut against the cap "
133
+ "the call will declare for its answer, and run.json declares it as a positive integer")
134
+ return bound.limits(entry["allowance_tokens"], seat=seat, capacity=capacity, reservation=reservation,
135
+ overhead=overhead)
136
+
137
+
138
+ def observed_input_of(capture):
139
+ """A retained capture's observed input, as `bound` defines it.
140
+
141
+ A capture missing any of the three components is refused rather than read as a smaller number: a
142
+ missing cache field would make every overrun look like a call within the bound."""
143
+ observed, missing = bound.observed_of((capture or {}).get("usage") or {})
144
+ if missing:
145
+ raise Refused(f"CAPTURE_USAGE_MISSING {capture.get('call_id')}: {', '.join(missing)}; the observed input of a "
146
+ "call is input + cache creation + cache read, and a missing field is not a zero")
147
+ return observed
148
+
149
+
150
+ def retained_capture(name, root=None):
151
+ """One retained capture, read from `session-distill/fixtures/captures/` and refused by name when its bytes
152
+ moved from the sha256 pinned in `captures.json`.
153
+
154
+ A dictionary written at the point of use is not a capture: its counts are whatever the test needed, so a
155
+ control built on one proves that the arithmetic runs, not that the boundary holds for anything a host
156
+ produced. These files are pinned, so a count cannot be adjusted to make a control pass without the pin
157
+ failing first.
158
+
159
+ Two of the three are RETAINED captures of the frozen probe evidence of 2026-10-20, copied with their
160
+ usage block alone and naming their source file, its sha256 and the extraction rule: `within-bound`
161
+ (24,806 observed input) and `r-authoring` (333,706, above the view-window bound - which the bound does
162
+ not govern, because an R-authoring call is a non-window call by the contract of design 8.6). The third,
163
+ `window-overrun`, is SYNTHETIC and says so in its own `origin`: no retained capture of a view-window
164
+ call above the bound exists, so its counts are fake and labelled as fake."""
165
+ # `root` is the directory holding `captures.json` and `captures/`. It is a parameter so a control can
166
+ # plant a mismatch in a COPY: the mismatch control used to write altered bytes into the tracked fixture
167
+ # in the checkout and restore them in `finally`, which needs write access to the checkout and shows
168
+ # other readers - a parallel self-test, an interrupted run - a fixture that is not the fixture.
169
+ root = pathlib.Path(root) if root is not None else records.fixture_root()
170
+ pins = json.loads((root / "captures.json").read_text(encoding="utf-8"))["captures"]
171
+ path, name = root / "captures" / f"{name}.json", f"{name}.json"
172
+ if name not in pins or not path.is_file():
173
+ raise Refused(f"CAPTURE_UNPINNED {name}: no capture fixture of that name is pinned in captures.json")
174
+ raw = path.read_bytes()
175
+ digest = hashlib.sha256(raw).hexdigest()
176
+ if digest != pins[name]:
177
+ raise Refused(f"CAPTURE_HASH_MISMATCH {path}: the file is sha256:{digest[:12]} and the pin says "
178
+ f"{pins[name][:12]}; a capture whose bytes moved is not the capture a control was written against")
179
+ return json.loads(raw.decode("utf-8"))
180
+
181
+
182
+ # ---- blocks, clipping, entries ---------------------------------------------------------------
183
+
184
+ def record_items(host, rec, child):
185
+ """The content blocks of one parsed record that the view shows: `(json_pointer, kind, tool, is_error, value)`.
186
+ `kind` is human, delegated (a parent's instruction to a child), summary, assistant, tool_call or tool_result."""
187
+ if not isinstance(rec, dict):
188
+ return
189
+ if host == "claude":
190
+ message = rec.get("message") if isinstance(rec.get("message"), dict) else None
191
+ if rec.get("type") == "user" and message and not rec.get("isMeta"):
192
+ who = "delegated" if child or rec.get("isSidechain") is True else "summary" if rec.get("isCompactSummary") else "human"
193
+ content = message.get("content")
194
+ if isinstance(content, str):
195
+ yield "/message/content", who, None, False, content
196
+ for i, block in enumerate(content if isinstance(content, list) else []):
197
+ if not isinstance(block, dict):
198
+ continue
199
+ if block.get("type") == "text" and isinstance(block.get("text"), str):
200
+ yield f"/message/content/{i}/text", who, None, False, block["text"]
201
+ elif block.get("type") == "tool_result":
202
+ failed, inner = block.get("is_error") is True, block.get("content")
203
+ if isinstance(inner, str):
204
+ yield f"/message/content/{i}/content", "tool_result", None, failed, inner
205
+ for j, part in enumerate(inner if isinstance(inner, list) else []):
206
+ if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str):
207
+ yield f"/message/content/{i}/content/{j}/text", "tool_result", None, failed, part["text"]
208
+ elif rec.get("type") == "assistant" and message and isinstance(message.get("content"), list):
209
+ for i, block in enumerate(message["content"]):
210
+ if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str):
211
+ yield f"/message/content/{i}/text", "assistant", None, False, block["text"]
212
+ elif isinstance(block, dict) and block.get("type") == "tool_use":
213
+ yield f"/message/content/{i}/input", "tool_call", block.get("name"), False, block.get("input")
214
+ elif rec.get("type") == "attachment" and isinstance(rec.get("attachment"), dict):
215
+ attachment = rec["attachment"] # what a person typed while the assistant was working
216
+ if attachment.get("type") == "queued_command" and isinstance(attachment.get("prompt"), str):
217
+ yield "/attachment/prompt", "delegated" if child else "human", None, False, attachment["prompt"]
218
+ return
219
+ payload = rec.get("payload") if isinstance(rec.get("payload"), dict) else None
220
+ if rec.get("type") != "response_item" or not payload:
221
+ return
222
+ kind = payload.get("type")
223
+ if kind == "message" and payload.get("role") in ("user", "assistant"):
224
+ who = "assistant" if payload["role"] == "assistant" else "delegated" if child else "human"
225
+ for i, block in enumerate(payload.get("content") if isinstance(payload.get("content"), list) else []):
226
+ if isinstance(block, dict) and isinstance(block.get("text"), str):
227
+ yield f"/payload/content/{i}/text", who, None, False, block["text"]
228
+ elif kind == "function_call":
229
+ yield "/payload/arguments", "tool_call", payload.get("name"), False, payload.get("arguments")
230
+ elif kind == "custom_tool_call":
231
+ yield "/payload/input", "tool_call", payload.get("name"), False, payload.get("input")
232
+ elif kind in ("function_call_output", "custom_tool_call_output"):
233
+ out = payload.get("output")
234
+ if isinstance(out, str):
235
+ yield "/payload/output", "tool_result", None, False, out
236
+ for j, part in enumerate(out if isinstance(out, list) else []):
237
+ if isinstance(part, dict) and isinstance(part.get("text"), str):
238
+ yield f"/payload/output/{j}/text", "tool_result", None, False, part["text"]
239
+
240
+
241
+ def clip_bounds(text):
242
+ """`(head end, tail start)` of a clipped block: on line boundaries where its text has them (WP-08c). A line ends
243
+ where `str.splitlines(keepends=True)` ends it - "\n", "\r", "\r\n" as one end, U+2028, "\x0c" and the others it
244
+ knows - which is how the clipper and the view check read error lines, so a result whose lines run on carriage returns
245
+ (a progress bar's output) is cut between lines too. The head ends at the last line boundary at or before
246
+ HEAD_CHARS, and the tail starts at the first at or after `len - TAIL_CHARS`. The cut is by characters, on
247
+ HEAD_CHARS or `len - TAIL_CHARS` itself, when the nearest line boundary would keep less than half of HEAD_CHARS or
248
+ of TAIL_CHARS: in a block that is one long line, and in one whose line around the cut is that long. Either cut keeps
249
+ a "\r\n" whole (X r2): a head end that would fall between its "\r" and "\n" moves back before the "\r", and a tail
250
+ start there moves on past the "\n" - which the boundary rule already does at the tail, since the boundary after a
251
+ "\r\n" keeps more than half of TAIL_CHARS. A cut inside a line split it between a shown side and the omitted middle,
252
+ so the middle's expansion began or ended mid-line (dw2-live1: it ended at "cleanup 028")."""
253
+ n = len(text)
254
+ head, tail = HEAD_CHARS, n - TAIL_CHARS
255
+ before, after, at = 0, None, 0
256
+ for line in text.splitlines(keepends=True):
257
+ at += len(line)
258
+ if at >= n:
259
+ break
260
+ if at <= HEAD_CHARS:
261
+ before = at
262
+ if at >= n - TAIL_CHARS:
263
+ after = at
264
+ break
265
+ if before >= HEAD_CHARS // 2:
266
+ head = before
267
+ if after is not None and n - after >= TAIL_CHARS // 2:
268
+ tail = after
269
+ if text[head - 1:head + 1] == "\r\n":
270
+ head -= 1
271
+ if text[tail - 1:tail + 1] == "\r\n":
272
+ tail += 1
273
+ return head, tail
274
+
275
+
276
+ def clip_parts(text, kind):
277
+ """`([(type, a, b)], meta)`: `text` parts are shown, `gap` parts omitted, together tiling [0, len(text)).
278
+ `meta` is None for a block shown whole; else the head, the tail, the error lines kept whole, the omitted span of
279
+ the middle with the sha256 of its characters, and the gaps. The head and tail end on line boundaries
280
+ (`clip_bounds`)."""
281
+ n = len(text)
282
+ if kind != "tool_result" or n <= CLIP_OVER:
283
+ return [("text", 0, n)], None
284
+ head, tail = clip_bounds(text)
285
+ shown, errors, offset = [(0, head), (tail, n)], [], 0
286
+ for line in text.splitlines(keepends=True):
287
+ a, b = offset, offset + len(line)
288
+ offset = b
289
+ if b > head and a < tail and ERROR_LINE.search(line):
290
+ errors.append([a, b])
291
+ shown.append((a, b))
292
+ parts, pos = [], 0
293
+ for a, b in coverage.normalize(shown):
294
+ if a > pos:
295
+ parts.append(("gap", pos, a))
296
+ parts.append(("text", a, b))
297
+ pos = b
298
+ if pos < n:
299
+ parts.append(("gap", pos, n))
300
+ if not any(p[0] == "gap" for p in parts):
301
+ return [("text", 0, n)], None
302
+ return parts, {"head": [0, head], "tail": [tail, n], "error_lines": errors,
303
+ "gaps": [[a, b] for t, a, b in parts if t == "gap"],
304
+ "omitted_span": {"start": head, "end": tail, "sha256": records.sha256_bytes(text[head:tail].encode("utf-8"))}}
305
+
306
+
307
+ def compose(text, parts):
308
+ """The view text of a block and its `segments`: where each shown stretch sits in the view and in the block."""
309
+ view, segments, pos = [], [], 0
310
+ for kind, a, b in parts:
311
+ piece = text[a:b] if kind == "text" else f"\n[... {b - a} chars omitted ({a}-{b}) ...]\n"
312
+ if kind == "text":
313
+ segments.append({"view": [pos, pos + len(piece)], "block": [a, b]})
314
+ view.append(piece)
315
+ pos += len(piece)
316
+ return "".join(view), segments
317
+
318
+
319
+ def make_entry(item, line, role, offset):
320
+ text = item["text"]
321
+ parts, meta = clip_parts(text, item["kind"])
322
+ view, segments = compose(text, parts)
323
+ entry = {"record_id": f"{line}{item['pointer']}", "line": line, "json_pointer": item["pointer"], "kind": item["kind"],
324
+ "tool": item.get("tool"), "ts": item.get("ts"), "error": bool(item.get("error")), "window_role": role,
325
+ # The locator rides on EVERY entry. It used to live inside `clipped`, which an ordinary human or
326
+ # assistant message does not have, so an overlap omission of such a message wrote `offset: None`
327
+ # into the manifest and expansion died on `seek(None)` - a defect no control could see, because
328
+ # the one control that expanded an overlap row supplied an offset of its own.
329
+ "size": len(text), "text": view, "segments": segments, "owned": True, "offset": offset}
330
+ if meta:
331
+ entry["clipped"] = {**meta, "forced_by": "none", "offset": offset}
332
+ return entry
333
+
334
+
335
+ def omission_id(record_id, start, end):
336
+ """The identity of ONE omitted interval: the record, the interval in the projected block's own
337
+ coordinates, and a digest of both.
338
+
339
+ A record id is not an identity. A record can lose several intervals - a clip in the middle, a context cut
340
+ at 700 characters, the rest of it when a side's budget ran out - and keying the accounting by record
341
+ meant one expansion discharged all of them. The digest is what makes the identity safe in a FILE NAME:
342
+ the path sanitiser folds characters, so two different records could otherwise write to one path."""
343
+ digest = hashlib.sha256(f"{record_id}\x00{start}\x00{end}".encode("utf-8")).hexdigest()[:12]
344
+ return f"{record_id}@{start}-{end}#{digest}"
345
+
346
+
347
+ def interval_of(entry, lo, hi, view_start, view_end):
348
+ """One segment's share of the view range [view_start, view_end), as a block interval with its hash, or
349
+ None when the segment lies outside the range."""
350
+ start, end = max(lo, view_start), min(hi, view_end)
351
+ return None if start >= end else (start, end)
352
+
353
+
354
+ def omitted_intervals(entry, view_start, view_end):
355
+ """Every interval of the PROJECTED BLOCK that the view range [view_start, view_end) of `entry` covers,
356
+ each with the hash of its own characters.
357
+
358
+ The coordinates matter more than they look. An overlap cut used to be recorded as `[700, len]` over the
359
+ entry's own view text, while expansion reads those numbers as offsets into the block - so for a split
360
+ span, or for a clipped record whose view elides a gap, the interval named characters that were never
361
+ omitted, and the hash could only disagree. `segments` is the mapping the entry already carries, and it
362
+ is the only thing that can turn a view range into block coordinates."""
363
+ out = []
364
+ for seg in entry["segments"]:
365
+ span = interval_of(entry, seg["view"][0], seg["view"][1], view_start, view_end)
366
+ if span is None:
367
+ continue
368
+ lo, hi = span
369
+ shift = seg["block"][0] - seg["view"][0]
370
+ out.append({"start": lo + shift, "end": hi + shift,
371
+ "sha256": records.sha256_bytes(entry["text"][lo:hi].encode("utf-8"))})
372
+ return out
373
+
374
+
375
+ def cap_text(text, max_bytes):
376
+ """`(text cut to at most max_bytes, whether it was cut)`."""
377
+ if len(text.encode("utf-8")) <= max_bytes:
378
+ return text, False
379
+ return text[:fit_end(text, 0, max_bytes)], True
380
+
381
+
382
+ def context_entry(item, line, role, offset=None):
383
+ """A record no window owns, kept as overlap context. Its cut is accounted like any other: the span it
384
+ leaves out and that span's hash, so an overlap entry never reports a cut nothing names."""
385
+ text, cut = cap_text(item["text"], OVERLAP_ITEM_BYTES)
386
+ entry = {"record_id": f"{line}{item['pointer']}", "line": line, "json_pointer": item["pointer"], "kind": item["kind"],
387
+ "tool": item.get("tool"), "ts": item.get("ts"), "error": bool(item.get("error")), "window_role": role,
388
+ "size": len(item["text"]), "text": text, "segments": [{"view": [0, len(text)], "block": [0, len(text)]}],
389
+ "cut": cut, "owned": False, "offset": offset}
390
+ if cut:
391
+ # the item text IS the block here, so the cut's view coordinates are already the block's; it is kept
392
+ # as a LIST because a context entry can lose this tail and then lose its shown part too, when the
393
+ # side's budget runs out, and both intervals have to survive into the manifest
394
+ entry["cut_spans"] = [{"start": len(text), "end": len(item["text"]),
395
+ "sha256": records.sha256_bytes(item["text"][len(text):].encode("utf-8"))}]
396
+ return entry
397
+
398
+
399
+ TURN_KINDS = ("human", "assistant") # design §5.4: a turn is a human or an assistant message
400
+
401
+
402
+ def is_turn(entry):
403
+ """Whether this entry is part of a transcript TURN. A tool call and its result belong to the assistant's
404
+ turn rather than being turns of their own, which is what §5.4 counts when it says five."""
405
+ return entry.get("kind") in TURN_KINDS
406
+
407
+
408
+ def turn_key(entry):
409
+ """The TURN an entry belongs to: the transcript record it came from, and that record's kind.
410
+
411
+ One message is one turn however many entries it becomes. Counting entries instead counted every content
412
+ block of a message, and then every span a split made of a block, as a turn of its own - so a five-turn
413
+ overlap could be five fragments of a single assistant message and carry no human turn at all. A record
414
+ line survives both block division and splitting (`slice_entry` copies it into every span), which is what
415
+ makes it the identity to count."""
416
+ return (entry["line"], entry["kind"])
417
+
418
+
419
+ def before_turns(seq, stop, turns):
420
+ """The start of the longest contiguous slice of `seq[:stop]` holding at most `turns` TURNS.
421
+
422
+ The slice is contiguous because context that skips the tool traffic between two turns is not the
423
+ conversation that happened; the tool traffic rides along with the turn it belongs to and is not counted
424
+ as one."""
425
+ seen, index = [], stop
426
+ while index > 0:
427
+ entry = seq[index - 1]
428
+ if is_turn(entry):
429
+ key = turn_key(entry)
430
+ if key not in seen:
431
+ if len(seen) == turns:
432
+ break
433
+ seen.append(key)
434
+ index -= 1
435
+ return index
436
+
437
+
438
+ def after_turns(seq, start, turns):
439
+ """The end of the shortest contiguous slice of `seq[start:]` holding at most `turns` TURNS."""
440
+ seen, index = [], start
441
+ while index < len(seq):
442
+ entry = seq[index]
443
+ if is_turn(entry):
444
+ key = turn_key(entry)
445
+ if key not in seen:
446
+ if len(seen) == turns:
447
+ break
448
+ seen.append(key)
449
+ index += 1
450
+ return index
451
+
452
+
453
+ def turns_in(entries):
454
+ """How many distinct transcript turns a slice of entries holds."""
455
+ return len({turn_key(e) for e in entries if is_turn(e)})
456
+
457
+
458
+ def eid(entry):
459
+ """The identity of an entry within its transcript: the record, and the span when it was split."""
460
+ span = entry.get("span")
461
+ return entry["record_id"] + (f"#{span['index']}/{span['of']}" if span else "")
462
+
463
+
464
+ def span_of(entry_id):
465
+ """The span an entry id names (`eid`), or None: an overlap entry carries its id, not its span."""
466
+ found = re.search(r"#([0-9]+)/([0-9]+)$", entry_id or "")
467
+ return {"index": int(found.group(1)), "of": int(found.group(2))} if found else None
468
+
469
+
470
+ def fit_end(text, start, max_bytes):
471
+ """The largest end such that text[start:end] is at most max_bytes in UTF-8, at least start + 1."""
472
+ end = min(len(text), start + max_bytes)
473
+ while end > start + 1:
474
+ size = len(text[start:end].encode("utf-8"))
475
+ if size <= max_bytes:
476
+ break
477
+ end = max(start + 1, start + int((end - start) * max_bytes / size))
478
+ while end > start + 1 and len(text[start:end].encode("utf-8")) > max_bytes:
479
+ end -= 1
480
+ return max(end, start + 1)
481
+
482
+
483
+ def slice_entry(entry, a, b, index, of):
484
+ """The span [a, b) of an entry's view text: its text, the segments inside it re-based, and its place."""
485
+ piece = copy.deepcopy({k: v for k, v in entry.items() if k not in ("text", "segments", "clipped")})
486
+ piece["text"] = entry["text"][a:b]
487
+ piece["segments"] = []
488
+ for seg in entry["segments"]:
489
+ lo, hi = max(seg["view"][0], a), min(seg["view"][1], b)
490
+ if lo < hi:
491
+ shift = seg["block"][0] - seg["view"][0]
492
+ piece["segments"].append({"view": [lo - a, hi - a], "block": [lo + shift, hi + shift]})
493
+ if "clipped" in entry and index == 1:
494
+ piece["clipped"] = copy.deepcopy(entry["clipped"])
495
+ piece["span"] = {"index": index, "of": of}
496
+ return piece
497
+
498
+
499
+ def split_entry(entry, max_bytes):
500
+ """The entry itself when its rendering fits `max_bytes`, else its spans, each of which does."""
501
+ if len(render_entry(entry, LABEL_BOUND).encode("utf-8")) <= max_bytes:
502
+ return [entry]
503
+ limit = max_bytes - len(render_entry({**entry, "text": "", "span": {"index": 9999, "of": 9999}}, LABEL_BOUND).encode("utf-8"))
504
+ cuts, pos, text = [], 0, entry["text"]
505
+ while pos < len(text):
506
+ end = fit_end(text, pos, limit)
507
+ if end < len(text):
508
+ newline = text.rfind("\n", pos + (end - pos) * 3 // 4, end)
509
+ end = newline + 1 if newline >= 0 else end
510
+ cuts.append((pos, end))
511
+ pos = end
512
+ return [slice_entry(entry, a, b, k, len(cuts)) for k, (a, b) in enumerate(cuts, 1)]
513
+
514
+
515
+ # ---- rendering: what the driver supplies ------------------------------------------------------
516
+
517
+ def role_label(role):
518
+ return "backlog" if ROLE_BACKLOG.match(role) else role
519
+
520
+
521
+ def normal_stamp(value):
522
+ """A record's timestamp as the view may carry it: parsed, then written back in one normal form - or None.
523
+
524
+ A transcript's `timestamp` is a string the host wrote, and this code treated it as a number and copied
525
+ it through to `header_of`, which renders it into the model's window. A string that carries a secret or
526
+ a home path is therefore model-visible metadata, and a field nobody projects is the one place such a
527
+ string can stand. Re-emitting only what `fromisoformat` parsed makes the field a timestamp by
528
+ construction: anything else it held is gone, with no pattern to keep up to date."""
529
+ if not isinstance(value, str):
530
+ return None
531
+ try:
532
+ when = datetime.datetime.fromisoformat(value)
533
+ except ValueError:
534
+ return None
535
+ when = when if when.tzinfo else when.replace(tzinfo=datetime.timezone.utc)
536
+ return when.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
537
+
538
+
539
+ def header_of(entry, label):
540
+ """An entry's heading: a line `entry: <label>` holding nothing but the value a reading writes as its `entry`, then
541
+ its kind, time and role. The value is the window's own short label of the entry (`entry_labels`), never the entry
542
+ itself: live readers wrote the entry without its last part (`7/message/content/0` for `7/message/content/0/text`,
543
+ WP-08 commit 7's apart leg) and, after it stood alone on its line, as a near copy in one window call of ten (C1,
544
+ 2026-11-05), so a reader copies a label of a few characters and code maps it back (WP-08b)."""
545
+ bits = [entry["kind"] + (f":{entry['tool']}" if entry.get("tool") else ""), entry.get("ts") or "-",
546
+ role_label(entry["window_role"])]
547
+ if entry.get("error"):
548
+ bits.append("ERROR")
549
+ # a span says which part of its record it is, as its entry did (`eid`): the label no longer carries it
550
+ span = entry.get("span") or span_of(entry.get("entry"))
551
+ if span:
552
+ bits.append(f"part {span['index']} of {span['of']}")
553
+ return f"entry: {label}\n" + " ".join(bits)
554
+
555
+
556
+ def render_entry(entry, label):
557
+ return header_of(entry, label) + "\n" + entry["text"] + "\n"
558
+
559
+
560
+ def entry_labels(window):
561
+ """`{entry: label}` of every entry `window` shows, in the order `render_window` renders them - the overlap before,
562
+ the records it owns, the overlap after - labelled e1, e2, ... A window's labels are its own: every window and every
563
+ expansion window numbers from e1, and the same record in two windows has a label in each. They follow from the
564
+ window alone, so a retry and a resumed run show the same ones, and nothing stores them (WP-08b)."""
565
+ shown = ([e["entry"] for e in window["overlap"]["prev"]] + [eid(r) for r in window["records"]]
566
+ + [e["entry"] for e in window["overlap"]["next"]])
567
+ return {entry: f"e{n}" for n, entry in enumerate(shown, 1)}
568
+
569
+
570
+ def shown_segments(entry, end):
571
+ """The segments of `entry` that the first `end` characters of its view text show, each in the same coordinates."""
572
+ out = []
573
+ for seg in entry["segments"]:
574
+ a, b = seg["view"]
575
+ if a >= end:
576
+ break
577
+ stop = min(b, end)
578
+ out.append({"view": [a, stop], "block": [seg["block"][0], seg["block"][0] + (stop - a)]})
579
+ return out
580
+
581
+
582
+ def overlap_of(entry):
583
+ """An entry as the overlap of its neighbour shows it: cut to OVERLAP_ITEM_BYTES, with its place in the
584
+ sequence and every interval it has lost, in the PROJECTED BLOCK's coordinates, each with its own hash.
585
+
586
+ Three things were wrong here at once, and each hid the next. The cut was once a bare `overlap_cut: true`,
587
+ which is not an accounting - a window could drop most of a human turn with nothing naming what went. Then
588
+ it became a single `omitted_span` in the ENTRY's own coordinates, which expansion reads as offsets into
589
+ the block, so for a split span or a clipped record it named characters that were never omitted. And a
590
+ singular field cannot hold what an entry has lost twice: a context entry cut to 700 characters and then
591
+ shown is still missing its tail, and that tail reached no manifest at all, so a session could report
592
+ itself source complete with content nobody had looked at.
593
+
594
+ `omitted_intervals` is the one shape, in block coordinates, and it carries BOTH what this cut loses and
595
+ what the entry had already lost."""
596
+ text, cut = cap_text(entry["text"], OVERLAP_ITEM_BYTES)
597
+ # `line` rides along because turn identity is the record's, and a consumer counting turns in a window
598
+ # cannot recover it from a record_id
599
+ # `size` is the record's own length - the full projected block - and it rides along unchanged. A row
600
+ # that substituted a span's end, or the length of a text already capped to 700, reported the head of a
601
+ # clipped result as the size of the record; §5.4 and done-when 4 read this number as the record's size.
602
+ # `json_pointer` and the `segments` of what is shown let a quote of the overlap be located exactly as one of an owned
603
+ # record: the overlap is evidence a reading may cite (an exposure seen before the action, X review of WP-08 r1), while
604
+ # owning it stays with its own window. The cut is a prefix, so the shown segments are the entry's, ended at the cut.
605
+ shown = {"entry": eid(entry), "record_id": entry["record_id"], "line": entry["line"], "json_pointer": entry["json_pointer"],
606
+ "size": entry["size"], "kind": entry["kind"], "tool": entry.get("tool"),
607
+ "ts": entry.get("ts"), "window_role": entry["window_role"], "error": entry.get("error", False),
608
+ "text": text, "segments": shown_segments(entry, len(text)), "overlap_cut": cut or bool(entry.get("cut"))}
609
+ lost = (omitted_intervals(entry, len(text), len(entry["text"])) if cut else []) \
610
+ + list(entry.get("cut_spans", []))
611
+ if lost:
612
+ shown["omitted_intervals"] = lost
613
+ return shown
614
+
615
+
616
+ def overlap_side(entries, budget=OVERLAP_SIDE_BYTES, from_end=False):
617
+ """`(shown, omitted)` for one side's overlap: the turns nearest the window, filled to `budget`.
618
+
619
+ A window stays bounded, so a side's overlap has a size. What changes is that the slice is counted in
620
+ turns and that the entries the budget cannot hold are returned rather than silently absent: the caller
621
+ lists them in the window, so every turn of the overlap is either shown or named."""
622
+ ordered = list(reversed(entries)) if from_end else list(entries)
623
+ shown, omitted, spent = [], [], 0
624
+ for entry in ordered:
625
+ rendered = overlap_of(entry)
626
+ cost = len(render_overlap(rendered, LABEL_BOUND).encode("utf-8"))
627
+ if spent + cost > budget and shown:
628
+ # A turn the budget cannot hold is OMITTED, and an omission with no span and no hash is not an
629
+ # accounting - it names a record and says nothing about what was in it. The whole text goes, so
630
+ # the span is the whole text and the hash is the whole text's.
631
+ # the role is the record's, as a shown entry's is: without it the manifest row named an in-window
632
+ # record context, and an expansion of that row carried the wrong role into evidence
633
+ omitted.append({"entry": eid(entry), "record_id": entry["record_id"], "line": entry["line"],
634
+ "kind": entry["kind"], "size": entry["size"], "reason": "overlap_budget",
635
+ "window_role": entry["window_role"],
636
+ # the whole of what this entry shows goes, in block coordinates, and so does
637
+ # anything it had already lost
638
+ "omitted_intervals": (omitted_intervals(entry, 0, len(entry["text"]))
639
+ + list(entry.get("cut_spans", [])))})
640
+ continue
641
+ spent += cost
642
+ shown.append(rendered)
643
+ if from_end:
644
+ shown.reverse()
645
+ omitted.reverse()
646
+ return shown, omitted
647
+
648
+
649
+ def render_overlap(entry, label):
650
+ return (header_of(entry, label) + " (overlap)\n" + entry["text"]
651
+ + ("\n[... cut ...]" if entry["overlap_cut"] else "") + "\n")
652
+
653
+
654
+ def render_window(window):
655
+ """The window as the driver puts it into a packet: this text's UTF-8 bytes are the window's part of
656
+ `driver_bytes`.
657
+
658
+ The version is checked HERE as well, because this is the last boundary before a model sees the text and
659
+ it takes a window object from any caller - a stale one rendered straight into a packet is exactly the
660
+ text a newer masking exists to withhold, and the checked readers above cannot help a caller that did
661
+ not use them."""
662
+ current_version(window, f"window {window.get('window_n')} of {window.get('transcript')}")
663
+ label = entry_labels(window)
664
+ out = [f"WINDOW {window['window_n']} of {window['transcript']} version {window['version']} "
665
+ f"sha256:{window['version_sha'][:12]} redaction {window['redaction_version']}"]
666
+ if window["overlap"]["prev"]:
667
+ out.append("--- overlap before: context, not owned by this window ---")
668
+ out.extend(render_overlap(e, label[e["entry"]]) for e in window["overlap"]["prev"])
669
+ out.append("--- records owned by this window ---")
670
+ out.extend(render_entry(e, label[eid(e)]) for e in window["records"])
671
+ if window["overlap"]["next"]:
672
+ out.append("--- overlap after: context, not owned by this window ---")
673
+ out.extend(render_overlap(e, label[e["entry"]]) for e in window["overlap"]["next"])
674
+ return "\n".join(out) + "\n"
675
+
676
+
677
+ def manifest_of(entries):
678
+ return [{"record_id": e["record_id"], "line": e["line"], "size": e["size"],
679
+ "omitted_span": e["clipped"]["omitted_span"], "error_lines": len(e["clipped"]["error_lines"]),
680
+ "forced_by": e["clipped"]["forced_by"], "locator": {"offset": e["clipped"]["offset"]},
681
+ "origin": "owned", "window_role": e["window_role"],
682
+ "omission_id": omission_id(e["record_id"], e["clipped"]["omitted_span"]["start"],
683
+ e["clipped"]["omitted_span"]["end"])}
684
+ for e in entries if "clipped" in e]
685
+
686
+
687
+ def span_map_of(entries):
688
+ return [{"record_id": e["record_id"], **e["span"], "segments": e["segments"]} for e in entries if "span" in e]
689
+
690
+
691
+ def overlap_manifest(window, seq):
692
+ """The overlap's omissions as manifest rows - ONE ROW PER INTERVAL, so the one list a consumer reads
693
+ covers them too.
694
+
695
+ An overlap omission was accounted nowhere. A turn the budget could not hold was named in
696
+ `overlap.omitted` and a turn cut to `OVERLAP_ITEM_BYTES` carried its cut, but neither entered
697
+ `omission_manifest`, so §5.4's expansion could not reach them (`EXPANSION_UNKNOWN`) and completeness
698
+ counted a view whole while part of its context was gone. One row per interval, because a row per RECORD
699
+ kept the first interval and dropped the rest, and because a decision about one interval is not a
700
+ decision about another. Rows carry `origin: "overlap"` - the record is context here rather than owned -
701
+ and the locator is the entry's own, which every entry now has."""
702
+ located = {e["record_id"]: e.get("offset") for e in seq}
703
+ rows, seen = [], set()
704
+ for side in ("prev", "next"):
705
+ for shown in list(window["overlap"][side]) + list(window["overlap"]["omitted"][side]):
706
+ for span in shown.get("omitted_intervals") or []:
707
+ ident = omission_id(shown["record_id"], span["start"], span["end"])
708
+ if ident in seen:
709
+ continue # the same interval named twice in one window is one omission
710
+ seen.add(ident)
711
+ rows.append({"record_id": shown["record_id"], "line": shown["line"],
712
+ "size": shown["size"], "omitted_span": span,
713
+ "omission_id": ident, "error_lines": 0, "forced_by": "none",
714
+ "locator": {"offset": located.get(shown["record_id"])},
715
+ "origin": "overlap", "window_role": shown.get("window_role", "context")})
716
+ return rows
717
+
718
+
719
+ # The longest tail an omission's line can take in a read packet: S3 marks a forced omission with the
720
+ # reason it must be expanded, and the reasons are these two (`stage_read.searched`, the pending events).
721
+ OMISSION_FORCED_TAIL = max(len(f", must expand ({why})") for why in ("search_match", "pending_event"))
722
+
723
+
724
+ def omission_reserve(window):
725
+ """The bytes the read packet's omission list can take for this window, at most.
726
+
727
+ A read packet carries, beside the window's text, one line per omission of the window's OWN records
728
+ (`stage_read.omissions_text`). The packet's fixed overhead leaves a few hundred bytes of room, which a
729
+ long list overruns: on the first run over three days of sessions thirty windows cut to the bound were
730
+ refused at S3 by up to 717 bytes, each for its list. So the window's measure counts the list, by an
731
+ upper bound S2 can compute before S3 labels anything: each line under the widest labels, with the
732
+ numbers it will print and the longest reason it can be forced by. S3 measures the packet it really
733
+ builds, which is never larger than this for the list's part."""
734
+ rows = [m for m in window["omission_manifest"] if m.get("origin") != "overlap"]
735
+ if not rows:
736
+ return len("none")
737
+ widest = f"o{len(rows)}"
738
+ return sum(len(f"- {widest}: in {LABEL_BOUND}, {m['omitted_span']['end'] - m['omitted_span']['start']} of "
739
+ f"{m['size']} characters omitted") + OMISSION_FORCED_TAIL + 1 for m in rows)
740
+
741
+
742
+ def make_window(base, number, seq, i, j, limits, overlap=True):
743
+ owned = [{k: v for k, v in e.items() if k != "owned"} for e in seq[i:j]]
744
+ prev, prev_out, following, next_out = [], [], [], []
745
+ if overlap:
746
+ prev, prev_out = overlap_side(seq[before_turns(seq, i, OVERLAP_TURNS):i], from_end=True)
747
+ following, next_out = overlap_side(seq[j:after_turns(seq, j, OVERLAP_TURNS)])
748
+ window = {**base, "window_n": number, "records": owned,
749
+ "overlap": {"prev": prev, "next": following, "omitted": {"prev": prev_out, "next": next_out}},
750
+ "span_map": span_map_of(owned), "omission_manifest": manifest_of(owned), "host_allowance": limits["allowance"]}
751
+ window["omission_manifest"] = window["omission_manifest"] + overlap_manifest(window, seq)
752
+ window["driver_bytes"] = (limits["overhead"] + len(render_window(window).encode("utf-8"))
753
+ + omission_reserve(window))
754
+ window["bound_ok"] = not bound.check_bound(window["driver_bytes"], limits)
755
+ return window
756
+
757
+
758
+ def cut_windows(base, seq, limits, overlap=True):
759
+ """Windows over `seq` (entries in record order; `owned` marks the ones to cut, the others are overlap context).
760
+
761
+ Each owned entry lands in exactly one window; one too large to fit is split into spans first. A window ends
762
+ where the next entry would push its driver bytes past the bound, and never spans a context entry."""
763
+ budget = bound.driver_budget(limits) - limits["overhead"]
764
+ ceiling = budget - HEADER_SLACK - (2 * OVERLAP_TURNS * (OVERLAP_ITEM_BYTES + OVERLAP_SLACK) if overlap else 0)
765
+ if ceiling < MIN_ENTRY_BYTES:
766
+ raise Refused(f"WINDOW_UNBOUNDED: {budget} bytes remain for a window after the packet's {limits['overhead']} and the "
767
+ f"allowance, and the heading and overlap need {budget - ceiling}; no entry of {MIN_ENTRY_BYTES} bytes fits")
768
+ cutting = []
769
+ for entry in seq:
770
+ cutting.extend(split_entry(entry, ceiling) if entry["owned"] else [entry])
771
+ # each entry is estimated under the widest label a window renders; the window's own bytes decide (`make_window`)
772
+ own = [len(render_entry(e, LABEL_BOUND).encode("utf-8")) if e["owned"] else 0 for e in cutting]
773
+ ctx = [len(render_overlap(overlap_of(e), LABEL_BOUND).encode("utf-8")) for e in cutting]
774
+ windows, i, n = [], 0, len(cutting)
775
+ while i < n:
776
+ if not cutting[i]["owned"]:
777
+ i += 1
778
+ continue
779
+ before = sum(ctx[max(0, i - OVERLAP_TURNS):i]) if overlap else 0
780
+ j, total = i, HEADER_SLACK + before
781
+ while j < n and cutting[j]["owned"]:
782
+ after = sum(ctx[j + 1:j + 1 + OVERLAP_TURNS]) if overlap else 0
783
+ if j > i and total + own[j] + after > budget:
784
+ break
785
+ total += own[j]
786
+ j += 1
787
+ window = make_window(base, len(windows) + 1, cutting, i, j, limits, overlap)
788
+ while not window["bound_ok"] and j > i + 1: # the estimate was loose: shrink by the real bytes
789
+ j -= 1
790
+ window = make_window(base, len(windows) + 1, cutting, i, j, limits, overlap)
791
+ if not window["bound_ok"]:
792
+ raise Refused(f"WINDOW_UNBOUNDED: one entry ({eid(cutting[i])}) cannot be placed in a window within the bound: "
793
+ + "; ".join(bound.check_bound(window["driver_bytes"], limits)))
794
+ windows.append(window)
795
+ i = j
796
+ return windows, [{"id": eid(e), "owned": e["owned"], "line": e["line"], "kind": e["kind"]} for e in cutting]
797
+
798
+
799
+ # ---- checks over a cut view -------------------------------------------------------------------
800
+
801
+ def error_lines_of(text):
802
+ """The error lines of a tool result's middle, as the clipper reads them (ranges in the block), between the bounds it
803
+ cuts at (`clip_bounds`)."""
804
+ out, offset = [], 0
805
+ head, tail = clip_bounds(text)
806
+ for line in text.splitlines(keepends=True):
807
+ a, b = offset, offset + len(line)
808
+ offset = b
809
+ if b > head and a < tail and ERROR_LINE.search(line):
810
+ out.append([a, b])
811
+ return out
812
+
813
+
814
+ def check_windows(sequence, windows):
815
+ """Violations of the window invariants: every owned entry in exactly one window (SET_MISMATCH), and each window's
816
+ overlap the entries the sequence puts around it (OVERLAP_MISSING)."""
817
+ errors = []
818
+ seen = [eid(r) for w in windows for r in w["records"]]
819
+ errors += records.observe_set(records.expect_set(s["id"] for s in sequence if s["owned"]),
820
+ [{"id": i, "outcome": "retained"} for i in seen])
821
+ rows = list(sequence)
822
+ order = [s["id"] for s in rows]
823
+ place = {i: k for k, i in enumerate(order)}
824
+ for w in windows:
825
+ ids = [eid(r) for r in w["records"]]
826
+ if not ids or any(i not in place for i in ids):
827
+ errors.append(f"SET_MISMATCH window {w['window_n']}: it holds no record, or one the sequence does not have")
828
+ continue
829
+ first, last = min(place[i] for i in ids), max(place[i] for i in ids)
830
+ # the overlap is counted in TURNS, and every turn of the slice is either shown or named as omitted
831
+ for side, want in (("prev", order[before_turns(rows, first, OVERLAP_TURNS):first]),
832
+ ("next", order[last + 1:after_turns(rows, last + 1, OVERLAP_TURNS)])):
833
+ have = [e["entry"] for e in w["overlap"][side]]
834
+ named = [e["entry"] for e in w["overlap"].get("omitted", {}).get(side, [])]
835
+ # a list is not a set: an entry listed twice in one side's shown or omitted list was counted as
836
+ # one by every check here, so a window could show the same turn twice, or name one omitted twice,
837
+ # and the accounting still balanced
838
+ for which, listed in (("shown", have), ("omitted", named)):
839
+ twice = sorted({i for i in listed if listed.count(i) > 1})
840
+ if twice:
841
+ errors.append(f"OVERLAP_MISSING window {w['window_n']} ({side}): {twice} appears more than "
842
+ f"once in the {which} list, so one turn is accounted as several")
843
+ # membership next: every entry of the turn slice is either shown or named omitted
844
+ if set(have) | set(named) != set(want):
845
+ errors.append(f"OVERLAP_MISSING window {w['window_n']} ({side}): it holds {have} and names {named} "
846
+ f"omitted, the sequence puts {want} there")
847
+ # ... and then the two must not overlap: an entry counted on both sides is accounted by neither
848
+ if set(have) & set(named):
849
+ errors.append(f"OVERLAP_MISSING window {w['window_n']} ({side}): {sorted(set(have) & set(named))} "
850
+ f"is both shown and named omitted, so it is accounted twice and verified once")
851
+ return errors
852
+
853
+
854
+ def check_tiling(windows, texts=None):
855
+ """Violations of the span mapping: for each record, the shown stretches and the gaps tile the block exactly (a message
856
+ split into spans has the message as their union), and, given the projected text of each record (`texts`), every
857
+ error line of a clipped result is within the shown stretches."""
858
+ errors, by_record = [], collections.defaultdict(list)
859
+ for w in windows:
860
+ for r in w["records"]:
861
+ by_record[r["record_id"]].append(r)
862
+ for record_id, parts in sorted(by_record.items()):
863
+ pieces = [list(s["block"]) for p in parts for s in p["segments"]]
864
+ gaps = [g for p in parts if "clipped" in p for g in p["clipped"]["gaps"]]
865
+ if coverage.normalize(pieces + gaps) != [[0, parts[0]["size"]]] or sum(b - a for a, b in pieces + gaps) != parts[0]["size"]:
866
+ errors.append(f"SPAN_UNION_MISMATCH {record_id}: its shown stretches and gaps do not tile its {parts[0]['size']} characters exactly")
867
+ if texts and record_id in texts:
868
+ shown = coverage.normalize(pieces)
869
+ for a, b in error_lines_of(texts[record_id]):
870
+ if coverage.subtract([[a, b]], shown):
871
+ errors.append(f"ERROR_LINE_DROPPED {record_id}: the error line at {a}-{b} is not kept whole")
872
+ return errors
873
+
874
+
875
+ # ---- the forcing, the decisions, the completeness ---------------------------------------------
876
+
877
+ def forced_records(clipped, human_lines, pending_first_records=(), search_hits=()):
878
+ """`{record_id: forced_by}` of the clipped records that may not be skipped (design §5.4): every one between a
879
+ pending event and the next human turn, and every one the full-source search matched. `clipped` is
880
+ `[{record_id, line}]`; `human_lines` the 0-based record indexes of the human turns; a pending event is its first
881
+ record's index; `search_hits` the record ids the search matched."""
882
+ humans, forced, matched = sorted(human_lines), {}, set(search_hits)
883
+ for item in clipped:
884
+ index = item["line"] - 1
885
+ for first in pending_first_records:
886
+ k = bisect.bisect_right(humans, first)
887
+ if index >= first and (k == len(humans) or index < humans[k]):
888
+ forced[item["record_id"]] = "pending_event"
889
+ if item["record_id"] not in forced and item["record_id"] in matched:
890
+ forced[item["record_id"]] = "search_match"
891
+ return forced
892
+
893
+
894
+ def forced_omissions(rows, forced):
895
+ """`forced` carried over to the OMISSION ids of `rows`: a forced record forces every interval it lost.
896
+
897
+ Forcing is a fact about a record - the search matched it, a pending event covers it - while a decision
898
+ is about one interval. Without this carry, a skip of a forced record's interval matched nothing in
899
+ `forced` and the refusal that exists to stop exactly that never fired."""
900
+ return {row["omission_id"]: forced[row["record_id"]] for row in rows if row["record_id"] in forced}
901
+
902
+
903
+ def check_decisions(manifest_ids, forced, decisions):
904
+ """Violations of S3's expand/skip answers over a window's omission manifest: one decision for each omitted
905
+ INTERVAL (SET_MISMATCH otherwise), a reason for each, and a forced record never skipped (EXPANSION_SKIPPED).
906
+
907
+ `manifest_ids` may be the manifest's rows or their ids; `forced` may be keyed by record or by omission, and
908
+ rows let the two be reconciled."""
909
+ errors = []
910
+ rows = [m for m in manifest_ids if isinstance(m, dict)]
911
+ manifest_ids = [m["omission_id"] if isinstance(m, dict) else m for m in manifest_ids]
912
+ forced = {**forced, **forced_omissions(rows, forced)}
913
+ ids = [decision_key(d) for d in decisions]
914
+ missing, extra = sorted(set(manifest_ids) - set(ids)), sorted(set(ids) - set(manifest_ids))
915
+ repeated = sorted({i for i in ids if ids.count(i) > 1})
916
+ if missing or extra or repeated:
917
+ errors.append(f"SET_MISMATCH omission manifest: missing={missing} extra={extra} repeated={repeated}")
918
+ for d in decisions:
919
+ if d.get("decision") not in DECISIONS or not str(d.get("reason") or "").strip():
920
+ errors.append(f"EXPANSION_DECISION_INVALID {d.get('record_id')}: a decision is expand or skip, with a reason")
921
+ # one refusal, one branch. `forced` carries both keys - the record's and, through the carry above,
922
+ # each of its omissions - so a decision that names either is caught here; two branches for one
923
+ # refusal is how one of them stops being exercised.
924
+ elif d["decision"] == "skip" and decision_key(d) in forced:
925
+ errors.append(f"EXPANSION_SKIPPED {decision_key(d)}: forced by {forced[decision_key(d)]}, so it "
926
+ "must be expanded")
927
+ return errors
928
+
929
+
930
+ def unresolved_versions(backlog, version):
931
+ """The work this stage did NOT resolve: the backlog of versions other than the one it viewed.
932
+
933
+ S2 views one version of a transcript, and a session whose earlier versions still hold unread ranges has
934
+ content nobody has looked at. This was a count (`backlog_other_versions`) that no consumer read, which
935
+ is an inert field: it recorded the shortfall and bound nothing. It is a state now, and
936
+ `completeness` enforces it - a session with unresolved versions is not source complete, so no claim of
937
+ absence can rest on it until the work is done or the ranges are deliberately closed."""
938
+ return [{"version": b["version"], "window": b["window"], "unread": b["unread"]}
939
+ for b in sorted(backlog, key=lambda b: b["version"]) if b["version"] != version]
940
+
941
+
942
+ def decision_key(decision):
943
+ """The omission a decision is about: its `omission_id`, or - for a caller that still speaks in records -
944
+ its record id. Accounting is by INTERVAL, and a record id answers for every interval of its record."""
945
+ return decision.get("omission_id") or decision.get("record_id")
946
+
947
+
948
+ def completeness(windows_ok, omission_ids, decisions, expanded_ok, unresolved=(), gathered=()):
949
+ """`{view_complete, source_complete, skipped, unresolved}` of one session: view complete when every window passed
950
+ the gate and every OMITTED INTERVAL has an executed expansion (`expanded_ok`: the ids whose expansion windows
951
+ passed) or a recorded skip; source complete when, in addition, nothing was skipped that a gather did not read
952
+ (`gathered`: the skipped ids whose gather windows passed, WP-08e) and no other version is unresolved. The skipped
953
+ omissions no gather read are listed, and so are the unresolved versions.
954
+
955
+ The identity is the interval, not the record. Keyed by record, one expansion of a record that had lost
956
+ three intervals discharged all three, and a session with content nobody had looked at reported itself
957
+ source complete - the strongest basis a claim of absence can rest on."""
958
+ chosen = {decision_key(d): d["decision"] for d in decisions}
959
+ clipped_ids = omission_ids
960
+ skipped = sorted(i for i in clipped_ids if chosen.get(i) == "skip" and i not in set(gathered))
961
+ held = [u["version"] for u in unresolved]
962
+ view = bool(windows_ok) and all(windows_ok) and all(
963
+ chosen.get(i) == "skip" or (chosen.get(i) == "expand" and i in expanded_ok) for i in clipped_ids)
964
+ return {"view_complete": view, "source_complete": view and not skipped and not held,
965
+ "skipped": skipped, "unresolved_versions": held}
966
+
967
+
968
+ INCOMPLETE_STATUSES = ("unreadable", "known_absent", "unknown_provenance", "read_partial", "failed", "deferred")
969
+
970
+
971
+ def coverage_basis(scope):
972
+ """`incomplete`, `view` or `source` for a claim's scope (design §5.4), checked in that order. `scope` is
973
+ `{sources: [{accounted, directory_present}], sessions: [{status, unprocessed, view_complete, source_complete}]}`."""
974
+ if any(not s["accounted"] or not s["directory_present"] for s in scope["sources"]):
975
+ return "incomplete"
976
+ for session in scope["sessions"]:
977
+ if session["status"] in INCOMPLETE_STATUSES or session.get("unprocessed"):
978
+ return "incomplete"
979
+ # A session that is not even view complete is a hole, and the predicate used to FALL THROUGH it to
980
+ # `source` - the strongest basis - because only the `view and not source` case was named. The mutation
981
+ # M#10 asks for (losing the recorded skip) lands exactly here: it made the session incomplete and the
982
+ # basis answered "source", so absence would have been claimable on work nobody finished.
983
+ if any(not s["view_complete"] for s in scope["sessions"]):
984
+ return "incomplete"
985
+ if any(s["view_complete"] and not s["source_complete"] for s in scope["sessions"]):
986
+ return "view"
987
+ return "source"
988
+
989
+
990
+ def absence_claim_allowed(basis):
991
+ """A claim of absence needs basis `source`; anything less leaves it `pending` (design §5.4)."""
992
+ return basis == "source"
993
+
994
+
995
+ # ---- the immutable copy and the projection ---------------------------------------------------
996
+
997
+ class RangeSet:
998
+ def __init__(self, ranges):
999
+ self.ranges = coverage.normalize(ranges)
1000
+ self.starts = [r[0] for r in self.ranges]
1001
+
1002
+ def __contains__(self, index):
1003
+ k = bisect.bisect_right(self.starts, index) - 1
1004
+ return k >= 0 and index < self.ranges[k][1]
1005
+
1006
+
1007
+ def safe_name(identity):
1008
+ return re.sub(r"[^A-Za-z0-9._-]", "_", identity)
1009
+
1010
+
1011
+ def copy_version(run_dir, path, zstd, version=None):
1012
+ """The immutable, hash-named copy of one transcript version: `(run-relative path, sha256)`.
1013
+
1014
+ The version is the census's (D-20261103-8facee): `{sha, record_count}`, the transcript's first `record_count`
1015
+ complete lines as S1 read them. Exactly those lines are copied, decompressed, and they must hash to `sha`; what
1016
+ the host appended after the census - more lines, or a line it is still writing - is the next run's, and is not
1017
+ copied. Fewer complete lines than the census read, or other bytes in them, means the transcript was rewritten or
1018
+ truncated: SOURCE_CHANGED. Without a version every complete line is copied."""
1019
+ directory = stagelock.confine(run_dir, pathlib.Path(run_dir) / "sources")
1020
+ directory.mkdir(parents=True, exist_ok=True)
1021
+ fd, tmp = tempfile.mkstemp(dir=directory, prefix=".copy.")
1022
+ digest, lines = hashlib.sha256(), 0
1023
+ count = version["record_count"] if version else None
1024
+ try:
1025
+ with os.fdopen(fd, "wb") as out, contextlib.closing(sources.read_lines(path, zstd, limit=count)) as read:
1026
+ for raw in read:
1027
+ if not raw.endswith(b"\n"):
1028
+ break # a record the host is still writing is no record yet
1029
+ out.write(raw)
1030
+ digest.update(raw)
1031
+ lines += 1
1032
+ sha = digest.hexdigest()
1033
+ if version and (lines < count or sha != version["sha"]):
1034
+ raise Refused(f"SOURCE_CHANGED {path}: its first {lines} complete lines hash {sha[:12]}, the census read {count} "
1035
+ f"hashing {version['sha'][:12]}; the transcript was rewritten or truncated after the census, so S1 "
1036
+ "must be run again")
1037
+ target = directory / f"{sha}.jsonl"
1038
+ if target.exists():
1039
+ if records.sha256_file(target) != sha:
1040
+ raise Refused(f"SOURCE_TAMPERED {target}: an existing copy does not hash to its name")
1041
+ os.unlink(tmp)
1042
+ else:
1043
+ os.chmod(tmp, 0o444)
1044
+ os.replace(tmp, target)
1045
+ except sources.Unreadable as exc:
1046
+ pathlib.Path(tmp).unlink(missing_ok=True)
1047
+ raise Refused(f"SOURCE_UNREADABLE {path}: {exc}") from exc
1048
+ except BaseException:
1049
+ pathlib.Path(tmp).unlink(missing_ok=True)
1050
+ raise
1051
+ return f"sources/{sha}.jsonl", sha
1052
+
1053
+
1054
+ def project_version(run_dir, copy_rel, host, child, version, dest_rel):
1055
+ """Write the projection of every content block of the complete lines of a copy; returns the counts."""
1056
+ dest = stagelock.confine(run_dir, pathlib.Path(run_dir) / dest_rel)
1057
+ dest.parent.mkdir(parents=True, exist_ok=True)
1058
+ fd, tmp = tempfile.mkstemp(dir=dest.parent, prefix=".projection.")
1059
+ count = items = 0
1060
+ # M#8: how many blocks the backstop replaced, by detector, for THIS projection. A blanked block is a
1061
+ # block the mapping could not cover, so the count is the one number that says how often that happened -
1062
+ # and a figure nobody records is a figure nobody can act on. Taken as a difference, because the counter
1063
+ # is process-wide and a run is not the process.
1064
+ blanked_before = collections.Counter(projection.BLANKED)
1065
+ blocks_before = collections.Counter(projection.BLOCKS)
1066
+ try:
1067
+ with open(pathlib.Path(run_dir) / copy_rel, "rb") as src, os.fdopen(fd, "wb") as out:
1068
+ for raw in src:
1069
+ if not raw.endswith(b"\n"):
1070
+ break # a record the host was still writing is not a record yet
1071
+ count += 1
1072
+ try:
1073
+ rec = json.loads(raw)
1074
+ except ValueError:
1075
+ continue
1076
+ # Every transcript-derived string that reaches a window goes through the projection, and the
1077
+ # tool name is one: `header_of` renders it into the model's window, so a tool whose name
1078
+ # carried a secret pattern stood unmasked there however well its arguments were masked.
1079
+ # `kind` and the window role are this code's own words, and the timestamp is a number.
1080
+ blocks = [{"pointer": p, "kind": k, "tool": projection.project(t, version) if t else t,
1081
+ "error": e, "text": projection.project(v, version)}
1082
+ for p, k, t, e, v in record_items(host, rec, child) if v is not None]
1083
+ blocks = [b for b in blocks if b["text"].strip() or b["kind"] == "tool_call"] # a call with no arguments still names its tool
1084
+ if blocks:
1085
+ items += len(blocks)
1086
+ out.write(json.dumps({"line": count, "ts": normal_stamp(rec.get("timestamp")),
1087
+ "items": blocks}, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n")
1088
+ os.replace(tmp, dest)
1089
+ except BaseException:
1090
+ pathlib.Path(tmp).unlink(missing_ok=True)
1091
+ raise
1092
+ # Two figures, because they answer two questions: how many CONTENT BLOCKS the backstop replaced, which
1093
+ # is what a reader of the run wants, and how many blanking operations ran - a structured block's leaves
1094
+ # each pass the exit, so one block with four masked leaves is four operations and one block.
1095
+ blanked = {reason: projection.BLOCKS[reason] - blocks_before[reason]
1096
+ for reason in projection.BLOCKS if projection.BLOCKS[reason] > blocks_before[reason]}
1097
+ operations = {reason: projection.BLANKED[reason] - blanked_before[reason]
1098
+ for reason in projection.BLANKED if projection.BLANKED[reason] > blanked_before[reason]}
1099
+ return {"records": count, "items": items, "blanked": blanked, "blank_operations": operations}
1100
+
1101
+
1102
+ def read_projection(path):
1103
+ """`(offset, record)` for each line of a projection file, in order."""
1104
+ with open(path, "rb") as handle:
1105
+ while True:
1106
+ offset = handle.tell()
1107
+ raw = handle.readline()
1108
+ if not raw:
1109
+ return
1110
+ yield offset, json.loads(raw)
1111
+
1112
+
1113
+ def build_sequence(proj_path, viewed, role_of, index):
1114
+ """The sequence of one version: `(entries, human_lines, counts, tools, texts)`. The entries are the viewed blocks
1115
+ (owned), each with its view form, and up to OVERLAP_TURNS blocks of context each side of every run of them. `index`
1116
+ takes the full projected text of each viewed block, and `texts` keeps it for the checks that need the block and not
1117
+ the view. `counts` and `tools` are the kept shape counts, over every block of the version rather than
1118
+ the viewed ones: they are hints for ranking what to read, never evidence (design §5.5: evidence is a locator)."""
1119
+ # Context is retained by TURNS, not by blocks. A deque of five BLOCKS was five of whatever came last, so
1120
+ # six tool results standing between the window and the previous human turn pushed every turn out of it and
1121
+ # the window opened on tool traffic alone - the very case §5.4's five turns is for. `recent` is trimmed by
1122
+ # `before_turns`, which is the same counting the overlap itself uses, and `after_keys` closes the trailing
1123
+ # side once five distinct turns have gone by.
1124
+ seq, recent, humans, counts = [], [], [], collections.Counter()
1125
+ after_open, after_keys = False, []
1126
+ texts, tools = {}, collections.Counter()
1127
+ for offset, rec in read_projection(proj_path):
1128
+ line = rec["line"]
1129
+ for block in rec["items"]:
1130
+ item = {**block, "ts": rec.get("ts")}
1131
+ counts["items"] += 1
1132
+ counts[item["kind"]] += 1
1133
+ if item["kind"] == "tool_call" and item.get("tool"):
1134
+ tools[item["tool"]] += 1
1135
+ if item["kind"] == "tool_result" and item.get("error"):
1136
+ counts["error_results"] += 1
1137
+ if item["kind"] == "human":
1138
+ humans.append(line - 1)
1139
+ # Indexed whatever window owns it, or none. The search is over the full redacted text of the
1140
+ # version (§5.4's "full-source search"), and it decides which clipped records must be expanded:
1141
+ # an index built only from the work ranges cannot match anything outside them, so a search
1142
+ # that found nothing there was reporting its own blind spot as an answer.
1143
+ index.add([line, item["pointer"]], item["text"])
1144
+ texts[f"{line}{item['pointer']}"] = item["text"]
1145
+ if (line - 1) in viewed:
1146
+ counts["viewed"] += 1
1147
+ seq.extend(recent)
1148
+ recent = []
1149
+ seq.append(make_entry(item, line, role_of(line - 1), offset))
1150
+ after_open, after_keys = True, []
1151
+ continue
1152
+ entry = context_entry(item, line, "context", offset)
1153
+ if after_open:
1154
+ if is_turn(entry):
1155
+ key = turn_key(entry)
1156
+ if key not in after_keys:
1157
+ if len(after_keys) == OVERLAP_TURNS:
1158
+ after_open = False
1159
+ else:
1160
+ after_keys.append(key)
1161
+ if after_open:
1162
+ seq.append(entry)
1163
+ continue
1164
+ recent.append(entry)
1165
+ recent = recent[before_turns(recent, len(recent), OVERLAP_TURNS):]
1166
+ return seq, humans, counts, tools, texts
1167
+
1168
+
1169
+ def hints_of(counts, tools):
1170
+ """The shape of a transcript, counted as the v1 digest counted it: what to read first, never what was said. A
1171
+ hint is not
1172
+ evidence and no claim rests on one."""
1173
+ return {"human_turns": counts["human"], "assistant_turns": counts["assistant"], "delegated_turns": counts["delegated"],
1174
+ "tool_calls": counts["tool_call"], "tool_results": counts["tool_result"],
1175
+ "error_results": counts["error_results"], "tools": dict(tools.most_common(15))}
1176
+
1177
+
1178
+ def projection_texts(run_dir, redacted_rel):
1179
+ """`{record_id: the block's full projected text}` of one version - the text the full-source search decides on,
1180
+ clipped spans included, read back from the projection rather than from any window."""
1181
+ texts = {}
1182
+ for _offset, rec in read_projection(pathlib.Path(run_dir) / redacted_rel):
1183
+ for block in rec["items"]:
1184
+ texts[f"{rec['line']}{block['pointer']}"] = block["text"]
1185
+ return texts
1186
+
1187
+
1188
+ def forced_by_search(run_dir, name, terms):
1189
+ """`{record_id: "search_match"}` for the clipped records of one view that the full-source search matches
1190
+ (design §5.4). The index narrows and the projection decides; a term that matches nothing forces nothing,
1191
+ and closes nothing either - the caller keeps it as such."""
1192
+ run_dir = pathlib.Path(run_dir)
1193
+ doc = sequence_doc(run_dir, name)
1194
+ texts = projection_texts(run_dir, doc["redacted"])
1195
+ clipped = {m["record_id"] for path in sorted((run_dir / "views" / name).glob("[0-9]*.json"))
1196
+ for m in window_doc(run_dir, name, path)["omission_manifest"]}
1197
+ index = search.load(run_dir / "index" / "bm25" / f"{name}.json")
1198
+ hits = search.search(index, terms, lambda ref: texts.get(f"{ref[0]}{ref[1]}", ""))
1199
+ return {rid: "search_match" for rid in (f"{h['ref'][0]}{h['ref'][1]}" for h in hits) if rid in clipped}
1200
+
1201
+
1202
+ def role_fn(owned, backlog, version):
1203
+ """The window role of a record index (design §5.2): `in_window`, `backlog(<window>)` or `context`."""
1204
+ mine, held = RangeSet(owned), [(RangeSet(b["unread"]), b["window"]) for b in backlog if b["version"] == version]
1205
+
1206
+ def role(index):
1207
+ if index in mine:
1208
+ return "in_window"
1209
+ for ranges, window in held:
1210
+ if index in ranges:
1211
+ return f"backlog({window})"
1212
+ return "context"
1213
+ return role
1214
+
1215
+
1216
+ # ---- the stage -------------------------------------------------------------------------------
1217
+
1218
+ def index_destination(run_dir, rel):
1219
+ """The confined path to write an index to, with its parent made.
1220
+
1221
+ The order is the whole of it: `mkdir(parents=True)` on an unconfined path follows a symlinked `index/`
1222
+ and creates `bm25/` inside whatever it points at, so a refusal that arrives afterwards arrives with a
1223
+ directory already made outside the run. Confinement first means nothing is created on the way to it."""
1224
+ destination = stagelock.confine(run_dir, pathlib.Path(run_dir) / rel)
1225
+ destination.parent.mkdir(parents=True, exist_ok=True)
1226
+ return destination
1227
+
1228
+
1229
+ def limits_refusal(golden_run):
1230
+ """The refusal `limits_of` gives for a declaration with no allowance, as a list of lines - so a control
1231
+ can read both stages' words for one stop side by side."""
1232
+ try:
1233
+ limits_of({"seats": {"S3": golden_run["seat"]}, "host_allowance": {}, "output_caps": {"S3": 32_000}})
1234
+ except Refused as exc:
1235
+ return str(exc).splitlines()
1236
+ return []
1237
+
1238
+
1239
+ def census_version(file):
1240
+ """`{sha, record_count}` of the version S1 read of one transcript file (`census.segments_of`): the census's sha and
1241
+ the record count of the version its work names, both from the census. Not from the run's coverage state: a targeted
1242
+ run's state is the periodic base, which never holds what the census observed (review c0fix r1 #3). A file the census
1243
+ did not read has no version to copy, and is refused by name."""
1244
+ number, versions = file["work"]["version"], file.get("versions") or []
1245
+ if not file.get("sha256") or number is None or not 0 <= number < len(versions):
1246
+ raise Refused(f"VERSION_MISMATCH {file['key']}: the census holds no version of it to copy")
1247
+ return {"sha": file["sha256"], "record_count": versions[number]["record_count"]}
1248
+
1249
+
1250
+ def view_transcript(run_dir, entry, file, state, ctx, unit=None):
1251
+ """Everything S2 leaves for one transcript file of a unit - `entry` its census row, `file` one of the row's files
1252
+ (`census.segments_of`), `unit` its root's identity; returns its line of `views.json`. A member's work is the census's,
1253
+ like a root's: S1 read every member of an eligible unit (D-20261103-85f3e8). Each file of a Codex thread written
1254
+ across several is a transcript of its own here, named by its coverage key (D-20261103-a7128a)."""
1255
+ run_dir = pathlib.Path(run_dir)
1256
+ ident = file["key"]
1257
+ child = entry["status"] == "child_of"
1258
+ rv, limits, zstd = ctx["redaction_version"], ctx["limits"], ctx["zstd"]
1259
+ copy_rel, sha = copy_version(run_dir, file["path"], zstd, census_version(file))
1260
+ name = safe_name(ident)
1261
+ proj_rel = f"redacted/{sha}.{rv}.jsonl"
1262
+ stats = project_version(run_dir, copy_rel, entry["host"], child, rv, proj_rel)
1263
+ work = file["work"]
1264
+ version, owned, backlog = work["version"], file["owned"], work["backlog"]
1265
+ viewed_ranges = coverage.union(work["in_window"], [r for b in backlog if b["version"] == version for r in b["unread"]])
1266
+ viewed, role_of = RangeSet(viewed_ranges), role_fn(owned, backlog, version)
1267
+ index = search.Index(sha, rv)
1268
+ seq, humans, counts, tools, texts = build_sequence(run_dir / proj_rel, viewed, role_of, index)
1269
+ pending = sorted(e["first_record"] for e in state["pending_events"] if e["transcript"] == ident and e["version"] == version)
1270
+ clipped = [e for e in seq if "clipped" in e]
1271
+ forced = forced_records([{"record_id": e["record_id"], "line": e["line"]} for e in clipped], humans, pending)
1272
+ for e in clipped:
1273
+ e["clipped"]["forced_by"] = forced.get(e["record_id"], "none")
1274
+ base = {"transcript": ident, "version": version, "version_sha": sha, "redaction_version": rv}
1275
+ windows, sequence = cut_windows(base, seq, limits)
1276
+ errors = check_windows(sequence, windows) + check_tiling(windows, texts)
1277
+ if errors:
1278
+ raise Refused("\n".join(errors[:5]))
1279
+ files = []
1280
+ for w in windows:
1281
+ rel = f"views/{name}/{w['window_n']}.json"
1282
+ records.write_json(run_dir, run_dir / rel, w)
1283
+ files.append({"path": rel, "sha256": records.sha256_file(run_dir / rel), "driver_bytes": w["driver_bytes"],
1284
+ "records": len(w["records"]),
1285
+ # the two kinds of omission are counted apart: a clipped OWNED record is work S3 must
1286
+ # decide about this window's own records, an overlap omission is context the budget
1287
+ # could not hold. One number over both says neither thing.
1288
+ "clipped": sum(1 for m in w["omission_manifest"] if m["origin"] == "owned"),
1289
+ "overlap_omissions": sum(1 for m in w["omission_manifest"] if m["origin"] == "overlap")})
1290
+ sequence_rel = f"views/{name}/sequence.json"
1291
+ records.write_json(run_dir, run_dir / sequence_rel, {
1292
+ **base, "source_copy": copy_rel, "redacted": proj_rel, "limits": limits, "sequence": sequence, "human_lines": humans,
1293
+ "pending_first_records": pending, "windows": len(windows)})
1294
+ index_rel = f"index/bm25/{name}.json"
1295
+ search.dump(index, index_destination(run_dir, index_rel))
1296
+ carried_only = {"carried_only": True} if not (work["in_window"] or work["backlog"]) else {}
1297
+ return {**carried_only, "transcript": ident, "session": census.key_of(entry), "segment": file["stem"], "name": name,
1298
+ "host": entry["host"],
1299
+ "kind": "child" if child else "session", "parent": entry.get("parent"), "unit": unit or census.key_of(entry),
1300
+ "version": version, "version_sha": sha, "source_copy": copy_rel, "redacted": proj_rel, "sequence": sequence_rel,
1301
+ "index": index_rel, "records": stats["records"], "items": counts["items"], "viewed_items": counts["viewed"],
1302
+ "windows": files, "clipped": len(clipped), "forced": sum(1 for v in forced.values() if v != "none"),
1303
+ "hints": hints_of(counts, tools), "unresolved_versions": unresolved_versions(backlog, version),
1304
+ "blanked": stats["blanked"], "blank_operations": stats["blank_operations"],
1305
+ "source_bytes": (run_dir / copy_rel).stat().st_size}
1306
+
1307
+
1308
+ def run(run_dir, overhead=bound.PACKET_OVERHEAD, seats_path=None):
1309
+ """`distill.py views`: S2 over the census and the coverage state S1 left in the run directory."""
1310
+ run_dir = pathlib.Path(run_dir)
1311
+ try:
1312
+ transcripts = census.rows(census.load(run_dir))
1313
+ except ValueError as exc:
1314
+ raise Refused(f"INPUT_INVALID S1: {run_dir}/census.json: {exc}") from exc
1315
+ state = coverage.load(run_dir / "coverage.json")[0]
1316
+ # The unit is a root with every member at any depth (D-20261103-85f3e8). Of an eligible unit S2 reads each transcript
1317
+ # that owes the window something - the root or a member, its records in the window or its backlog. A file that owes
1318
+ # nothing and holds an event an earlier run left pending is viewed too, with no window (`carried_only`): the unit's
1319
+ # stitch shows that event from this run's copy and projection, which only a view makes (W r1). No other file is: a
1320
+ # member with nothing to read would cut no window. An eligible root whose unit owes nothing contradicts S1.
1321
+ by_id = {census.key_of(e): e for e in transcripts}
1322
+ units = census.units(transcripts)
1323
+ owes = lambda f: bool(f["path"] and (f["work"]["in_window"] or f["work"]["backlog"])) # noqa: E731
1324
+ pending_on = {p["transcript"] for p in state["pending_events"]}
1325
+ todo, idle = [], []
1326
+ for root in (e for e in transcripts if e["status"] == "eligible"):
1327
+ unit = census.key_of(root)
1328
+ files = [(e, f) for e in [root] + [by_id[m] for m in units.get(unit, [])] if e is root or e["status"] == "child_of"
1329
+ for f in census.segments_of(e)]
1330
+ if not any(owes(f) for _e, f in files):
1331
+ idle.append(unit)
1332
+ todo += [(e, f, unit) for e, f in files if owes(f) or (f["path"] and f["key"] in pending_on)]
1333
+ if idle:
1334
+ raise Refused(f"SET_MISMATCH S2: eligible sessions whose unit owes the window nothing: {sorted(idle)}")
1335
+ names = collections.Counter(safe_name(f["key"]) for _e, f, _unit in todo)
1336
+ clash = sorted(n for n, c in names.items() if c > 1)
1337
+ if clash:
1338
+ raise Refused(f"VIEW_NAME_COLLISION: {clash} name more than one transcript")
1339
+ done = {}
1340
+ with records.run_stage(run_dir, "S2", [{"artifact": "census.json", "producer_stage": "S1"},
1341
+ {"artifact": "coverage.json", "producer_stage": "S1"}],
1342
+ part="views") as stage:
1343
+ # the limits are the declaration this stage was admitted against: a read made before admission could be
1344
+ # overtaken by an amendment of the cap, and the windows would be cut at a cap the record does not name (X r1)
1345
+ declaration = stage.declaration
1346
+ limits = limits_of(declaration, overhead, seats_path)
1347
+ _, _, window_id = coverage.window_bounds(declaration["window"])
1348
+ ctx = {"limits": limits, "redaction_version": projection.CURRENT, "zstd": sources.declared(declaration).get("zstd"),
1349
+ "window_bounds": coverage.window_bounds(declaration["window"])[:2]}
1350
+
1351
+ def work(item):
1352
+ done[item["id"]] = view_transcript(run_dir, item["entry"], item["file"], state, ctx, item["unit"])
1353
+
1354
+ # a unit fails together: under the production posture a failing file quarantines its root and every other
1355
+ # file of the unit with it, because they share the unit (records.run_items)
1356
+ items = [{"id": f["key"], "unit": unit, "entry": e, "file": f} for e, f, unit in todo]
1357
+ outcome = stage.run_items(items, work)
1358
+ # the views published are the ones the stage still holds done: a file whose view was made before another file of
1359
+ # its unit failed went to the quarantine with the unit, and its view goes with it (review c0fix r1 #4)
1360
+ owed, published = {f["key"] for _e, f, _unit in todo}, set(outcome["done"])
1361
+ missing = sorted(owed - published - {q["id"] for q in outcome["quarantined"]})
1362
+ if missing:
1363
+ raise Refused(f"SET_MISMATCH S2: transcripts that owe the window something without a view: {missing}")
1364
+ manifest = {"window": window_id, "redaction_version": projection.CURRENT, "limits": limits,
1365
+ "quarantined": outcome["quarantined"], "transcripts": [done[i] for i in sorted(published)]}
1366
+ manifest["totals"] = totals_of(manifest["transcripts"])
1367
+ records.write_json(run_dir, run_dir / "views.json", manifest)
1368
+ stage.output("views.json")
1369
+ return manifest
1370
+
1371
+
1372
+ def totals_of(transcripts):
1373
+ """The manifest's totals. A line of the manifest is one file's view, and a Codex thread written in several files has a
1374
+ line for each (D-20261103-a7128a), so `files` counts the lines and `sessions` and `children` the distinct sessions
1375
+ they belong to (review c0fix r2)."""
1376
+ drivers = [w["driver_bytes"] for t in transcripts for w in t["windows"]]
1377
+ return {"files": len(transcripts), "sessions": len({t["session"] for t in transcripts if t["kind"] == "session"}),
1378
+ "children": len({t["session"] for t in transcripts if t["kind"] == "child"}), "windows": len(drivers),
1379
+ "driver_bytes": sum(drivers), "max_driver_bytes": max(drivers, default=0),
1380
+ "records": sum(t["records"] for t in transcripts), "items": sum(t["items"] for t in transcripts),
1381
+ "viewed_items": sum(t["viewed_items"] for t in transcripts), "clipped": sum(t["clipped"] for t in transcripts),
1382
+ "forced": sum(t["forced"] for t in transcripts), "source_bytes": sum(t["source_bytes"] for t in transcripts),
1383
+ # the work S2 did not resolve, where a reader of the artifact meets it. `completeness` is what
1384
+ # ENFORCES it - a session with any of these is not source complete - and the stage that holds the
1385
+ # S3 decisions is its caller, so this number is the state's visible form, never its authority.
1386
+ "unresolved_versions": sum(len(t["unresolved_versions"]) for t in transcripts),
1387
+ "overlap_omissions": sum(w["overlap_omissions"] for t in transcripts for w in t["windows"]),
1388
+ "hints": {key: sum(t["hints"][key] for t in transcripts)
1389
+ for key in ("human_turns", "assistant_turns", "delegated_turns", "tool_calls", "tool_results",
1390
+ "error_results")}}
1391
+
1392
+
1393
+ def report_lines(manifest):
1394
+ """Counts, window numbers and byte totals - never a transcript's content."""
1395
+ t, limits = manifest["totals"], manifest["limits"]
1396
+ per = sorted(len(x["windows"]) for x in manifest["transcripts"])
1397
+ mean = t["driver_bytes"] / t["windows"] if t["windows"] else 0
1398
+ return [f"views window {manifest['window']}: {t['sessions']} sessions and {t['children']} children in {t['files']} files, "
1399
+ f"{t['windows']} windows (per file: min {per[0] if per else 0}, median {per[len(per) // 2] if per else 0}, max {per[-1] if per else 0})",
1400
+ f" driver bytes: total {t['driver_bytes']}, mean {mean:.0f}, max {t['max_driver_bytes']} of {bound.driver_budget(limits)} "
1401
+ f"(allowance {limits['allowance']}, overhead {limits['overhead']})",
1402
+ f" estimated tokens at 3.5 bytes each (a packing diagnostic, not a bound): {t['driver_bytes'] / 3.5:.0f}",
1403
+ f" source bytes {t['source_bytes']}, {t['records']} records, {t['items']} blocks, {t['viewed_items']} viewed, "
1404
+ f"{t['clipped']} clipped, {t['forced']} forced by a pending event",
1405
+ f" hints (shape only, never evidence): {t['hints']['human_turns']} human turns, "
1406
+ f"{t['hints']['assistant_turns']} assistant turns, {t['hints']['tool_calls']} tool calls, "
1407
+ f"{t['hints']['error_results']} failed tool results",
1408
+ f" quarantined {len(manifest['quarantined'])}"]
1409
+
1410
+
1411
+ # ---- expansion -------------------------------------------------------------------------------
1412
+
1413
+ def current_version(document, where):
1414
+ """`document`, refused by name when it was built under another projection.
1415
+
1416
+ The check belongs at every boundary where a stored artifact is CONSUMED, not only where a quote is
1417
+ verified: a window built under a projection that masked less is a window of text the current one would
1418
+ have masked, and reading it hands a model exactly what the newer masking exists to withhold."""
1419
+ stored = document.get("redaction_version")
1420
+ if stored != projection.CURRENT:
1421
+ raise Refused(f"REDACTION_VERSION_MISMATCH {where}: made under {stored!r}, the projection is "
1422
+ f"{projection.CURRENT!r}; build the view again from the source")
1423
+ return document
1424
+
1425
+
1426
+ def window_doc(run_dir, name, path):
1427
+ """One window of a view, refused if it was built under another projection."""
1428
+ return current_version(records.read_json(path), f"{name}/{pathlib.Path(path).name}")
1429
+
1430
+
1431
+ def sequence_doc(run_dir, name):
1432
+ path = pathlib.Path(run_dir) / "views" / name / "sequence.json"
1433
+ return current_version(records.read_json(path), f"{name}/sequence.json")
1434
+
1435
+
1436
+ class _Unindexed:
1437
+ """`build_sequence` indexes what it reads; an expansion rebuilding the sequence searches nothing."""
1438
+
1439
+ def add(self, *_args):
1440
+ pass
1441
+
1442
+
1443
+ def expansion_entries(run_dir, name, doc, record_id, middle):
1444
+ """What an expansion of `record_id` is cut from (WP-08c): `middle` owned, between the record's neighbours as S2's
1445
+ sequence holds them - up to OVERLAP_TURNS turns each side - as context it does not own. The sequence is rebuilt
1446
+ from the projection with the lines and roles the view's windows own, as S2 built it. The record itself is not among
1447
+ them: its head and tail are its window's, and an entry of it beside its own middle would carry the same label key.
1448
+ So an expansion shows what came before and after the record but not the record's own head or tail, and an exposure
1449
+ shown only in that head is not shown to it (`stage_read.settle_occasions` then finds the two readings differ)."""
1450
+ roles = {}
1451
+ for path in sorted((pathlib.Path(run_dir) / "views" / name).glob("[0-9]*.json")):
1452
+ for r in window_doc(run_dir, name, path)["records"]:
1453
+ roles[r["line"] - 1] = r["window_role"]
1454
+ seq = build_sequence(pathlib.Path(run_dir) / doc["redacted"], roles, roles.__getitem__, _Unindexed())[0]
1455
+ at = next(k for k, e in enumerate(seq) if e["record_id"] == record_id)
1456
+ context = lambda part: [{**e, "owned": False} for e in part] # noqa: E731
1457
+ return (context(seq[before_turns(seq, at, OVERLAP_TURNS):at]) + [middle]
1458
+ + context(seq[at + 1:after_turns(seq, at + 1, OVERLAP_TURNS)]))
1459
+
1460
+
1461
+ def expand(run_dir, call_id, name, record_id, reason, forced_by="none", omission=None):
1462
+ """The omitted middle of a clipped record as additional windows (`expansion_windows`), written beside the view; the
1463
+ decision is logged. Returns the windows."""
1464
+ run_dir = pathlib.Path(run_dir)
1465
+ first, windows, _sequence = expansion_windows(run_dir, name, record_id, omission)
1466
+ # The path carries the OMISSION, not only the call. Two records expanded under one call id wrote
1467
+ # `expansion-<call>-1.json` each, and `records.write_text` replaces, so the first expansion's windows were
1468
+ # gone and `expansions.jsonl` still held both decisions - an artifact set that reads as complete and is
1469
+ # not. The omission id's digest is what makes the name safe through the path sanitiser.
1470
+ safe = re.sub(r"[^A-Za-z0-9._-]", "_", call_id)
1471
+ tag = re.sub(r"[^A-Za-z0-9._-]", "_", first["omission_id"])[-24:]
1472
+ for w in windows:
1473
+ records.write_json(run_dir, run_dir / "views" / name / f"expansion-{safe}-{tag}-{w['window_n']}.json", w)
1474
+ record_decision(run_dir, call_id, name, record_id, "expand", reason, forced_by,
1475
+ omission=first["omission_id"])
1476
+ return windows
1477
+
1478
+
1479
+ def omitted_middle(run_dir, name, doc, record_id, omission=None):
1480
+ """`(manifest row, its window, entry)` of one omitted interval: the row the record's own window lists it by (an
1481
+ overlap row when no window owns the record), and the omitted characters as an owned entry, re-read from the
1482
+ projection under the same span mapping as its view; they must hash to the manifest's `omitted_span.sha256`
1483
+ (EXPANSION_SOURCE_DRIFT). EXPANSION_UNKNOWN when no window lists it; EXPANSION_AMBIGUOUS when the record lost several
1484
+ intervals and `omission` does not name one."""
1485
+ run_dir = pathlib.Path(run_dir)
1486
+ first, window = None, None
1487
+ for path in sorted((run_dir / "views" / name).glob("[0-9]*.json")):
1488
+ doc_here = window_doc(run_dir, name, path)
1489
+ rows = [m for m in doc_here["omission_manifest"]
1490
+ if (m["omission_id"] == omission if omission else m["record_id"] == record_id)]
1491
+ # the record's OWN window decides: the same record is also context in its neighbours, and an
1492
+ # overlap row describes the cut the context made, not the record's own clip
1493
+ owned_row = next((m for m in rows if m.get("origin") != "overlap"), None)
1494
+ if owned_row:
1495
+ first, window = owned_row, doc_here
1496
+ break
1497
+ if rows and first is None:
1498
+ first, window = rows[0], doc_here
1499
+ if first is None:
1500
+ raise Refused(f"EXPANSION_UNKNOWN {omission or record_id}: no window of {name} lists it as clipped")
1501
+ if omission is None:
1502
+ every = sorted({m["omission_id"] for path in sorted((run_dir / "views" / name).glob("[0-9]*.json"))
1503
+ for m in window_doc(run_dir, name, path)["omission_manifest"]
1504
+ if m["record_id"] == record_id})
1505
+ if len(every) > 1:
1506
+ raise Refused(f"EXPANSION_AMBIGUOUS {record_id}: it lost {len(every)} intervals ({every}); name the "
1507
+ "omission to expand, because expanding one of them discharges only that one")
1508
+ with open(run_dir / doc["redacted"], "rb") as handle:
1509
+ handle.seek(first["locator"]["offset"])
1510
+ line = json.loads(handle.readline())
1511
+ block = next(b for b in line["items"] if f"{line['line']}{b['pointer']}" == record_id)
1512
+ span = first["omitted_span"]
1513
+ middle = block["text"][span["start"]:span["end"]]
1514
+ if records.sha256_bytes(middle.encode("utf-8")) != span["sha256"]:
1515
+ raise Refused(f"EXPANSION_SOURCE_DRIFT {record_id}: the omitted characters no longer hash to the manifest's span")
1516
+ # an overlap omission belongs to no window's own records, so the row carries the role
1517
+ role = next((r["window_role"] for r in window["records"] if r["record_id"] == record_id),
1518
+ first.get("window_role", "context"))
1519
+ entry = {"record_id": record_id, "line": line["line"], "json_pointer": block["pointer"], "kind": block["kind"],
1520
+ "tool": block.get("tool"), "ts": line.get("ts"), "error": bool(block.get("error")), "window_role": role,
1521
+ "size": len(middle), "text": middle, "segments": [{"view": [0, len(middle)], "block": [span["start"], span["end"]]}],
1522
+ "owned": True, "offset": first["locator"]["offset"]}
1523
+ return first, window, entry
1524
+
1525
+
1526
+ def expansion_windows(run_dir, name, record_id, omission=None):
1527
+ """`(manifest row, windows, sequence)` of one expansion, made and checked but not written: the omitted middle of a
1528
+ clipped record (`omitted_middle`) under the same bound and span mapping as its view, with the record's neighbours as
1529
+ overlap (`expansion_entries`, WP-08c), held to the window invariants as S2's windows are (`check_windows`)."""
1530
+ run_dir = pathlib.Path(run_dir)
1531
+ doc = sequence_doc(run_dir, name)
1532
+ first, _window, entry = omitted_middle(run_dir, name, doc, record_id, omission)
1533
+ base = {"transcript": doc["transcript"], "version": doc["version"], "version_sha": doc["version_sha"],
1534
+ "redaction_version": doc["redaction_version"], "expansion_of": record_id}
1535
+ windows, sequence = cut_windows(base, expansion_entries(run_dir, name, doc, record_id, entry), doc["limits"])
1536
+ errors = check_windows(sequence, windows)
1537
+ if errors:
1538
+ raise Refused("\n".join(errors[:5]))
1539
+ return first, windows, sequence
1540
+
1541
+
1542
+ def gather_windows(run_dir, name, rows):
1543
+ """`(windows, sequence)` of one window's gather, made and checked but not written (WP-08e, lead decision
1544
+ D-20261111-360c9b): the omitted middles of `rows` - omissions of the window's own records its reading skipped - in
1545
+ the order the window lists them, each an owned entry re-read from the projection as an expansion's is
1546
+ (`omitted_middle`), with no record's neighbours: the window that skipped them showed their heads, tails and context.
1547
+ Cut under the view's bound and held to the window invariants as S2's windows are; a gather too large for one window
1548
+ is cut into several, each showing its neighbouring middles as overlap."""
1549
+ run_dir = pathlib.Path(run_dir)
1550
+ doc = sequence_doc(run_dir, name)
1551
+ entries = [omitted_middle(run_dir, name, doc, m["record_id"], m["omission_id"])[2] for m in rows]
1552
+ base = {"transcript": doc["transcript"], "version": doc["version"], "version_sha": doc["version_sha"],
1553
+ "redaction_version": doc["redaction_version"], "gather_of": [m["omission_id"] for m in rows]}
1554
+ windows, sequence = cut_windows(base, entries, doc["limits"])
1555
+ errors = check_windows(sequence, windows)
1556
+ if errors:
1557
+ raise Refused("\n".join(errors[:5]))
1558
+ return windows, sequence
1559
+
1560
+
1561
+ def gather(run_dir, call_id, name, rows):
1562
+ """The omitted middles a window's reading skipped, as windows of their own (`gather_windows`), written beside the
1563
+ view under the skipping call's id. The skips stay in `expansions.jsonl` as the reading decided them; what the gather
1564
+ read is the read record's. Returns the windows."""
1565
+ run_dir = pathlib.Path(run_dir)
1566
+ windows, _sequence = gather_windows(run_dir, name, rows)
1567
+ safe = re.sub(r"[^A-Za-z0-9._-]", "_", call_id)
1568
+ for w in windows:
1569
+ records.write_json(run_dir, run_dir / "views" / name / f"gather-{safe}-{w['window_n']}.json", w)
1570
+ return windows
1571
+
1572
+
1573
+ def record_decision(run_dir, call_id, name, record_id, decision, reason, forced_by="none", omission=None):
1574
+ """Append one decision to `expansions.jsonl`. A skip of a forced record is refused (EXPANSION_SKIPPED); a call's
1575
+ decision of an omission is written once, and another decision of it by the same call is refused where it would be
1576
+ written (EXPANSION_DECISION_CONFLICT)."""
1577
+ if decision not in DECISIONS or forced_by not in FORCED_BY or not str(reason or "").strip():
1578
+ raise Refused(f"EXPANSION_DECISION_INVALID {record_id}: decision {decision!r} (expand or skip), forced_by {forced_by!r}, "
1579
+ "and a reason are required")
1580
+ if decision == "skip" and forced_by != "none":
1581
+ raise Refused(f"EXPANSION_SKIPPED {record_id}: forced by {forced_by}, so it must be expanded")
1582
+ path = stagelock.confine(run_dir, pathlib.Path(run_dir) / "expansions.jsonl")
1583
+ # the locator names the OMISSION as well as the record: accounting is by interval, and a decision
1584
+ # that names only the record answers for intervals nobody looked at
1585
+ locator = {"transcript": name, "record_id": record_id, "omission_id": omission}
1586
+ line = json.dumps({"call_id": call_id, "locator": locator, "reason": reason, "decision": decision, "forced_by": forced_by},
1587
+ sort_keys=True, ensure_ascii=False)
1588
+ # the same decision of the same call again, as a resumed run makes it when its call is reused, is not written
1589
+ # twice, and the same call deciding the same omission otherwise is refused (WP-08 commit 5a); a decision by another
1590
+ # call is another line
1591
+ # units read side by side append here: the read and the append are one step under the log's lock (WP-08 commit 5b)
1592
+ with stagelock.hold(run_dir, "expansions", wait_s=DECISIONS_LOCK_WAIT_S):
1593
+ # read by the one JSONL splitter: a reason may hold U+2028, U+2029 or U+0085 raw, which str.splitlines breaks at
1594
+ held = [h for h in records.jsonl_read(path) if h.strip()] if path.is_file() else []
1595
+ if line in held:
1596
+ return
1597
+ if any((d["call_id"], d["locator"]) == (call_id, locator) for d in map(json.loads, held)):
1598
+ raise Refused(f"EXPANSION_DECISION_CONFLICT {record_id}: call {call_id} decided {omission or 'the record'} of "
1599
+ f"{name} already, otherwise; a call's decision of an omission is written once")
1600
+ with open(path, "a", encoding="utf-8") as handle:
1601
+ handle.write(line + "\n")
1602
+
1603
+
1604
+ DECISIONS_LOCK_WAIT_S = 30 # how long a decision waits for another unit's to be written
1605
+
1606
+
1607
+ def order_decisions(run_dir, rank):
1608
+ """`expansions.jsonl` with its lines in the `rank` order of the view each decides, each view's in the order they
1609
+ were made, replaced whole (WP-08 commit 5b). Units read side by side append their decisions interleaved; in this
1610
+ order the log is the same bytes however many were read at once. A view `rank` does not name keeps its order, after
1611
+ the ranked ones."""
1612
+ path = stagelock.confine(run_dir, pathlib.Path(run_dir) / "expansions.jsonl")
1613
+ with stagelock.hold(run_dir, "expansions", wait_s=DECISIONS_LOCK_WAIT_S):
1614
+ if not path.is_file():
1615
+ return
1616
+ lines = [line for line in records.jsonl_read(path) if line.strip()]
1617
+ ordered = sorted(lines, key=lambda line: rank.get(json.loads(line)["locator"]["transcript"], len(rank)))
1618
+ if ordered != lines:
1619
+ records.write_text(run_dir, path, "".join(line + "\n" for line in ordered))
1620
+
1621
+
1622
+ # ---- fixtures ---------------------------------------------------------------------------------
1623
+
1624
+ REALIZATION = "golden" # every fixture is synthetic: `golden` writes the transcripts and the run directory it reads
1625
+ FX_WINDOW = {"start": "2026-10-01T00:00:00", "end": "2026-10-08T00:00:00", "tz": "UTC"}
1626
+ FX_PREV_WINDOW = "2026-09-24T00:00:00/2026-10-01T00:00:00@UTC"
1627
+ FX_SECRET = "sk-ant-oat01-" + "Ab1_" * 12 # the shape P4 sweeps the run directory for
1628
+ FX_HOME = "/Users/fixtureowner"
1629
+ FX_RAW_PATH = f"{FX_HOME}/Documents/repo/notes.md"
1630
+ FX_TERM = "plain version" # a retrieval term of an expected observation (§7.3)
1631
+ # M#3: metadata reaches the model too. The one tool call of the fixture is named after the swept shape, so
1632
+ # the end-to-end sweep proves the projection covers every transcript-derived string a window renders and not
1633
+ # only a block's text - `header_of` writes this name into the window.
1634
+ FX_TOOL_SECRET = f"mcp__{FX_SECRET[:24]}__call"
1635
+ FX_QUOTE = f"show me the {FX_TERM}"
1636
+ FX_HIDDEN_PLAIN = "the person asked again for a simpler telling of it" # carries no retrieval term
1637
+ FX_HIDDEN_TERM = f"the person asked again for the {FX_TERM} of it" # carries one
1638
+ FX_HIDDEN_WIDTH = max(len(FX_HIDDEN_PLAIN), len(FX_HIDDEN_TERM))
1639
+ # R#0: the shapes whose masking depends on the ORDER of decoding and masking, planted inside a record the
1640
+ # window owns so the sweep reaches them through every artifact. The first is a floor match that crosses the
1641
+ # structure's own syntax with an encoded key behind it; the second is a header whose scheme crosses a
1642
+ # newline; the third is a home path encoded as a dictionary KEY.
1643
+ FX_PLANTED_JSON = "r0planted-" + "Zz9" * 6
1644
+ FX_PLANTED_HEADER = "r0opaque-" + "Yy8" * 6
1645
+ FX_ENCODED_HOME = FX_HOME.replace("/", "\\u002f")
1646
+ FX_MIXED = ('{"note":"api_key=abc", "\\u0070assword":"' + FX_PLANTED_JSON + '", '
1647
+ '"' + FX_ENCODED_HOME + '\\u002fx":1}')
1648
+ FX_MULTILINE = "Authorization: Bearer\n" + FX_PLANTED_HEADER
1649
+ # Q#0 and Q#2: the shapes whose masking depends on the FALLBACK and on the original text's obligations
1650
+ # rather than on what the decoded form can reach. Each is planted in a transcript of its own so the whole
1651
+ # stage runs over it - projection, windows, index, evidence - instead of the projection alone.
1652
+ FX_FALLBACK_SCALAR = "q2encoded-secret-7Xy" # reachable only by decoding, in a block that falls back
1653
+ FX_FALLBACK_LEFTOVER = "q2leftover-credential" # the cross-member floor claim that causes the fallback
1654
+ FX_OBLIGATION_JSON = "q2leakme-structure-9" # a secret-named key in prose whose value is a structure
1655
+ FX_OBLIGATION_QUOTED = "q2quoted-credential-4" # a quoted scalar that itself holds a structure
1656
+ FX_FALLBACK_TOKEN = "sk-" + "A1b2" * 6
1657
+ # A#3: the shapes of the last two rounds, downstream as well: an escaped array under a readable keyed name
1658
+ # (Z#0), a quoted scalar whose keyed value holds a structure (A#0), and a literal mask standing beside a
1659
+ # credential (rule 2) - each in a record of its own so a control can name its locator.
1660
+ FX_ESCAPED_ARRAY = "a3escaped-array-credential"
1661
+ FX_QUOTED_SCALAR = "a3quoted-scalar-credential"
1662
+ FX_MASK_NEIGHBOUR = "a3beside-the-mask-credential"
1663
+ # A#1 downstream: a plain structure, then an ESCAPED member. Nothing reads the escaped part unless escaped
1664
+ # regions are read in their own coordinates, and the plain part used to excuse it.
1665
+ FX_ESCAPED_TAIL = "a1tail-credential-after-a-plain-structure"
1666
+ # M#7: the three shapes of the fifth round, each as its own located block, so a control can name a locator
1667
+ # and a quote can be refused at it.
1668
+ FX_SIBLING_KEY = "e0siblingnamecredential" # the key's name stands in an unrelated value
1669
+ FX_MIXED_DEPTH = "e1mixeddepthcredential" # a twice-encoded token beside an already plain path
1670
+ FX_NO_QUOTE_BODY = "e2noquotebodycredential" # a decodable body with no escaped quote in it
1671
+ # M#8: a credential behind six layers of escaped escapes, in prose a plain structure begins. No raw rule
1672
+ # matches it and no mapping locates it; the verifier reads it through its lenient decoding and blanks the
1673
+ # block. It is here so the recorded blank count has something to count.
1674
+ FX_LAYERED = "m8layeredcredentialabcdefgh"
1675
+ # R#4: the cross-member claim arriving as a STRUCTURE rather than as text. Each member is clean on its own;
1676
+ # the floor match exists only in the serialisation between them, which is the text a reader sees.
1677
+ FX_STRUCTURED_CROSS = "r4structuredcrosscredential"
1678
+ # S#3: the rows the case table still lacked. A secret-named member whose colon carries a newline, which no
1679
+ # textual key scanner with a space-only separator reads; an unreadable escape run; and S#0's keyed fragment
1680
+ # in mixed text, which is a member of no object.
1681
+ FX_MEMBER_NEWLINE = "s3membernewlinecredential"
1682
+ FX_MIXED_TEXT = "s3mixedtextcredential"
1683
+ # S#5: one content block with TWO leaves the backstop takes. It goes through the transcript, so the figures
1684
+ # the run records are read from views.json rather than from the counters a control just moved itself.
1685
+ FX_TWO_LEAF = "s5twoleafabcdefghijklmn"
1686
+ # U#2: the shapes of the last two rounds, downstream as well. A long name a cap would have split; a value
1687
+ # that merely starts with the mask and carries a comma; an escape run before a real newline; and a duplicate
1688
+ # secret-named member whose masked copy stands last.
1689
+ FX_LONG_NAME = "u2longnamecredential"
1690
+ FX_MASK_COMMA = "u2maskcommacredential"
1691
+ FX_ESCAPE_RUN = "u2escaperuncredential"
1692
+ FX_DUPLICATE_LAST = "u2duplicatelastcredential"
1693
+ # X#3: the reviewer's round-14 shapes as TRANSCRIPT ROWS rather than as strings handed to the detector. A
1694
+ # detector string says what the rule answers; a row says what the stage does with it - the window it writes,
1695
+ # the postings it makes, the quote it stores and the quote it refuses.
1696
+ FX_READABLE_ARRAY = "x3readablearraycredential"
1697
+ FX_READABLE_OBJECT = "x3readableobjectcredential"
1698
+ FX_SCALAR_SUFFIX = "x3scalarsuffixcredential"
1699
+ FX_NEWLINE_SEPARATOR = "x3newlineseparatorcredential"
1700
+
1701
+
1702
+ def fx_stamp(day, hour=1, minute=0, month=10):
1703
+ return f"2026-{month:02d}-{day:02d}T{hour:02d}:{minute:02d}:00.000Z"
1704
+
1705
+
1706
+ def fx_human(stamp, text):
1707
+ return {"type": "user", "timestamp": stamp, "message": {"role": "user", "content": text}}
1708
+
1709
+
1710
+ def fx_assistant(stamp, text):
1711
+ return {"type": "assistant", "timestamp": stamp, "message": {"role": "assistant", "content": [{"type": "text", "text": text}]}}
1712
+
1713
+
1714
+ def fx_call(stamp, tool, arguments):
1715
+ return {"type": "assistant", "timestamp": stamp,
1716
+ "message": {"role": "assistant", "content": [{"type": "tool_use", "name": tool, "input": arguments}]}}
1717
+
1718
+
1719
+ def fx_result(stamp, text, failed=False):
1720
+ return {"type": "user", "timestamp": stamp,
1721
+ "message": {"role": "user", "content": [{"type": "tool_result", "is_error": failed, "content": text}]}}
1722
+
1723
+
1724
+ def fx_clipped(hidden, filler=6):
1725
+ """A tool result long enough to be clipped (design §5.4): a head and a tail that two of these share byte for
1726
+ byte, two lines of the middle that read as errors, and one sentence hidden in the gap between them. `filler`
1727
+ sets how much of the middle is omitted, so an expansion of it can be made to need more than one window."""
1728
+ head = "\n".join(f" file {i:03d} ok {'.' * 30}" for i in range(70))
1729
+ tail = "\n".join(f" summary {i:03d} done {'-' * 24}" for i in range(45))
1730
+ ordinary = [f" middle line {i:03d} {'=' * 30}" for i in range(filler)]
1731
+ middle = ordinary[:filler // 2] + [" error: the write was denied", " Traceback (most recent call last):",
1732
+ " " + hidden.ljust(FX_HIDDEN_WIDTH, ".")] + ordinary[filler // 2:]
1733
+ return head + "\n" + "\n".join(middle) + "\n" + tail
1734
+
1735
+
1736
+ def fx_main_records():
1737
+ """T1, the eligible Claude session: one record before the window, the viewed turns, two after it. The record before
1738
+ is longer than an overlap item, so the first window's overlap cuts it and a record the run does not owe carries an
1739
+ overlap row by construction (D-20261103-8bfd69), not by how a side's budget happens to fill."""
1740
+ return [
1741
+ fx_assistant(fx_stamp(30, month=9, hour=10), "an answer from the week before this window. "
1742
+ + "".join(f"note {i:03d} of that answer. " for i in range(40))),
1743
+ fx_human(fx_stamp(3, hour=1), f"{FX_QUOTE} of that, and see {FX_RAW_PATH} please"),
1744
+ fx_assistant(fx_stamp(3, hour=2), f"here it is; the slot still holds {FX_SECRET} for the runner"),
1745
+ fx_call(fx_stamp(3, hour=3), FX_TOOL_SECRET, {"command": f"ls {FX_HOME}/Documents/repo"}),
1746
+ fx_result(fx_stamp(3, hour=4), fx_clipped("the outcome of this read lands after the window", filler=500), failed=True),
1747
+ fx_human(fx_stamp(3, hour=5), f"and the other thing? {FX_MIXED} {FX_MULTILINE}"),
1748
+ # P#2: a host wrote this field, so it is a string like any other - and nothing projected it. The
1749
+ # fixture plants the swept shape and a home path in it, end to end.
1750
+ fx_result(f"{FX_SECRET} at {FX_RAW_PATH}", fx_clipped("nothing worth keeping is hidden here")),
1751
+ fx_assistant(fx_stamp(3, hour=7), "".join(f"paragraph {i:03d} of the long answer, which no window holds whole. "
1752
+ for i in range(300))),
1753
+ fx_result(fx_stamp(3, hour=8), fx_clipped(FX_HIDDEN_PLAIN)),
1754
+ fx_result(fx_stamp(3, hour=9), fx_clipped(FX_HIDDEN_TERM)),
1755
+ fx_assistant(fx_stamp(9, hour=10), "an answer from the week after this window"),
1756
+ fx_assistant(fx_stamp(9, hour=11), "and one more after it"),
1757
+ ]
1758
+
1759
+
1760
+ def fx_child_records():
1761
+ """T2, the child transcript linked to T1: a parent's instruction and the child's answer."""
1762
+ return [{"type": "user", "timestamp": fx_stamp(3, hour=3), "isSidechain": True,
1763
+ "message": {"role": "user", "content": "find every place the plain version is asked for"}},
1764
+ fx_assistant(fx_stamp(3, hour=4), "two places, both in the guides"),
1765
+ {"type": "attachment", "timestamp": fx_stamp(3, hour=4),
1766
+ "attachment": {"type": "queued_command", "prompt": "while you are there, check the Korean reference"}}]
1767
+
1768
+
1769
+ def fx_codex_records():
1770
+ """T3, the Codex session deferred by the previous window: its records are the backlog this run reads first."""
1771
+ return [{"type": "response_item", "timestamp": fx_stamp(26, month=9, hour=1),
1772
+ "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "summarize the week"}]}},
1773
+ {"type": "response_item", "timestamp": fx_stamp(26, month=9, hour=2),
1774
+ "payload": {"type": "function_call", "name": "shell", "arguments": '{"command":"git log"}'}},
1775
+ {"type": "response_item", "timestamp": fx_stamp(26, month=9, hour=3),
1776
+ "payload": {"type": "function_call_output", "output": "two commits, both on the lane branch"}}]
1777
+
1778
+
1779
+ def fx_write(path, rows):
1780
+ path.parent.mkdir(parents=True, exist_ok=True)
1781
+ path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows), encoding="utf-8")
1782
+ return records.sha256_file(path)
1783
+
1784
+
1785
+ def fx_entry(host, ident, source, path, sha, status="eligible", **fields):
1786
+ """A census row of one transcript file, in its host's shape (`census.finish`)."""
1787
+ fields.setdefault("counted", status == "eligible")
1788
+ file = {k: fields.pop(k) for k in ("owned", "work", "versions") if k in fields}
1789
+ entry = census.blank(host, ident, source, str(path), status=status, provenance="indexed", window_overlap="inside", **fields)
1790
+ entry["segments"][0].update(sha256=sha, **file)
1791
+ return census.finish(entry)
1792
+
1793
+
1794
+ def fx_versions(state, tid):
1795
+ """The versions of `tid` a census row carries, as S1 writes them from the state it observed (`census.build`)."""
1796
+ return [{k: v[k] for k in ("sha", "record_count", "prefix_sha")} for v in state["transcripts"][tid]["versions"]]
1797
+
1798
+
1799
+ def fx_owned(rows, window=None):
1800
+ """The records of `rows` the window owns, decided the way S1 decides them (`coverage.Ownership`)."""
1801
+ start, end, _id = coverage.window_bounds(window or FX_WINDOW)
1802
+ own = coverage.Ownership(start, end)
1803
+ for index, row in enumerate(rows):
1804
+ own.feed(index, row.get("timestamp"))
1805
+ return own.finish(len(rows))["owned"]
1806
+
1807
+
1808
+ def fx_census(window_id, entries):
1809
+ """The census document a golden run reads: the fields S1 writes, over the fixture's transcripts. Each source has
1810
+ discovered what is filed under it and totals it by status, as S1 does, so the census S3 hands back is accountable
1811
+ (`census.account`)."""
1812
+ sources = {name: {"state": "present", "path": f"/srv/golden/{name}",
1813
+ "discovered": sum(1 for e in entries if e["source"] == name),
1814
+ "unrecognized": 0, "totals": {}, "detail": None} for name in census.DIRECTORIES}
1815
+ census.totals_of(entries, sources)
1816
+ return {"kind": "periodic", "window": window_id, "originator_table_sha256": records.sha256_bytes(b"golden"),
1817
+ "sources": sources,
1818
+ "originators": {}, "provenance": {}, "pins": {},
1819
+ "independence": {"components": 1, "unknown_components": 0, "sessions": len(entries), "unknown_sessions": 0},
1820
+ "unowned": {"earlier_windows": 0, "rewritten": {"files": 0, "records": 0}, "first_seen": {"files": 0, "records": 0}},
1821
+ "pending_events": [], "transcripts": entries}
1822
+
1823
+
1824
+ def fx_seats(root, capacity, seat=None, host_version=None, name=None):
1825
+ """A `seats.json` fixture that differs from the checkout's in one declared context capacity.
1826
+
1827
+ The capacity is read through `gate.seat_capacity` like every other, so a control that needs a narrower
1828
+ seat declares one instead of handing the window builder a number (BB#5). The seat and the host version
1829
+ default to the checkout's S3 seat and pinned Claude host."""
1830
+ seat = seat or declare.fixture()["seats"][declare.VIEW_WINDOW_STAGE]
1831
+ host_version = host_version or gate.seats()["hosts"]["claude"]["version"]
1832
+ held = json.loads(gate.SEATS.read_text(encoding="utf-8"))
1833
+ held["seat_capacity"] = {**(held.get("seat_capacity") or {}),
1834
+ seat: {"context_capacity": capacity, "host_version": host_version,
1835
+ "basis": "a fixture's own declaration, not a measurement"}}
1836
+ path = pathlib.Path(root) / (name or f"seats-capacity-{capacity}.json")
1837
+ path.write_text(json.dumps(held), encoding="utf-8")
1838
+ return path
1839
+
1840
+
1841
+ def golden(root, name="g", overhead=bound.PACKET_OVERHEAD, capacity=None, reservation=32_000,
1842
+ allowance=3200, census_sha=None, compressed=False, main_records=None, owned=None, allowance_entry=None,
1843
+ window=None, state=None, prefix_ok=None, ledger_doc=None, child_records=None, main_only=False, pending_at=4,
1844
+ density=None):
1845
+ """A run directory S2 can be run over, and the result of running it (realization: golden).
1846
+
1847
+ The transcripts are `fx_main_records` (eligible, with a pending event and four clipped tool results), its child,
1848
+ and a Codex session the previous window deferred. `overhead` is what makes the bound bite: the packet's bytes are
1849
+ the one part of the driver's budget a fixture can set, so a small corpus produces several windows, split spans and
1850
+ overlaps instead of a 100 KB one. `census_sha` plants a census that read other bytes than the copy now hashes to.
1851
+ `window` and `state` make the run of a later window over the coverage state an earlier run left (WP-08 done-when 4):
1852
+ the transcripts are observed into that state as S1 observes them, `prefix_ok` saying whether a changed file kept the
1853
+ earlier version as its prefix (`coverage.observe`), and nothing is planted in it. The declaration's checkout holds
1854
+ `ledger_doc` (an empty schema 2 ledger by default) and pins its hash, as S0 pins the ledger S3 reads the expected
1855
+ observations due from. `child_records` runs it over another child transcript, as `main_records` does the main one.
1856
+ `main_only` leaves the child and the Codex session out of the census, so S2 views the main session alone and a run
1857
+ over it makes only the calls that session needs (WP-08 commit 7's live legs). `pending_at` is the first record of the
1858
+ pending event the planted state carries on the main session; None plants none. `density` is the declaration's
1859
+ density table (WP-08e), left out when None."""
1860
+ root = pathlib.Path(root)
1861
+ run_dir, host = root / name, root / f"{name}-host"
1862
+ child_rows = child_records() if child_records else fx_child_records()
1863
+ main_path, child_path = host / "t1.jsonl", host / "t1-child.jsonl"
1864
+ codex_path = host / ("rollout-t3.jsonl.zst" if compressed else "rollout-t3.jsonl")
1865
+ # `main_records` lets a control run the WHOLE stage over a different transcript - the overlap cases need
1866
+ # long turns, and a case that cannot be built as a real run can only be tested against hand-made rows
1867
+ main_rows = main_records() if main_records else fx_main_records()
1868
+ main_sha = fx_write(main_path, main_rows)
1869
+ child_sha = codex_sha = None
1870
+ if not main_only:
1871
+ child_sha = fx_write(child_path, child_rows)
1872
+ if main_only:
1873
+ pass # neither the child nor the Codex session is written, so no source lists them
1874
+ elif compressed:
1875
+ plain = host / "rollout-t3.jsonl"
1876
+ codex_sha = fx_write(plain, fx_codex_records())
1877
+ zstd = sources.declared(declare.fixture()).get("zstd")
1878
+ if not os.access(zstd or "", os.X_OK):
1879
+ raise Refused(f"ZSTD_UNAVAILABLE {zstd}: the compressed fixture is made with the declared zstd")
1880
+ try:
1881
+ subprocess.run([sources.checked_zstd(zstd), "-q", "-f", str(plain), "-o", str(codex_path)], check=True)
1882
+ except ValueError as exc:
1883
+ raise Refused(f"ZSTD_UNAVAILABLE {zstd}: {exc}") from exc
1884
+ plain.unlink()
1885
+ else:
1886
+ codex_sha = fx_write(codex_path, fx_codex_records())
1887
+
1888
+ main_id, child_id, codex_id = "a1000000-0000-4000-8000-000000000001", "a1000000-0000-4000-8000-000000000002", \
1889
+ "019e0001-0000-7000-8000-000000000003"
1890
+ # a Codex file's coverage key names the file (D-20261103-a7128a)
1891
+ main_tid, child_tid, codex_tid = (lineage.identity("claude", main_id), lineage.identity("claude", child_id),
1892
+ f"{lineage.identity('codex', codex_id)}@{census.stem_of(codex_path)}")
1893
+ window = window or FX_WINDOW
1894
+ _start, _end, window_id = coverage.window_bounds(window)
1895
+
1896
+ planted, state = state is None, copy.deepcopy(state) if state is not None else coverage.new_state()
1897
+ observed = [(main_tid, main_sha, len(main_rows))]
1898
+ if not main_only:
1899
+ observed += [(codex_tid, codex_sha, len(fx_codex_records())), (child_tid, child_sha, len(child_rows))]
1900
+ for tid, sha, count in observed:
1901
+ coverage.observe(state, tid, sha, count, records.sha256_bytes(f"prefix-{tid}".encode()), prefix_ok)
1902
+ if planted:
1903
+ state["pending_events"] = [] if pending_at is None else [
1904
+ {"id": "pe-1", "transcript": main_tid, "version": 0, "window": window_id, "first_record": pending_at}]
1905
+ state["backlog"] = [] if main_only else [{"transcript": codex_tid, "version": 0, "window": FX_PREV_WINDOW,
1906
+ "status": "deferred", "unread": [[0, len(fx_codex_records())]]}]
1907
+ # the records whose timestamps fall in the window; for the default transcript the first and the last two
1908
+ # do not. A caller whose transcript puts a case on the first record says so, or the control it writes
1909
+ # would be about a record no window owns.
1910
+ main_owned = [[1, 10]] if owned is None else owned
1911
+ entries = [
1912
+ fx_entry("claude", main_id, "claude_projects", main_path, census_sha or main_sha, owned=main_owned,
1913
+ work=coverage.work_of(state, main_tid, main_owned, window_id), versions=fx_versions(state, main_tid))]
1914
+ codex_work = None if main_only else coverage.work_of(state, codex_tid, [], window_id)
1915
+ entries += [] if main_only else [
1916
+ # S1 reads a member of an eligible unit like its root (D-20261103-85f3e8): the child carries its own work
1917
+ fx_entry("claude", child_id, "claude_projects", child_path, child_sha, status="child_of", parent=main_id,
1918
+ owned=fx_owned(child_rows, window),
1919
+ work=coverage.work_of(state, child_tid, fx_owned(child_rows, window), window_id),
1920
+ versions=fx_versions(state, child_tid)),
1921
+ # a later window's run may find the Codex session owing it nothing, which S1 records as nothing new
1922
+ fx_entry("codex", codex_id, "codex_sessions", codex_path, codex_sha, owned=[], work=codex_work,
1923
+ status="eligible" if codex_work["in_window"] or codex_work["backlog"] else "nothing_new",
1924
+ versions=fx_versions(state, codex_tid)),
1925
+ ]
1926
+ document = fx_census(window_id, entries)
1927
+ problems = validate.validate_instance(census.validator(), document)
1928
+ if problems:
1929
+ raise Refused("CENSUS_INVALID the golden census does not conform: " + "; ".join(problems[:3]))
1930
+
1931
+ declaration = {**declare.fixture(), "window": window, "output_caps": {declare.VIEW_WINDOW_STAGE: reservation}}
1932
+ seat = declaration["seats"][declare.VIEW_WINDOW_STAGE]
1933
+ declaration["host_allowance"] = {seat: {**declaration["host_allowance"][seat], "allowance_tokens": allowance}}
1934
+ if allowance_entry is not None:
1935
+ # a stage that DISPATCHES over these windows declares the allowance seats.json measured, which the
1936
+ # dispatcher admits a view-window call against; S2's own controls keep the small one that bites
1937
+ declaration["host_allowance"] = {seat: allowance_entry}
1938
+ checkout = root / f"{name}-checkout"
1939
+ ledger_path = checkout / ledger.STATE_LEDGER_REL
1940
+ ledger_path.parent.mkdir(parents=True, exist_ok=True)
1941
+ ledger_path.write_text(ledger.render(ledger_doc if ledger_doc is not None else ledger.sample_ledger()), encoding="utf-8")
1942
+ declaration["destinations"] = {**declaration["destinations"], "checkout": str(checkout.resolve())}
1943
+ declaration["starting_hashes"] = {**declaration["starting_hashes"], "ledger": records.sha256_file(ledger_path)}
1944
+ if density is not None:
1945
+ declaration["density"] = density
1946
+ run_dir.mkdir(parents=True, exist_ok=True)
1947
+ declare.create(run_dir, declaration)
1948
+ with records.run_stage(run_dir, "S1") as stage:
1949
+ records.write_text(run_dir, run_dir / "census.json", census.dump(document))
1950
+ records.write_json(run_dir, run_dir / "coverage.json", state)
1951
+ stage.output("census.json")
1952
+ stage.output("coverage.json")
1953
+
1954
+ # a narrower capacity than the checkout declares is a seats fixture, read by the shared reader (BB#5)
1955
+ manifest = run(run_dir, overhead,
1956
+ fx_seats(root, capacity) if capacity is not None else None)
1957
+ by_name = {t["name"]: t for t in manifest["transcripts"]}
1958
+ main = by_name.get(safe_name(main_tid)) # absent when the run quarantined it, which `census_sha` plants
1959
+ # through the checked reader like every other window read, so the fixture cannot be the one place a
1960
+ # stale artifact would be accepted
1961
+ windows = [window_doc(run_dir, main["name"], run_dir / w["path"]) for w in main["windows"]] if main else []
1962
+ return {"run_dir": run_dir, "run": declaration, "seat": seat, "manifest": manifest, "limits": manifest["limits"],
1963
+ "main": main, "child": by_name.get(safe_name(child_tid)), "codex": by_name.get(safe_name(codex_tid)),
1964
+ "by_name": by_name, "windows": windows, "state": state, "census": document, "window": window_id,
1965
+ "paths": {"main": main_path, "child": None if main_only else child_path,
1966
+ "codex": None if main_only else codex_path, "ledger": ledger_path},
1967
+ "tids": {"main": main_tid, "child": child_tid, "codex": codex_tid},
1968
+ "lines": {"before": 1, "human": 2, "secret": 3, "call": 4, "pending_clip": 5, "second_human": 6,
1969
+ "late_clip": 7, "long": 8, "pair_plain": 9, "pair_term": 10, "after": 11},
1970
+ "raw_path": FX_RAW_PATH, "secret": FX_SECRET, "home": FX_HOME, "term": FX_TERM, "realization": REALIZATION}
1971
+
1972
+
1973
+ def golden_unit(root, name, plant=None):
1974
+ """A run whose census holds one unit (D-20261103-85f3e8): a Claude root, a member under it, a member under that
1975
+ member, and a third level whose records all lie before the window. `plant` is `changed` (the second level's
1976
+ census read other bytes), `idle` (the root's unit owes the window nothing) or `mid_unreadable` (S1 could not read the
1977
+ first level, which keeps its parent: review c0fix r1 #2). Returns `(run_dir, ids, manifest or the refusal)`."""
1978
+ root = pathlib.Path(root)
1979
+ run_dir, host = root / name, root / f"{name}-host"
1980
+ ids = {"root": "a2000000-0000-4000-8000-000000000001", "d1": "a2000000-0000-4000-8000-000000000002",
1981
+ "d2": "a2000000-0000-4000-8000-000000000003", "d3": "a2000000-0000-4000-8000-000000000004"}
1982
+ before = [{**row, "timestamp": fx_stamp(26, month=9, hour=row_n)} for row_n, row in enumerate(fx_child_records())]
1983
+ rows = {"root": fx_main_records(), "d1": fx_child_records(), "d2": fx_child_records(), "d3": before}
1984
+ parents = {"d1": "root", "d2": "d1", "d3": "d2"}
1985
+ _start, _end, window_id = coverage.window_bounds(FX_WINDOW)
1986
+ state, entries = coverage.new_state(), []
1987
+ for key in ("root", "d1", "d2", "d3"):
1988
+ path = host / f"{key}.jsonl"
1989
+ sha = fx_write(path, rows[key])
1990
+ tid = lineage.identity("claude", ids[key])
1991
+ coverage.observe(state, tid, sha, len(rows[key]), sha, None)
1992
+ owned = [] if plant == "idle" else fx_owned(rows[key])
1993
+ census_sha = "00" * 32 if (plant == "changed" and key == "d2") else sha
1994
+ fields = {"status": "child_of", "parent": ids[parents[key]]} if key in parents else {}
1995
+ if plant == "mid_unreadable" and key == "d1":
1996
+ fields.update(status="unreadable", reason=f"READ_FAILED {path}: planted")
1997
+ entries.append(fx_entry("claude", ids[key], "claude_projects", path, census_sha, owned=owned,
1998
+ work=coverage.work_of(state, tid, owned, window_id), versions=fx_versions(state, tid), **fields))
1999
+ document = fx_census(window_id, entries)
2000
+ declaration = {**declare.fixture(), "window": FX_WINDOW}
2001
+ run_dir.mkdir(parents=True, exist_ok=True)
2002
+ declare.create(run_dir, declaration)
2003
+ with records.run_stage(run_dir, "S1") as stage:
2004
+ records.write_text(run_dir, run_dir / "census.json", census.dump(document))
2005
+ records.write_json(run_dir, run_dir / "coverage.json", state)
2006
+ stage.output("census.json")
2007
+ stage.output("coverage.json")
2008
+ try:
2009
+ outcome = run(run_dir, 32_000)
2010
+ except Exception as exc: # the refusal, or what a reverted check raises: a control reads it, never a traceback
2011
+ outcome = exc
2012
+ return run_dir, {key: lineage.identity("claude", value) for key, value in ids.items()}, outcome
2013
+
2014
+
2015
+ def golden_split(root, name, owns, base=None):
2016
+ """A run whose census holds one Codex thread written in two files (D-20261103-a7128a), the window owning `owns[0]` of
2017
+ the first and `owns[1]` of the second. `base` writes the run's coverage state as a targeted run leaves it, the
2018
+ periodic base instead of what S1 observed (review c0fix r1 #3): `empty`, or `older` (it saw two records fewer of each
2019
+ file). Returns `(the two files' coverage keys, manifest or the refusal)`."""
2020
+ root = pathlib.Path(root)
2021
+ run_dir, host = root / name, root / f"{name}-host"
2022
+ thread = "019e0002-0000-7000-8000-000000000004"
2023
+ _start, _end, window_id = coverage.window_bounds(FX_WINDOW)
2024
+ state, files = coverage.new_state(), []
2025
+ for n, owned in enumerate(owns):
2026
+ path = host / f"rollout-2026-10-0{n + 2}T10-00-00-{thread}.jsonl"
2027
+ sha = fx_write(path, fx_codex_records())
2028
+ key = f"{lineage.identity('codex', thread)}@{census.stem_of(path)}"
2029
+ coverage.observe(state, key, sha, len(fx_codex_records()), sha, None)
2030
+ files.append({**census.segment(census.stem_of(path), "codex_sessions", str(path)), "sha256": sha, "owned": owned,
2031
+ "work": coverage.work_of(state, key, owned, window_id), "versions": fx_versions(state, key)})
2032
+ entry = census.blank("codex", thread, "codex_sessions", status="eligible", counted=True, provenance="indexed", window_overlap="inside")
2033
+ entry["segments"] = files
2034
+ document = fx_census(window_id, [census.finish(entry)])
2035
+ run_dir.mkdir(parents=True, exist_ok=True)
2036
+ declare.create(run_dir, {**declare.fixture(), "window": FX_WINDOW})
2037
+ with records.run_stage(run_dir, "S1") as stage:
2038
+ records.write_text(run_dir, run_dir / "census.json", census.dump(document))
2039
+ written = state
2040
+ if base == "empty":
2041
+ written = coverage.new_state()
2042
+ elif base == "older":
2043
+ written = copy.deepcopy(state)
2044
+ for entry in written["transcripts"].values():
2045
+ entry["versions"][-1]["record_count"] -= 2
2046
+ records.write_json(run_dir, run_dir / "coverage.json", written)
2047
+ stage.output("census.json")
2048
+ stage.output("coverage.json")
2049
+ try:
2050
+ outcome = run(run_dir, 32_000)
2051
+ except Exception as exc: # the refusal, or what a reverted check raises: a control reads it, never a traceback
2052
+ outcome = exc
2053
+ return [f"{lineage.identity('codex', thread)}@{census.stem_of(f['path'])}" for f in files], outcome
2054
+
2055
+
2056
+ # ---- self-test --------------------------------------------------------------------------------
2057
+
2058
+ # The window invariants of plan WP-06 done-when 3 and 4: this is the self-test's branch list, and the
2059
+ # run below asserts that every one of them was exercised by a label of its own.
2060
+ INVARIANTS = ("owned once", "overlap", "span union", "error line", "bound (a)", "bound (d)", "unbounded",
2061
+ "observed input", "omission manifest", "completeness", "forced", "basis")
2062
+
2063
+
2064
+ class Checks:
2065
+ """The self-test's assertions, each under a label that is reported when it fails."""
2066
+
2067
+ def __init__(self):
2068
+ self.failures, self.ran = [], []
2069
+
2070
+ def expect(self, label, got, want):
2071
+ self.ran.append(label)
2072
+ if got != want:
2073
+ self.failures.append(f"{label}: got {got!r}, expected {want!r}")
2074
+
2075
+ def named(self, label, errors, *codes):
2076
+ """`errors` is a list of violation lines: it must carry every code, and with none it must be empty."""
2077
+ self.ran.append(label)
2078
+ if not codes and errors:
2079
+ self.failures.append(f"{label}: expected no violation, got {errors}")
2080
+ for code in codes:
2081
+ if not any(code in line for line in errors):
2082
+ self.failures.append(f"{label}: expected {code!r} in {errors}")
2083
+
2084
+ def refused(self, label, call, *codes):
2085
+ self.ran.append(label)
2086
+ try:
2087
+ call()
2088
+ except Refused as exc:
2089
+ self.named(label, [str(exc)], *codes)
2090
+ self.ran.pop()
2091
+ return
2092
+ except BaseException as exc: # a reverted check must not hide behind a traceback
2093
+ self.failures.append(f"{label}: raised {type(exc).__name__}: {exc}")
2094
+ return
2095
+ self.failures.append(f"{label}: nothing was refused")
2096
+
2097
+
2098
+ def fx_instrument():
2099
+ """The assertions are what everything below rests on, so they are tested first, by assert: a statement that
2100
+ vouches for itself vouches for nothing."""
2101
+ probe = Checks()
2102
+ probe.expect("wrong value", 1, 2)
2103
+ probe.named("missing code", ["CODE_A x"], "CODE_B")
2104
+ probe.named("unexpected violation", ["CODE_A x"])
2105
+ probe.refused("nothing refused", lambda: None, "CODE_A")
2106
+ probe.refused("wrong code", lambda: (_ for _ in ()).throw(Refused("CODE_A x")), "CODE_B")
2107
+ probe.refused("other exception", lambda: (_ for _ in ()).throw(ValueError("boom")), "CODE_A")
2108
+ probe.expect("right value", 1, 1)
2109
+ probe.refused("right code", lambda: (_ for _ in ()).throw(Refused("CODE_A x")), "CODE_A")
2110
+ labels = [f.split(":")[0] for f in probe.failures]
2111
+ assert labels == ["wrong value", "missing code", "unexpected violation", "nothing refused", "wrong code",
2112
+ "other exception"], f"the assertions do not fail by label: {probe.failures}"
2113
+
2114
+
2115
+ def fx_sweep(root, needles):
2116
+ """`{needle: [paths]}` for every file under `root` that holds one of `needles` as a fixed string - the sweep
2117
+ P4 and WP-06 done-when 2 run over a run directory, which is why no artifact of it is compressed."""
2118
+ found = {needle: [] for needle in needles}
2119
+ for path in sorted(pathlib.Path(root).rglob("*")):
2120
+ if not path.is_file():
2121
+ continue
2122
+ text = path.read_bytes()
2123
+ for needle in needles:
2124
+ if needle.encode("utf-8") in text:
2125
+ found[needle].append(str(path.relative_to(root)))
2126
+ return found
2127
+
2128
+
2129
+ def fx_texts(run_dir, line):
2130
+ """The projected text of every viewed block of one transcript's version."""
2131
+ return projection_texts(run_dir, line["redacted"])
2132
+
2133
+
2134
+ def fx_entries(windows):
2135
+ """The owned entries of a cut view, by their entry identity (a split message has one per span)."""
2136
+ return {eid(r): r for w in windows for r in w["records"]}
2137
+
2138
+
2139
+ def self_test():
2140
+ try:
2141
+ records.fixture_root("captures")
2142
+ except Refused as exc: # a tree without fixtures/ ends the suite by name, never by a traceback
2143
+ print(f"views --self-test: {exc}")
2144
+ return 1
2145
+ fx_instrument()
2146
+ checks = Checks()
2147
+ expect, named, refused = checks.expect, checks.named, checks.refused
2148
+ # the evidence store is a consumer of these windows, imported here so the production side of this
2149
+ # module does not depend on it
2150
+ from runlib import evidence as evidence_store
2151
+ with tempfile.TemporaryDirectory() as td:
2152
+ root = pathlib.Path(td)
2153
+ golden_run = golden(root, "tight", overhead=100_000)
2154
+ run_dir, manifest, main = golden_run["run_dir"], golden_run["manifest"], golden_run["main"]
2155
+ # The fixture's own precondition, named. `main` is None when the run quarantined the transcript the
2156
+ # rest of this self-test reads, and every assertion after it then died on a NoneType rather than
2157
+ # reporting which invariant refused the view - a regression that crashes names nothing.
2158
+ if main is None:
2159
+ print("views --self-test [FAIL] the fixture's main transcript was quarantined, so no control below ran: "
2160
+ + "; ".join(q.get("reason", "?") for q in manifest["quarantined"]))
2161
+ return 1
2162
+ windows, lines = golden_run["windows"], golden_run["lines"]
2163
+ texts = fx_texts(run_dir, main)
2164
+ name = main["name"]
2165
+ rid = lambda key, pointer="/message/content/0/content": f"{lines[key]}{pointer}" # noqa: E731
2166
+
2167
+ # ---- positive controls, before any planted violation ------------------------------------
2168
+ expect("the fixtures are declared golden", golden_run["realization"], "golden")
2169
+ expect("done-when 1: the immutable copy is named by its own sha256 and is read-only",
2170
+ (records.sha256_file(run_dir / main["source_copy"]) == main["version_sha"],
2171
+ oct((run_dir / main["source_copy"]).stat().st_mode & 0o777)), (True, "0o444"))
2172
+ expect("done-when 1: the copy is the transcript's bytes exactly, decompression aside",
2173
+ (run_dir / main["source_copy"]).read_bytes() == golden_run["paths"]["main"].read_bytes(), True)
2174
+ before = sorted(p.name for p in (run_dir / "sources").iterdir())
2175
+ expect("copying the same version twice leaves the one copy, and no temporary beside it",
2176
+ (copy_version(run_dir, golden_run["paths"]["main"], None, {"sha": main["version_sha"], "record_count": main["records"]})[1],
2177
+ sorted(p.name for p in (run_dir / "sources").iterdir())), (main["version_sha"], before))
2178
+ named("done-when 3, owned once and overlap: every owned entry is in exactly one window and each window's "
2179
+ "overlap is what the sequence puts around it",
2180
+ check_windows(records.read_json(run_dir / main["sequence"])["sequence"], windows))
2181
+ named("done-when 3, span union and error line: the shown stretches and the gaps tile every block, and every "
2182
+ "error line of a clipped result is kept whole", check_tiling(windows, texts))
2183
+ expect("done-when 3, bound (a) and (d): every window the stage cut is within the bound",
2184
+ [w["bound_ok"] for w in windows], [True] * len(windows))
2185
+ expect("a message larger than a window is split into mapped spans whose union is the message",
2186
+ (len([e for e in fx_entries(windows) if e.startswith(f"{lines['long']}/")]) > 1,
2187
+ coverage.normalize([s["block"] for e in fx_entries(windows).values() if e["line"] == lines["long"]
2188
+ for s in e["segments"]])),
2189
+ (True, [[0, len(texts[f"{lines['long']}/message/content/0/text"])]]))
2190
+ expect("design §5.2: every entry carries a window role, and the three the design names are all reached",
2191
+ sorted({role_label(r["window_role"]) for t in manifest["transcripts"]
2192
+ for w in [records.read_json(run_dir / f["path"]) for f in t["windows"]]
2193
+ for r in w["records"] + [{"window_role": e["window_role"]} for e in w["overlap"]["prev"] + w["overlap"]["next"]]}),
2194
+ ["backlog", "context", "in_window"])
2195
+ expect("the child transcript is viewed as the parent's, with the parent's instruction shown as delegated",
2196
+ (golden_run["child"]["kind"], sorted({r["kind"] for w in [records.read_json(run_dir / f["path"])
2197
+ for f in golden_run["child"]["windows"]] for r in w["records"]})),
2198
+ ("child", ["assistant", "delegated"]))
2199
+ expect("the Codex session's blocks are read through its own record shape",
2200
+ sorted({r["kind"] for w in [records.read_json(run_dir / f["path"]) for f in golden_run["codex"]["windows"]]
2201
+ for r in w["records"]}), ["human", "tool_call", "tool_result"])
2202
+ # S2 holds two producers (records.STAGE_PARTS): this stage run is the views part, and the
2203
+ # stage itself is complete only once the inventory part has run too.
2204
+ expect("the views part of S2 is complete with views.json as its output",
2205
+ [(r["parts"]["views"]["status"], [o["artifact"] for o in r["parts"]["views"]["outputs"]])
2206
+ for s, r in records.stage_records(run_dir).items() if s == "S2"],
2207
+ [("complete", ["views.json"])])
2208
+ expect("the stage is partial while the other part of S2 has not run",
2209
+ [r["status"] for s, r in records.stage_records(run_dir).items() if s == "S2"], ["partial"])
2210
+ expect("the totals of views.json add up over the transcripts it lists",
2211
+ (manifest["totals"]["windows"], manifest["totals"]["clipped"]),
2212
+ (sum(len(t["windows"]) for t in manifest["transcripts"]), sum(t["clipped"] for t in manifest["transcripts"])))
2213
+ expect("the kept shape counts are carried as hints over every block of the version, viewed or not, "
2214
+ "and no claim rests on one",
2215
+ (main["hints"]["human_turns"], main["hints"]["assistant_turns"], main["hints"]["tool_calls"],
2216
+ main["hints"]["error_results"], main["hints"]["tools"]),
2217
+ # the tool's name is counted as the projection wrote it: the hint is a shape, and a hint that
2218
+ # carried the unmasked name would be one more place the name reached
2219
+ (2, 5, 1, 1, {projection.project(FX_TOOL_SECRET): 1}))
2220
+ expect("the report is counts, window numbers and byte totals, and holds no transcript text",
2221
+ [line for line in report_lines(manifest) if FX_TERM in line or FX_HOME in line], [])
2222
+
2223
+ # ---- done-when 2: the projection is the only text, and the planted secret and path stay in the raw copy
2224
+ # M#3: the planted shape stands in a tool NAME as well as in a block's text, and the sweep looks for
2225
+ # it in both - a name `header_of` renders into the window is as model-visible as the text under it.
2226
+ expect("done-when 2: the tool name a window renders is the projection's, not the transcript's",
2227
+ [line for w in windows for r in w["records"] for line in [header_of(r, "e1")] if FX_SECRET[:10] in line], [])
2228
+ # P#2: the timestamp a window renders is a timestamp by construction - parsed and written back in one
2229
+ # normal form - so a host string carrying a secret or a path cannot stand in it
2230
+ expect("done-when 2: a record whose timestamp carried the planted shape renders no timestamp at all, "
2231
+ "and neither the shape nor the path reaches a header",
2232
+ [line for w in windows for r in w["records"] for line in [header_of(r, "e1")]
2233
+ if FX_SECRET[:10] in line or FX_HOME in line], [])
2234
+ expect("done-when 2: every timestamp a window carries is one `fromisoformat` parses and this code "
2235
+ "re-emitted, never the host's own string",
2236
+ sorted({r["ts"] for w in windows for r in w["records"] if r["ts"]}
2237
+ - {normal_stamp(r["ts"]) for w in windows for r in w["records"] if r["ts"]}), [])
2238
+ expect("done-when 2: ... and the projection file carries no unparsable timestamp either",
2239
+ [line["ts"] for line in (json.loads(l) for l in
2240
+ (run_dir / main["redacted"]).read_text(encoding="utf-8").splitlines() if l.strip())
2241
+ if line["ts"] is not None and normal_stamp(line["ts"]) != line["ts"]], [])
2242
+ expect("done-when 2: the projection file carries no unmasked tool name either",
2243
+ [b for line in (json.loads(l) for l in
2244
+ (run_dir / main["redacted"]).read_text(encoding="utf-8").splitlines() if l.strip())
2245
+ for b in line["items"] if FX_SECRET[:10] in (b.get("tool") or "")], [])
2246
+ # V#2: the sweep claims the EVIDENCE store too, and the golden run creates none - so the claim was
2247
+ # over an empty directory. Quotes are made here, from the very blocks that carry the planted shapes,
2248
+ # verified and stored, before the sweep runs. A masked quote must verify; a quote of the raw secret
2249
+ # must not exist in the projection at all, which is the same statement from the other side.
2250
+ quoted = []
2251
+ for record_key, needle in (("second_human", "and the other thing?"),
2252
+ ("second_human", projection.FLOOR.PLACEHOLDER)):
2253
+ entry = fx_entries(windows).get(f"{lines[record_key]}/message/content")
2254
+ if entry is None or needle not in entry["text"]:
2255
+ continue
2256
+ made = evidence_store.from_view(run_dir, main["version_sha"], entry, needle,
2257
+ occurrence=0 if entry["text"].count(needle) > 1 else None)
2258
+ expect(f"V#2: a quote of the projected text ({needle[:24]!r}) verifies against the immutable copy",
2259
+ evidence_store.verify(run_dir, made), [])
2260
+ evidence_store.append(run_dir, "wp06-r4", made)
2261
+ quoted.append(made["evidence_id"])
2262
+ expect("V#2: the evidence store is not empty, so the sweep below judges something",
2263
+ (len(quoted) > 0, len(evidence_store.load(run_dir, "wp06-r4"))), (True, len(quoted)))
2264
+ for planted in (FX_PLANTED_JSON, FX_PLANTED_HEADER, FX_SECRET):
2265
+ refused(f"V#2: a quote of the raw secret {planted[:14]!r} cannot be made from the projection at all",
2266
+ lambda needle=planted: evidence_store.from_quote(
2267
+ run_dir, main["version_sha"], lines["second_human"], "/message/content", needle,
2268
+ "in_window"),
2269
+ "QUOTE_MISMATCH")
2270
+ sweep = fx_sweep(run_dir, [FX_SECRET[:10], FX_RAW_PATH, FX_PLANTED_JSON, FX_PLANTED_HEADER])
2271
+ expect("done-when 2 / R#0: the planted token, home path, the value behind a floor match that crosses "
2272
+ "JSON syntax, the credential after a multiline scheme, and an encoded home path used as a "
2273
+ "dictionary key are in no projection, window, index, evidence or report, and the raw copy "
2274
+ "keeps them (the instrument control: a sweep that found nothing anywhere proves nothing)",
2275
+ ({needle: sorted({p.split("/")[0] for p in paths}) for needle, paths in sweep.items()}),
2276
+ {FX_SECRET[:10]: ["sources"], FX_RAW_PATH: ["sources"], FX_PLANTED_JSON: ["sources"],
2277
+ FX_PLANTED_HEADER: ["sources"]})
2278
+ # An encoded home path is a question about the DECODED text, not about bytes: the artifacts are JSON,
2279
+ # so a backslash in the text is `\\` in the file and a byte sweep for the encoded form finds it
2280
+ # nowhere - in the raw copy either, which is how such a sweep reports clean over nothing.
2281
+ decoded_texts = [b["text"] for line in (json.loads(l) for l in
2282
+ (run_dir / main["redacted"]).read_text(encoding="utf-8").splitlines()
2283
+ if l.strip()) for b in line["items"]]
2284
+ raw_copy = (run_dir / main["source_copy"]).read_text(encoding="utf-8")
2285
+ expect("R#0: the raw copy really holds the encoded home path, so the next control judges something",
2286
+ FX_ENCODED_HOME.replace("\\", "\\\\") in raw_copy, True)
2287
+ expect("R#0: ... and no projected block's decoded text holds it, however it was encoded",
2288
+ [t[:40] for t in decoded_texts if FX_ENCODED_HOME in t or FX_HOME in t], [])
2289
+ expect("done-when 2: the home path is masked in the view, the rest of the path kept",
2290
+ f"see {projection.HOME_MASK}/Documents/repo/notes.md" in fx_entries(windows)[f"{lines['human']}/message/content"]["text"], True)
2291
+
2292
+ # ---- Q#0, Q#2 and A#3: the decoded shapes, through the whole stage -----------------------
2293
+ #
2294
+ # The projection's own controls judge `project_text`. These judge the ARTIFACTS: a transcript of the
2295
+ # blocks whose secrets only decoding reaches, and of the blocks whose obligations only the original
2296
+ # text can see, run through the stage so the sweep covers the projection, the windows, the index and
2297
+ # a stored evidence record. Positive controls first - the run really reaches those sources, and the
2298
+ # store really holds a record - because a sweep over nothing reports clean.
2299
+ # The projection has ONE path now, so there is no fallback to count. What these controls judge
2300
+ # instead is that the transcript really exercised the masking sources the cases are about: an
2301
+ # encoded literal, an encoded secret-named key, and an escaped region.
2302
+ sources_before = {key: projection.STATS[key] for key in
2303
+ ("encoded_secret_key", "unmappable_escape", "undecodable_claim")}
2304
+ fb = golden(root, "fb", main_records=fx_fallback_records, owned=[[0, 27]])
2305
+ fb_dir, fb_main = fb["run_dir"], fb["main"]
2306
+ expect("Q#2 / A#3: projecting this transcript really exercised the decoded sources these controls "
2307
+ "are about, so they judge the path they name",
2308
+ projection.STATS["encoded_secret_key"] > sources_before["encoded_secret_key"], True)
2309
+ fb_entries = fx_entries([window_doc(fb_dir, fb_main["name"], fb_dir / f["path"])
2310
+ for f in fb_main["windows"]])
2311
+ fb_texts = projection_texts(fb_dir, fb_main["redacted"])
2312
+ planted_by_name = {"FX_FALLBACK_SCALAR": FX_FALLBACK_SCALAR, "FX_HOME": FX_HOME,
2313
+ "FX_OBLIGATION_JSON": FX_OBLIGATION_JSON,
2314
+ "FX_OBLIGATION_QUOTED": FX_OBLIGATION_QUOTED,
2315
+ "FX_ESCAPED_ARRAY": FX_ESCAPED_ARRAY, "FX_QUOTED_SCALAR": FX_QUOTED_SCALAR,
2316
+ "FX_MASK_NEIGHBOUR": FX_MASK_NEIGHBOUR, "FX_ESCAPED_TAIL": FX_ESCAPED_TAIL,
2317
+ "FX_SIBLING_KEY": FX_SIBLING_KEY, "FX_MIXED_DEPTH": FX_MIXED_DEPTH,
2318
+ "FX_NO_QUOTE_BODY": FX_NO_QUOTE_BODY,
2319
+ "FX_STRUCTURED_CROSS": FX_STRUCTURED_CROSS,
2320
+ "FX_MEMBER_NEWLINE": FX_MEMBER_NEWLINE, "FX_MIXED_TEXT": FX_MIXED_TEXT,
2321
+ "FX_LONG_NAME": FX_LONG_NAME, "FX_MASK_COMMA": FX_MASK_COMMA,
2322
+ "FX_ESCAPE_RUN": FX_ESCAPE_RUN, "FX_DUPLICATE_LAST": FX_DUPLICATE_LAST,
2323
+ "FX_READABLE_ARRAY": FX_READABLE_ARRAY,
2324
+ "FX_READABLE_OBJECT": FX_READABLE_OBJECT,
2325
+ "FX_SCALAR_SUFFIX": FX_SCALAR_SUFFIX,
2326
+ "FX_NEWLINE_SEPARATOR": FX_NEWLINE_SEPARATOR}
2327
+ fb_quoted = []
2328
+ def every_spelling_of(value):
2329
+ """Every spelling of a planted value that this transcript or the projection can write."""
2330
+ return list(projection.spellings(value)) + [
2331
+ value, value.replace("/", "\\u002f"), value.replace("/", "\\\\/"),
2332
+ "".join(f"\\u{ord(character):04x}" for character in value)]
2333
+
2334
+ # The vocabulary is built from the records' OWN strings rather than from a JSON dump of them: a dump
2335
+ # re-escapes every backslash, so the encoded spelling of a planted value no longer matched the text
2336
+ # being cleaned and stayed in the vocabulary - which then subtracted it from the very subjects it
2337
+ # should have been.
2338
+ cleaned = []
2339
+ for record in fx_fallback_records():
2340
+ for form in projection.spellings_of(record):
2341
+ for value in planted_by_name.values():
2342
+ for spelling in every_spelling_of(value):
2343
+ form = form.replace(spelling, " ")
2344
+ cleaned.append(form)
2345
+ ordinary = " ".join(cleaned)
2346
+ vocabulary = search.keys_of(ordinary)[0]
2347
+
2348
+ # V#3: every row of the table states which detector must find it, and a CLEAN counterpart of the
2349
+ # same shape must be found by none - a row whose shape is blanked whatever it holds proves nothing
2350
+ # about the detector it names.
2351
+ def one_span_difference(clean, dirty):
2352
+ """`(whether the two differ in exactly one span, what stands there in the dirty text)`.
2353
+
2354
+ A common prefix and a common suffix leave one span in each text; the pair is a pair only when
2355
+ the dirty span is the target value and the clean span is what the row masks it to."""
2356
+ start = 0
2357
+ while start < min(len(clean), len(dirty)) and clean[start] == dirty[start]:
2358
+ start += 1
2359
+ end = 0
2360
+ while (end < min(len(clean), len(dirty)) - start
2361
+ and clean[len(clean) - 1 - end] == dirty[len(dirty) - 1 - end]):
2362
+ end += 1
2363
+ return True, dirty[start:len(dirty) - end]
2364
+
2365
+ # Y#2: the dirty text of each pair is a LITERAL copy of the persisted row's own text, with exactly
2366
+ # the target value changed - not the row with its first mask substituted, which produced a different
2367
+ # shape and so read a rule the fixture does not run. The mask-plus-comma row keeps its comma; the
2368
+ # newline-separated member is the one that changes, not the nested member before it.
2369
+ row_detectors = {
2370
+ "FX_LONG_NAME": ("keyed fragment",
2371
+ '{"note":"plain"} "' + "x" * 38 + '\\u0070assword":"'
2372
+ + projection.FLOOR.PLACEHOLDER + '"',
2373
+ '{"note":"plain"} "' + "x" * 38 + '\\u0070assword":"' + FX_LONG_NAME + '"'),
2374
+ "FX_MASK_COMMA": ("keyed fragment",
2375
+ '{"note":"plain"} "\\u0070assword":"'
2376
+ + projection.FLOOR.PLACEHOLDER + '"',
2377
+ '{"note":"plain"} "\\u0070assword":"'
2378
+ + projection.FLOOR.PLACEHOLDER + ',' + FX_MASK_COMMA + '"'),
2379
+ "FX_ESCAPE_RUN": ("verifier-limit", '{"note":"plain"} \\n ordinary words',
2380
+ '{"note":"plain"} \\\n' + FX_ESCAPE_RUN),
2381
+ "FX_DUPLICATE_LAST": ("secret-named key",
2382
+ '{"password":"' + projection.FLOOR.PLACEHOLDER + '","password":"'
2383
+ + projection.FLOOR.PLACEHOLDER + '"}',
2384
+ '{"password":"' + FX_DUPLICATE_LAST + '","password":"'
2385
+ + projection.FLOOR.PLACEHOLDER + '"}'),
2386
+ "FX_MEMBER_NEWLINE": ("secret-named key",
2387
+ '{"safe":{"password":"' + projection.FLOOR.PLACEHOLDER
2388
+ + '"},"password"\n:"' + projection.FLOOR.PLACEHOLDER + '"}',
2389
+ '{"safe":{"password":"' + projection.FLOOR.PLACEHOLDER
2390
+ + '"},"password"\n:"' + FX_MEMBER_NEWLINE + '"}'),
2391
+ "FX_MIXED_TEXT": ("keyed fragment",
2392
+ '{"note":"plain"} "\\u0070assword":"'
2393
+ + projection.FLOOR.PLACEHOLDER + '"',
2394
+ '{"note":"plain"} "\\u0070assword":"' + FX_MIXED_TEXT + '"'),
2395
+ }
2396
+
2397
+ # W#3: separator gaps at and beyond the span the old rule capped at eight characters - the pair
2398
+ # differs only in the number of spaces, so what the control reads is the rule and not the shape.
2399
+ for spaces in (0, 1, 7, 8, 9, 40):
2400
+ gap = " " * spaces
2401
+ dirty = '{"note":"plain"} "\\u0070assword"' + gap + ':"w3gap_canary"'
2402
+ clean = '{"note":"plain"} "\\u0070assword"' + gap + ':"' + projection.FLOOR.PLACEHOLDER + '"'
2403
+ # AB#1: the clean case first for each gap, so a detector that fires on everything is read as
2404
+ # a failure here rather than confirmed by the dirty assertion that follows it
2405
+ expect(f"W#3: the clean counterpart at {spaces} space(s) is found by nothing",
2406
+ projection.discloses(clean, FX_HOME), None)
2407
+ expect(f"W#3: ... and a separator {spaces} space(s) after the key is read",
2408
+ projection.discloses(dirty, FX_HOME), "keyed fragment")
2409
+
2410
+ # X#4: the pairs are the PERSISTED rows, with the planted value swapped for the mask and nothing
2411
+ # else changed - the previous pair substituted a shape of its own, so it read a rule the fixture
2412
+ # does not run. The clean case is asserted first in each pair.
2413
+ persisted_pairs = [
2414
+ ("X#3 / V#0: a readable array under an encoded key",
2415
+ '{"note":"plain"} "\\u0070assword":["%s"]', FX_READABLE_ARRAY, "keyed fragment"),
2416
+ ("X#3 / V#0: a readable object under an encoded key",
2417
+ '{"note":"plain"} "\\u0070assword":{"inner":"%s"}', FX_READABLE_OBJECT, "keyed fragment"),
2418
+ ("X#3 / V#1: a suffix after a masked scalar",
2419
+ '{"note":"plain"} "\\u0070assword":"' + projection.FLOOR.PLACEHOLDER + '"%s',
2420
+ FX_SCALAR_SUFFIX, "keyed fragment"),
2421
+ ("X#3 / V#2: a quoted key whose separator is on the next line",
2422
+ '{"note":"plain"} "password"\n: "%s"', FX_NEWLINE_SEPARATOR, "keyed fragment"),
2423
+ ]
2424
+ for label, shape, planted, detector in persisted_pairs:
2425
+ clean = shape % projection.FLOOR.PLACEHOLDER if "%s" in shape else shape
2426
+ if label.endswith("a suffix after a masked scalar"):
2427
+ clean = shape % "" # the suffix removed, which is this row's only difference
2428
+ expect(f"X#4: {label}: the masked form of the persisted row is found by nothing",
2429
+ projection.discloses(clean, FX_HOME), None)
2430
+ expect(f"X#4: {label}: the row as the transcript writes it is found by {detector!r}",
2431
+ projection.discloses(shape % planted, FX_HOME), detector)
2432
+
2433
+ for planted_name, (detector, clean, dirty) in sorted(row_detectors.items()):
2434
+ planted = planted_by_name[planted_name]
2435
+ # Y#2: clean and dirty differ in exactly ONE span, and that span is the target value
2436
+ # Y#2: the two texts differ in exactly ONE span, and that span carries the target value. For
2437
+ # the mask-plus-comma row the span is the comma and the value, which is what that row is about;
2438
+ # for the escape-run row it is the run, which is what THAT row is about.
2439
+ single, span = one_span_difference(clean, dirty)
2440
+ subject = planted if planted_name != "FX_ESCAPE_RUN" else FX_ESCAPE_RUN
2441
+ # the span is the target value, and what else it holds is only the punctuation the row is
2442
+ # about - stated per row rather than compared with itself
2443
+ extra = {"FX_MASK_COMMA": ",", "FX_ESCAPE_RUN": "\n"}.get(planted_name, "")
2444
+ expect(f"Y#2: {planted_name}: clean and dirty differ in exactly one span, and that span is the "
2445
+ f"target value{' with the punctuation this row is about' if extra else ''}",
2446
+ (single, span), (True, extra + subject))
2447
+ # the clean case first, then the exact detector the row is about
2448
+ expect(f"V#3: {planted_name}: its clean counterpart is found by nothing",
2449
+ projection.discloses(clean, FX_HOME), None)
2450
+ expect(f"V#3: {planted_name}: the shape is found by {detector!r}",
2451
+ projection.discloses(dirty, FX_HOME), detector)
2452
+
2453
+ fb_index = search.load(fb_dir / fb_main["index"])
2454
+ for label, line, pointer, planted_name in FX_FALLBACK_CASES:
2455
+ planted, record = planted_by_name[planted_name], f"{line}{pointer}"
2456
+ # the case is at the locator it names, and the window owns it
2457
+ entry = fb_entries.get(record) or next(
2458
+ (e for key, e in fb_entries.items() if key.startswith(record)), None)
2459
+ if entry is None:
2460
+ checks.failures.append(f"Z#1: {label}: no window owns {record}, so nothing below judges it")
2461
+ continue
2462
+ expect(f"Z#1: {label}: the projected block at {record} holds no part of the planted value",
2463
+ [form for form in projection.spellings(planted)
2464
+ if len(form) >= projection.PARTIAL_SURVIVAL and form in fb_texts.get(record, "")], [])
2465
+ expect(f"Z#1: ... and the projection of that block discharges every obligation of the original",
2466
+ projection.readable_survivors(
2467
+ projection.serialise(
2468
+ evidence_store.read_block(fb_dir / fb_main["source_copy"], line, pointer) or ""),
2469
+ fb_texts.get(record, "")), [])
2470
+ # S#3: the row's own window, read by decoding rather than by bytes. The sweep below covers the
2471
+ # whole run; this says the block's own window is clean, which is what the row is about.
2472
+ projected = fb_texts.get(record, "")
2473
+ expect(f"S#3: {label}: no decoding of this block's window text reads the planted value",
2474
+ [form for form in projection.spellings_of(projected)
2475
+ if planted.lower() in form.lower()], [])
2476
+ # T#4: the PERSISTED window files, read from disk and decoded - not the projection file the
2477
+ # row's text came from. A window is what a reader opens, and it is written separately.
2478
+ window_hits = []
2479
+ for window in fb_main["windows"]:
2480
+ body = (fb_dir / window["path"]).read_text(encoding="utf-8", errors="replace")
2481
+ if any(planted.lower() in form.lower() for form in projection.spellings_of(body)):
2482
+ window_hits.append(window["path"])
2483
+ expect(f"T#4: {label}: no persisted window file reads the planted value, decoded or raw",
2484
+ window_hits, [])
2485
+ expect(f"S#3: {label}: the index holds no distinctive posting key of this row",
2486
+ sorted(key for key in {k for form in every_spelling_of(planted)
2487
+ for k in search.keys_of(form)[0]} - vocabulary
2488
+ if key in fb_index.postings), [])
2489
+ expect(f"R#4: {label}: projecting the projected block again changes nothing",
2490
+ projection.project(projected, home=FX_HOME), projected)
2491
+ made = evidence_store.from_view(fb_dir, fb_main["version_sha"], entry,
2492
+ projection.FLOOR.PLACEHOLDER, occurrence=0)
2493
+ expect(f"Z#1: ... and a masked quote AT THAT LOCATOR verifies against the immutable copy",
2494
+ (evidence_store.verify(fb_dir, made), made["line"], made["json_pointer"]),
2495
+ ([], line, pointer))
2496
+ evidence_store.append(fb_dir, "wp06-r6", made)
2497
+ fb_quoted.append(made["evidence_id"])
2498
+ # T#4: and the record as the STORE holds it, read back rather than trusted from memory
2499
+ stored = [record for record in evidence_store.load(fb_dir, "wp06-r6")
2500
+ if record["evidence_id"] == made["evidence_id"]]
2501
+ expect(f"T#4: {label}: the stored evidence record holds the mask and verifies from the copy",
2502
+ [(record["redacted_text"], evidence_store.verify(fb_dir, record)) for record in stored],
2503
+ [(projection.FLOOR.PLACEHOLDER, [])])
2504
+ refused(f"Z#1: ... while a quote of the raw value at that same locator is refused",
2505
+ lambda needle=planted, at=line, ptr=pointer: evidence_store.from_quote(
2506
+ fb_dir, fb_main["version_sha"], at, ptr, needle, "in_window"),
2507
+ "QUOTE_MISMATCH")
2508
+ expect("Z#1: every planted case was judged at its own locator, and each left a stored record",
2509
+ (len(fb_quoted), len(evidence_store.load(fb_dir, "wp06-r6"))),
2510
+ (len(FX_FALLBACK_CASES), len(FX_FALLBACK_CASES)))
2511
+ # A#3: the index is inspected by its POSTINGS, not by asking it a question. `search` re-checks every
2512
+ # candidate against the projected text, so an index full of secret postings answers "no hits" while
2513
+ # carrying the secret in a file a reader can open. The postings are the artifact; they are what must
2514
+ # be clean.
2515
+ fb_index = search.load(fb_dir / fb_main["index"])
2516
+ # The vocabulary of this transcript with the planted values taken OUT: a key in it is ordinary
2517
+ # English the fixture's prose contains anyway, and asking the index to lack `secret` or `users` would
2518
+ # fail on the prose rather than on a leak. What remains - the keys only a planted value produces -
2519
+ # is this control's subject, and each case must contribute at least one or it judges nothing.
2520
+ for label, _line, _pointer, planted_name in FX_FALLBACK_CASES:
2521
+ planted = planted_by_name[planted_name]
2522
+ # M#4: every spelling the value is ACTUALLY emitted in - the plain one, each of the projection's
2523
+ # own spellings, and the encoded and slash-escaped forms the transcript writes - tokenised by
2524
+ # the index's own tokeniser rather than by a guess about what a key looks like.
2525
+ spelled = every_spelling_of(planted)
2526
+ distinctive = sorted({key for form in spelled for key in search.keys_of(form)[0]} - vocabulary)
2527
+ expect(f"A#3: {label} has a posting key of its own, so the index control below is about it",
2528
+ len(distinctive) > 0, True)
2529
+ present = sorted(key for key in distinctive if key in fb_index.postings)
2530
+ expect(f"A#3: the index holds no posting key of {label} - in any spelling of the value",
2531
+ present, [])
2532
+ hits = search.search(fb_index, [planted], lambda ref: fb_texts.get(f"{ref[0]}{ref[1]}", ""))
2533
+ expect(f"A#3: ... and the search over it matches nothing for that value either", hits, [])
2534
+ # ... and every artifact of this run is swept in its DECODED strings as well as its bytes, for both
2535
+ # spellings of the owner's path: the encoded one is what the source locator carries
2536
+ # E#5: every artifact is read by its OWN shape - a `.json` file parsed whole, a `.jsonl` file
2537
+ # parsed per record - and then every string in it is decoded by the verifier's decoder. Reading the
2538
+ # bytes alone misses a credential split across a record's escaping, and reading only one run's
2539
+ # projection misses contamination that lives in an index or a window and nowhere else.
2540
+ encoded_home = FX_HOME.replace("/", "\\u002f")
2541
+ slash_home = FX_HOME.replace("/", "\\\\/")
2542
+ decoded_strings, parsed_artifacts = [], 0
2543
+ for path in sorted(fb_dir.rglob("*")):
2544
+ if not path.is_file() or "sources" in path.parts:
2545
+ continue
2546
+ where = str(path.relative_to(fb_dir))
2547
+ raw = path.read_text(encoding="utf-8", errors="replace")
2548
+ decoded_strings.append((where, raw))
2549
+ documents = []
2550
+ if path.suffix == ".json":
2551
+ try:
2552
+ documents.append(json.loads(raw))
2553
+ parsed_artifacts += 1
2554
+ except ValueError:
2555
+ expect(f"E#5: {where} is a .json artifact that parses, so its strings can be read",
2556
+ False, True)
2557
+ elif path.suffix == ".jsonl":
2558
+ for line in raw.splitlines():
2559
+ if not line.strip():
2560
+ continue
2561
+ try:
2562
+ documents.append(json.loads(line))
2563
+ except ValueError:
2564
+ expect(f"E#5: every record of {where} parses, so its strings can be read",
2565
+ False, True)
2566
+ parsed_artifacts += 1 if documents else 0
2567
+ for document in documents:
2568
+ decoded_strings += [(where, form) for form in projection.spellings_of(document)]
2569
+ expect("E#5: the run's .json and .jsonl artifacts were parsed by their own shape, so the sweep "
2570
+ "below reads their strings and not only their bytes", parsed_artifacts > 3, True)
2571
+ expect("A#3: the artifacts of the fallback run really were read, so the sweep below judges them",
2572
+ len(decoded_strings) > 10, True)
2573
+ # ---- M#2: an artifact made under the PREDECESSOR's projection is refused at every boundary -----
2574
+ #
2575
+ # The projection changed, so its version changed with it: r9 masked less than r10 does, and a window,
2576
+ # an index or an evidence record built under r9 is text the current masking exists to withhold. Each
2577
+ # boundary is asked separately, because each one is a different reader.
2578
+ stale_cases = []
2579
+ stale_window = dict(json.loads((fb_dir / fb_main["windows"][0]["path"]).read_text(encoding="utf-8")))
2580
+ stale_window["redaction_version"] = "r21"
2581
+ try:
2582
+ current_version(stale_window, "a window made under r21")
2583
+ stale_cases.append("a window made under r21 was accepted")
2584
+ except Refused as exc:
2585
+ if "REDACTION_VERSION_MISMATCH" not in str(exc):
2586
+ stale_cases.append(f"a stale window was refused unnamed: {exc}")
2587
+ stale_index_root = fb_dir.parent / "stale-index"
2588
+ shutil.copytree(fb_dir, stale_index_root)
2589
+ stale_index_path = stale_index_root / fb_main["index"]
2590
+ stale_index = json.loads(stale_index_path.read_text(encoding="utf-8"))
2591
+ stale_index["redaction_version"] = "r21"
2592
+ stale_index_path.write_text(json.dumps(stale_index, ensure_ascii=False), encoding="utf-8")
2593
+ try:
2594
+ search.load(stale_index_path, projection.CURRENT)
2595
+ stale_cases.append("an index made under r21 was accepted")
2596
+ except Exception as exc:
2597
+ if "REDACTION_VERSION_MISMATCH" not in str(exc):
2598
+ stale_cases.append(f"a stale index was refused unnamed: {exc}")
2599
+ shutil.rmtree(stale_index_root)
2600
+ try:
2601
+ projection.project("x", "r21")
2602
+ stale_cases.append("the r21 projection is still callable, so a stale artifact can be remade")
2603
+ except KeyError as exc:
2604
+ if "REDACTION_VERSION_MISMATCH" not in str(exc):
2605
+ stale_cases.append(f"the r21 projection was refused unnamed: {exc}")
2606
+ expect("M#2: a window, an index and the projection itself all refuse r21 by name", stale_cases, [])
2607
+
2608
+ # M#8: the blanking is recorded where a reader of the run can see it. A figure nobody keeps is a
2609
+ # figure nobody can act on - and these transcripts really do blank blocks, so the field is not an
2610
+ # always-empty map.
2611
+ expect("M#8: the run's view stats carry a blanked-block count by detector",
2612
+ isinstance(fb_main.get("blanked"), dict), True)
2613
+ expect("M#8: a transcript whose blocks the mapping cannot cover records at least one blanked block",
2614
+ sum(fb_main.get("blanked", {}).values()) > 0, True)
2615
+ # S#5: read from the run's own views.json. The two-leaf block above is in the transcript, so one
2616
+ # blanked content block and two blanking operations is a statement about what the stage recorded -
2617
+ # not about counters a control moved itself, which would pass even if both fields held the same
2618
+ # figure.
2619
+ # T#6: the two-leaf block in a transcript of ITS OWN, so the figures are not an aggregate over
2620
+ # other blanking blocks, and views.json is reopened from disk rather than read from the return value.
2621
+ def fx_two_leaf_only():
2622
+ layered_leaf = "sk" + "\\\\u005c" * 6 + "u002d" + FX_TWO_LEAF
2623
+ return [fx_human(fx_stamp(1), "one block, two leaves"),
2624
+ fx_call(fx_stamp(2), "Write", {"a": layered_leaf, "b": layered_leaf + "two",
2625
+ "c": "plain words"})]
2626
+
2627
+ isolated = golden(root, "two-leaf", main_records=fx_two_leaf_only, owned=[[0, 3]])
2628
+ reopened = json.loads((isolated["run_dir"] / "views.json").read_text(encoding="utf-8"))
2629
+ transcripts = reopened["transcripts"] if "transcripts" in reopened else [reopened]
2630
+ mine = [entry for entry in transcripts if entry.get("blanked")]
2631
+ expect("T#6: the isolated transcript's views.json records exactly one blanked content block and two "
2632
+ "blanking operations",
2633
+ [(entry.get("blanked"), entry.get("blank_operations")) for entry in mine],
2634
+ [({"floor": 1}, {"floor": 2})])
2635
+
2636
+ # V#3 / T#2: the unfinished-escape row, counted from a persisted run of its OWN. The fixture is
2637
+ # chosen so the mapping cannot be what blanked it: no floor match, no locatable keyed value, only a
2638
+ # run this verifier cannot finish - so a verifier-limit count of exactly one block and one operation
2639
+ # is a statement about the verifier and about nothing else.
2640
+ def fx_escape_run_only():
2641
+ return [fx_human(fx_stamp(1), "one block with an unfinished escape run"),
2642
+ fx_assistant(fx_stamp(2), '{"note":"plain"} \\\n' + FX_ESCAPE_RUN)]
2643
+
2644
+ run_only = golden(root, "escape-run", main_records=fx_escape_run_only, owned=[[0, 3]])
2645
+ run_main = json.loads((run_only["run_dir"] / "views.json").read_text(encoding="utf-8"))
2646
+ entries = run_main["transcripts"] if "transcripts" in run_main else [run_main]
2647
+ counted = [(entry.get("blanked"), entry.get("blank_operations"))
2648
+ for entry in entries if entry.get("blanked")]
2649
+ expect("V#3 / T#2: an isolated run of the unfinished-escape block records exactly one blanked "
2650
+ "content block and one blanking operation, both for verifier-limit",
2651
+ counted, [({"verifier-limit": 1}, {"verifier-limit": 1})])
2652
+ expect("V#3 / T#2: and the credential is in none of that run's artifacts, decoded or raw",
2653
+ [str(path.relative_to(run_only["run_dir"]))
2654
+ for path in sorted(run_only["run_dir"].rglob("*"))
2655
+ if path.is_file() and "sources" not in path.parts
2656
+ and any(FX_ESCAPE_RUN in form for form in projection.spellings_of(
2657
+ path.read_text(encoding="utf-8", errors="replace")))], [])
2658
+
2659
+ floor_blocks = fb_main.get("blanked", {}).get("floor", 0)
2660
+ floor_operations = fb_main.get("blank_operations", {}).get("floor", 0)
2661
+ expect("S#5: the run recorded blanked content blocks and blanking operations, and the two-leaf "
2662
+ "block is the one block that contributes a SECOND operation - so the operations exceed the "
2663
+ "blocks by exactly one",
2664
+ (floor_blocks > 0, floor_operations - floor_blocks), (True, 1))
2665
+ layered = "sk" + "\\\\u005c" * 6 + "u002dr6leafabcdefghijkl"
2666
+ ops_before = sum(projection.BLANKED.values())
2667
+ blocks_before = sum(projection.BLOCKS.values())
2668
+ projection.project({"a": layered, "b": layered + "two", "c": "plain words"}, home=FX_HOME)
2669
+ expect("R#6: a structured block with two blanking leaves counts two operations",
2670
+ sum(projection.BLANKED.values()) - ops_before, 2)
2671
+ expect("R#6: ... and exactly one blanked content block",
2672
+ sum(projection.BLOCKS.values()) - blocks_before, 1)
2673
+ expect("R#6: the run records blanked content blocks and blanking operations separately",
2674
+ sorted(fb_main.get("blank_operations", {}).values(), reverse=True)[:1]
2675
+ >= sorted(fb_main.get("blanked", {}).values(), reverse=True)[:1], True)
2676
+ expect("M#8: the recorded reasons are the verifier's own detector names",
2677
+ sorted(set(fb_main.get("blanked", {})) - {"floor", "home path", "secret-named key",
2678
+ "keyed fragment", "verifier-limit",
2679
+ "broken syntax"}), [])
2680
+
2681
+ # ... and the two checks are proven on deliberate contamination, because a sweep that has never
2682
+ # rejected anything is a sweep whose reach is unknown. One copy of the run gets an encoded home path
2683
+ # in the INDEX alone, another in a WINDOW alone: each is a file the earlier controls did not read.
2684
+ for what, relative, mutate in (
2685
+ ("an encoded home path in the index and nowhere else", fb_main["index"],
2686
+ lambda data: {**data, "postings": {**data["postings"],
2687
+ **{key: [0] for key
2688
+ in search.keys_of(encoded_home)[0]}}}),
2689
+ ("an encoded home path in a window, readable only after decoding",
2690
+ fb_main["windows"][0]["path"], None)):
2691
+ planted_root = fb_dir.parent / f"planted-{abs(hash(what)) % 10000}"
2692
+ shutil.copytree(fb_dir, planted_root)
2693
+ target = planted_root / relative
2694
+ if mutate is None:
2695
+ # R#3: the contamination is written so that NO raw search for any spelling of the path
2696
+ # finds it - every character of the home is a \u escape - and only a decoding exposes it.
2697
+ # The window stays valid JSON, so the planted file is a window a reader could open.
2698
+ # TWICE encoded: inside the window's JSON string this reads as `\u002f\u0055...`, which
2699
+ # one decoding turns into the escape sequence and a second into the path itself. None of the
2700
+ # spellings the sweep searches for appears in the file's bytes.
2701
+ deep_home = "".join(f"\\\\u{ord(character):04x}" for character in FX_HOME)
2702
+ body = target.read_text(encoding="utf-8")
2703
+ planted_body = body.replace(projection.FLOOR.PLACEHOLDER, deep_home, 1)
2704
+ target.write_text(planted_body, encoding="utf-8")
2705
+ def reads_as_json(text):
2706
+ """Whether a window file parses - as one document, or as one per line."""
2707
+ try:
2708
+ json.loads(text)
2709
+ return True
2710
+ except ValueError:
2711
+ pass
2712
+ lines = [line for line in text.splitlines() if line.strip()]
2713
+ try:
2714
+ for line in lines:
2715
+ json.loads(line)
2716
+ except ValueError:
2717
+ return False
2718
+ return bool(lines)
2719
+
2720
+ expect("R#3: the planted window is still a window - it parses as it did before",
2721
+ reads_as_json(planted_body), reads_as_json(body))
2722
+ expect("R#3: no raw search for any spelling of the owner's path finds the plant",
2723
+ [spelling for spelling in every_spelling_of(FX_HOME)
2724
+ if spelling in planted_body], [])
2725
+ else:
2726
+ target.write_text(json.dumps(mutate(json.loads(target.read_text(encoding="utf-8"))),
2727
+ ensure_ascii=False), encoding="utf-8")
2728
+ # The subjects are the index's OWN keys for the owner's path: a posting drops the backslashes,
2729
+ # so comparing the path's characters to a posting file's bytes can never match. This is what
2730
+ # M#4 means by deriving subjects from the emitted spellings through the real tokeniser.
2731
+ path_subjects = sorted({key for form in every_spelling_of(FX_HOME)
2732
+ for key in search.keys_of(form)[0]} - vocabulary)
2733
+ expect(f"M#4: the owner's path has index keys of its own, so the check below has subjects",
2734
+ len(path_subjects) > 0, True)
2735
+ caught = []
2736
+ for path in sorted(planted_root.rglob("*")):
2737
+ if not path.is_file() or "sources" in path.parts:
2738
+ continue
2739
+ raw = path.read_text(encoding="utf-8", errors="replace")
2740
+ forms = [raw]
2741
+ if path.suffix == ".json":
2742
+ try:
2743
+ forms += projection.spellings_of(json.loads(raw))
2744
+ except ValueError:
2745
+ pass
2746
+ elif path.suffix == ".jsonl":
2747
+ for line in raw.splitlines():
2748
+ try:
2749
+ forms += projection.spellings_of(json.loads(line))
2750
+ except ValueError:
2751
+ pass
2752
+ # case-insensitively: the index lowercases its posting keys, so a contaminated posting is
2753
+ # the owner's path in a spelling the earlier byte comparison could not see
2754
+ lowered = [form.lower() for form in forms]
2755
+ if any(needle.lower() in form
2756
+ for needle in (FX_HOME, encoded_home, slash_home) for form in lowered):
2757
+ caught.append(str(path.relative_to(planted_root)))
2758
+ continue
2759
+ # ... and an index is judged by its postings, which is where a tokenised path hides
2760
+ if '"postings"' in raw:
2761
+ try:
2762
+ postings = json.loads(raw).get("postings", {})
2763
+ except ValueError:
2764
+ postings = {}
2765
+ if any(key in postings for key in path_subjects):
2766
+ caught.append(str(path.relative_to(planted_root)))
2767
+ expect(f"E#5: the sweep rejects {what}", sorted(caught), [relative])
2768
+ if mutate is not None:
2769
+ planted_index = search.load(planted_root / relative)
2770
+ expect("M#4: the posting check rejects the planted index",
2771
+ sorted(key for key in path_subjects if key in planted_index.postings) != [], True)
2772
+ shutil.rmtree(planted_root)
2773
+
2774
+ for needle, what in ((FX_SIBLING_KEY, "the credential under an encoded key with a sibling name"),
2775
+ (FX_MIXED_DEPTH, "the twice-encoded token beside a plain path"),
2776
+ (FX_NO_QUOTE_BODY, "the credential in a body with no escaped quote"),
2777
+ (FX_ESCAPED_TAIL, "the credential in an escaped member after a plain structure"),
2778
+ (FX_ESCAPED_ARRAY, "the credential inside an escaped array"),
2779
+ (FX_QUOTED_SCALAR, "the credential inside a quoted scalar's structure"),
2780
+ (FX_MASK_NEIGHBOUR, "the credential standing beside a literal mask"),
2781
+ (FX_HOME, "the owner's home in plain form"),
2782
+ (encoded_home, "the owner's home in its encoded spelling"),
2783
+ (slash_home, "the owner's home in its slash-escaped spelling"),
2784
+ (FX_FALLBACK_SCALAR, "the encoded scalar credential"),
2785
+ (FX_OBLIGATION_JSON, "the credential inside a readable structure"),
2786
+ (FX_OBLIGATION_QUOTED, "the credential inside a quoted structure")):
2787
+ expect(f"A#3: no artifact of the run holds {what}, in its bytes or in any decoded string of it",
2788
+ sorted({where for where, text in decoded_strings
2789
+ if needle.lower() in text.lower()}), [])
2790
+ fb_sweep = fx_sweep(fb_dir, [FX_FALLBACK_SCALAR, FX_FALLBACK_LEFTOVER, FX_OBLIGATION_JSON,
2791
+ FX_OBLIGATION_QUOTED, FX_HOME])
2792
+ expect("Q#0 and Q#2: the credential only decoding could reach, the cross-member floor claim, the value "
2793
+ "of a secret-named key whose value is a readable structure, the credential inside a quoted "
2794
+ "structure, and the owner's home are in no projection, window, index, evidence or report of "
2795
+ "the fallback run - and the immutable copy keeps every one of them",
2796
+ {needle: sorted({path.split("/")[0] for path in paths}) for needle, paths in fb_sweep.items()},
2797
+ {needle: ["sources"] for needle in (FX_FALLBACK_SCALAR, FX_FALLBACK_LEFTOVER,
2798
+ FX_OBLIGATION_JSON, FX_OBLIGATION_QUOTED, FX_HOME)})
2799
+ expect("Q#2: ... and the run it swept really has the artifacts the claim covers",
2800
+ sorted({part.split("/")[0] for part in
2801
+ [str(x.relative_to(fb_dir)) for x in fb_dir.rglob("*") if x.is_file()]}
2802
+ & {"sources", "redacted", "views", "index", "evidence"}),
2803
+ ["evidence", "index", "redacted", "sources", "views"])
2804
+
2805
+ # ---- done-when 3 and 4 controls: each invariant fails by its name when it is broken -------
2806
+ duplicated = copy.deepcopy(windows)
2807
+ duplicated[1]["records"].append(copy.deepcopy(duplicated[0]["records"][0]))
2808
+ named("control, owned once: a record owned by two windows is named",
2809
+ check_windows(records.read_json(run_dir / main["sequence"])["sequence"], duplicated), "SET_MISMATCH")
2810
+ merged = copy.deepcopy(windows)
2811
+ merged[0]["records"] += merged[1]["records"] # every owned id is still placed once, so only the empty window is wrong
2812
+ merged[1]["records"] = []
2813
+ named("control, owned once: a window that holds no record of its own is named",
2814
+ check_windows(records.read_json(run_dir / main["sequence"])["sequence"], merged), "SET_MISMATCH")
2815
+ thinned = copy.deepcopy(windows)
2816
+ thinned[0]["overlap"]["next"].pop()
2817
+ named("control, overlap: an overlap entry removed is named",
2818
+ check_windows(records.read_json(run_dir / main["sequence"])["sequence"], thinned), "OVERLAP_MISSING")
2819
+ both = copy.deepcopy(windows)
2820
+ for w in both:
2821
+ if w["overlap"]["prev"]:
2822
+ turn = next((e for e in w["overlap"]["prev"] if e["kind"] in TURN_KINDS), None)
2823
+ if turn:
2824
+ w["overlap"]["omitted"]["prev"].append({"entry": turn["entry"], "record_id": turn["record_id"],
2825
+ "kind": turn["kind"], "size": 1, "reason": "overlap_budget"})
2826
+ break
2827
+ named("control, overlap: an entry both shown and named omitted is named, because a turn counted twice is "
2828
+ "neither accounted nor shown",
2829
+ check_windows(records.read_json(run_dir / main["sequence"])["sequence"], both), "OVERLAP_MISSING")
2830
+ # M#7: the overlap is five TURNS of design §5.4, not five sequence entries, and its text is the
2831
+ # sequence's text up to an omission that is named. Entry ids alone said nothing about either.
2832
+ sequence_rows = records.read_json(run_dir / main["sequence"])["sequence"]
2833
+ kinds = {r["id"]: r["kind"] for r in sequence_rows}
2834
+ for w in windows:
2835
+ for side in ("prev", "next"):
2836
+ shown = w["overlap"][side]
2837
+ # distinct TURNS, not entries of a turn kind: this control read entries and also called a
2838
+ # name that does not exist in this function, so it could neither fire nor be noticed
2839
+ turns = {(e["line"], e["kind"]) for e in shown if e["kind"] in TURN_KINDS}
2840
+ if len(turns) > OVERLAP_TURNS:
2841
+ checks.failures.append(f"overlap {side} of window {w['window_n']} holds {len(turns)} turns, not at most "
2842
+ f"{OVERLAP_TURNS}")
2843
+ expect("done-when 3: every overlap entry's kind is the sequence's own, so a turn is counted as a turn",
2844
+ sorted({e["kind"] for w in windows for side in ("prev", "next") for e in w["overlap"][side]}
2845
+ - set(kinds.values())), [])
2846
+ # the case that tells the two definitions apart: six tool results stand between the window and the
2847
+ # last human turn, so counting five ENTRIES reaches no turn at all while counting five TURNS does
2848
+ def synthetic(n, kind, text="x" * 40):
2849
+ return {"record_id": f"{n}/message/content", "line": n, "json_pointer": "/message/content", "kind": kind,
2850
+ "tool": None, "ts": fx_stamp(1, hour=n), "error": False, "window_role": "in_window",
2851
+ "size": len(text), "text": text, "segments": [{"view": [0, len(text)], "block": [0, len(text)]}],
2852
+ "owned": True}
2853
+ straight = ([synthetic(1, "human"), synthetic(2, "assistant")]
2854
+ + [synthetic(n, "tool_result") for n in range(3, 9)]
2855
+ + [synthetic(9, "human")])
2856
+ probe = make_window({"transcript": "t", "version": 1, "version_sha": "ab" * 32,
2857
+ "redaction_version": projection.CURRENT}, 1, straight, 8, 9, golden_run["limits"])
2858
+ expect("done-when 3: with six tool results between, the overlap still reaches the human and assistant "
2859
+ "turns before them - which five entries could never do",
2860
+ [e["kind"] for e in probe["overlap"]["prev"]][:2], ["human", "assistant"])
2861
+
2862
+ # ---- P#3: the four cases of the five-turn overlap, each specified on its own -------------------
2863
+ base_probe = {"transcript": "t", "version": 1, "version_sha": "ab" * 32,
2864
+ "redaction_version": projection.CURRENT}
2865
+ # (1) a SPLIT MESSAGE is one turn. Five spans of one assistant message used to count as five turns,
2866
+ # so the overlap was five fragments of one message and reached no other turn at all.
2867
+ long_one = synthetic(2, "assistant", "y" * 4_000)
2868
+ split = split_entry(long_one, 600)
2869
+ if len(split) < 5:
2870
+ checks.failures.append(f"the split-message case needs a message of several spans, got {len(split)}")
2871
+ split_seq = [synthetic(1, "human")] + split + [synthetic(3, "human")]
2872
+ expect("P#3(1): the spans of one message are one turn, however many spans there are",
2873
+ (turns_in(split), before_turns(split_seq, len(split_seq) - 1, OVERLAP_TURNS)), (1, 0))
2874
+ split_window = make_window(base_probe, 1, split_seq, len(split_seq) - 1, len(split_seq), golden_run["limits"])
2875
+ expect("P#3(1): ... so the window's overlap reaches the human turn BEFORE that message, which counting "
2876
+ "spans never did",
2877
+ sorted({e["kind"] for e in split_window["overlap"]["prev"]}), ["assistant", "human"])
2878
+ # (2) UNOWNED TOOL TRAFFIC does not push turns out of the retained context. The sequence builder kept
2879
+ # five BLOCKS, so six tool results between the window and the previous turn lost every turn.
2880
+ traffic = ([synthetic(1, "human"), synthetic(2, "assistant")]
2881
+ + [synthetic(n, "tool_result") for n in range(3, 13)] + [synthetic(13, "human")])
2882
+ for entry in traffic[:12]:
2883
+ entry["owned"] = False
2884
+ expect("P#3(2): ten unowned tool results do not displace the turns before them, because the slice is "
2885
+ "counted in turns", traffic[before_turns(traffic, 12, OVERLAP_TURNS)]["kind"], "human")
2886
+ # ... and the same case through the SEQUENCE BUILDER, which is where the context is retained: it kept
2887
+ # five blocks, so ten tool results between the window and the turns before it lost every one of them
2888
+ probe_proj = run_dir / "p3-traffic.jsonl"
2889
+ with open(probe_proj, "w", encoding="utf-8") as handle:
2890
+ for n in range(1, 14):
2891
+ kind = "human" if n in (1, 13) else "assistant" if n == 2 else "tool_result"
2892
+ handle.write(json.dumps({"line": n, "ts": fx_stamp(1, hour=(n % 24)),
2893
+ "items": [{"pointer": "/message/content", "kind": kind,
2894
+ "tool": None, "text": "t" * 60}]}) + "\n")
2895
+ built, _humans, _counts, _tools, _texts = build_sequence(
2896
+ probe_proj, {12}, lambda _line: "in_window", search.Index())
2897
+ expect("P#3(2): the sequence builder retains context by TURNS, so the human and assistant turns before "
2898
+ "ten tool results are still there when the window is cut",
2899
+ [e["kind"] for e in built][:2], ["human", "assistant"])
2900
+ expect("P#3(2): ... and the retained context is contiguous with the owned record, tool traffic included",
2901
+ len(built), 13)
2902
+ # (3) BUDGET EXHAUSTION: a turn the side's budget cannot hold is named omitted, with a span and a hash,
2903
+ # and the manifest a consumer reads carries it
2904
+ # five turns with tool traffic between them: the turns alone fit the side's budget, and the traffic
2905
+ # that belongs to them is what exhausts it
2906
+ fat = []
2907
+ for n in range(1, 11):
2908
+ fat.append(synthetic(n, "assistant" if n % 2 else "tool_result", "z" * 600))
2909
+ fat.append(synthetic(11, "human"))
2910
+ shown_side, gone_side = overlap_side(fat[:7], budget=1_200)
2911
+ expect("P#3(3): the entries the overlap budget cannot hold are NAMED omitted, never silently absent",
2912
+ (bool(shown_side), bool(gone_side), len(shown_side) + len(gone_side)), (True, True, 7))
2913
+ expect("P#3(3): ... and every one of them carries the intervals and hashes of what went, so the "
2914
+ "omission is verifiable rather than a label",
2915
+ [g["record_id"] for g in gone_side
2916
+ if [i["sha256"] for i in g.get("omitted_intervals") or []]
2917
+ != [records.sha256_bytes(("z" * 600).encode("utf-8"))]], [])
2918
+ fat_window = make_window(base_probe, 1, fat, 10, 11, golden_run["limits"])
2919
+ expect("P#3(3): the side's budget is exhausted in this case, which is what the next control reads",
2920
+ bool(fat_window["overlap"]["omitted"]["prev"]), True)
2921
+ expect("P#3(3): ... and an overlap omission is in the omission manifest, which is the one list a "
2922
+ "consumer reads",
2923
+ sorted({m["origin"] for m in fat_window["omission_manifest"]}) or ["(none)"], ["overlap"])
2924
+ # (4) DUPLICATE MEMBERSHIP: one turn listed twice in a side's list is one turn accounted as several
2925
+ doubled = copy.deepcopy(probe)
2926
+ doubled["overlap"]["prev"] = doubled["overlap"]["prev"] + doubled["overlap"]["prev"][-1:]
2927
+ def as_sequence(entries, owned_from):
2928
+ """The sequence rows `check_windows` reads: only the window's own entries are owned."""
2929
+ return [{"id": eid(e), "owned": k >= owned_from} for k, e in enumerate(entries)]
2930
+ named("control, P#3(4): a turn shown twice in one side's overlap is named, because the sets every other "
2931
+ "check used counted it once",
2932
+ check_windows(as_sequence(straight, 8), [doubled]), "OVERLAP_MISSING")
2933
+ twice_omitted = copy.deepcopy(fat_window)
2934
+ twice_omitted["overlap"]["omitted"]["prev"] = twice_omitted["overlap"]["omitted"]["prev"] * 2
2935
+ named("control, P#3(4): ... and so is a turn named omitted twice",
2936
+ check_windows(as_sequence(fat, 10), [twice_omitted]), "OVERLAP_MISSING")
2937
+ # M#8: the index is over the FULL redacted text of the version, not over the work ranges. The
2938
+ # fixture's first and last records are outside the window on purpose, so a term that occurs only
2939
+ # there is the test: with an index built from the viewed ranges it could not be found at all.
2940
+ full_index = search.load(run_dir / main["index"])
2941
+ full_texts = projection_texts(run_dir, main["redacted"])
2942
+ outside = search.search(full_index, ["week before this window"],
2943
+ lambda ref: full_texts.get(f"{ref[0]}{ref[1]}", ""))
2944
+ expect("done-when 5: a term that occurs only outside the work ranges is found, because every projected "
2945
+ "block is indexed whatever window owns it",
2946
+ [f"{h['ref'][0]}{h['ref'][1]}" for h in outside], [f"{lines['before']}/message/content/0/text"])
2947
+ expect("done-when 5: the index holds a document for every projected block of the version, not only the "
2948
+ "viewed ones",
2949
+ len(full_index.docs), sum(len(line["items"]) for line in
2950
+ (json.loads(l) for l in (run_dir / main["redacted"]).read_text(
2951
+ encoding="utf-8").splitlines() if l.strip())))
2952
+ first_prev = next((w["overlap"]["prev"] for w in windows if w["overlap"]["prev"]), [])
2953
+ expect("done-when 3: a window's overlap reaches back over the tool traffic to a real turn, which five "
2954
+ "entries of a split message never did",
2955
+ any(e["kind"] in TURN_KINDS for e in first_prev), True)
2956
+ # the overlap shows the owning window's own entry text; a split span's overlap starts at the span,
2957
+ # so the comparison is against that entry, not against the whole block
2958
+ # an overlap entry is either a window's own entry seen from the side, or a record no window owns at
2959
+ # all (a turn outside the work ranges, kept as context); the base text differs for the two
2960
+ own_text = {eid(r): r["text"] for w in windows for r in w["records"]}
2961
+ base_text = lambda e: own_text.get(e["entry"], texts.get(e["record_id"], "")) # noqa: E731
2962
+ expect("done-when 3 / V#1: the text an overlap entry shows is the start of the entry the sequence owns, "
2963
+ "and a cut is accounted by hashed intervals of the projected BLOCK rather than by a boolean",
2964
+ [e["entry"] for w in windows for side in ("prev", "next") for e in w["overlap"][side]
2965
+ if not base_text(e).startswith(e["text"])
2966
+ or (e["overlap_cut"] and not e.get("omitted_intervals"))
2967
+ or any(records.sha256_bytes(
2968
+ texts.get(e["record_id"], "")[i["start"]:i["end"]].encode("utf-8")) != i["sha256"]
2969
+ for i in e.get("omitted_intervals") or [])], [])
2970
+ wrong_text = copy.deepcopy(windows)
2971
+ for w in wrong_text:
2972
+ if w["overlap"]["prev"]:
2973
+ w["overlap"]["prev"][0]["text"] = w["overlap"]["prev"][0]["text"][5:]
2974
+ break
2975
+ expect("control, overlap: an overlap entry whose text is not the owned entry's own is found",
2976
+ [e["entry"] for w in wrong_text for e in w["overlap"]["prev"]
2977
+ if not base_text(e).startswith(e["text"])] != [], True)
2978
+ short = [copy.deepcopy(w) for w in windows]
2979
+ for w in short:
2980
+ w["records"] = [r for r in w["records"] if not (r["line"] == lines["long"] and r.get("span", {}).get("index") == 2)]
2981
+ named("control, span union: a span dropped from a split message is named", check_tiling(short, texts), "SPAN_UNION_MISMATCH")
2982
+ hidden_error = copy.deepcopy(windows)
2983
+ for w in hidden_error:
2984
+ for r in w["records"]:
2985
+ if r["record_id"] != rid("pending_clip"):
2986
+ continue
2987
+ a, b = r["clipped"]["error_lines"][0] # cut the error line out of the stretch that shows it
2988
+ segments = []
2989
+ for seg in r["segments"]:
2990
+ lo, hi = seg["block"]
2991
+ if lo <= a and b <= hi:
2992
+ segments += [{"view": seg["view"], "block": [lo, a]}] if lo < a else []
2993
+ segments += [{"view": seg["view"], "block": [b, hi]}] if b < hi else []
2994
+ else:
2995
+ segments.append(seg)
2996
+ r["segments"] = segments
2997
+ r["clipped"]["gaps"] = coverage.normalize(r["clipped"]["gaps"] + [[a, b]])
2998
+ named("control, error line: an error line of a clipped result moved into the gap is named",
2999
+ check_tiling(hidden_error, texts), "ERROR_LINE_DROPPED")
3000
+ # the clip's bounds (WP-08c): a log of 41-character lines, whose 1,200th and (n-800)th characters fall inside
3001
+ # lines; one long line; a block whose only line end before the head would keep less than half of it; and one
3002
+ # whose only line start after the tail would keep less than half of it
3003
+ lined = "".join(f"line {i:04d} of the build log, still going.\n" for i in range(300))
3004
+ cuts = {}
3005
+ for label, text in (("lined", lined), ("one line", "x" * 10_000), ("sparse head", "a" * 99 + "\n" + "b" * 9_900),
3006
+ ("sparse tail", "c" * 9_699 + "\n" + "d" * 300)):
3007
+ _parts, meta = clip_parts(text, "tool_result")
3008
+ span = meta["omitted_span"]
3009
+ cuts[label] = (meta["head"][1], meta["tail"][0], span["start"], span["end"])
3010
+ lined_view = compose(lined, clip_parts(lined, "tool_result")[0])[0]
3011
+ expect("WP-08c: a clipped tool result's head ends at a line end and its tail starts at a line start, so its "
3012
+ "omitted middle is whole lines; a block with no line boundary that keeps half of the head or tail is cut "
3013
+ "by characters",
3014
+ (len(lined.splitlines()[0]) + 1, cuts, "[... 10332 chars omitted (1189-11521) ...]" in lined_view,
3015
+ lined[1188], lined[11520]),
3016
+ (41, {"lined": (1189, 11521, 1189, 11521), "one line": (1200, 9200, 1200, 9200),
3017
+ "sparse head": (1200, 9200, 1200, 9200), "sparse tail": (1200, 9200, 1200, 9200)}, True, "\n", "\n"))
3018
+ # ... and on the other line ends str.splitlines knows, as the clipper and the view check read error lines (WP-08c,
3019
+ # X r1): lines that run on carriage returns (a progress bar's output) or on U+2028 are cut between lines as "\n"
3020
+ # lines are; "\r\n" is one line end, never cut between its "\r" and "\n" - here at the 1,200th character and at
3021
+ # the (n-800)th - and mixed line ends are each a line end
3022
+ line_ends = {}
3023
+ for label, end in (("\\r", "\r"), ("U+2028", "\u2028"), ("\\r\\n", "\r\n")):
3024
+ line_ends[label] = clip_bounds("".join(f"line {i:04d} of the build log, still going.{end}" for i in range(300)))
3025
+ crlf_lines = lambda lo, hi: "".join(f"line {i:04d} of the build log, still going.\r\n" for i in range(lo, hi)) # noqa: E731
3026
+ straddle = crlf_lines(0, 28) + "z" * 23 + "\r\n" + crlf_lines(28, 200) + "w" * 20 + "\r\n" + "u" * 799
3027
+ mixed_ends = ["\n", "\r", "\r\n", "\u2028", "\x0c", "\x85"]
3028
+ mixed = "".join(f"entry {i:04d} of the mixed log.{mixed_ends[i % 6]}" for i in range(400))
3029
+ expect("WP-08c: a clipped tool result's bounds are line boundaries as str.splitlines ends lines - on carriage "
3030
+ "returns, on U+2028, on mixed line ends - and never fall between the \\r and \\n of one line end",
3031
+ (line_ends, clip_bounds(straddle), straddle[1199:1201], straddle[len(straddle) - 801:len(straddle) - 799],
3032
+ clip_bounds(mixed), mixed[1195], mixed[10878]),
3033
+ ({"\\r": (1189, 11521), "U+2028": (1189, 11521), "\\r\\n": (1176, 11802)}, (1176, len(straddle) - 799),
3034
+ "\r\n", "\r\n", (1196, 10879), "\x0c", "\n"))
3035
+ # ... and a cut by characters keeps a "\r\n" whole too (X r2): a head with no line end that keeps half of it,
3036
+ # whose 1,200th character is the "\n" of a "\r\n", ends before the "\r"; at the tail the line boundary after
3037
+ # such a "\r\n" keeps 799 characters, so the tail starts past its "\n" by the boundary rule
3038
+ crlf_head, crlf_tail = "a" * 1199 + "\r\n" + "b" * 5000, "b" * 5000 + "\r\n" + "c" * 799
3039
+ expect("WP-08c: a clipped tool result's cut by characters never falls between the \\r and \\n of one line end - "
3040
+ "the head moves back before the \\r, the tail starts past the \\n",
3041
+ (clip_bounds(crlf_head), crlf_head[1199:1201], clip_bounds(crlf_tail), crlf_tail[5000:5002]),
3042
+ ((1199, 5401), "\r\n", (1200, 5002), "\r\n"))
3043
+ # ... and the view check reads the error lines between the same bounds the clipper cut at, and the manifest names
3044
+ # the same omitted span (WP-08c): a progress bar's output on carriage returns, an error line in its middle
3045
+ stepped = "".join(f"step {i:04d} of the progress bar, still going.\r" for i in range(150)) \
3046
+ + "ERROR: disk full at block 7\r" + "".join(f"step {i:04d} of the progress bar, still going.\r" for i in range(150, 300))
3047
+ stepped_entry = make_entry({"pointer": "/x", "kind": "tool_result", "text": stepped}, 1, "in_window", 0)
3048
+ stepped_rows = manifest_of([stepped_entry])
3049
+ stepped_hidden = copy.deepcopy(stepped_entry)
3050
+ for a, b in stepped_hidden["clipped"]["error_lines"]:
3051
+ stepped_hidden["segments"] = [s for s in stepped_hidden["segments"] if s["block"] != [a, b]]
3052
+ stepped_hidden["clipped"]["gaps"] = coverage.normalize(stepped_hidden["clipped"]["gaps"] + [[a, b]])
3053
+ expect("WP-08c: on a result whose lines end in carriage returns, the clip, the view check's error lines and the "
3054
+ "manifest's row (manifest_of) name the same bounds and the same error line; it is kept, and named "
3055
+ "ERROR_LINE_DROPPED when hidden",
3056
+ ((stepped_entry["clipped"]["head"][1], stepped_entry["clipped"]["tail"][0]),
3057
+ [((r["omitted_span"]["start"], r["omitted_span"]["end"]), r["error_lines"],
3058
+ r["omission_id"] == omission_id(r["record_id"], 1188, 12436),
3059
+ r["omitted_span"]["sha256"] == records.sha256_bytes(stepped[1188:12436].encode("utf-8")))
3060
+ for r in stepped_rows],
3061
+ stepped_entry["clipped"]["error_lines"], error_lines_of(stepped),
3062
+ check_tiling([{"records": [stepped_entry]}], {"1/x": stepped}),
3063
+ any("ERROR_LINE_DROPPED 1/x" in e for e in check_tiling([{"records": [stepped_hidden]}], {"1/x": stepped}))),
3064
+ ((1188, 12436), [((1188, 12436), 1, True, True)], [[6600, 6628]], [[6600, 6628]], [], True))
3065
+
3066
+ # ---- WP-08c: an expansion shows its record's neighbours as overlap, and a middle too long for one window is cut
3067
+ # across several, each owning its spans with the overlap the sequence puts around them
3068
+ def fx_split_records():
3069
+ log = "".join(f" migrating shard {i:04d} ok {'.' * 30}\n" for i in range(1200))
3070
+ return [fx_human(fx_stamp(3, hour=1), "please migrate every shard"),
3071
+ fx_call(fx_stamp(3, hour=2), "Bash", {"command": "migrate --all"}),
3072
+ fx_result(fx_stamp(3, hour=3), log),
3073
+ fx_assistant(fx_stamp(3, hour=4), "the migration finished")]
3074
+ split_run = golden(root, "split", overhead=100_000, main_records=fx_split_records, main_only=True, pending_at=None)
3075
+ split_name, split_dir = split_run["main"]["name"], split_run["run_dir"]
3076
+ split_docs = [window_doc(split_dir, split_name, split_dir / f["path"]) for f in split_run["main"]["windows"]]
3077
+ split_row = next(m for d in split_docs for m in d["omission_manifest"] if m["origin"] == "owned")
3078
+ split_rid, split_span = split_row["record_id"], split_row["omitted_span"]
3079
+ try:
3080
+ split_x = expand(split_dir, "r1/S3/split/1", split_name, split_rid, "the whole migration log",
3081
+ omission=split_row["omission_id"])
3082
+ _row, again_x, sequence_x = expansion_windows(split_dir, split_name, split_rid, split_row["omission_id"])
3083
+ owned_blocks = [s["block"] for w in split_x for r in w["records"] for s in r["segments"]]
3084
+ shown_own = [s["block"] for w in split_x for side in ("prev", "next") for e in w["overlap"][side]
3085
+ if e["record_id"] == split_rid for s in e["segments"]]
3086
+ split_facts = (len(split_x) > 1, {r["record_id"] for w in split_x for r in w["records"]},
3087
+ coverage.normalize(owned_blocks), sum(b - a for a, b in owned_blocks),
3088
+ [e["line"] for e in split_x[0]["overlap"]["prev"]], [e["line"] for e in split_x[-1]["overlap"]["next"]],
3089
+ all(split_span["start"] <= a and b <= split_span["end"] for a, b in shown_own),
3090
+ check_windows(sequence_x, split_x), again_x == split_x)
3091
+ except Refused as exc: # a broken expansion fails the control by name, not the suite
3092
+ split_facts = ("refused", str(exc)[:300])
3093
+ expect("WP-08c: a middle too long for one window is cut across several expansion windows that own its spans alone, "
3094
+ "tiling it with no gap and no overlap; each window's overlap is the turn slice the sequence puts around it "
3095
+ "(the first's opens on the call, the last's closes on the reply), and no overlap shows the record's own head "
3096
+ "or tail", split_facts,
3097
+ (True, {split_rid}, [[split_span["start"], split_span["end"]]], split_span["end"] - split_span["start"],
3098
+ [1, 2], [4], True, [], True))
3099
+
3100
+ # ---- done-when 3: the bound as the owner's amendment of §5.4 states it --------------------
3101
+ limits = golden_run["limits"]
3102
+ named("bound (a) and (d): a window inside both checks passes", bound.check_bound(1000, limits))
3103
+ named("control, bound (a): driver bytes above 120k minus the declared allowance are named",
3104
+ bound.check_bound(bound.INPUT_BOUND - limits["allowance"] + 1, limits), "WINDOW_BOUND_EXCEEDED")
3105
+ named("control, bound (d): driver bytes that pass (a) but leave no room for the output reservation are named",
3106
+ bound.check_bound(50_000, {**limits, "capacity": 60_000}), "WINDOW_CAPACITY_EXCEEDED")
3107
+ tighter = golden(root, "capped", overhead=100_000, capacity=150_000)
3108
+ expect("a run whose (d) check is the tighter bound cuts the same corpus into more windows: a window failing "
3109
+ "(d) is split", (bound.driver_budget(tighter["limits"]) < bound.driver_budget(limits),
3110
+ tighter["manifest"]["totals"]["windows"] > manifest["totals"]["windows"]), (True, True))
3111
+ expect("WP-08: S2 cuts every window reserving the output cap run.json declares for S3",
3112
+ golden(root, "cap48", reservation=48_000)["manifest"]["limits"]["reservation"], 48_000)
3113
+ # the omission list a read packet carries is part of what a window is cut against (the first three-day run:
3114
+ # thirty windows over the bound at S3, each by its list). Rows built here, so the control needs no corpus.
3115
+ fx_omitted = [{"record_id": f"r{k}", "size": 5000 + k, "omitted_span": {"start": 100, "end": 4000 + k},
3116
+ "forced_by": "none"} for k in range(12)]
3117
+ fx_line = lambda m: (len(f"- o12: in {LABEL_BOUND}, {m['omitted_span']['end'] - m['omitted_span']['start']} of " # noqa: E731
3118
+ f"{m['size']} characters omitted") + len(", must expand (pending_event)") + 1)
3119
+ expect("a window's measure counts one line per omission of its own records at the line's longest, and none of "
3120
+ "the overlap's", (omission_reserve({"omission_manifest": fx_omitted + [{**fx_omitted[0], "origin": "overlap"}]}),
3121
+ omission_reserve({"omission_manifest": [{**fx_omitted[0], "origin": "overlap"}]})),
3122
+ (sum(fx_line(m) for m in fx_omitted), len("none")))
3123
+ fx_sized = make_window({"transcript": "t", "version": 0, "version_sha": "ab" * 32, "redaction_version": projection.CURRENT},
3124
+ 1, [make_entry({"pointer": "/message/content", "kind": "human", "text": "x" * 100}, 1, "in_window", 0)],
3125
+ 0, 1, limits, overlap=False)
3126
+ expect("and that count is in the bytes the window is held to the bound by",
3127
+ fx_sized["driver_bytes"], limits["overhead"] + len(render_window(fx_sized).encode("utf-8"))
3128
+ + omission_reserve(fx_sized))
3129
+ one = make_entry({"pointer": "/message/content", "kind": "human", "text": "x" * 100}, 1, "in_window", 0)
3130
+ refused("control, unbounded: a packet that leaves no room for an entry is refused, never cut away",
3131
+ lambda: cut_windows({"transcript": "t", "version": 0, "version_sha": "ab" * 32, "redaction_version": projection.CURRENT},
3132
+ [one], {**limits, "overhead": bound.INPUT_BOUND - 10_000}), "WINDOW_UNBOUNDED")
3133
+ named("control, unbounded: under the production posture the transcript whose windows cannot be bounded is "
3134
+ "quarantined by name", [q["reason"] for q in golden(root, "nobound", overhead=bound.INPUT_BOUND - 10_000)["manifest"]["quarantined"]],
3135
+ "WINDOW_UNBOUNDED")
3136
+ # The S3 seat and the Claude host version these controls cut against are the checkout's pins.
3137
+ s3_seat, pinned_claude = gate.seats()["stage_seats"]["S3"][0], gate.seats()["hosts"]["claude"]["version"]
3138
+ # BA#1: cutting a window reads the SAME declaration the dispatcher admits against, and there is no
3139
+ # default - a window cut against an invented capacity is cut against nothing.
3140
+ refused("control, BA#1: a seat seats.json declares no context capacity for cuts no window",
3141
+ lambda: limits_of({"seats": {"S3": "claude:no-such-model/high"},
3142
+ "host_allowance": {"claude:no-such-model/high": {
3143
+ "allowance_tokens": 4000, "host_version": pinned_claude}}, "output_caps": {"S3": 32_000}}),
3144
+ "CAPACITY_UNDECLARED")
3145
+ # ... and the cap itself: a window is cut against the cap the call will declare, never a constant
3146
+ refused("control, the ruling of 2026-10-22: a window cut with no declared output cap is refused",
3147
+ lambda: limits_of({"seats": {"S3": s3_seat},
3148
+ "host_allowance": {s3_seat: {
3149
+ "allowance_tokens": 3886, "host_version": pinned_claude}}}),
3150
+ "CAP_UNDECLARED")
3151
+ expect("the ruling of 2026-10-22: the reservation in the window's limits IS the declared cap",
3152
+ limits_of({"seats": {"S3": s3_seat},
3153
+ "host_allowance": {s3_seat: {
3154
+ "allowance_tokens": 3886, "host_version": pinned_claude}}, "output_caps": {"S3": 48_000}})["reservation"], 48_000)
3155
+ expect("BA#1: the S3 seat's capacity is the host-reported one seats.json declares, not a constant",
3156
+ limits_of({"seats": {"S3": s3_seat},
3157
+ "host_allowance": {s3_seat: {
3158
+ "allowance_tokens": 3886, "host_version": pinned_claude}}, "output_caps": {"S3": 32_000}})["capacity"],
3159
+ gate.seat_capacity(s3_seat, pinned_claude)[0])
3160
+ # BB#5: there is no way to hand the window builder a capacity. Both entry points resolve it through
3161
+ # the shared declaration reader, and a control that needs another one declares it in a seats fixture -
3162
+ # so no production path, and no test, can cut a window against a number no declaration carries.
3163
+ import inspect
3164
+ for entry in (limits_of, run):
3165
+ expect(f"BB#5: {entry.__name__} takes no capacity of its own",
3166
+ "capacity" in inspect.signature(entry).parameters, False)
3167
+ # WP-08: nor a reservation - the cap is the declaration's, so no caller can cut against another one
3168
+ expect(f"WP-08: {entry.__name__} takes no output reservation of its own",
3169
+ "reservation" in inspect.signature(entry).parameters, False)
3170
+ narrower = fx_seats(root, 150_000)
3171
+ expect("BB#5: a capacity a seats fixture declares is read by the same reader production reads",
3172
+ limits_of({"seats": {"S3": s3_seat},
3173
+ "host_allowance": {s3_seat: {
3174
+ "allowance_tokens": 3886, "host_version": pinned_claude}}, "output_caps": {"S3": 32_000}},
3175
+ seats_path=narrower)["capacity"],
3176
+ gate.seat_capacity(s3_seat, pinned_claude, path=narrower)[0])
3177
+ refused("control, BB#5: a fixture that declares no capacity for the seat cuts no window either",
3178
+ lambda: limits_of({"seats": {"S3": s3_seat},
3179
+ "host_allowance": {s3_seat: {
3180
+ "allowance_tokens": 3886, "host_version": "9.9.9"}}, "output_caps": {"S3": 32_000}},
3181
+ seats_path=narrower),
3182
+ "CAPACITY_UNDECLARED")
3183
+ refused("control, allowance: a declaration with no measured host allowance for the S3 seat cuts no window",
3184
+ lambda: limits_of({"seats": {"S3": "claude:x/high"}, "host_allowance": {}}), "ALLOWANCE_UNDECLARED")
3185
+ no_allowance = {**golden_run["run"], "host_allowance": {}}
3186
+ # P#7: one code for one refusal. S0 named it HOST_ALLOWANCE_MISSING and WP-06's contract names it
3187
+ # ALLOWANCE_UNDECLARED; two names for the same stop is a contract that cannot be read from either
3188
+ # side, so S0's name was changed to the plan's and the old one must be gone everywhere.
3189
+ named("control, allowance at S0: the declaration itself is refused before any window is cut, under the "
3190
+ "one code WP-06's contract names",
3191
+ declare.check_declaration(no_allowance), "ALLOWANCE_UNDECLARED")
3192
+ expect("control, allowance: the superseded S0 spelling is in no refusal of either stage",
3193
+ [line for line in declare.check_declaration(no_allowance) + limits_refusal(golden_run)
3194
+ if "HOST_ALLOWANCE_MISSING" in line], [])
3195
+ named("observed input: a view-window call within 120k is accepted", bound.check_observed(bound.INPUT_BOUND, True))
3196
+ named("control, observed input: a view-window call above 120k is a host change",
3197
+ bound.check_observed(bound.INPUT_BOUND + 1, True), "INPUT_BOUND_EXCEEDED")
3198
+ named("observed input: the same observation on a call that carries no view window is accepted, so the R "
3199
+ "authoring of §8.6 keeps its own section's contract", bound.check_observed(136_000, False))
3200
+ # The boundary itself is the DISPATCHER's: `runlib/bound.py` owns the rule and `dispatch.py`
3201
+ # admits, settles, stops and recovers against it (the seam record of 2026-10-22). What stays here
3202
+ # is what this module owns - the retained captures and what the rule says about them.
3203
+ #
3204
+ # P#4: the captures these controls settle are FILES, each pinned by sha256 in
3205
+ # `fixtures/captures.json`, and `retained_capture` refuses one whose bytes moved. A dictionary
3206
+ # written at the point of use carries whatever counts the control wanted, so it can be adjusted until
3207
+ # the control passes; a pinned file cannot. Two of the three are retained probe captures of
3208
+ # 2026-10-20, copied with their usage block alone and naming their source file and its sha256:
3209
+ # `within-bound` and the R-authoring call, whose observed input really is above the bound. An
3210
+ # R-authoring call is a non-window call by the contract of design 8.6, so the bound does not govern
3211
+ # it and no evidence about a view window is needed. `window-overrun` stays constructed and says so:
3212
+ # no retained capture of a VIEW-WINDOW call above the bound exists.
3213
+ within = retained_capture("within-bound")
3214
+ overrun = retained_capture("window-overrun")
3215
+ authoring = retained_capture("r-authoring")
3216
+ usage = within["usage"]
3217
+ expect("done-when 3(b): the retained view-window capture within 120k settles, and its observed input is "
3218
+ "input + cache creation + cache read as the capture itself records them",
3219
+ (observed_input_of(within), bound.check_observed(observed_input_of(within), True)),
3220
+ (usage["input_tokens"] + usage["cache_creation_input_tokens"] + usage["cache_read_input_tokens"], []))
3221
+ refused("control, P#4: a capture name no pin covers is refused rather than read",
3222
+ lambda: retained_capture("not-pinned"), "CAPTURE_UNPINNED")
3223
+ # R#6: the mismatch is planted in a COPY of the fixture tree, under this run's own directory, so the
3224
+ # control never writes to the checkout
3225
+ copied = run_dir / "captures-copy"
3226
+ shutil.copytree(records.fixture_root(), copied, dirs_exist_ok=True)
3227
+ expect("control, R#6: the copied fixture tree is the same fixture - it reads clean before the plant",
3228
+ retained_capture("within-bound", root=copied)["call_id"], within["call_id"])
3229
+ moved = copied / "captures" / "within-bound.json"
3230
+ moved.write_bytes(moved.read_bytes().replace(b'"input_tokens"', b'"input_tokens" '))
3231
+ refused("control, P#4: a capture whose bytes moved from its pin is not the capture a control was "
3232
+ "written against", lambda: retained_capture("within-bound", root=copied), "CAPTURE_HASH_MISMATCH")
3233
+ expect("control, R#6: ... and the fixture in the checkout is untouched by that plant",
3234
+ retained_capture("within-bound")["call_id"], within["call_id"])
3235
+ refused("control, done-when 3(b): a capture missing a cache field is refused, never read as a smaller number",
3236
+ lambda: observed_input_of({"call_id": "r1/S3/t1/0b", "usage": {"input_tokens": 1}}),
3237
+ "CAPTURE_USAGE_MISSING")
3238
+ expect("done-when 3: a retained R-authoring capture above 120k read as a NON-window call is accepted, and "
3239
+ "the window rule is untouched",
3240
+ bound.check_observed(observed_input_of(authoring), authoring["view_window"]), [])
3241
+ expect("control, P#4: the two retained captures name the source file they were copied from, its "
3242
+ "sha256 and the extraction rule, so a reader can go back to the evidence",
3243
+ [cap["call_id"] for cap in (within, authoring)
3244
+ if not all(mark in cap["origin"] for mark in ("sanitised", "sha256", "Extraction rule"))], [])
3245
+ expect("control, P#4: the R-authoring capture's observed input really is above the view-window bound, "
3246
+ "which is what makes it the case the non-window contract is for",
3247
+ observed_input_of(authoring) > bound.INPUT_BOUND, True)
3248
+ expect("control, P#4: every capture fixture carries usage counts and nothing else - no prompt, no "
3249
+ "completion, no identifier",
3250
+ sorted({key for cap in (within, overrun, authoring) for key in cap
3251
+ if key not in ("call_id", "view_window", "origin", "note", "usage")}), [])
3252
+ expect("control, P#4: ... and the fixture bytes themselves are swept for the shape and for an owner "
3253
+ "path, the pins with them",
3254
+ [path.name for path in sorted(records.fixture_root("captures").glob("*.json")) + [records.fixture_root() / "captures.json"]
3255
+ for text in [path.read_text(encoding="utf-8")]
3256
+ if "sk-ant-" + "oat" in text or FX_HOME in text
3257
+ or any(owner in text for owner in (str(pathlib.Path.home()), "/home/", "/Users/Shared"))], [])
3258
+ named("control, done-when 3(c): a view-window capture above 120k is INPUT_BOUND_EXCEEDED (this one is "
3259
+ "the synthetic fixture: no retained capture of that case exists)",
3260
+ bound.check_observed(observed_input_of(overrun), True), "INPUT_BOUND_EXCEEDED")
3261
+ expect("control, done-when 3(c): the excess record the dispatcher writes carries that observation and the "
3262
+ "declaration it ran under, which is what the recovery rule reads",
3263
+ {key: bound.committed(bound.excess(overrun["call_id"], observed_input_of(overrun),
3264
+ records.now()), 2)[key]
3265
+ for key in ("code", "call_id", "observed", "declaration_seq")},
3266
+ {"code": "INPUT_BOUND_EXCEEDED", "call_id": overrun["call_id"],
3267
+ "observed": observed_input_of(overrun), "declaration_seq": 2})
3268
+
3269
+ def owned_omission(record):
3270
+ """The omission id of a record's own clip - the row whose origin is `owned`. A record can also
3271
+ have overlap rows now, so an expansion of "the clipped middle" has to say which interval it
3272
+ means."""
3273
+ return next(m["omission_id"] for w in windows for m in w["omission_manifest"]
3274
+ if m["record_id"] == record and m["origin"] == "owned")
3275
+
3276
+ # ---- done-when 4: the omission manifest and the two completeness levels -------------------
3277
+ clip = next(m for w in windows for m in w["omission_manifest"] if m["record_id"] == rid("pending_clip"))
3278
+ expect("done-when 4, omission manifest: a clipped record is named with its size and its omitted span",
3279
+ (clip["record_id"], clip["size"], clip["omitted_span"]["start"] < clip["omitted_span"]["end"],
3280
+ clip["omitted_span"]["sha256"] == records.sha256_bytes(
3281
+ texts[rid("pending_clip")][clip["omitted_span"]["start"]:clip["omitted_span"]["end"]].encode("utf-8"))),
3282
+ (rid("pending_clip"), len(texts[rid("pending_clip")]), True, True))
3283
+ # the accounting unit is the omitted INTERVAL, which is what the manifest's rows now are
3284
+ clipped_ids = sorted({m["omission_id"] for w in windows for m in w["omission_manifest"]})
3285
+ expanded = {i: "expand" for i in clipped_ids}
3286
+ # R#2: a record that lost SEVERAL intervals is not discharged by one expansion. The case the finding
3287
+ # names is a context entry truncated at OVERLAP_ITEM_BYTES and THEN omitted for a side's budget: the
3288
+ # first cut lost its tail, the omission lost what was left, and the two intervals together are the
3289
+ # record. Nonrepetitive text, so a hash cannot match the wrong interval by accident.
3290
+ def wordy(n, length):
3291
+ return "".join(f"{n}-{k} " for k in range(length))[:length]
3292
+ wide = []
3293
+ for n in range(1, 11):
3294
+ item = {"pointer": "/message/content", "kind": "assistant" if n % 2 else "tool_result",
3295
+ "text": wordy(n, 2_000), "tool": None, "ts": fx_stamp(1, hour=n % 24)}
3296
+ wide.append(context_entry(item, n, "context", offset=n * 7))
3297
+ wide.append(synthetic(11, "human"))
3298
+ wide_window = make_window(base_probe, 1, wide, 10, 11, golden_run["limits"])
3299
+ wide_rows = wide_window["omission_manifest"]
3300
+ by_record = collections.defaultdict(list)
3301
+ for m in wide_rows:
3302
+ by_record[m["record_id"]].append(m["omission_id"])
3303
+ several = {r: ids for r, ids in by_record.items() if len(ids) > 1}
3304
+ expect("R#2: a context entry truncated at 700 characters and then omitted for the side's budget has "
3305
+ "lost TWO intervals, and both are in the manifest", bool(several), True)
3306
+ worst = sorted(several)[0] if several else None
3307
+ expect("R#2: ... whose intervals tile the record's 2000 characters exactly, in the block's own "
3308
+ "coordinates",
3309
+ coverage.normalize([[m["omitted_span"]["start"], m["omitted_span"]["end"]]
3310
+ for m in wide_rows if m["record_id"] == worst]) if worst else None,
3311
+ [[0, 2_000]])
3312
+ expect("R#2: ... and each interval's hash is the hash of its own characters, so one cannot discharge "
3313
+ "another",
3314
+ len({m["omitted_span"]["sha256"] for m in wide_rows if m["record_id"] == worst}) if worst else None, 2)
3315
+ expect("R#2: ... and every row carries a usable locator, which is what expansion seeks with",
3316
+ [m["omission_id"] for m in wide_rows if m["locator"]["offset"] is None], [])
3317
+ if several:
3318
+ record, ids = sorted(several.items())[0]
3319
+ wide_ids = sorted(m["omission_id"] for m in wide_rows)
3320
+ partial = [{"omission_id": i, "decision": "expand", "reason": "the first interval only"}
3321
+ for i in ids[:1]]
3322
+ expect(f"R#2: one interval expanded does not discharge the {len(ids)} that record lost - the "
3323
+ "decision set is short, so the session is not view complete",
3324
+ completeness([True], wide_ids, partial, set(ids[:1]))["view_complete"], False)
3325
+ expect("R#2: ... and the decision set is named incomplete rather than accepted",
3326
+ bool([e for e in check_decisions(wide_rows, {}, partial) if "SET_MISMATCH" in e]), True)
3327
+ every = [{"omission_id": i, "decision": "expand", "reason": "all of them"} for i in wide_ids]
3328
+ expect("R#2: ... while a decision for every interval is complete",
3329
+ (completeness([True], wide_ids, every, set(wide_ids))["view_complete"],
3330
+ check_decisions(wide_rows, {}, every)), (True, []))
3331
+ oid_of = {}
3332
+ for w in windows:
3333
+ for m in w["omission_manifest"]:
3334
+ oid_of.setdefault(m["record_id"], m["omission_id"])
3335
+ with_skip = [{"omission_id": i, "decision": "skip" if i == oid_of[rid("pair_plain")] else "expand"}
3336
+ for i in clipped_ids]
3337
+ expect("done-when 4, completeness: a recorded skip leaves the session view complete and not source complete, "
3338
+ "and the skipped span is listed",
3339
+ completeness([True] * len(windows), clipped_ids, with_skip,
3340
+ set(clipped_ids) - {oid_of[rid("pair_plain")]}),
3341
+ {"view_complete": True, "source_complete": False, "skipped": [oid_of[rid("pair_plain")]],
3342
+ "unresolved_versions": []})
3343
+ # M#8: the backlog of an older version was a count no consumer read. It is a state, and completeness
3344
+ # enforces it: unread ranges of a version this stage did not view are content nobody has looked at,
3345
+ # so the session is not source complete and no claim of absence may rest on it.
3346
+ held = unresolved_versions([{"version": 1, "window": "w-1", "unread": [[0, 4]]},
3347
+ {"version": 2, "window": "w-2", "unread": [[7, 9]]}], 2)
3348
+ expect("done-when 4: the backlog of another version is carried as the work it is, not as a count",
3349
+ held, [{"version": 1, "window": "w-1", "unread": [[0, 4]]}])
3350
+ expect("done-when 4, completeness: a session with an unresolved earlier version is view complete and NOT "
3351
+ "source complete, and the version is named",
3352
+ completeness([True] * len(windows), clipped_ids,
3353
+ [{"omission_id": i, "decision": d} for i, d in expanded.items()], set(clipped_ids),
3354
+ unresolved=held),
3355
+ {"view_complete": True, "source_complete": True and False, "skipped": [], "unresolved_versions": [1]})
3356
+ expect("done-when 6: and no claim of absence may rest on it, because its basis is not source",
3357
+ absence_claim_allowed(coverage_basis(
3358
+ {"sources": [{"accounted": True, "directory_present": True}],
3359
+ "sessions": [{"status": "read_complete", "unprocessed": False, "view_complete": True,
3360
+ "source_complete": False}]})), False)
3361
+ expect("done-when 4: views.json carries the unresolved state per transcript and in its totals, and the "
3362
+ "fixture's own transcripts have none",
3363
+ ({t["name"]: t["unresolved_versions"] for t in manifest["transcripts"] if t["unresolved_versions"]},
3364
+ manifest["totals"]["unresolved_versions"]), ({}, 0))
3365
+ expect("done-when 4, completeness: a clipped record with neither an executed expansion nor a skip is not view "
3366
+ "complete", completeness([True] * len(windows), clipped_ids,
3367
+ [{"record_id": i, "decision": "expand"} for i in clipped_ids], set())["view_complete"], False)
3368
+ expect("done-when 4, completeness: a window that did not pass the gate is not view complete",
3369
+ completeness([True, False], clipped_ids, with_skip, set(clipped_ids))["view_complete"], False)
3370
+ # P#6: every branch of the forcing predicate, each as a case of its own with its own expected answer.
3371
+ # The golden run exercises one shape - a pending event before every clipped record with a later human
3372
+ # turn - and no call of it anywhere passed a search hit, so the search branch and the boundary cases
3373
+ # were covered by a label and nothing else.
3374
+ # `line` is 1-based and the predicate works in 0-based indexes, so each case names the INDEX it means
3375
+ def forcing(clipped_at, humans_at, events=(), hits=()):
3376
+ clipped = [{"record_id": f"r{index}", "line": index + 1} for index in clipped_at]
3377
+ return forced_records(clipped, humans_at, events, hits)
3378
+ for label, args, want in (
3379
+ ("a clipped record before the pending event is not forced",
3380
+ ([3], [9], [5]), {}),
3381
+ ("the clipped record at the event is forced by the event",
3382
+ ([5], [9], [5]), {"r5": "pending_event"}),
3383
+ ("one between the event and the next human turn is forced",
3384
+ ([7], [9], [5]), {"r7": "pending_event"}),
3385
+ ("one at the next human turn itself is not forced, because the stretch ends there",
3386
+ ([9], [9], [5]), {}),
3387
+ ("one after the next human turn is not forced",
3388
+ ([11], [9], [5]), {}),
3389
+ ("with no later human turn at all, everything from the event on is forced",
3390
+ ([7, 11], [2], [5]), {"r7": "pending_event", "r11": "pending_event"}),
3391
+ ("a search match forces a record no event covers",
3392
+ ([11], [9], [5], ["r11"]), {"r11": "search_match"}),
3393
+ ("a search match alone forces, with no pending event declared",
3394
+ ([4], [9], (), ["r4"]), {"r4": "search_match"}),
3395
+ ("when both reasons apply the event is the one recorded, because it is the stronger claim",
3396
+ ([7], [9], [5], ["r7"]), {"r7": "pending_event"}),
3397
+ ("two events each force their own stretch",
3398
+ ([3, 7], [5, 9], [2, 6]), {"r3": "pending_event", "r7": "pending_event"}),
3399
+ # the event index IS a human turn: the stretch runs from it to the NEXT human turn, not to
3400
+ # itself, which is the difference between the two sides of the search for that turn
3401
+ ("an event that falls on a human turn forces up to the following one",
3402
+ ([5, 7, 11], [5, 9], [5]), {"r5": "pending_event", "r7": "pending_event"}),
3403
+ ("nothing is forced when neither reason applies",
3404
+ ([3], [9], (), ()), {})):
3405
+ expect(f"done-when 5, forcing branch: {label}", forcing(*args), want)
3406
+ forced = forced_records([{"record_id": m["record_id"], "line": m["line"]} for w in windows for m in w["omission_manifest"]],
3407
+ records.read_json(run_dir / main["sequence"])["human_lines"],
3408
+ [e["first_record"] for e in golden_run["state"]["pending_events"]])
3409
+ manifest_rows = [m for w in windows for m in w["omission_manifest"]]
3410
+ named("done-when 5, forced: a decision for each omitted interval, with a reason, and no forced record skipped",
3411
+ check_decisions(manifest_rows, forced, [{"record_id": i, "decision": "expand", "reason": "the gap may hold the outcome"}
3412
+ for i in clipped_ids]))
3413
+ named("control, forced: a clipped record with no decision is named",
3414
+ check_decisions(clipped_ids, forced, [{"record_id": clipped_ids[0], "decision": "skip", "reason": "small"}]),
3415
+ "SET_MISMATCH")
3416
+ named("control, forced: a decision without a reason is named",
3417
+ check_decisions(clipped_ids, forced, [{"record_id": i, "decision": "expand", "reason": " " if i == clipped_ids[0] else "r"}
3418
+ for i in clipped_ids]), "EXPANSION_DECISION_INVALID")
3419
+ named("control, forced: a forced record answered with skip is named, whichever interval of it the "
3420
+ "decision was about",
3421
+ check_decisions(manifest_rows, forced,
3422
+ [{"omission_id": i, "decision": "skip", "reason": "r"} for i in clipped_ids]),
3423
+ "EXPANSION_SKIPPED")
3424
+
3425
+ # ---- done-when 5: the mandatory expansion predicate, by code ------------------------------
3426
+ expect("done-when 5, forced: a clipped record between a pending event and the next human turn is forced, and "
3427
+ "one after that human turn is not",
3428
+ (forced.get(rid("pending_clip")), rid("late_clip") in forced), ("pending_event", False))
3429
+ hits = forced_by_search(run_dir, name, [FX_TERM])
3430
+ expect("done-when 5, forced: the full-source search forces every clipped record it matches, clipped spans "
3431
+ "included", hits, {rid("pair_term"): "search_match"})
3432
+
3433
+ def try_expand(call):
3434
+ """`(windows, None)` of an expansion, or `([], "not run (...)")` when the product refuses it: the refusal
3435
+ fails each control that reads the expansion by its name, never as a traceback that would hide every control
3436
+ after it (WP-08c)."""
3437
+ try:
3438
+ return call(), None
3439
+ except Refused as exc:
3440
+ return [], f"not run ({str(exc).splitlines()[0][:160]})"
3441
+ expansion, unexpanded = try_expand(lambda: expand(run_dir, "r1/S3/t1/2", name, rid("pending_clip"),
3442
+ "the outcome may be in the gap", "pending_event",
3443
+ omission=owned_omission(rid("pending_clip"))))
3444
+ expect("done-when 5: an expansion is additional windows under the same bound and span mapping, and one larger "
3445
+ "than a window is itself split",
3446
+ unexpanded or (len(expansion) > 1, [w["bound_ok"] for w in expansion],
3447
+ coverage.normalize([s["block"] for w in expansion for r in w["records"] for s in r["segments"]])),
3448
+ (True, [True] * len(expansion), [[clip["omitted_span"]["start"], clip["omitted_span"]["end"]]]))
3449
+ expect("the expansion's text is the omitted characters, and the decision is logged with its reason",
3450
+ unexpanded or ("".join(r["text"] for w in expansion for r in w["records"])
3451
+ == texts[rid("pending_clip")][clip["omitted_span"]["start"]:clip["omitted_span"]["end"]],
3452
+ [(d["locator"]["record_id"], d["decision"], d["forced_by"]) for d in
3453
+ (json.loads(l) for l in records.jsonl_read(run_dir / "expansions.jsonl") if l.strip())]),
3454
+ (True, [(rid("pending_clip"), "expand", "pending_event")]))
3455
+ refused("control: an expansion of a record no window lists as clipped is refused",
3456
+ lambda: expand(run_dir, "r1/S3/t1/3", name, "99/message/content", "why not"), "EXPANSION_UNKNOWN")
3457
+ refused("control: a skip recorded against a forced record is refused",
3458
+ lambda: record_decision(run_dir, "r1/S3/t1/4", name, rid("pending_clip"), "skip", "too long", "pending_event"),
3459
+ "EXPANSION_SKIPPED")
3460
+ refused("control: a decision that is neither expand nor skip, or carries no reason, is refused",
3461
+ lambda: record_decision(run_dir, "r1/S3/t1/5", name, rid("late_clip"), "expand", ""),
3462
+ "EXPANSION_DECISION_INVALID")
3463
+ projected = run_dir / main["redacted"]
3464
+ kept = projected.read_bytes()
3465
+ projected.write_bytes(kept.replace(b"middle line 004", b"middle line 014"))
3466
+ refused("control: an expansion whose omitted characters no longer hash to the manifest's span is refused",
3467
+ lambda: expand(run_dir, "r1/S3/t1/6", name, rid("pending_clip"), "again",
3468
+ omission=owned_omission(rid("pending_clip"))), "EXPANSION_SOURCE_DRIFT")
3469
+ projected.write_bytes(kept)
3470
+
3471
+ # M#5: the projection's version is enforced where a stored artifact is CONSUMED, not only where a
3472
+ # quote is verified. Positive control first - every expansion above read these same files.
3473
+ seq_path = run_dir / "views" / name / "sequence.json"
3474
+ seq_kept = seq_path.read_bytes()
3475
+ seq_path.write_bytes(seq_kept.replace(f'"redaction_version": "{projection.CURRENT}"'.encode(),
3476
+ b'"redaction_version": "r1"'))
3477
+ refused("control: a sequence document built under another projection version is refused",
3478
+ lambda: sequence_doc(run_dir, name), "REDACTION_VERSION_MISMATCH")
3479
+ seq_path.write_bytes(seq_kept)
3480
+ win_path = sorted((run_dir / "views" / name).glob("[0-9]*.json"))[0]
3481
+ win_kept = win_path.read_bytes()
3482
+ win_path.write_bytes(win_kept.replace(f'"redaction_version": "{projection.CURRENT}"'.encode(),
3483
+ b'"redaction_version": "r1"'))
3484
+ refused("control: a window built under another projection version is refused where it is read",
3485
+ lambda: window_doc(run_dir, name, win_path), "REDACTION_VERSION_MISMATCH")
3486
+ refused("control: an expansion that must read such a window is refused by the same name",
3487
+ lambda: expand(run_dir, "r1/S3/t1/8", name, rid("late_clip"), "under a stale window",
3488
+ omission=owned_omission(rid("late_clip"))),
3489
+ "REDACTION_VERSION_MISMATCH")
3490
+ # P#5: the rendering a model sees is its own boundary. It takes a window from any caller, so a
3491
+ # caller that skipped the checked readers must still not be able to put a stale window in a packet.
3492
+ stale_window = {**records.read_json(win_path), "redaction_version": "r1"}
3493
+ refused("control, P#5: a stale window rendered for a model is refused at the rendering itself",
3494
+ lambda: render_window(stale_window), "REDACTION_VERSION_MISMATCH")
3495
+ refused("control, P#5: and the search that reads every window of a view reads them through the checked "
3496
+ "reader", lambda: forced_by_search(run_dir, name, [FX_TERM]), "REDACTION_VERSION_MISMATCH")
3497
+ win_path.write_bytes(win_kept)
3498
+ index_path = run_dir / main["index"]
3499
+ index_kept = index_path.read_bytes()
3500
+ index_path.write_bytes(index_kept.replace(f'"redaction_version":"{projection.CURRENT}"'.encode(),
3501
+ b'"redaction_version":"r1"'))
3502
+ def load_stale_index():
3503
+ try:
3504
+ search.load(index_path)
3505
+ except search.SearchError as exc:
3506
+ return f"refused: {exc}"
3507
+ return "loaded"
3508
+ expect("control: an index built under another projection version is refused where it is read",
3509
+ load_stale_index().startswith("refused: REDACTION_VERSION_MISMATCH"), True)
3510
+ index_path.write_bytes(index_kept)
3511
+
3512
+ # ---- done-when 6: the F-O9-04 pair ------------------------------------------------------
3513
+ pair = fx_entries(windows)
3514
+ expect("done-when 6: the pair's visible head and tail are the same bytes, and the manifest tells them apart by "
3515
+ "the hash of what each hides",
3516
+ (pair[rid("pair_plain")]["text"] == pair[rid("pair_term")]["text"],
3517
+ pair[rid("pair_plain")]["clipped"]["omitted_span"]["sha256"]
3518
+ != pair[rid("pair_term")]["clipped"]["omitted_span"]["sha256"]), (True, True))
3519
+ expect("done-when 6: the search misses the paraphrased occasion, so nothing forces its expansion",
3520
+ (rid("pair_plain") in forced_by_search(run_dir, name, [FX_TERM]), rid("pair_plain") in forced), (False, False))
3521
+ # M#10: the scope is DERIVED from the skip that was actually recorded, not asserted. The control used
3522
+ # to construct `source_complete: False` by hand, so it would have passed with the skip lost before
3523
+ # completeness was ever computed - it assumed the result it claimed to prove.
3524
+ rows_by_oid = {m["omission_id"]: m for w in windows for m in w["omission_manifest"]}
3525
+ record_decision(run_dir, "r1/S3/t1/9", name, rid("pair_plain"), "skip",
3526
+ "the paraphrased occasion is not worth the window",
3527
+ omission=oid_of[rid("pair_plain")])
3528
+ for other in clipped_ids:
3529
+ if other != oid_of[rid("pair_plain")]:
3530
+ row = rows_by_oid[other]
3531
+ record_decision(run_dir, f"r1/S3/t1/9-{other}", name, row["record_id"], "expand", "read whole",
3532
+ "pending_event" if row["record_id"] == rid("pending_clip") else "none",
3533
+ omission=other)
3534
+ recorded = [json.loads(l) for l in records.jsonl_read(run_dir / "expansions.jsonl") if l.strip()]
3535
+ mine = [d for d in recorded if d["locator"]["transcript"] == name and d["call_id"].startswith("r1/S3/t1/9")]
3536
+ derived = completeness([True] * len(windows), clipped_ids,
3537
+ [{"omission_id": d["locator"]["omission_id"], "decision": d["decision"]} for d in mine],
3538
+ {d["locator"]["omission_id"] for d in mine if d["decision"] == "expand"},
3539
+ unresolved=unresolved_versions(golden_run["main"].get("unresolved_versions", []), 1))
3540
+ expect("done-when 6: the skip recorded for the paraphrased member is what makes the session view complete "
3541
+ "and not source complete, and it is the one span listed",
3542
+ (derived["view_complete"], derived["source_complete"], derived["skipped"]),
3543
+ (True, False, [oid_of[rid("pair_plain")]]))
3544
+ scope = {"sources": [{"accounted": True, "directory_present": True}],
3545
+ "sessions": [{"status": "read_complete", "unprocessed": False,
3546
+ "view_complete": derived["view_complete"], "source_complete": derived["source_complete"]}]}
3547
+ expect("done-when 6, basis: S3's skip leaves the session at basis view, and a claim of absence over it is "
3548
+ "refused - it stays pending",
3549
+ (coverage_basis(scope), absence_claim_allowed(coverage_basis(scope))), ("view", False))
3550
+ # the mutation M#10 asks for: the skip is lost before completeness is computed, and the chain must break
3551
+ without = [d for d in mine if d["locator"]["omission_id"] != oid_of[rid("pair_plain")]]
3552
+ lost = completeness([True] * len(windows), clipped_ids,
3553
+ [{"omission_id": d["locator"]["omission_id"], "decision": d["decision"]} for d in without],
3554
+ {d["locator"]["omission_id"] for d in without if d["decision"] == "expand"})
3555
+ lost_scope = {**scope, "sessions": [{"status": "read_complete", "unprocessed": False,
3556
+ "view_complete": lost["view_complete"],
3557
+ "source_complete": lost["source_complete"]}]}
3558
+ expect("control, done-when 6: with the skip lost, the session is not even view complete and the basis is "
3559
+ "incomplete - so absence stays pending for a different reason, and the link is what carried it",
3560
+ (lost["view_complete"], lost["source_complete"], lost["skipped"],
3561
+ coverage_basis(lost_scope), absence_claim_allowed(coverage_basis(lost_scope))),
3562
+ (False, False, [], "incomplete", False))
3563
+ # R#1/R#2/R#5: expansion against REAL generated overlap manifests. The whole stage is run over a
3564
+ # transcript of long human and assistant turns with tool traffic between them, which is the shape
3565
+ # whose overlap is really cut and whose side budget really runs out. The rows below are the stage's
3566
+ # own; nothing here writes a manifest by hand, which is how the previous control passed while
3567
+ # production wrote `locator.offset: None` and expansion died on it.
3568
+ long_run = golden(root, "long", main_records=fx_long_records)
3569
+ long_name, long_dir = long_run["main"]["name"], long_run["run_dir"]
3570
+ long_rows = [m for f in long_run["main"]["windows"]
3571
+ for m in window_doc(long_dir, long_name, long_dir / f["path"])["omission_manifest"]]
3572
+ expect("R#1: the long-turn run really does omit overlap content, so these controls judge something",
3573
+ bool(long_rows), True)
3574
+ expect("R#1: every generated omission row carries a usable locator, which expansion seeks with",
3575
+ [m["omission_id"] for m in long_rows if m["locator"]["offset"] is None], [])
3576
+ # R#1 at the unit: the locator is on EVERY entry, owned or context, and a split span keeps it. The
3577
+ # rows above are all context today - an owned entry shown in a neighbour's overlap is not cut at the
3578
+ # moment, so the generated rows cannot see this - and the defect was exactly an owned message's
3579
+ # missing locator.
3580
+ long_seq = records.read_json(long_dir / long_run["main"]["sequence"])["sequence"]
3581
+ own_entries = [e for e in build_sequence(long_dir / long_run["main"]["redacted"],
3582
+ {r["line"] - 1 for r in long_seq if r["owned"]},
3583
+ lambda _l: "in_window", search.Index())[0]]
3584
+ expect("R#1: every sequence entry carries its projection offset, owned and context alike",
3585
+ [e["record_id"] for e in own_entries if e.get("offset") is None], [])
3586
+ wide_owned = next(e for e in own_entries if e["owned"] and len(e["text"]) > 1_000)
3587
+ expect("R#1: ... and a split span keeps the locator of the record it came from",
3588
+ [piece.get("offset") for piece in split_entry(wide_owned, 900)],
3589
+ [wide_owned.get("offset")] * len(split_entry(wide_owned, 900)))
3590
+ # R#2 at the unit: a view range of a SPLIT span maps to the block's own coordinates, not the span's.
3591
+ # Expansion reads these numbers as offsets into the block, so a span-local interval names characters
3592
+ # that were never omitted - and its hash can only disagree.
3593
+ piece = split_entry(wide_owned, 900)[1]
3594
+ mapped = omitted_intervals(piece, 100, len(piece["text"]))
3595
+ expect("R#2: the omitted interval of a split span is in the BLOCK's coordinates, so it starts past "
3596
+ "the span's own beginning",
3597
+ (bool(mapped), mapped[0]["start"] > 100 if mapped else None), (True, True))
3598
+ expect("R#2: ... and its hash is the hash of the characters it names, read from the block itself",
3599
+ [i["sha256"] for i in mapped],
3600
+ [records.sha256_bytes(wide_owned["text"][i["start"]:i["end"]].encode("utf-8")) for i in mapped])
3601
+ clip_entry = next((e for e in own_entries if "clipped" in e), None)
3602
+ if clip_entry is None:
3603
+ checks.failures.append("the long run holds no clipped record, so the clipped-coordinate control "
3604
+ "would pass over nothing")
3605
+ else:
3606
+ across = omitted_intervals(clip_entry, 0, len(clip_entry["text"]))
3607
+ expect("R#2: a clipped record's view elides its middle, so a view range across the elision maps "
3608
+ "to SEVERAL block intervals rather than one",
3609
+ len(across) == len(clip_entry["segments"]) and len(across) > 1, True)
3610
+ # ... and the invariant over EVERY generated row: the characters the block really holds at the row's
3611
+ # interval are the characters the row's hash names
3612
+ long_texts = projection_texts(long_dir, long_run["main"]["redacted"])
3613
+ wrong = [m["omission_id"] for m in long_rows
3614
+ if records.sha256_bytes(long_texts.get(m["record_id"], "")
3615
+ [m["omitted_span"]["start"]:m["omitted_span"]["end"]].encode("utf-8"))
3616
+ != m["omitted_span"]["sha256"]]
3617
+ expect("R#2: every generated omission row's interval, read against the projected block itself, holds "
3618
+ "the characters its hash names", wrong, [])
3619
+ for row in long_rows[:3]:
3620
+ back, unexpanded = try_expand(lambda row=row: expand(long_dir, "r1/S3/long/1", long_name, row["record_id"],
3621
+ "the overlap omitted it and a claim needs it",
3622
+ omission=row["omission_id"]))
3623
+ text = "".join(r["text"] for w in back for r in w["records"])
3624
+ expect(f"R#1: the omitted interval {row['omitted_span']['start']}-{row['omitted_span']['end']} of "
3625
+ f"{row['record_id']} is expanded from the generated manifest, and its characters hash to "
3626
+ "the interval the manifest named",
3627
+ unexpanded or records.sha256_bytes(text.encode("utf-8")), row["omitted_span"]["sha256"])
3628
+ # ... a record that lost several intervals may not be expanded without saying which
3629
+ multi = sorted({m["record_id"] for m in long_rows
3630
+ if sum(1 for x in long_rows if x["record_id"] == m["record_id"]) > 1})
3631
+ expect("R#2: the long-turn run has records that lost several intervals, so the next control judges "
3632
+ "something", bool(multi), True)
3633
+ if multi:
3634
+ refused("R#2: expanding such a record without naming the interval is refused, because expanding "
3635
+ "one of them discharges only that one",
3636
+ lambda: expand(long_dir, "r1/S3/long/2", long_name, multi[0], "all of it"),
3637
+ "EXPANSION_AMBIGUOUS")
3638
+ # WP-08 overlap role: a record the overlap budget omits from a NEIGHBOUR's overlap keeps its own role. The
3639
+ # omitted entries carried none, so the manifest gave the row `context` and an expansion of that row put
3640
+ # `context` on an in-window record. At the unit, the two cases are the same entries and differ only in
3641
+ # their role; the run is this fixture's own, every record of it in a window, so no row is borrowed.
3642
+ gone_roles = []
3643
+ for role in ("context", "in_window"):
3644
+ same = [{**synthetic(n, "assistant" if n % 2 else "tool_result", "z" * 600), "window_role": role}
3645
+ for n in range(1, 8)]
3646
+ gone_roles.append(sorted({g.get("window_role") for g in overlap_side(same, budget=1_200)[1]}))
3647
+ expect("WP-08 overlap role: an entry the side's budget omits keeps its own role, for an in-window entry as "
3648
+ "for a context one", gone_roles, [["context"], ["in_window"]])
3649
+ role_run = golden(root, "roles", overhead=100_000, main_only=True, main_records=fx_role_records,
3650
+ owned=fx_owned(fx_role_records()), pending_at=None)
3651
+ role_name, role_dir = role_run["main"]["name"], role_run["run_dir"]
3652
+ role_docs = [window_doc(role_dir, role_name, role_dir / f["path"]) for f in role_run["main"]["windows"]]
3653
+ own_role = {r["record_id"]: r["window_role"] for d in role_docs for r in d["records"]}
3654
+ budget_rows = [m for d in role_docs for m in d["omission_manifest"] if m["origin"] == "overlap"
3655
+ and m["record_id"] in {g["record_id"] for side in ("prev", "next")
3656
+ for g in d["overlap"]["omitted"][side]}]
3657
+ expect("WP-08 overlap role: this fixture's overlap budget omits records that are in a window, so the next "
3658
+ "two controls judge something",
3659
+ (len(role_docs) > 1, bool(budget_rows), sorted({own_role.get(m["record_id"]) for m in budget_rows})),
3660
+ (True, True, ["in_window"]))
3661
+ expect("WP-08 overlap role: the overlap row of such a record carries the record's own role, not context",
3662
+ [m["omission_id"] for m in budget_rows if m["window_role"] != own_role.get(m["record_id"])], [])
3663
+ if budget_rows:
3664
+ row = budget_rows[0]
3665
+ try:
3666
+ back = sorted({r["window_role"] for w in expand(role_dir, "r1/S3/roles/1", role_name, row["record_id"],
3667
+ "the overlap omitted it and a claim needs it",
3668
+ omission=row["omission_id"]) for r in w["records"]})
3669
+ except Refused as exc:
3670
+ back = f"refused: {exc}"
3671
+ expect("WP-08 overlap role: ... and what is expanded from that row carries the record's own role",
3672
+ back, [own_role.get(row["record_id"])])
3673
+ # V#1: every DISPLAYED cut of a generated window is in the manifest, hashed against the projected
3674
+ # block, expandable, and required for completeness. A displayed cut is the easy one to lose - the
3675
+ # entry is still shown, so nothing looks missing - and a 2000-character context entry shown as 700
3676
+ # used to contribute no row at all.
3677
+ displayed = [(w_n, e) for w_n, w in [(f["path"], window_doc(long_dir, long_name, long_dir / f["path"]))
3678
+ for f in long_run["main"]["windows"]]
3679
+ for side in ("prev", "next") for e in w["overlap"][side] if e.get("omitted_intervals")]
3680
+ expect("V#1: the long-turn run really shows entries whose text was cut, so these controls judge "
3681
+ "something", bool(displayed), True)
3682
+ if displayed:
3683
+ long_texts_v1 = projection_texts(long_dir, long_run["main"]["redacted"])
3684
+ manifested = {m["omission_id"] for m in long_rows}
3685
+ expect("V#1: every interval a DISPLAYED overlap entry has lost is in the omission manifest",
3686
+ sorted({omission_id(e["record_id"], i["start"], i["end"])
3687
+ for _w, e in displayed for i in e["omitted_intervals"]} - manifested), [])
3688
+ expect("V#1: ... and each of those intervals hashes to the characters the projected block holds there",
3689
+ [e["record_id"] for _w, e in displayed for i in e["omitted_intervals"]
3690
+ if records.sha256_bytes(long_texts_v1.get(e["record_id"], "")[i["start"]:i["end"]].encode("utf-8"))
3691
+ != i["sha256"]], [])
3692
+ shown_row = next(m for m in long_rows
3693
+ if m["omission_id"] in {omission_id(e["record_id"], i["start"], i["end"])
3694
+ for _w, e in displayed for i in e["omitted_intervals"]})
3695
+ back, unexpanded = try_expand(lambda: expand(long_dir, "r1/S3/long/displayed", long_name, shown_row["record_id"],
3696
+ "the overlap showed only the head of it",
3697
+ omission=shown_row["omission_id"]))
3698
+ expect("V#1: ... and a displayed entry's lost tail is expandable, its characters hashing to the row",
3699
+ unexpanded or records.sha256_bytes("".join(r["text"] for w in back for r in w["records"]).encode("utf-8")),
3700
+ shown_row["omitted_span"]["sha256"])
3701
+ expect("V#1: ... and completeness requires a decision about it, so a view that ignores it is not "
3702
+ "complete",
3703
+ completeness([True], sorted(manifested),
3704
+ [{"omission_id": i, "decision": "expand", "reason": "r"}
3705
+ for i in sorted(manifested) if i != shown_row["omission_id"]],
3706
+ manifested - {shown_row["omission_id"]})["view_complete"], False)
3707
+ # Q#1: `size` means the record's own length in every row, whatever the row is about. The projected
3708
+ # block is the authority, so each row is read against it - and the three shapes that got it wrong
3709
+ # are each present: a context entry capped before it got here, a clipped result whose view elides a
3710
+ # middle, and a split message whose entry is one span of it.
3711
+ block_len = {rid: len(text) for rid, text in long_texts_v1.items()} if displayed else {}
3712
+ if not displayed:
3713
+ block_len = {rid: len(text) for rid, text
3714
+ in projection_texts(long_dir, long_run["main"]["redacted"]).items()}
3715
+ wrong_size = [(m["record_id"], m["size"], block_len.get(m["record_id"]))
3716
+ for m in long_rows if m["size"] != block_len.get(m["record_id"])]
3717
+ expect("Q#1: every generated omission row's size is the full projected block's length, not a span's "
3718
+ "end and not the length of a text already capped", wrong_size, [])
3719
+ # Z#2: a record whose unsplit text is long is not a split record. The split ones are generated
3720
+ # here - a run whose packet overhead leaves a small window, so `cut_windows` really divides the long
3721
+ # messages into spans - and their span metadata is asserted before any size claim rests on them.
3722
+ split_records = [r for w in windows for r in w["records"] if "span" in r]
3723
+ expect("Z#2: the fixture really splits a message into spans, so the claims below judge split entries",
3724
+ bool(split_records), True)
3725
+ expect("Z#2: every split entry carries its place in the message - index, count and its own segments",
3726
+ [eid(r) for r in split_records
3727
+ if not (r["span"]["index"] >= 1 and r["span"]["of"] > 1 and r["segments"])], [])
3728
+ # WP-08b: a window names an entry by its label, so a span's heading says which part of its record it is, as its
3729
+ # entry did; an overlap entry, which carries its entry and no span, says it the same way
3730
+ headings = {(w["window_n"], eid(r)): next((line for line in render_window(w).split("entry: " + entry_labels(w)[eid(r)] + "\n", 1)[1:2]), "")
3731
+ .split("\n", 1)[0] for w in windows for r in w["records"] if "span" in r}
3732
+ overlap_spans = [(e["entry"], next((h for h in [render_overlap(e, "e1")]), "")) for w in windows
3733
+ for side in ("prev", "next") for e in w["overlap"][side] if "#" in e["entry"]]
3734
+ expect("WP-08b: every split entry's heading ends its kind line with its part of the record, `part k of n`, owned or "
3735
+ "in an overlap, and the label line holds the label alone",
3736
+ [key for key, line in headings.items()
3737
+ if not line.endswith(f"part {key[1].rsplit('#', 1)[1].replace('/', ' of ')}")]
3738
+ + [ident for ident, text in overlap_spans
3739
+ if f"part {ident.rsplit('#', 1)[1].replace('/', ' of ')} (overlap)" not in text.split("\n")[1]],
3740
+ [])
3741
+ expect("WP-08b: ... and the fixture has split entries in an overlap as well as owned", bool(headings) and bool(overlap_spans), True)
3742
+ by_split = {rid: [r for r in split_records if r["record_id"] == rid]
3743
+ for rid in {r["record_id"] for r in split_records}}
3744
+ expect("Z#2: ... and the spans of one message tile it, so no row derived from one rests on a guess",
3745
+ [rid for rid, parts in sorted(by_split.items())
3746
+ if coverage.normalize([list(seg["block"]) for part in parts for seg in part["segments"]]
3747
+ + [list(gap) for part in parts
3748
+ for gap in (part.get("clipped") or {}).get("gaps", [])])
3749
+ != [[0, parts[0]["size"]]]], [])
3750
+ split_rows = [m for w in windows for m in w["omission_manifest"] if m["record_id"] in by_split]
3751
+ expect("Z#2: the manifest really holds rows about those split messages", bool(split_rows), True)
3752
+ expect("Z#2: every displayed and omitted row derived from a split message reports the FULL projected "
3753
+ "block's length as its size, never a span's",
3754
+ [(m["record_id"], m["size"], len(texts.get(m["record_id"], "")))
3755
+ for m in split_rows if m["size"] != len(texts.get(m["record_id"], ""))], [])
3756
+ expect("Q#1: and so does every other row of this run, whatever it is about",
3757
+ [(m["record_id"], m["size"]) for w in windows for m in w["omission_manifest"]
3758
+ if m["size"] != len(texts.get(m["record_id"], ""))], [])
3759
+ # ... and the same for a SPLIT OWNED message shown in a neighbour's overlap, whose intervals are the
3760
+ # block's and not the span's
3761
+ split_owned = next((e for e in own_entries if e["owned"] and len(e["text"]) > OVERLAP_ITEM_BYTES * 2), None)
3762
+ if split_owned is None:
3763
+ checks.failures.append("the long run holds no owned entry long enough to be cut by the overlap, so "
3764
+ "the split-message control would pass over nothing")
3765
+ else:
3766
+ # the LAST span whose own text is longer than the overlap's item cap: that is the one the
3767
+ # overlap really cuts, and the one whose coordinates are not the block's unless they are mapped
3768
+ spans = split_entry(split_owned, 1_200)
3769
+ piece = next(x for x in reversed(spans) if len(x["text"]) > OVERLAP_ITEM_BYTES)
3770
+ shown_piece = overlap_of(piece)
3771
+ expect("V#1: a split owned message shown in an overlap reports its cut in the BLOCK's coordinates, "
3772
+ "past the span's own beginning",
3773
+ (bool(shown_piece.get("omitted_intervals")),
3774
+ shown_piece["omitted_intervals"][0]["start"] > OVERLAP_ITEM_BYTES
3775
+ if shown_piece.get("omitted_intervals") else None), (True, True))
3776
+ expect("V#1: ... and that interval hashes to the characters the block holds there",
3777
+ [i["sha256"] for i in shown_piece.get("omitted_intervals") or []],
3778
+ [records.sha256_bytes(split_owned["text"][i["start"]:i["end"]].encode("utf-8"))
3779
+ for i in shown_piece.get("omitted_intervals") or []])
3780
+ # R#5: two expansions under ONE call id, both complete and both readable
3781
+ pair_rows = [m for m in long_rows if m["record_id"] != long_rows[0]["record_id"]][:1] + long_rows[:1]
3782
+ sets, unexpanded_pair = [], []
3783
+ for row in pair_rows:
3784
+ got, unexpanded = try_expand(lambda row=row: expand(long_dir, "r1/S3/long/same-call", long_name, row["record_id"],
3785
+ "both under one call", omission=row["omission_id"]))
3786
+ sets.append((row, got))
3787
+ unexpanded_pair += [unexpanded] if unexpanded else []
3788
+ written = sorted((long_dir / "views" / long_name).glob("expansion-r1_S3_long_same-call-*.json"))
3789
+ expect("R#5: two expansions under one call id leave two independent artifact sets, not one overwriting "
3790
+ "the other", unexpanded_pair[0] if unexpanded_pair else len(written), sum(len(got) for _row, got in sets))
3791
+ for row, got in sets:
3792
+ tag = re.sub(r"[^A-Za-z0-9._-]", "_", row["omission_id"])[-24:]
3793
+ mine = sorted((long_dir / "views" / long_name).glob(f"expansion-r1_S3_long_same-call-{tag}-*.json"))
3794
+ expect(f"R#5: ... and each set is readable on its own and carries its own record",
3795
+ unexpanded_pair[0] if unexpanded_pair else
3796
+ ([window_doc(long_dir, long_name, path)["expansion_of"] for path in mine], len(mine)),
3797
+ ([row["record_id"]] * len(got), len(got)))
3798
+ decided = [json.loads(l) for l in records.jsonl_read(long_dir / "expansions.jsonl") if l.strip()] \
3799
+ if (long_dir / "expansions.jsonl").is_file() else []
3800
+ expect("R#5: ... and each decision names the omission it was about, not only the record",
3801
+ unexpanded_pair[0] if unexpanded_pair else [d for d in decided if not d["locator"].get("omission_id")], [])
3802
+ found, unexpanded = try_expand(lambda: expand(run_dir, "r1/S3/t1/7", name, rid("pair_term"),
3803
+ "the search matched inside the gap", "search_match",
3804
+ omission=owned_omission(rid("pair_term"))))
3805
+ expect("done-when 6, control: the same occasion written with a retrieval term is matched, forced, expanded, and "
3806
+ "found", unexpanded or FX_HIDDEN_TERM in "".join(r["text"] for w in found for r in w["records"]), True)
3807
+
3808
+ # ---- the coverage basis of §5.4, in the order the design checks it ------------------------
3809
+ expect("basis: every session source complete is basis source, and absence may rest on it",
3810
+ (coverage_basis({**scope, "sessions": [{"status": "read_complete", "unprocessed": False,
3811
+ "view_complete": True, "source_complete": True}]}),
3812
+ absence_claim_allowed("source")), ("source", True))
3813
+ for label, change in (("a source that is not accounted", {"sources": [{"accounted": False, "directory_present": True}]}),
3814
+ ("a source directory that is missing", {"sources": [{"accounted": True, "directory_present": False}]}),
3815
+ ("a deferred session", {"sessions": [{"status": "deferred", "unprocessed": False,
3816
+ "view_complete": True, "source_complete": True}]}),
3817
+ ("a session with records this window owns and has not processed",
3818
+ {"sessions": [{"status": "read_complete", "unprocessed": True,
3819
+ "view_complete": True, "source_complete": True}]})):
3820
+ expect(f"basis: {label} makes the basis incomplete", coverage_basis({**scope, **change}), "incomplete")
3821
+
3822
+ # ---- done-when 1: the copy is where tampering is caught ----------------------------------
3823
+ refused("control: a copy whose bytes the census did not read is refused",
3824
+ lambda: copy_version(root / "changed", golden_run["paths"]["main"], None, {"sha": "00" * 32, "record_count": main["records"]}),
3825
+ "SOURCE_CHANGED")
3826
+ quarantined = golden(root, "changed-run", overhead=100_000, census_sha="00" * 32)
3827
+ named("control: under the production posture the session whose source changed is quarantined by name and the "
3828
+ "run goes on", [q["reason"] for q in quarantined["manifest"]["quarantined"]], "SOURCE_CHANGED")
3829
+ planted = root / "tampered" / "sources"
3830
+ planted.mkdir(parents=True)
3831
+ (planted / f"{main['version_sha']}.jsonl").write_text("not the bytes this name claims\n", encoding="utf-8")
3832
+ refused("control: an existing copy that does not hash to its own name is refused",
3833
+ lambda: copy_version(root / "tampered", golden_run["paths"]["main"], None, {"sha": main["version_sha"], "record_count": main["records"]}),
3834
+ "SOURCE_TAMPERED")
3835
+ refused("control: a source that cannot be read is named, never silently skipped",
3836
+ lambda: copy_version(run_dir, root / "nothing-here.jsonl", None), "SOURCE_UNREADABLE")
3837
+ # D-20261103-8facee: the version S2 copies is the census's complete-line prefix. The host may append after the census
3838
+ # - lines, or the end of a line it was still writing - and that is the next run's; changed lines are not.
3839
+ version = {"sha": main["version_sha"], "record_count": main["records"]}
3840
+ original = golden_run["paths"]["main"].read_bytes()
3841
+
3842
+ def copied(where, source):
3843
+ """The copy's `(run-relative path, sha256)`, or the refusal: a control reads either, never a traceback."""
3844
+ try:
3845
+ return copy_version(root / where, source, None, version)
3846
+ except Refused as exc:
3847
+ return exc
3848
+ appended = root / "appended" / "t1.jsonl"
3849
+ appended.parent.mkdir()
3850
+ appended.write_bytes(original + b'{"type": "user", "timestamp": "2026-10-03T23:00:00.000Z", "message": {"role": "user", "content": "later"}}\n')
3851
+ grown = copied("appended-run", appended)
3852
+ expect("8facee: a transcript the host appended to after the census is copied as the census read it",
3853
+ (grown[1], (root / "appended-run" / grown[0]).read_bytes() == original) if isinstance(grown, tuple) else grown,
3854
+ (main["version_sha"], True))
3855
+ writing = root / "appended" / "writing.jsonl"
3856
+ writing.write_bytes(original + b'{"type": "user", "timestamp": "2026-10-03T23:00:00.000Z", "message": {"role": "user", "content": "lat')
3857
+ writing_copy = copied("writing-run", writing)
3858
+ expect("8facee: a line the host is still writing is no record: the copy is the census's lines",
3859
+ writing_copy[1] if isinstance(writing_copy, tuple) else writing_copy, main["version_sha"])
3860
+ with writing.open("ab") as handle:
3861
+ handle.write(b'er"}}\n')
3862
+ completed_copy = copied("completed-run", writing)
3863
+ expect("8facee: a line still being written at the census and completed since is not copied either",
3864
+ completed_copy[1] if isinstance(completed_copy, tuple) else completed_copy, main["version_sha"])
3865
+ rewritten = root / "appended" / "rewritten.jsonl"
3866
+ rewritten.write_bytes(original.replace(b"2026-10-0", b"2026-11-0", 1))
3867
+ refused("8facee: a transcript whose census lines changed is SOURCE_CHANGED",
3868
+ lambda: copy_version(root / "rewritten-run", rewritten, None, version), "SOURCE_CHANGED", "rewritten or truncated")
3869
+ truncated = root / "appended" / "truncated.jsonl"
3870
+ truncated.write_bytes(b"".join(original.splitlines(keepends=True)[:-1]))
3871
+ refused("8facee: a transcript shorter than the census read is SOURCE_CHANGED",
3872
+ lambda: copy_version(root / "truncated-run", truncated, None, version), "SOURCE_CHANGED", "rewritten or truncated")
3873
+ # D-20261103-85f3e8: S2 reads a unit - the root and every member at any depth that owes the window something
3874
+ _unit_dir, unit_ids, unit_manifest = golden_unit(root, "unit")
3875
+ expect("85f3e8: S2 reads each member of the unit that owes the window something, at any depth, as part of the root's unit",
3876
+ sorted((t["transcript"], t["unit"], t["kind"]) for t in unit_manifest["transcripts"])
3877
+ if isinstance(unit_manifest, dict) else repr(unit_manifest),
3878
+ sorted([(unit_ids["root"], unit_ids["root"], "session"), (unit_ids["d1"], unit_ids["root"], "child"),
3879
+ (unit_ids["d2"], unit_ids["root"], "child")]))
3880
+ _changed_dir, _ids, changed_manifest = golden_unit(root, "unit-changed", plant="changed")
3881
+ expect("85f3e8: under the production posture a member whose source changed quarantines its whole unit",
3882
+ sorted((q["id"], "SOURCE_CHANGED" in q["reason"], q["because"]) for q in changed_manifest["quarantined"])
3883
+ if isinstance(changed_manifest, dict) else repr(changed_manifest),
3884
+ sorted([(unit_ids["d2"], True, None), (unit_ids["root"], False, unit_ids["d2"]), (unit_ids["d1"], False, unit_ids["d2"])]))
3885
+ expect("r1 #4: the views made for a unit before one of its members failed are quarantined with it, not published",
3886
+ ([t["transcript"] for t in changed_manifest["transcripts"]], changed_manifest["totals"]["files"])
3887
+ if isinstance(changed_manifest, dict) else repr(changed_manifest), ([], 0))
3888
+ _mid_dir, _ids, mid_manifest = golden_unit(root, "unit-mid", plant="mid_unreadable")
3889
+ expect("r1 #2: a member S1 could not read leaves the unit, and the member below it is still read as part of the root's unit",
3890
+ sorted((t["transcript"], t["unit"], t["kind"]) for t in mid_manifest["transcripts"])
3891
+ if isinstance(mid_manifest, dict) else repr(mid_manifest),
3892
+ sorted([(unit_ids["root"], unit_ids["root"], "session"), (unit_ids["d2"], unit_ids["root"], "child")]))
3893
+ _idle_dir, _ids, idle = golden_unit(root, "unit-idle", plant="idle")
3894
+ named("85f3e8: an eligible root whose unit owes the window nothing contradicts S1 and is refused by name",
3895
+ [str(idle)] if isinstance(idle, Exception) else [], "SET_MISMATCH S2", unit_ids["root"])
3896
+ # D-20261103-a7128a: S2 reads each file of a thread written in several that owes the window something, as a
3897
+ # transcript of its own under its coverage key, and no other
3898
+ for label, owns, read in (("only its first file", ([[0, 3]], []), [0]), ("only its last file", ([], [[0, 3]]), [1]),
3899
+ ("both its files", ([[0, 3]], [[0, 3]]), [0, 1])):
3900
+ split_keys, split = golden_split(root, f"split-{read}", owns)
3901
+ expect(f"a7128a: a thread whose window lies in {label} has that file copied and viewed, under its own key",
3902
+ sorted((t["transcript"], t["session"], t["segment"]) for t in split["transcripts"])
3903
+ if isinstance(split, dict) else repr(split),
3904
+ sorted((split_keys[n], split_keys[n].split("@")[0], split_keys[n].split("@")[1]) for n in read))
3905
+ if read == [0, 1]:
3906
+ expect("r2: a thread viewed in both its files is one session in two files, in the totals and in the report",
3907
+ ((split["totals"]["sessions"], split["totals"]["children"], split["totals"]["files"]), report_lines(split)[0].split(": ", 1)[1].split(",")[0])
3908
+ if isinstance(split, dict) else repr(split), ((1, 0, 2), "1 sessions and 0 children in 2 files"))
3909
+ for base, why in (("empty", "an empty base"), ("older", "a base that saw fewer records")):
3910
+ split_keys, targeted = golden_split(root, f"targeted-{base}", ([[0, 3]], [[0, 3]]), base=base)
3911
+ expect(f"r1 #3: a targeted run's views copy the version its census read, over {why}",
3912
+ (sorted(t["transcript"] for t in targeted["transcripts"]), targeted["quarantined"])
3913
+ if isinstance(targeted, dict) else repr(targeted), (sorted(split_keys), []))
3914
+ # M#12: the index destination is confined before anything is created. `index/` is replaced by a
3915
+ # symlink to a directory outside the run; the write must be refused AND the outside directory must
3916
+ # be exactly as it was - a refusal that arrives after `mkdir` has run is not a confinement.
3917
+ outside = root / "outside-the-run"
3918
+ outside.mkdir()
3919
+ escape_run = golden(root, "escape", overhead=100_000)["run_dir"]
3920
+ index_dir = escape_run / "index"
3921
+ shutil.rmtree(index_dir)
3922
+ index_dir.symlink_to(outside, target_is_directory=True)
3923
+ before = sorted(q.name for q in outside.iterdir())
3924
+ # the production path's own function, not a copy of its two lines in the test
3925
+ def confine_index():
3926
+ try:
3927
+ index_destination(escape_run, "index/bm25/x.json")
3928
+ except stagelock.Escaped as exc:
3929
+ return str(exc).split(" ", 1)[0]
3930
+ return "nothing was refused"
3931
+ expect("control: the index destination behind a symlink out of the run is refused by name",
3932
+ confine_index(), "RUN_PATH_ESCAPE")
3933
+ expect("control: ... and the directory outside the run is untouched, because nothing was created before "
3934
+ "the destination was confined",
3935
+ sorted(q.name for q in outside.iterdir()), before)
3936
+ compressed = golden(root, "zst", overhead=100_000, compressed=True)
3937
+ from runlib import sources as source_reader # the name `sources` is a loop variable further down
3938
+ kept_declared = source_reader.declared
3939
+ source_reader.declared = lambda run: {**kept_declared(run), "zstd": "/bin/cat"} # executable, and not zstd
3940
+ try:
3941
+ refused("control: the compressed fixture refuses a declared zstd that is another program",
3942
+ lambda: golden(root, "zst-cat", overhead=100_000, compressed=True), "ZSTD_UNAVAILABLE /bin/cat")
3943
+ finally:
3944
+ source_reader.declared = kept_declared
3945
+ expect("done-when 1: a compressed rollout is copied decompressed, and the copy is named by the hash of those bytes",
3946
+ (records.sha256_file(compressed["run_dir"] / compressed["codex"]["source_copy"]) == compressed["codex"]["version_sha"],
3947
+ compressed["codex"]["windows"][0]["records"]), (True, 3))
3948
+
3949
+ # ---- done-when 7: the contract the schema carries ----------------------------------------
3950
+ schema = claims.read_schema("evidence")
3951
+ expect("done-when 7: every evidence record carries window_role, and the schema cites the section each field "
3952
+ "comes from (the field list itself is copied once, in claims.py's self-test, cited to §5.5)",
3953
+ ("window_role" in schema["required"], schema["$comment"]),
3954
+ (True, "design §5.5, plus window_role from design §5.2"))
3955
+ refused("control: two transcripts that would be written to one view directory are refused",
3956
+ lambda: run(fx_prepared_run(root, "collide")), "VIEW_NAME_COLLISION")
3957
+ bare = root / "bare"
3958
+ bare.mkdir()
3959
+ declare.create(bare, {**golden_run["run"], "declaration_seq": 0})
3960
+ refused("control: S2 over a run whose census S1 never wrote is refused by name, never over an empty set",
3961
+ lambda: run(bare), "INPUT_INVALID S1")
3962
+ reporting = records.run_items
3963
+ records.run_items = lambda posture, items, work, jobs=1: {"done": [], "quarantined": []}
3964
+ try: # a stage runner that reports neither a view nor a quarantine for an eligible session
3965
+ refused("control: an eligible session that ends with neither a view nor a quarantine is named",
3966
+ lambda: run(fx_prepared_run(root, "silent", COLLIDING[:1])), "SET_MISMATCH S2")
3967
+ finally:
3968
+ records.run_items = reporting
3969
+
3970
+ missing = [part for part in INVARIANTS if not any(part in label for label in checks.ran)]
3971
+ if missing:
3972
+ checks.failures.append(f"the self-test's branch list is not covered: no label exercises {missing}")
3973
+
3974
+ # M#11: a label check is not a contract check. Covering INVARIANTS by phrase was satisfied while
3975
+ # OVERLAP_TURNS changed from five to four, because the construction and the checking moved together and
3976
+ # both labels still read "overlap". These pin the design's own constants and the complete branch set of
3977
+ # each predicate here, independently of any label - and each branch is exercised with its own row.
3978
+ checks.expect("design §5.4: the constants this stage is built on are the design's own",
3979
+ {"overlap turns": OVERLAP_TURNS, "input bound": bound.INPUT_BOUND, "turn kinds": TURN_KINDS},
3980
+ {"overlap turns": 5, "input bound": 120_000, "turn kinds": ("human", "assistant")})
3981
+ # every status §5.4 forbids a basis to rest on, each in a scope of its own
3982
+ prohibited = ("unreadable", "known_absent", "unknown_provenance", "read_partial", "failed", "deferred")
3983
+ checks.expect("design §5.4: the statuses that make a basis incomplete are exactly the six the design lists",
3984
+ [status for status in prohibited
3985
+ if coverage_basis({"sources": [{"accounted": True, "directory_present": True}],
3986
+ "sessions": [{"status": status, "unprocessed": False, "view_complete": True,
3987
+ "source_complete": True}]}) != "incomplete"], [])
3988
+ # ... and the complete branch set of coverage_basis, each with its own row and its own expected answer
3989
+ def basis_of(sources, session):
3990
+ return coverage_basis({"sources": [sources], "sessions": [session]})
3991
+ good_source = {"accounted": True, "directory_present": True}
3992
+ complete = {"status": "read_complete", "unprocessed": False, "view_complete": True, "source_complete": True}
3993
+ for label, sources, session, want in (
3994
+ ("a source not accounted", {"accounted": False, "directory_present": True}, complete, "incomplete"),
3995
+ ("a source directory missing", {"accounted": True, "directory_present": False}, complete, "incomplete"),
3996
+ ("a session with unprocessed records", good_source, {**complete, "unprocessed": True}, "incomplete"),
3997
+ ("a session that is not view complete", good_source,
3998
+ {**complete, "view_complete": False, "source_complete": False}, "incomplete"),
3999
+ ("a session view complete but not source complete", good_source,
4000
+ {**complete, "source_complete": False}, "view"),
4001
+ ("everything complete", good_source, complete, "source")):
4002
+ checks.expect(f"design §5.4, basis branch: {label} gives {want}", basis_of(sources, session), want)
4003
+ checks.expect("design §5.4: a claim of absence rests on basis source and on nothing else",
4004
+ {basis: absence_claim_allowed(basis) for basis in ("incomplete", "view", "source")},
4005
+ {"incomplete": False, "view": False, "source": True})
4006
+ with tempfile.TemporaryDirectory(prefix="views-x1-") as td:
4007
+ x1 = pathlib.Path(td)
4008
+ # X review of WP-08 r1 #2 and r2: an amendment of the cap landing just before S2's admission is the cap the windows
4009
+ # are cut with; one landing just after it changes nothing they were cut with
4010
+ cap = [(f"output_caps.{declare.VIEW_WINDOW_STAGE}", 48_000)]
4011
+ for when, want in (("before", 48_000), ("after", 32_000)):
4012
+ with records.fx_amended_at_admission("S2", cap, when):
4013
+ try:
4014
+ raced = golden(x1, f"raced-{when}", overhead=100_000)
4015
+ except Exception as exc: # noqa: BLE001 - reported by the control below, by name
4016
+ raced = {"error": repr(exc)}
4017
+ label = (f"X r1: an amendment just before S2's admission is the cap the views record and their windows are cut "
4018
+ f"with, under the declaration S2 recorded" if when == "before" else
4019
+ "X r2: an amendment just after S2's admission changes nothing the windows were cut with")
4020
+ if "error" in raced:
4021
+ checks.expect(label, raced["error"], None)
4022
+ continue
4023
+ raced_dir = pathlib.Path(raced["run_dir"])
4024
+ part = records.read_json(records.record_path(raced_dir, "S2")).get("parts", {}).get("views", {})
4025
+ # the amendment landed in both cases: run.json is at sequence 1 either way
4026
+ checks.expect(label, ({raced["manifest"]["limits"]["reservation"]},
4027
+ {sequence_doc(raced_dir, t["name"])["limits"]["reservation"] for t in raced["manifest"]["transcripts"]},
4028
+ part.get("declaration_seq"), records.read_json(records.run_json_path(raced_dir))["declaration_seq"]),
4029
+ ({want}, {want}, 1 if when == "before" else 0, 1))
4030
+ # X review of WP-08 r1 #1: what the overlap shows is located like an owned record's text, and nothing past its cut
4031
+ shown_run = golden(x1, "shown", overhead=100_000)
4032
+ shown_dir, shown_main = pathlib.Path(shown_run["run_dir"]), shown_run["main"]
4033
+ # a record some window owns, whose text past the cut that window shows (the record before the window is cut in
4034
+ # the first window's overlap too, and no window owns it)
4035
+ owned_entries = {eid(r) for w in shown_run["windows"] for r in w["records"]}
4036
+ cut_entry = next((e for w in shown_run["windows"] for e in w["overlap"]["prev"]
4037
+ if e["overlap_cut"] and e["entry"] in owned_entries), None)
4038
+ split_part = next((e for w in shown_run["windows"] for e in w["overlap"]["prev"] + w["overlap"]["next"]
4039
+ if "#" in e["entry"]), None)
4040
+ for label, entry in (("a cut overlap entry", cut_entry), ("an overlap entry of a split span", split_part)):
4041
+ if entry is None:
4042
+ checks.expect(f"X r1: the golden windows hold {label}", None, "an entry")
4043
+ continue
4044
+ try:
4045
+ made = evidence_store.from_view(shown_dir, shown_main["version_sha"], entry, entry["text"][:30])
4046
+ got = (evidence_store.verify(shown_dir, made), made["window_role"])
4047
+ except Exception as exc: # noqa: BLE001 - an entry that cannot be located fails this control by name
4048
+ got = repr(exc)
4049
+ checks.expect(f"X r1: a quote of {label} as shown is located and walks back to the copy, keeping its role",
4050
+ got, ([], entry["window_role"]))
4051
+ if cut_entry is not None:
4052
+ checks.expect("X r1: a cut overlap entry's segments end where its shown text ends, so they claim no more than "
4053
+ "it shows", max((s["view"][1] for s in cut_entry.get("segments", [])), default=None),
4054
+ len(cut_entry["text"]))
4055
+ owner_text = next((r["text"] for w in shown_run["windows"] for r in w["records"]
4056
+ if eid(r) == cut_entry["entry"]), None)
4057
+ if owner_text is None:
4058
+ checks.expect("X r1: a window owns the cut overlap entry, which shows what the cut left out", None, "an owner")
4059
+ else:
4060
+ past = owner_text[len(cut_entry["text"]):len(cut_entry["text"]) + 30]
4061
+ checks.refused("X r1: a quote of what the overlap cut off is not located in the overlap",
4062
+ lambda: evidence_store.from_view(shown_dir, shown_main["version_sha"], cut_entry, past),
4063
+ "QUOTE_MISMATCH")
4064
+ # WP-08 commit 5a: a call's decision of an omission is written once - again as it was, nothing more; otherwise, refused
4065
+ with tempfile.TemporaryDirectory() as decided:
4066
+ decided_dir = pathlib.Path(decided)
4067
+ omitted = {"name": "v", "record_id": "1/message/content", "omission": "1/message/content@0-9#ab"}
4068
+
4069
+ def decide(call_id, decision, reason):
4070
+ """`written`, or the refusal's code: a reverted rule fails its control by name, not by a traceback."""
4071
+ try:
4072
+ record_decision(decided_dir, call_id, omitted["name"], omitted["record_id"], decision, reason,
4073
+ omission=omitted["omission"])
4074
+ except Refused as exc:
4075
+ return str(exc).split()[0]
4076
+ return "written"
4077
+
4078
+ def logged():
4079
+ path = decided_dir / "expansions.jsonl"
4080
+ return path.read_bytes() if path.is_file() else b""
4081
+ first_decision = decide("r1/S3/w1", "expand", "read it whole")
4082
+ log_once = logged()
4083
+ checks.expect("5a: a call's decision of an omission made again as it was is not written twice",
4084
+ (first_decision, decide("r1/S3/w1", "expand", "read it whole"), logged() == log_once,
4085
+ len(log_once.splitlines())), ("written", "written", True, 1))
4086
+ checks.expect("5a: the same call deciding the same omission otherwise is refused where it would be written",
4087
+ (decide("r1/S3/w1", "skip", "not worth it"), logged() == log_once),
4088
+ ("EXPANSION_DECISION_CONFLICT", True))
4089
+ checks.expect("5a: another call's decision of the same omission is another line",
4090
+ (decide("r1/S3/w2", "skip", "not worth it"), len(logged().splitlines())), ("written", 2))
4091
+ # W r1: a reason may hold what JSON allows raw and str.splitlines breaks a line at. The log is read by the one JSONL
4092
+ # splitter, so a decision made again is still found, the order is still kept, and two runs leave the same bytes.
4093
+ for char in ("\u0085", "\u2028", "\u2029"):
4094
+ label, reason = f"U+{ord(char):04X}", f"kept{char}whole"
4095
+ logs = []
4096
+ for _run in (1, 2):
4097
+ with tempfile.TemporaryDirectory() as raw:
4098
+ raw_dir = pathlib.Path(raw)
4099
+
4100
+ def decide_raw(call_id, view):
4101
+ try:
4102
+ record_decision(raw_dir, call_id, view, "1/message/content", "expand", reason,
4103
+ omission=f"{view}#om")
4104
+ except (Refused, ValueError) as exc: # a fragment that does not parse is a ValueError
4105
+ return f"{exc.__class__.__name__} {str(exc).split()[0] if str(exc) else ''}"
4106
+ return "written"
4107
+
4108
+ def ordered_raw():
4109
+ try:
4110
+ order_decisions(raw_dir, {"a": 0, "b": 1})
4111
+ except (Refused, ValueError) as exc:
4112
+ return f"{exc.__class__.__name__}"
4113
+ return "ordered"
4114
+ steps = (decide_raw("r1/S3/w2", "b"), decide_raw("r1/S3/w2", "b"), decide_raw("r1/S3/w1", "a"),
4115
+ ordered_raw())
4116
+ once = (raw_dir / "expansions.jsonl").read_bytes()
4117
+ again = ordered_raw()
4118
+ read = [json.loads(line) for line in records.jsonl_read(raw_dir / "expansions.jsonl")]
4119
+ logs.append((steps, again, once == (raw_dir / "expansions.jsonl").read_bytes(),
4120
+ [(d["locator"]["transcript"], d["reason"]) for d in read], once))
4121
+ checks.expect(f"W r1: a reason holding {label} is appended once, ordered, and read back whole",
4122
+ logs[0][:4], (("written", "written", "written", "ordered"), "ordered", True,
4123
+ [("a", reason), ("b", reason)]))
4124
+ checks.expect(f"W r1: two runs deciding the same with a reason holding {label} leave the same bytes",
4125
+ logs[0][4] == logs[1][4], True)
4126
+ if not checks.ran:
4127
+ checks.failures.append("the self-test asserted nothing")
4128
+ for failure in checks.failures:
4129
+ print(f"views --self-test [FAIL] {failure}")
4130
+ if checks.failures:
4131
+ return 1
4132
+ print(f"views --self-test: OK ({len(checks.ran)} controls over golden transcripts: the immutable copy and its "
4133
+ f"projection, the planted token and home path in no artifact but the copy, windows owned once with their "
4134
+ f"overlaps, split spans tiling their message, every error line kept, the five-turn overlap in each of its "
4135
+ f"four cases (a split message, unowned tool traffic, an exhausted side budget, duplicate membership) with "
4136
+ f"every omission hashed, manifested and expandable, the bound's (a), (d), observed-input and allowance "
4137
+ f"branches driven by hash-pinned retained captures, the omission manifest, both completeness levels, every "
4138
+ f"branch of the forced-expansion predicate, expansion against the generated manifests of a long-turn "
4139
+ f"run with two expansions under one call id, the stale-artifact refusals at the reading and rendering "
4140
+ f"boundaries, the F-O9-04 pair, and every coverage basis of §5.4)")
4141
+ return 0
4142
+
4143
+
4144
+ COLLIDING = ("019e0001:0000-7000-8000-00000000000a", "019e0001_0000-7000-8000-00000000000a")
4145
+
4146
+
4147
+ def fx_long_records():
4148
+ """A transcript of long human and assistant turns with tool traffic between them: the shape whose
4149
+ overlap really is cut and really does exhaust a side's budget, so `expand` can be exercised against
4150
+ generated manifest rows instead of rows a control wrote itself. The text is nonrepetitive, so no
4151
+ interval's hash can match another's by accident."""
4152
+ def wordy(tag, length):
4153
+ return "".join(f"{tag}-{k} " for k in range(length))[:length]
4154
+ out = []
4155
+ for n in range(1, 13):
4156
+ day, hour = 2 + n // 6, (n * 3) % 24
4157
+ out.append(fx_human(fx_stamp(day, hour=hour), wordy(f"h{n}", 2_400)))
4158
+ out.append(fx_assistant(fx_stamp(day, hour=hour), wordy(f"a{n}", 2_600)))
4159
+ out.append(fx_call(fx_stamp(day, hour=hour), "Bash", {"command": f"ls -la dir{n}"}))
4160
+ # the first result is over CLIP_OVER, so the run really holds a clipped record within the range the
4161
+ # window views: its view elides a middle, which is the case whose coordinates a view-local interval
4162
+ # gets wrong
4163
+ out.append(fx_result(fx_stamp(day, hour=hour), wordy(f"r{n}", 6_000 if n == 1 else 1_500)))
4164
+ return out
4165
+
4166
+
4167
+ def fx_role_records():
4168
+ """One request and ten assistant turns, each with its call and result, every record inside the window: the
4169
+ turns are longer than an overlap item and the results long enough that a side's budget runs out, so a
4170
+ neighbour's overlap omits records that are IN a window rather than context (the overlap-role control)."""
4171
+ out = [fx_human(fx_stamp(3, hour=1), "please tidy the build scripts and report each step")]
4172
+ for i in range(10):
4173
+ out += [fx_assistant(fx_stamp(3, hour=2, minute=3 * i),
4174
+ "".join(f"note {i}.{k:02d} on the build. " for k in range(60))),
4175
+ fx_call(fx_stamp(3, hour=2, minute=3 * i + 1), "Bash", {"command": f"make step-{i}"}),
4176
+ fx_result(fx_stamp(3, hour=2, minute=3 * i + 2),
4177
+ "\n".join(f" step {i} line {k:02d} ok {'.' * 20}" for k in range(40)))]
4178
+ return out
4179
+
4180
+
4181
+ # Z#1: each planted case by the line it stands on and the pointer of its block, so a control can name the
4182
+ # locator it is making a claim about instead of searching for one. The lines are 1-based record numbers of
4183
+ # `fx_fallback_records`, and every one of them is inside the range the window views.
4184
+ FX_FALLBACK_CASES = (
4185
+ ("an encoded scalar credential behind a cross-member floor claim", 1, "/message/content", "FX_FALLBACK_SCALAR"),
4186
+ ("an encoded home path behind a cross-member floor claim", 2, "/message/content/0/text", "FX_HOME"),
4187
+ ("a secret-named key in prose whose value is a readable structure", 3, "/message/content", "FX_OBLIGATION_JSON"),
4188
+ ("a quoted scalar that itself holds a structure", 4, "/message/content/0/text", "FX_OBLIGATION_QUOTED"),
4189
+ ("an escaped array under a readable keyed name", 6, "/message/content/0/text", "FX_ESCAPED_ARRAY"),
4190
+ ("a quoted scalar whose keyed value holds a structure", 7, "/message/content", "FX_QUOTED_SCALAR"),
4191
+ ("a credential beside a literal mask inside the value", 8, "/message/content/0/text", "FX_MASK_NEIGHBOUR"),
4192
+ ("an escaped member after a plain structure", 9, "/message/content", "FX_ESCAPED_TAIL"),
4193
+ ("R#4: a cross-member claim arriving as a structure", 14, "/message/content/0/input",
4194
+ "FX_STRUCTURED_CROSS"),
4195
+ ("E#0 downstream: an encoded key whose name stands in a sibling value", 10,
4196
+ "/message/content/0/text", "FX_SIBLING_KEY"),
4197
+ ("E#1 downstream: a twice-encoded token beside a plain path", 11, "/message/content", "FX_MIXED_DEPTH"),
4198
+ ("E#2 downstream: a decodable body with no escaped quote", 12, "/message/content/0/text",
4199
+ "FX_NO_QUOTE_BODY"),
4200
+ ("S#3: a secret-named member with a newline before its colon", 15, "/message/content/0/text",
4201
+ "FX_MEMBER_NEWLINE"),
4202
+ ("S#0 downstream: a keyed fragment in mixed text", 16, "/message/content", "FX_MIXED_TEXT"),
4203
+ ("U#2 / T#0: a secret-named key behind 38 characters of name", 18, "/message/content/0/text",
4204
+ "FX_LONG_NAME"),
4205
+ ("U#0: a value that starts with the mask and goes on past a comma", 19, "/message/content",
4206
+ "FX_MASK_COMMA"),
4207
+ ("U#2 / T#2: an escape run before an actual newline", 20, "/message/content/0/text", "FX_ESCAPE_RUN"),
4208
+ ("U#2 / T#4: a duplicate member whose masked copy comes last", 21, "/message/content",
4209
+ "FX_DUPLICATE_LAST"),
4210
+ ("X#3 / V#0: a readable array under an encoded key", 22, "/message/content/0/text",
4211
+ "FX_READABLE_ARRAY"),
4212
+ ("X#3 / V#0: a readable object under an encoded key", 23, "/message/content", "FX_READABLE_OBJECT"),
4213
+ ("X#3 / V#1: a suffix after a masked scalar", 24, "/message/content/0/text", "FX_SCALAR_SUFFIX"),
4214
+ ("X#3 / V#2: a quoted key whose separator is on the next line", 25, "/message/content",
4215
+ "FX_NEWLINE_SEPARATOR"),
4216
+ )
4217
+
4218
+
4219
+ def fx_fallback_records():
4220
+ """A transcript of the blocks whose secrets only decoding reaches, or whose obligations the decoded form
4221
+ cannot see. All of them sit in the range the window views, so the stage really processes them.
4222
+
4223
+ The name is the history: these were the blocks that took the superseded fallback path. They are kept
4224
+ because each is a shape some round leaked on, and the single pass has to answer for all of them."""
4225
+ encoded_home = FX_HOME.replace("/", "\\u002f")
4226
+ return [
4227
+ fx_human(fx_stamp(3, hour=1),
4228
+ 'a fallback case: {"a":"' + FX_FALLBACK_TOKEN + ' api_key=","b":"' + FX_FALLBACK_LEFTOVER
4229
+ + '", "\\u0070assword":"' + FX_FALLBACK_SCALAR + '"}'),
4230
+ fx_assistant(fx_stamp(3, hour=2),
4231
+ 'and one with a path: {"a":"' + FX_FALLBACK_TOKEN + ' api_key=","b":"'
4232
+ + FX_FALLBACK_LEFTOVER + '", "' + encoded_home + '\\u002fx":1}'),
4233
+ fx_human(fx_stamp(3, hour=3),
4234
+ 'prefix "password": {"value":"' + FX_OBLIGATION_JSON + '","token":"x"}'),
4235
+ fx_assistant(fx_stamp(3, hour=4),
4236
+ 'authorization: "{\\"value\\":\\"' + FX_OBLIGATION_QUOTED + '\\"}"'),
4237
+ # the home path in plain form as well, so the sweep's instrument control has raw bytes to find
4238
+ fx_human(fx_stamp(3, hour=5), f"and what did that leave under {FX_HOME}/Documents?"),
4239
+ # Z#0: a readable keyed name whose value is an escaped array
4240
+ fx_assistant(fx_stamp(3, hour=6), 'prefix "password": [ "'
4241
+ + "".join(f"\\u{ord(ch):04x}" for ch in FX_ESCAPED_ARRAY) + '" ]'),
4242
+ # A#0: a quoted scalar that holds a structure
4243
+ fx_human(fx_stamp(3, hour=7), 'note "api_key": "x{}' + FX_QUOTED_SCALAR + '"'),
4244
+ # rule 2: a literal mask beside a credential inside the value
4245
+ fx_assistant(fx_stamp(3, hour=8), '"secret": {"seen":"' + projection.FLOOR.PLACEHOLDER
4246
+ + '","v":"' + FX_MASK_NEIGHBOUR + '"}'),
4247
+ # A#1: a plain structure followed by an escaped member
4248
+ fx_human(fx_stamp(3, hour=9), '{"a":"' + FX_FALLBACK_TOKEN + ' api_key=","b":"left"} '
4249
+ + '\\"' + "".join(f"\\u{ord(ch):04x}" for ch in "password") + '\\": \\"'
4250
+ + FX_ESCAPED_TAIL + '\\"'),
4251
+ # M#7 / E#0: the secret-named key is encoded and its name also stands in a sibling's value
4252
+ fx_assistant(fx_stamp(3, hour=10), '{"note":"password","'
4253
+ + "".join(f"\\u{ord(ch):04x}" for ch in "password") + '":"' + FX_SIBLING_KEY + '"}'),
4254
+ # M#7 / E#1: a twice-encoded token beside an already plain encoded path, in one region
4255
+ fx_human(fx_stamp(3, hour=11), '\\"note\\":\\"sk\\\\u002d' + FX_MIXED_DEPTH
4256
+ + '\\", \\"path\\":\\"' + FX_HOME.replace("/", "\\u002f") + '/x\\"'),
4257
+ # M#7 / E#2: a decodable body carrying no escaped quote at all
4258
+ fx_assistant(fx_stamp(3, hour=12), 'see sk\\u002d' + FX_NO_QUOTE_BODY + ' here'),
4259
+ # M#8: the shape the mapping cannot locate, which the verifier blanks
4260
+ fx_assistant(fx_stamp(3, hour=13), '{"note":"plain"} sk' + "\\\\u005c" * 6 + "u002d"
4261
+ + FX_LAYERED),
4262
+ # R#4: a structured content block whose members form a claim only once serialised
4263
+ fx_call(fx_stamp(3, hour=14), "Write", {"a": FX_FALLBACK_TOKEN + " api_key=",
4264
+ "b": FX_STRUCTURED_CROSS}),
4265
+ # S#3: a secret-named member with a newline before its colon
4266
+ fx_assistant(fx_stamp(3, hour=15), '{"safe":{"password":"' + projection.FLOOR.PLACEHOLDER
4267
+ + '"},"password"\n:"' + FX_MEMBER_NEWLINE + '"}'),
4268
+ # S#3 / S#0: a keyed fragment in mixed text, read by no member rule
4269
+ fx_human(fx_stamp(3, hour=16), '{"note":"plain"} "\\u0070assword":"' + FX_MIXED_TEXT + '"'),
4270
+ # S#5: one structured block whose two leaves each take the backstop
4271
+ fx_call(fx_stamp(3, hour=17), "Write",
4272
+ {"a": "sk" + "\\\\u005c" * 6 + "u002d" + FX_TWO_LEAF,
4273
+ "b": "sk" + "\\\\u005c" * 6 + "u002d" + FX_TWO_LEAF + "two",
4274
+ "c": "plain words"}),
4275
+ # U#2 / T#0: a secret-named key behind 38 characters of name
4276
+ fx_assistant(fx_stamp(3, hour=18), '{"note":"plain"} "' + "x" * 38
4277
+ + '\\u0070assword":"' + FX_LONG_NAME + '"'),
4278
+ # U#2 / T#1 and U#0: a value that starts with the mask and goes on past a comma
4279
+ fx_human(fx_stamp(3, hour=19), '{"note":"plain"} "\\u0070assword":"'
4280
+ + projection.FLOOR.PLACEHOLDER + ',' + FX_MASK_COMMA + '"'),
4281
+ # U#2 / T#2: an escape run before an actual newline, with the credential after it
4282
+ fx_assistant(fx_stamp(3, hour=20), '{"note":"plain"} \\\n' + FX_ESCAPE_RUN),
4283
+ # U#2 / T#4: a duplicate secret-named member whose MASKED copy comes last
4284
+ fx_human(fx_stamp(3, hour=21), '{"password":"' + FX_DUPLICATE_LAST + '","password":"'
4285
+ + projection.FLOOR.PLACEHOLDER + '"}'),
4286
+ # X#3 / V#0: a readable array and a readable object under an encoded key
4287
+ fx_assistant(fx_stamp(3, hour=22), '{"note":"plain"} "\\u0070assword":["' + FX_READABLE_ARRAY + '"]'),
4288
+ fx_human(fx_stamp(3, hour=23), '{"note":"plain"} "\\u0070assword":{"inner":"'
4289
+ + FX_READABLE_OBJECT + '"}'),
4290
+ # X#3 / V#1: a suffix standing after a masked scalar
4291
+ fx_assistant(fx_stamp(3, hour=24), '{"note":"plain"} "\\u0070assword":"'
4292
+ + projection.FLOOR.PLACEHOLDER + '"' + FX_SCALAR_SUFFIX),
4293
+ # X#3 / V#2: a quoted key whose separator stands on the next line
4294
+ fx_human(fx_stamp(3, hour=25), '{"note":"plain"} "password"\n: "' + FX_NEWLINE_SEPARATOR + '"'),
4295
+ fx_assistant(fx_stamp(3, hour=6), "nothing a window may show"),
4296
+ fx_call(fx_stamp(3, hour=7), "Bash", {"command": "ls -la"}),
4297
+ fx_result(fx_stamp(3, hour=8), "two files and a directory"),
4298
+ fx_human(fx_stamp(3, hour=9), "good"),
4299
+ ]
4300
+
4301
+
4302
+ def fx_prepared_run(root, name, idents=COLLIDING):
4303
+ """A declared run with a census of `idents` and no view cut yet. The default pair differs only in a character
4304
+ `safe_name` folds, so both would be written to one view directory."""
4305
+ run_dir = root / name
4306
+ run_dir.mkdir(parents=True, exist_ok=True)
4307
+ host = root / f"{name}-host"
4308
+ sha = fx_write(host / "one.jsonl", fx_codex_records())
4309
+ _s, _e, window_id = coverage.window_bounds(FX_WINDOW)
4310
+ entries = [fx_entry("codex", ident, "codex_sessions", host / "one.jsonl", sha, owned=[[0, 3]],
4311
+ work={"version": 0, "in_window": [[0, 3]], "backlog": []})
4312
+ for ident in idents]
4313
+ document = fx_census(window_id, entries)
4314
+ declaration = {**declare.fixture(), "window": FX_WINDOW}
4315
+ declare.create(run_dir, declaration)
4316
+ with records.run_stage(run_dir, "S1") as stage:
4317
+ records.write_text(run_dir, run_dir / "census.json", census.dump(document))
4318
+ records.write_json(run_dir, run_dir / "coverage.json", coverage.new_state())
4319
+ stage.output("census.json")
4320
+ stage.output("coverage.json")
4321
+ return run_dir
4322
+
4323
+
4324
+ if __name__ == "__main__":
4325
+ if "--self-test" not in sys.argv[1:]:
4326
+ sys.exit("usage: views.py --self-test")
4327
+ sys.exit(self_test())