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,890 @@
1
+ #!/usr/bin/env python3
2
+ """The evidence store (design §5.5): a quote that can be walked back to bytes nobody has touched.
3
+
4
+ An evidence record's fields are declared in `schemas/evidence.schema.json` and checked against design §5.5 by
5
+ `claims.py`, which is the one place that list is written down; restating it here would make this a second
6
+ authority for it. What the fields MEAN: the locator is the immutable copy S2 made, a 1-based line in it and the
7
+ content block of that record; the span is over the block's **redacted projection** (`projection.project` of the
8
+ block's value), never over the raw bytes, and the stored text is that span. Nothing here lets a model type a locator or a quote: `make` takes the span
9
+ and reads the text from the projection, `from_view` finds a quote in what a window showed and maps it to the block's
10
+ characters through the entry's segments, and a quote that is not exactly there (a character changed, or the raw
11
+ bytes where the projection holds a mask) is `QUOTE_MISMATCH`. A quote found more than once names its `occurrence`
12
+ (QUOTE_AMBIGUOUS otherwise), and an occurrence it does not have is QUOTE_OCCURRENCE_UNKNOWN.
13
+
14
+ `verify` re-derives everything from the immutable copy and does not trust the projection file or the record:
15
+
16
+ 1. the record conforms to its schema (EVIDENCE_INVALID);
17
+ 2. the copy exists and hashes to `version_sha` (SOURCE_MISSING, SOURCE_TAMPERED);
18
+ 3. `redaction_version` is the current one (REDACTION_VERSION_MISMATCH) - an old quote is made again from the
19
+ same source, it is not patched;
20
+ 4. the line and pointer resolve to a content block (LOCATOR_UNRESOLVED);
21
+ 5. `redacted_text` equals the span of the block's projection (QUOTE_MISMATCH).
22
+
23
+ The review shows the quote with `openable`: the copy's path and the line. A hash of a copy is remembered for the
24
+ process by the file's size, mtime and inode, so a copy that is edited in place is hashed again.
25
+
26
+ evidence.py --self-test
27
+ """
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import pathlib
32
+ import sys
33
+
34
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
35
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
36
+ from runlib import claims, projection, records, stagelock
37
+ from runlib.records import Refused
38
+
39
+ _HASHES = {}
40
+
41
+
42
+ def copy_sha(path):
43
+ stat = os.stat(path)
44
+ key = (str(path), stat.st_mtime_ns, stat.st_size, stat.st_ino)
45
+ if key not in _HASHES:
46
+ _HASHES[key] = records.sha256_file(path)
47
+ return _HASHES[key]
48
+
49
+
50
+ def resolve_pointer(value, pointer):
51
+ for token in pointer.split("/")[1:]:
52
+ token = token.replace("~1", "/").replace("~0", "~")
53
+ try:
54
+ value = value[int(token)] if isinstance(value, list) else value[token]
55
+ except (KeyError, IndexError, ValueError, TypeError) as exc:
56
+ raise KeyError(pointer) from exc
57
+ return value
58
+
59
+
60
+ ABSENT = object() # distinct from a block whose value is JSON null
61
+
62
+
63
+ def read_block(copy_path, line, pointer):
64
+ """The value of the content block at `line` and `pointer` of a copy, or `ABSENT` when it is not there.
65
+ The value, not its characters: the projection walks a structure before serialising it, so handing it text
66
+ is what let a serialised secret through. A last line without its newline is a record the host was still
67
+ writing, not a record."""
68
+ with open(copy_path, "rb") as handle:
69
+ for number, raw in enumerate(handle, 1):
70
+ if number == line:
71
+ if not raw.endswith(b"\n"):
72
+ return ABSENT
73
+ try:
74
+ return resolve_pointer(json.loads(raw), pointer)
75
+ except (ValueError, KeyError):
76
+ return ABSENT
77
+ return ABSENT
78
+
79
+
80
+ def projection_of(copy_path, line, pointer, version):
81
+ block = read_block(copy_path, line, pointer)
82
+ return None if block is ABSENT else projection.project(block, version)
83
+
84
+
85
+ def evidence_id(version_sha, line, pointer, span, version):
86
+ return "e-" + hashlib.sha256(f"{version_sha}|{line}|{pointer}|{span[0]}-{span[1]}|{version}".encode()).hexdigest()[:16]
87
+
88
+
89
+ def copy_rel(version_sha):
90
+ """The one locator an evidence record may carry for its source. A record names the copy the owner opens;
91
+ verification hashes the copy the version names. When the two are allowed to differ, the bytes that were
92
+ checked and the file the owner is sent to are not the same file, and the record still verifies."""
93
+ return f"sources/{version_sha}.jsonl"
94
+
95
+
96
+ def copy_problem(run_dir, version_sha):
97
+ """`(path, None)` for an intact copy, else `(path, the named problem)`."""
98
+ path = pathlib.Path(run_dir) / copy_rel(version_sha)
99
+ if not path.is_file():
100
+ return path, f"SOURCE_MISSING {path}: the immutable copy of version {version_sha[:12]} is not in the run"
101
+ if copy_sha(path) != version_sha:
102
+ return path, f"SOURCE_TAMPERED {path}: the copy hashes {copy_sha(path)[:12]}, the evidence names {version_sha[:12]}"
103
+ return path, None
104
+
105
+
106
+ def make(run_dir, version_sha, line, pointer, span, window_role, version=projection.CURRENT):
107
+ """The evidence record for `span` of one content block; the quote is read from the projection, never supplied."""
108
+ path, problem = copy_problem(run_dir, version_sha)
109
+ if problem:
110
+ raise Refused(problem)
111
+ text = projection_of(path, line, pointer, version)
112
+ if text is None:
113
+ raise Refused(f"LOCATOR_UNRESOLVED line {line} {pointer}: no content block there in {path.name}")
114
+ a, b = span
115
+ if not 0 <= a < b <= len(text):
116
+ raise Refused(f"LOCATOR_UNRESOLVED line {line} {pointer}: span {a}-{b} is not within the block's {len(text)} characters")
117
+ # The STRICT rule, and it is the owner's: a quote is persisted and shared, so the context that makes a
118
+ # secret-named key with a masked value safe to READ in a window does not travel with it. A quote that
119
+ # names a secret in any spelling cannot be stored at all - not masked, not partly accepted. Owner
120
+ # decision of 2026-10-21; `design/session-distill/2026-10-21T2223--1bfd4c7--strict-rule-uses-the-floors-own-matching.md`.
121
+ admissible, why = projection.evidence_quote_admissible(text[a:b])
122
+ if not admissible:
123
+ raise Refused(f"EVIDENCE_QUOTE_SENSITIVE line {line} {pointer}: {why}; a quote that names a secret "
124
+ "cannot be stored, so quote a span that does not")
125
+ record = {"evidence_id": evidence_id(version_sha, line, pointer, span, version), "source_copy": copy_rel(version_sha),
126
+ "version_sha": version_sha, "line": line, "json_pointer": pointer, "char_span": [a, b],
127
+ "redaction_version": version, "redacted_text": text[a:b], "window_role": window_role}
128
+ problems = claims.validate_record("evidence", record)
129
+ if problems:
130
+ raise Refused("EVIDENCE_INVALID " + "; ".join(problems))
131
+ return record
132
+
133
+
134
+ def quote_spans(text, quote):
135
+ """Every span of `text` that is exactly `quote`."""
136
+ spans, start = [], text.find(quote) if quote else -1
137
+ while start >= 0:
138
+ spans.append([start, start + len(quote)])
139
+ start = text.find(quote, start + 1)
140
+ return spans
141
+
142
+
143
+ def nth(spans, occurrence, where):
144
+ """The index of the span a quote names: its only span, or the `occurrence` it names, which must be one of the spans
145
+ found (QUOTE_OCCURRENCE_UNKNOWN). A model may answer any integer the schema admits, and an index past the spans was an
146
+ IndexError that quarantined the whole unit instead of dropping the one quote (X review of WP-08 r2)."""
147
+ if occurrence is None:
148
+ return 0
149
+ if isinstance(occurrence, bool) or not isinstance(occurrence, int) or not 0 <= occurrence < len(spans):
150
+ raise Refused(f"QUOTE_OCCURRENCE_UNKNOWN {where}: occurrence {occurrence!r} of a quote found {len(spans)} time(s)")
151
+ return occurrence
152
+
153
+
154
+ def from_quote(run_dir, version_sha, line, pointer, quote, window_role, version=projection.CURRENT, occurrence=None):
155
+ """The evidence record for `quote` in a block's projection: unique, or named by `occurrence`."""
156
+ path, problem = copy_problem(run_dir, version_sha)
157
+ if problem:
158
+ raise Refused(problem)
159
+ text = projection_of(path, line, pointer, version)
160
+ spans = quote_spans(text or "", quote)
161
+ if not spans:
162
+ raise Refused(f"QUOTE_MISMATCH line {line} {pointer}: the quote is not in the block's projection at {version}")
163
+ if len(spans) > 1 and occurrence is None:
164
+ raise Refused(f"QUOTE_AMBIGUOUS line {line} {pointer}: the quote occurs {len(spans)} times; name the occurrence")
165
+ return make(run_dir, version_sha, line, pointer, spans[nth(spans, occurrence, f"line {line} {pointer}")], window_role, version)
166
+
167
+
168
+ def view_spans(entry, quote):
169
+ """Where `quote` sits in the block, for each place the entry's view text shows it inside one shown stretch."""
170
+ found = []
171
+ for seg in entry["segments"]:
172
+ piece = entry["text"][seg["view"][0]:seg["view"][1]]
173
+ for a, b in quote_spans(piece, quote):
174
+ found.append([seg["block"][0] + a, seg["block"][0] + b])
175
+ return found
176
+
177
+
178
+ def from_view(run_dir, version_sha, entry, quote, version=projection.CURRENT, occurrence=None):
179
+ """The evidence record for a quote read out of a window's entry: the span is found in what the window showed and
180
+ mapped to the block's characters, then `make` reads the text from the projection."""
181
+ spans = view_spans(entry, quote)
182
+ if not spans:
183
+ raise Refused(f"QUOTE_MISMATCH {entry['record_id']}: the quote is not in any stretch the window showed")
184
+ if len(spans) > 1 and occurrence is None:
185
+ raise Refused(f"QUOTE_AMBIGUOUS {entry['record_id']}: the quote occurs {len(spans)} times; name the occurrence")
186
+ return make(run_dir, version_sha, entry["line"], entry["json_pointer"], spans[nth(spans, occurrence, entry["record_id"])],
187
+ entry["window_role"], version)
188
+
189
+
190
+ def verify(run_dir, record, current=projection.CURRENT):
191
+ """Violations of one evidence record against the immutable copy; empty when the quote walks back to untouched bytes."""
192
+ problems = claims.validate_record("evidence", record)
193
+ if problems:
194
+ return ["EVIDENCE_INVALID " + "; ".join(problems)]
195
+ if record["source_copy"] != copy_rel(record["version_sha"]):
196
+ return [f"SOURCE_LOCATOR_MISMATCH {record['evidence_id']}: the record points at {record['source_copy']}, but the "
197
+ f"version it names is copied at {copy_rel(record['version_sha'])}; the bytes verified and the file the "
198
+ f"owner opens must be one file"]
199
+ path, problem = copy_problem(run_dir, record["version_sha"])
200
+ if problem:
201
+ return [problem]
202
+ if record["redaction_version"] != current:
203
+ return [f"REDACTION_VERSION_MISMATCH {record['evidence_id']}: made under {record['redaction_version']}, the projection is "
204
+ f"{current}; make it again from {record['source_copy']}"]
205
+ text = projection_of(path, record["line"], record["json_pointer"], current)
206
+ if text is None:
207
+ return [f"LOCATOR_UNRESOLVED {record['evidence_id']}: line {record['line']} {record['json_pointer']} is not a content block of the copy"]
208
+ a, b = record["char_span"]
209
+ if not 0 <= a < b <= len(text) or text[a:b] != record["redacted_text"]:
210
+ return [f"QUOTE_MISMATCH {record['evidence_id']}: the quote is not the span {a}-{b} of the block's projection"]
211
+ return []
212
+
213
+
214
+ def openable(run_dir, record):
215
+ """The path and line the owner opens to see the quote's source."""
216
+ return f"{pathlib.Path(run_dir) / record['source_copy']}:{record['line']}"
217
+
218
+
219
+ def append(run_dir, name, record):
220
+ """Store a verified record under `evidence/<name>.jsonl`; storing the same record again changes nothing.
221
+
222
+ The admission rule is asked again here, not only where the record was made: a record can arrive from
223
+ anywhere - another tool, an older file, a hand-written line - and this is the boundary where text
224
+ becomes persisted and shareable."""
225
+ admissible, why = projection.evidence_quote_admissible(record.get("redacted_text", ""))
226
+ if not admissible:
227
+ raise Refused(f"EVIDENCE_QUOTE_SENSITIVE {record.get('evidence_id')}: {why}; a quote that names a "
228
+ "secret cannot be stored")
229
+ problems = verify(run_dir, record)
230
+ if problems:
231
+ raise Refused("\n".join(problems))
232
+ path = stagelock.confine(run_dir, pathlib.Path(run_dir) / "evidence" / f"{name}.jsonl")
233
+ path.parent.mkdir(parents=True, exist_ok=True)
234
+ if record["evidence_id"] in {r["evidence_id"] for r in load(run_dir, name)}:
235
+ return False
236
+ with open(path, "a", encoding="utf-8") as handle:
237
+ handle.write(json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n")
238
+ return True
239
+
240
+
241
+ def load(run_dir, name, current=None):
242
+ """The stored records of one file. `current` is the projection they must have been made under, and
243
+ `False` reads them without the check - which only a tool migrating a store may ask for.
244
+
245
+ The check belongs in the READER, not only in `verify`: a caller that lists or resolves a record and
246
+ hands its `redacted_text` on has published a quote made under a projection that masked less, and
247
+ nothing in the path it took would have said so."""
248
+ path = pathlib.Path(run_dir) / "evidence" / f"{name}.jsonl"
249
+ if not path.is_file():
250
+ return []
251
+ records_read = [json.loads(line) for line in records.jsonl_read(path) if line.strip()]
252
+ if current is False:
253
+ return records_read
254
+ want = projection.CURRENT if current is None else current
255
+ stale = [r["evidence_id"] for r in records_read if r.get("redaction_version") != want]
256
+ if stale:
257
+ raise Refused(f"REDACTION_VERSION_MISMATCH {path}: {len(stale)} record(s) were made under another "
258
+ f"projection ({stale[:3]}); the projection is {want} - make the quotes again from the source")
259
+ return records_read
260
+
261
+
262
+ def resolve(run_dir, evidence_id, current=None):
263
+ """The stored record with this id, or None. Refused by name when the store holds a record of another
264
+ projection, for the same reason `load` is."""
265
+ for path in sorted((pathlib.Path(run_dir) / "evidence").glob("*.jsonl")):
266
+ for record in load(run_dir, path.stem, current):
267
+ if record["evidence_id"] == evidence_id:
268
+ return record
269
+ return None
270
+
271
+
272
+ def self_test():
273
+ import tempfile
274
+ from runlib import views
275
+
276
+ failures = []
277
+ with tempfile.TemporaryDirectory() as td:
278
+ golden = views.golden(pathlib.Path(td), "ev")
279
+ run_dir, manifest = golden["run_dir"], golden["manifest"]
280
+ main = golden["main"]
281
+ sha = main["version_sha"]
282
+ copy = pathlib.Path(run_dir) / main["source_copy"]
283
+ entries = {r["record_id"]: r for w in golden["windows"] for r in w["records"]}
284
+ human = entries[f"{golden['lines']['human']}/message/content"]
285
+ quote = "show me the plain version"
286
+
287
+ # a stored record ends at "\n" only; the writer keeps U+2028 and U+2029 raw (ensure_ascii=False)
288
+ held = {"evidence_id": "f21", "redacted_text": "before\u2028between\u2029after"}
289
+ (pathlib.Path(run_dir) / "evidence").mkdir(exist_ok=True)
290
+ (pathlib.Path(run_dir) / "evidence" / "f21.jsonl").write_text(json.dumps(held, ensure_ascii=False) + "\n", encoding="utf-8")
291
+ try:
292
+ got = load(run_dir, "f21", current=False)
293
+ except ValueError as exc:
294
+ got = str(exc)
295
+ if got != [held]:
296
+ failures.append(f"jsonl-line-separators-inside-a-string-read-whole (load): {got!r}")
297
+ # a bare CR is JSON whitespace, which text-mode reading would turn into a line break; CRLF still ends a record
298
+ later = {"evidence_id": "f21b", "redacted_text": "after a bare CR"}
299
+ (pathlib.Path(run_dir) / "evidence" / "f21.jsonl").write_bytes(
300
+ ("{\r" + json.dumps(held)[1:] + "\r\n" + json.dumps(later) + "\n").encode("utf-8"))
301
+ try:
302
+ got = load(run_dir, "f21", current=False)
303
+ except ValueError as exc:
304
+ got = str(exc)
305
+ finally:
306
+ (pathlib.Path(run_dir) / "evidence" / "f21.jsonl").unlink() # the store the controls below read is the golden run's
307
+ if got != [held, later]:
308
+ failures.append(f"jsonl-bare-cr-whitespace-and-crlf-read-whole (load): {got!r}")
309
+
310
+ # positive controls: a quote read out of a window verifies, stores, resolves, and opens at its source
311
+ record = from_view(run_dir, sha, human, quote)
312
+ if verify(run_dir, record):
313
+ failures.append(f"positive control: a quote read out of a window did not verify: {verify(run_dir, record)}")
314
+ if record["redacted_text"] != quote or record["window_role"] != "in_window" or record["source_copy"] != copy_rel(sha):
315
+ failures.append(f"positive control: the record is not the quote at its source: {record}")
316
+ if not append(run_dir, "t1", record) or append(run_dir, "t1", record) or resolve(run_dir, record["evidence_id"]) != record:
317
+ failures.append("a record was not stored once and resolved by its id")
318
+ if openable(run_dir, record) != f"{run_dir}/sources/{sha}.jsonl:{golden['lines']['human']}":
319
+ failures.append(f"the openable locator is {openable(run_dir, record)}")
320
+
321
+
322
+ # ---- Y#0 and Y#1: the strict rule through the REAL paths, from source fixtures ----------------
323
+ #
324
+ # Not the predicate loop: these names stand in a transcript, are projected, and the projected quote
325
+ # still carries them - which is the only way to show that `make` refuses and that an independently
326
+ # built record is refused at `append`, into a new file and into a populated one, with every stored
327
+ # byte unchanged.
328
+ def surrogate_pair_escape(text):
329
+ """`text` with every non-BMP character written as the two escapes a serialiser writes."""
330
+ out = []
331
+ for character in text:
332
+ code = ord(character)
333
+ if code > 0xFFFF:
334
+ high = ((code - 0x10000) >> 10) + 0xD800
335
+ low = ((code - 0x10000) & 0x3FF) + 0xDC00
336
+ out.append(f"\\\\u{high:04x}\\\\u{low:04x}")
337
+ else:
338
+ out.append(character)
339
+ return "".join(out)
340
+
341
+ def wide_text(text):
342
+ """`text` with each ASCII lowercase letter as its fullwidth form, which NFKC folds back."""
343
+ return "".join(chr(ord(character) - 0x61 + 0xFF41) if "a" <= character <= "z" else character
344
+ for character in text)
345
+
346
+ maths_name = "".join(chr(0x1D5BA + (ord(c) - ord("a"))) for c in "password")
347
+ turkish_name = "AP" + chr(0x0130) + "_KEY" # AA#1: the CHARACTER, not its escape
348
+ korean_words = chr(0xC554) + chr(0xD638) + " " + chr(0xD544) + chr(0xB4DC)
349
+ backslash = chr(0x5C)
350
+ # Each row declares the spelling its source text actually has, asserted below before any boundary
351
+ # is asked: a row written as `"AP\\u0130_KEY"` in this file holds the ESCAPE, and reading it as the
352
+ # character is how Y#1's plain case went missing twice.
353
+ # (label, source text, spelling, outcome)
354
+ # spelling: "plain" - no backslash in the source text; "escaped" - at least one
355
+ # outcome: False - the projected quote is refused; True - admitted;
356
+ # "blanked" - the projection blanks the block, and the raw text is refused as undecodable
357
+ strict_rows = [
358
+ ("a compatibility name in mathematical letters", maths_name, "plain", False),
359
+ ("... written as surrogate pair escapes", surrogate_pair_escape(maths_name), "escaped", False),
360
+ ("a secret-named token with U+0130", turkish_name, "plain", False),
361
+ ("... written as an escape", "AP" + backslash + "u0130_KEY", "escaped", False),
362
+ # a lone surrogate is an encoding the verifier cannot finish, so the PROJECTION already blanks
363
+ # the block: there is no sensitive quote left to refuse, which is the stronger outcome. The
364
+ # predicate is still asked about the raw text below.
365
+ ("a lone high surrogate escape", "a field " + backslash + "ud83d here", "escaped", "blanked"),
366
+ ("a lone low surrogate escape", "a field " + backslash + "ude00 here", "escaped", "blanked"),
367
+ # AA#0: a backslash sequence the JSON escape table does not define. The lenient reading drops
368
+ # the backslash and reads `x41`, which is why the strict traversal tracks this itself. Only the
369
+ # short `\u` run is blanked in the view: the view side is best-effort by the owner's split, and
370
+ # these rows are about the STRICT boundary refusing what the view still carries.
371
+ ("an \\x escape", "a " + backslash + "x41 field", "escaped", False),
372
+ ("a \\q escape", "a " + backslash + "q field", "escaped", False),
373
+ ("a short \\u escape", "a " + backslash + "u12 field", "escaped", "blanked"),
374
+ ("a \\U escape", "a " + backslash + "U0001D5C9 field", "escaped", False),
375
+ ("a trailing lone backslash", "a field ends here " + backslash, "escaped", False),
376
+ # AB#0: an invisible character inside a secret name. Each renders nothing of its own or only
377
+ # modifies its neighbour, so `pass<it>word` reads as `password` to a person and tokenised as
378
+ # two ordinary names before the skeleton dropped them. One row per category, plain and
379
+ # JSON-escaped.
380
+ ("an Mc mark inside the name", "the pass" + chr(0x093E) + "word field", "plain", False),
381
+ ("an Me mark inside the name", "the pass" + chr(0x0488) + "word field", "plain", False),
382
+ ("a zero-width space inside the name", "the pass" + chr(0x200B) + "word field", "plain", False),
383
+ ("a zero-width joiner inside the name", "the pass" + chr(0x200D) + "word field", "plain", False),
384
+ ("a soft hyphen inside the name", "the pass" + chr(0x00AD) + "word field", "plain", False),
385
+ ("a variation selector inside the name",
386
+ "the pass" + chr(0xFE0F) + "word field", "plain", False),
387
+ ("a tag character inside the name", "the pass" + chr(0xE0041) + "word field", "plain", False),
388
+ ("... the zero-width space, JSON-escaped",
389
+ "the pass" + backslash + "u200bword field", "escaped", False),
390
+ ("... the soft hyphen, JSON-escaped",
391
+ "the pass" + backslash + "u00adword field", "escaped", False),
392
+ ("... the variation selector, JSON-escaped",
393
+ "the pass" + backslash + "ufe0fword field", "escaped", False),
394
+ # AC#0: a Unicode variant of an OWNER PATH and of a FLOOR VALUE. These are the two detectors
395
+ # that saw only the decoded spelling while the name detector normalised; each goes through
396
+ # the real writers here, not the predicate. Two of the path rows are masked in the view
397
+ # already - the projection's own home rule reaches them - so those assert the masking and
398
+ # the raw refusal, and the three the view still carries assert the boundary refusing them.
399
+ ("an owner path with a fullwidth letter",
400
+ "the file /U" + wide_text("sers") + "/fixtureowner/Documents/notes.md was read",
401
+ "plain", False),
402
+ ("an owner path with a zero-width space",
403
+ "the file /Users/fixture" + chr(0x200B) + "owner/Documents/notes.md was read",
404
+ "plain", "masked"),
405
+ ("an owner path with a combining mark",
406
+ "the file /Users/fixtureowne" + chr(0x0301) + "r/Documents/notes.md was read",
407
+ "plain", "masked"),
408
+ ("a floor value in fullwidth",
409
+ "the key sk-" + wide_text("abcdefghijklmnopqrst") + " was used", "plain", False),
410
+ ("a floor value with a zero-width space",
411
+ "the key sk-abcdefghij" + chr(0x200B) + "klmnopqrst was used", "plain", False),
412
+ # AD#0 / AD#1: one row per ORDER the pipeline could not reach. The invisible character sits
413
+ # inside a CASE-SENSITIVE owner path and credential, which the casefolded skeleton could
414
+ # never have matched; the escapes are revealed by NFKC and by casefolding, after the decoding
415
+ # step had already run.
416
+ ("an invisible character inside a case-sensitive owner path",
417
+ "the file /Us" + chr(0x200B) + "ers/fixtureowner/Documents/notes.md was read",
418
+ "plain", False),
419
+ ("an invisible character inside a case-sensitive credential",
420
+ "the key sk-abcdefghij" + chr(0x200B) + "klmnopqrst was used", "plain", False),
421
+ # AE#0: a credential whose REQUIRED PREFIX is case-sensitive. The `sk-` row above is matched
422
+ # by the casefolded skeleton too, so it passes with or without case preservation and tests
423
+ # nothing about the order. `AKIA[0-9A-Z]{12,}` does not survive casefolding, so only a
424
+ # spelling that is invisible-stripped AND case-preserved reaches the floor with it. The
425
+ # property is asserted directly below, before the boundary is asked.
426
+ ("an invisible character inside a case-SENSITIVE credential",
427
+ "the key AKI" + chr(0x200B) + "A0123456789ABCDEF was used", "plain", False),
428
+ ("an escape revealed by NFKC",
429
+ "the " + chr(0xFF3C) + "u0070assword field was empty", "plain", False),
430
+ ("an escape revealed by casefolding",
431
+ "the A " + backslash + "U0070ASSWORD FIELD was empty", "escaped", False),
432
+ ("an ordinary escaped e-acute", "the caf" + backslash + "u00e9 menu was read", "escaped", True),
433
+ # ... and the admitted side for the same two detectors
434
+ ("an ordinary non-owner path with Unicode letters",
435
+ "the file /opt/caf" + chr(0xE9) + "/bin/tool was run", "plain", True),
436
+ # ... and the invisible characters where they name nothing
437
+ ("an emoji with a zero-width joiner sequence",
438
+ "a family " + chr(0x1F468) + chr(0x200D) + chr(0x1F469) + chr(0x200D) + chr(0x1F467)
439
+ + " stands here", "plain", True),
440
+ ("a variation selector in a non-secret word",
441
+ "the caf" + chr(0xE9) + chr(0xFE0F) + " menu", "plain", True),
442
+ # ... and the admitted controls: the table's own escapes, and characters that need none
443
+ ("an ordinary non-ASCII word", korean_words, "plain", True),
444
+ ("... written as escapes",
445
+ backslash + "uc554" + backslash + "ud638 " + backslash + "ud544" + backslash + "ub4dc",
446
+ "escaped", True),
447
+ ("only table escapes, and characters needing none",
448
+ "a " + backslash + "n b " + backslash + '" c ' + chr(0xE9) + " " + chr(0x1F600),
449
+ "escaped", True),
450
+ ]
451
+
452
+ def fx_strict_rows():
453
+ records = [views.fx_human(views.fx_stamp(1), "a block a reader may see")]
454
+ for index, (_label, text, _spelling, _state) in enumerate(strict_rows, start=2):
455
+ records.append(views.fx_assistant(views.fx_stamp(index), f"the {text} field was empty"))
456
+ return records
457
+
458
+ strict_run = views.golden(pathlib.Path(td), "strict-rows", main_records=fx_strict_rows,
459
+ owned=[[0, len(strict_rows) + 2]])
460
+ strict_dir, strict_main = strict_run["run_dir"], strict_run["main"]
461
+ strict_texts = views.projection_texts(strict_dir, strict_main["redacted"])
462
+ # a clean record of this run is stored first, so there is a populated file to protect
463
+ clean_strict = make(strict_dir, strict_main["version_sha"], 1, "/message/content",
464
+ [0, len("a block a reader")], "in_window")
465
+ if not append(strict_dir, "populated", clean_strict):
466
+ failures.append("the clean record of the strict-rows run was not stored")
467
+ populated_strict = pathlib.Path(strict_dir) / "evidence" / "populated.jsonl"
468
+ if not populated_strict.read_bytes():
469
+ failures.append("the strict-rows populated file is empty, so byte-identity proves nothing")
470
+ # AE#0: the fixture only tests the case-preserving step if the floor pattern behind it really is
471
+ # case-sensitive. Asserted here, of the floor itself, rather than assumed of a pattern that could
472
+ # gain an IGNORECASE flag later.
473
+ case_clean = "AKIA0123456789ABCDEF"
474
+ floor_rules = projection.floor_patterns()
475
+ if not any(pattern.search(case_clean) for pattern in floor_rules):
476
+ failures.append(f"the floor does not claim {case_clean!r}, so the case-sensitive credential "
477
+ f"fixture tests nothing")
478
+ if any(pattern.search(case_clean.casefold()) for pattern in floor_rules):
479
+ failures.append(f"the floor claims the casefold of {case_clean!r} too, so that fixture passes "
480
+ f"without case preservation and tests nothing")
481
+
482
+ for index, (label, text, spelling, state) in enumerate(strict_rows, start=2):
483
+ admissible = state is True
484
+ # AA#1: the source spelling, asserted before any boundary is asked of the row
485
+ if (backslash in text) != (spelling == "escaped"):
486
+ failures.append(f"{label}: the source text is not {spelling}: {text!r}")
487
+ continue
488
+ record_id = f"{index}/message/content/0/text"
489
+ projected = strict_texts.get(record_id)
490
+ if projected is None:
491
+ failures.append(f"{label}: the fixture wrote no block at {record_id}")
492
+ continue
493
+ if state == "masked":
494
+ # the projection's own home-path masking already rewrote the span, so there is no
495
+ # sensitive quote left to refuse. The predicate is still asked about the raw text.
496
+ if text in projected or projection.HOME_MASK not in projected:
497
+ failures.append(f"{label}: the projection did not mask the path: {projected[:60]!r}")
498
+ allowed, why = projection.evidence_quote_admissible(text, views.FX_HOME)
499
+ if allowed or "home path" not in (why or ""):
500
+ failures.append(f"{label}: the strict rule does not refuse the raw text as the "
501
+ f"owner's home path: {why!r}")
502
+ continue
503
+ if state == "blanked":
504
+ if projected != projection.FLOOR.PLACEHOLDER:
505
+ failures.append(f"{label}: the projection did not blank the block: {projected[:40]!r}")
506
+ allowed, why = projection.evidence_quote_admissible(text, views.FX_HOME)
507
+ if allowed or "undecodable" not in (why or ""):
508
+ failures.append(f"{label}: the strict rule does not refuse the raw text as "
509
+ f"undecodable: {why!r}")
510
+ continue
511
+ if text not in projected and not admissible:
512
+ failures.append(f"{label}: the projected quote no longer carries the name, so refusing it "
513
+ f"proves nothing: {projected[:40]!r}")
514
+ span = [0, len(projected)]
515
+ before_bytes = {path: path.read_bytes() for path in
516
+ sorted((pathlib.Path(strict_dir) / "evidence").glob("*"))}
517
+ # the MAKING path
518
+ try:
519
+ made_row = make(strict_dir, strict_main["version_sha"], index,
520
+ "/message/content/0/text", span, "in_window")
521
+ if not admissible:
522
+ failures.append(f"{label}: make built a record for a quote that names a secret")
523
+ except Refused as exc:
524
+ made_row = None
525
+ if admissible:
526
+ failures.append(f"{label}: make refused an admissible quote: {exc}")
527
+ elif "EVIDENCE_QUOTE_SENSITIVE" not in str(exc):
528
+ failures.append(f"{label}: make refused it unnamed: {exc}")
529
+ # the INDEPENDENT record, appended to a new file and to the populated one
530
+ independent_row = {
531
+ "evidence_id": evidence_id(strict_main["version_sha"], index,
532
+ "/message/content/0/text", span, projection.CURRENT),
533
+ "source_copy": copy_rel(strict_main["version_sha"]),
534
+ "version_sha": strict_main["version_sha"], "line": index,
535
+ "json_pointer": "/message/content/0/text", "char_span": span,
536
+ "redaction_version": projection.CURRENT, "redacted_text": projected,
537
+ "window_role": "in_window"}
538
+ for name in (f"new{index}", "populated"):
539
+ try:
540
+ append(strict_dir, name, independent_row)
541
+ if not admissible:
542
+ failures.append(f"{label}: an independently built record was stored into "
543
+ f"{name}.jsonl")
544
+ except Refused as exc:
545
+ if admissible:
546
+ failures.append(f"{label}: an admissible record was refused at append: {exc}")
547
+ elif "EVIDENCE_QUOTE_SENSITIVE" not in str(exc):
548
+ failures.append(f"{label}: an independently built record was refused unnamed: {exc}")
549
+ if not admissible:
550
+ if (pathlib.Path(strict_dir) / "evidence" / f"new{index}.jsonl").exists():
551
+ failures.append(f"{label}: the refused record created its own store file")
552
+ after_bytes = {path: path.read_bytes() for path in
553
+ sorted((pathlib.Path(strict_dir) / "evidence").glob("*"))}
554
+ if after_bytes != before_bytes:
555
+ failures.append(f"{label}: a refusal changed a stored evidence file")
556
+ elif made_row is None:
557
+ failures.append(f"{label}: an admissible row produced no record at all")
558
+
559
+ # ---- the owner's strict quote rule, at the boundary where text becomes shareable ----------
560
+ #
561
+ # A quote is lifted out of its block and carried into a report, so the context that makes
562
+ # `"password": "<REDACTED>"` a correct thing to READ in a window does not travel with it. The rule
563
+ # refuses such a quote outright: not masked, not partly accepted. Clean counterpart first - the
564
+ # ordinary quote above was stored and verified - and then each trigger, plain and encoded, through
565
+ # the real admission path rather than through the predicate alone.
566
+ strict_cases = [
567
+ ("a secret-named token", 'the "password" field was empty'),
568
+ # X#0: every spelling the FLOOR recognises, each one plain and then one encoding down. The
569
+ # dotted capital I is the one that casefolding alone loses: `APİ_KEY` casefolds to `api` plus a
570
+ # combining dot, which the floor's `api[_-]?key` no longer matches.
571
+ ("a secret-named token with U+0130", "the AP\u0130_KEY field was empty"),
572
+ ("... and the same name one encoding down", "the AP\\u0130_KEY field was empty"),
573
+ ("a secret-named token spelled with U+017F", "the pa\u017f\u017fword field was empty"),
574
+ ("... and the same name one encoding down", "the pa\\u017f\\u017fword field was empty"),
575
+ # a fullwidth spelling, which NFKC folds to the floor's own name
576
+ ("a secret-named token in a compatibility spelling",
577
+ "the \uff53\uff45\uff43\uff52\uff45\uff54 field was empty"),
578
+ ("... and the same name one encoding down",
579
+ "the \\uff53\\uff45\\uff43\\uff52\\uff45\\uff54 field was empty"),
580
+ ("a secret-named token carrying a combining mark", "the passwo\u0301rd field was empty"),
581
+ ("... and the same name one encoding down", "the passwo\\u0301rd field was empty"),
582
+ # X#1: a name the floor claims only because something was prefixed to it
583
+ ("a prefixed secret name", "my_password was empty"),
584
+ ("a prefixed secret name in a Unicode spelling", "my_pa\u017f\u017fword was empty"),
585
+ ("a credential the floor claims", "use sk-" + "Ab1_" * 6 + " now"),
586
+ ("a credential the floor claims, encoded",
587
+ "use " + "".join(f"\\u{ord(c):04x}" for c in "sk-" + "Ab1_" * 6) + " now"),
588
+ ("the owner's home path", f"{views.FX_HOME}/Documents/notes.md"),
589
+ ("the owner's home path, encoded",
590
+ views.FX_HOME.replace("/", "\\u002f") + "\\u002fDocuments"),
591
+ # the reviewer's shapes of this round, as quotes
592
+ ("V#0: a readable array under an encoded key", '"\\u0070assword":["v0canary"]'),
593
+ ("V#1: a suffix after a masked scalar", '"\\u0070assword":"<REDACTED>"v1suffix'),
594
+ ("V#2: a quoted key with a newline before its separator", '"password"\n: "v2canary"'),
595
+ ]
596
+ refused_quotes = 0
597
+ for label, text in strict_cases:
598
+ admissible, why = projection.evidence_quote_admissible(text, views.FX_HOME)
599
+ if admissible:
600
+ failures.append(f"the strict quote rule admits {label}: {text[:40]!r}")
601
+ continue
602
+ refused_quotes += 1
603
+ if not why:
604
+ failures.append(f"the strict quote rule refused {label} without naming a reason")
605
+ if refused_quotes != len(strict_cases):
606
+ failures.append(f"only {refused_quotes} of {len(strict_cases)} sensitive quotes were refused")
607
+ # X#1: the POSITIVE controls - names the floor does not claim stay admissible, or the strict rule is
608
+ # a rule against the word `token` rather than against a secret's name
609
+ for label, text in (("an ordinary accounting field", "input_tokens were 412 this turn"),
610
+ ("an ordinary tool name", "the tokenizer ran twice"),
611
+ ("an ordinary sentence with no name at all", "three files changed"),
612
+ ("the mask by itself", projection.FLOOR.PLACEHOLDER)):
613
+ allowed, why = projection.evidence_quote_admissible(text, views.FX_HOME)
614
+ if not allowed:
615
+ failures.append(f"the strict quote rule refuses {label}: {why}")
616
+ # ... and on the MAKING path too, through a transcript whose projected block really holds a
617
+ # secret-named key with a masked value - which a window may show and a quote may not carry
618
+ def fx_keyed_block():
619
+ return [views.fx_human(views.fx_stamp(1), "a block a reader may see"),
620
+ views.fx_assistant(views.fx_stamp(2), '{"password":"keyed-value-for-the-quote-rule"}')]
621
+
622
+ keyed = views.golden(pathlib.Path(td), "keyed", main_records=fx_keyed_block, owned=[[0, 3]])
623
+ keyed_dir, keyed_main = keyed["run_dir"], keyed["main"]
624
+ keyed_text = next((text for record, text in
625
+ views.projection_texts(keyed_dir, keyed_main["redacted"]).items()
626
+ if "password" in text), None)
627
+ if keyed_text is None:
628
+ failures.append("the keyed fixture's projection holds no secret-named key, so the control below "
629
+ "is about nothing")
630
+ else:
631
+ try:
632
+ from_quote(keyed_dir, keyed_main["version_sha"], 2, "/message/content/0/text",
633
+ keyed_text, "in_window")
634
+ failures.append(f"a quote naming a secret-named key was made: {keyed_text[:40]!r}")
635
+ except Refused as exc:
636
+ if "EVIDENCE_QUOTE_SENSITIVE" not in str(exc):
637
+ failures.append(f"a quote naming a secret-named key was refused unnamed: {exc}")
638
+
639
+ # ... and the refusal really happens on the WRITING path, by name
640
+ sensitive = dict(record)
641
+ sensitive["redacted_text"] = 'the "password" field was empty'
642
+ try:
643
+ append(run_dir, "strict", sensitive)
644
+ failures.append("a sensitive quote was stored, so the admission rule is not on the write path")
645
+ except Refused as exc:
646
+ if "EVIDENCE_QUOTE_SENSITIVE" not in str(exc):
647
+ failures.append(f"a sensitive quote was refused unnamed: {exc}")
648
+ # W#1: a record built INDEPENDENTLY of make - as another tool, or an older file, would hand it in -
649
+ # is refused by append all the same, and nothing is written. The clean storage case above ran first,
650
+ # so this is a refusal and not a store that never worked.
651
+ if keyed_text is not None:
652
+ independent = {"evidence_id": evidence_id(keyed_main["version_sha"], 2,
653
+ "/message/content/0/text", [0, len(keyed_text)],
654
+ projection.CURRENT),
655
+ "source_copy": copy_rel(keyed_main["version_sha"]),
656
+ "version_sha": keyed_main["version_sha"], "line": 2,
657
+ "json_pointer": "/message/content/0/text",
658
+ "char_span": [0, len(keyed_text)], "redaction_version": projection.CURRENT,
659
+ "redacted_text": keyed_text, "window_role": "in_window"}
660
+ if claims.validate_record("evidence", independent):
661
+ failures.append("the independently built record is not a valid record, so refusing it "
662
+ "proves nothing about the admission rule")
663
+ # X#2: a CLEAN record of this run is stored first, so there is a populated file to protect and
664
+ # the refusals below are refusals rather than a store that never worked at all.
665
+ clean_keyed = make(keyed_dir, keyed_main["version_sha"], 1, "/message/content",
666
+ [0, len("a block a reader")], "in_window")
667
+ if not append(keyed_dir, "populated", clean_keyed):
668
+ failures.append("the clean record of the keyed run was not stored, so the controls below "
669
+ "protect nothing")
670
+ populated = pathlib.Path(keyed_dir) / "evidence" / "populated.jsonl"
671
+ if not populated.exists() or not populated.read_bytes():
672
+ failures.append("the populated evidence file is empty, so byte-identity proves nothing")
673
+ # ... and `verify` is otherwise clean about the sensitive record: what refuses it is the
674
+ # admission rule and not a locator or a version problem
675
+ if verify(keyed_dir, independent):
676
+ failures.append(f"the independently built record is not otherwise verifiable: "
677
+ f"{verify(keyed_dir, independent)}")
678
+ before_files = {path: path.read_bytes() for path in
679
+ sorted((pathlib.Path(keyed_dir) / "evidence").glob("*"))}
680
+ # to a NEW filename, and to the POPULATED one: both refused by name
681
+ for name in ("independent", "populated"):
682
+ try:
683
+ append(keyed_dir, name, independent)
684
+ failures.append(f"an independently built record naming a secret-named key was stored "
685
+ f"into {name}.jsonl")
686
+ except Refused as exc:
687
+ if "EVIDENCE_QUOTE_SENSITIVE" not in str(exc):
688
+ failures.append(f"an independently built record was refused unnamed: {exc}")
689
+ if (pathlib.Path(keyed_dir) / "evidence" / "independent.jsonl").exists():
690
+ failures.append("the refused independent record created its store file")
691
+ after_files = {path: path.read_bytes() for path in
692
+ sorted((pathlib.Path(keyed_dir) / "evidence").glob("*"))}
693
+ if after_files != before_files:
694
+ failures.append("the refused independent record changed an existing evidence file")
695
+ if not populated.read_bytes():
696
+ failures.append("the populated evidence file was emptied by a refusal")
697
+
698
+ # ... and NOTHING was written by that refusal: a refusal that leaves a line behind is a disclosure
699
+ # with an error message in front of it
700
+ store = pathlib.Path(run_dir) / "evidence" / "strict.jsonl"
701
+ if store.exists():
702
+ failures.append(f"the refused quote created {store.name}, so the refusal still wrote")
703
+ before = (pathlib.Path(run_dir) / "evidence" / "t1.jsonl").read_bytes()
704
+ try:
705
+ append(run_dir, "t1", sensitive)
706
+ failures.append("a sensitive quote was stored into an existing file")
707
+ except Refused:
708
+ pass
709
+ if (pathlib.Path(run_dir) / "evidence" / "t1.jsonl").read_bytes() != before:
710
+ failures.append("the refused quote changed an existing evidence file")
711
+ if make(run_dir, sha, record["line"], record["json_pointer"], record["char_span"], "in_window") != record:
712
+ failures.append("make and from_view disagree about the same span")
713
+ if claims.validate_record("evidence", record):
714
+ failures.append("the record does not conform to the evidence schema")
715
+
716
+ # O2 altered quote: one character changed in the quote -> QUOTE_MISMATCH; the raw bytes where the projection holds a mask -> the same
717
+ for label, edit in (("one character changed", lambda r: {**r, "redacted_text": r["redacted_text"].replace("plain", "plaim")}),
718
+ ("the span moved by one", lambda r: {**r, "char_span": [r["char_span"][0] + 1, r["char_span"][1] + 1]}),
719
+ ("the span past the block", lambda r: {**r, "char_span": [10_000, 10_005]})):
720
+ found = verify(run_dir, edit(record))
721
+ if not any(f.startswith("QUOTE_MISMATCH") for f in found):
722
+ failures.append(f"{label}: not named QUOTE_MISMATCH: {found}")
723
+ masked = entries[f"{golden['lines']['human']}/message/content"]["text"]
724
+ if golden["raw_path"] in masked or "<HOME>" not in masked:
725
+ failures.append("instrument control: the planted path is not masked in the window, so the raw/masked controls prove nothing")
726
+ raw_quote, masked_quote = f"see {golden['raw_path']}", "see <HOME>/Documents/repo/notes.md"
727
+ try:
728
+ from_quote_raw = from_quote(run_dir, sha, golden["lines"]["human"], "/message/content", raw_quote, "in_window")
729
+ failures.append(f"a quote carrying the raw bytes was accepted: {from_quote_raw['redacted_text']!r}")
730
+ except Refused as exc:
731
+ if "QUOTE_MISMATCH" not in str(exc):
732
+ failures.append(f"a raw-bytes quote was refused unnamed: {exc}")
733
+ masked_record = from_quote(run_dir, sha, golden["lines"]["human"], "/message/content", masked_quote, "in_window")
734
+ if verify(run_dir, masked_record) or masked_record["redacted_text"] != masked_quote:
735
+ failures.append("a quote carrying the masked form did not validate")
736
+ if any(golden["secret"] in json.dumps(r) or golden["raw_path"] in json.dumps(r) for r in (record, masked_record)):
737
+ failures.append("a planted secret or path reached an evidence record")
738
+ try:
739
+ from_view(run_dir, sha, human, quote + " and then some")
740
+ failures.append("a quote that is not in the window was made into evidence")
741
+ except Refused as exc:
742
+ if "QUOTE_MISMATCH" not in str(exc):
743
+ failures.append(f"a quote not in the window was refused unnamed: {exc}")
744
+ try:
745
+ from_quote(run_dir, sha, golden["lines"]["human"], "/message/content", "e", "in_window")
746
+ failures.append("an ambiguous quote was resolved without naming the occurrence")
747
+ except Refused as exc:
748
+ if "QUOTE_AMBIGUOUS" not in str(exc):
749
+ failures.append(f"an ambiguous quote was refused unnamed: {exc}")
750
+ for label, call in (("by line and pointer", lambda n: from_quote(run_dir, sha, golden["lines"]["human"], "/message/content",
751
+ quote, "in_window", occurrence=n)),
752
+ ("out of a window", lambda n: from_view(run_dir, sha, human, quote, occurrence=n))):
753
+ for n in (1, -1): # the quote occurs once: occurrence 1 names nothing, and -1 must not index from the end
754
+ try:
755
+ call(n)
756
+ failures.append(f"an occurrence the quote does not have ({n}, {label}) was made into evidence")
757
+ except Refused as exc:
758
+ if not str(exc).startswith("QUOTE_OCCURRENCE_UNKNOWN"):
759
+ failures.append(f"an occurrence the quote does not have ({n}, {label}) was refused unnamed: {exc}")
760
+ except Exception as exc: # noqa: BLE001 - an IndexError here is the defect this control names
761
+ failures.append(f"an occurrence the quote does not have ({n}, {label}) raised {exc!r}")
762
+ try: # the same, read out of a window's entry rather than named by line and pointer
763
+ from_view(run_dir, sha, human, "e")
764
+ failures.append("an ambiguous quote in a window was resolved without naming the occurrence")
765
+ except Refused as exc:
766
+ if "QUOTE_AMBIGUOUS" not in str(exc):
767
+ failures.append(f"an ambiguous quote in a window was refused unnamed: {exc}")
768
+ # `make` is where a locator is first resolved: a pointer that names no block, and a span outside the block
769
+ for label, line, pointer, span in (("a pointer that names no block", golden["lines"]["human"], "/message/nowhere", [0, 3]),
770
+ ("a line past the end", 9999, "/message/content", [0, 3]),
771
+ ("a span past the block", golden["lines"]["human"], "/message/content", [10_000, 10_005]),
772
+ ("an empty span", golden["lines"]["human"], "/message/content", [3, 3])):
773
+ try:
774
+ make(run_dir, sha, line, pointer, span, "in_window")
775
+ failures.append(f"evidence was made for {label}")
776
+ except Refused as exc:
777
+ if "LOCATOR_UNRESOLVED" not in str(exc):
778
+ failures.append(f"{label} was refused unnamed: {exc}")
779
+ # a locator that is not a block, a role the schema does not know, a record that is not a record
780
+ if "LOCATOR_UNRESOLVED" not in "\n".join(verify(run_dir, {**record, "json_pointer": "/message/nowhere"})):
781
+ failures.append("a pointer that names no block was not LOCATOR_UNRESOLVED")
782
+ if "LOCATOR_UNRESOLVED" not in "\n".join(verify(run_dir, {**record, "line": 9999})):
783
+ failures.append("a line past the end was not LOCATOR_UNRESOLVED")
784
+ if "EVIDENCE_INVALID" not in "\n".join(verify(run_dir, {**record, "window_role": "elsewhere"})):
785
+ failures.append("a record with a role the schema does not know was not EVIDENCE_INVALID")
786
+ if "EVIDENCE_INVALID" not in "\n".join(verify(run_dir, {k: v for k, v in record.items() if k != "window_role"})):
787
+ failures.append("a record without window_role was not EVIDENCE_INVALID")
788
+ # M#6: the locator the owner opens is the file whose bytes were verified. Positive control first -
789
+ # `record` itself verifies above - then the same record with only its source_copy substituted. A
790
+ # second intact copy is planted under another name, so the substituted path is a real, openable,
791
+ # unmodified file and nothing but the locator rule can refuse it.
792
+ other = pathlib.Path(run_dir) / "sources" / "another-copy.jsonl"
793
+ other.write_bytes((pathlib.Path(run_dir) / copy_rel(sha)).read_bytes())
794
+ moved = {**record, "source_copy": "sources/another-copy.jsonl"}
795
+ found = verify(run_dir, moved)
796
+ if not any(f.startswith("SOURCE_LOCATOR_MISMATCH") for f in found):
797
+ failures.append(f"a record whose source_copy points elsewhere verified: {found}")
798
+ if openable(run_dir, moved) == openable(run_dir, record):
799
+ failures.append("the substituted locator opened the same file, so the control proves nothing")
800
+ try:
801
+ append(run_dir, "mismatched", moved)
802
+ failures.append("a record whose source_copy points elsewhere was stored")
803
+ except Refused as exc:
804
+ if "SOURCE_LOCATOR_MISMATCH" not in str(exc):
805
+ failures.append(f"storing it was refused unnamed: {exc}")
806
+ other.unlink()
807
+ # P#5: the READER refuses a store made under another projection. `verify` always did; `load` and
808
+ # `resolve` handed the record - and its quote - straight back. Positive control first: the store
809
+ # holds this run's own record and both readers return it.
810
+ if not load(run_dir, "t1") or resolve(run_dir, record["evidence_id"]) is None:
811
+ failures.append("the store's own record is not readable through load and resolve")
812
+ store = pathlib.Path(run_dir) / "evidence" / "stale.jsonl"
813
+ store.write_text(json.dumps({**record, "redaction_version": "r1"}, sort_keys=True) + "\n", encoding="utf-8")
814
+ for label, call in (("load", lambda: load(run_dir, "stale")),
815
+ ("resolve", lambda: resolve(run_dir, record["evidence_id"]))):
816
+ try:
817
+ call()
818
+ failures.append(f"{label} returned a record made under another projection version")
819
+ except Refused as exc:
820
+ if "REDACTION_VERSION_MISMATCH" not in str(exc):
821
+ failures.append(f"{label} refused a stale store unnamed: {exc}")
822
+ if [r["evidence_id"] for r in load(run_dir, "stale", current=False)] != [record["evidence_id"]]:
823
+ failures.append("an explicit unchecked load did not read the stale store it was asked for")
824
+ store.unlink()
825
+
826
+ # the projection's version moves: the old quote fails by name, the same quote made again passes
827
+ projection.VERSIONS["rt"] = lambda value, home=None: projection.project_r22(value, home) # a new version, the same text
828
+ try:
829
+ found = verify(run_dir, record, current="rt")
830
+ if not any(f.startswith("REDACTION_VERSION_MISMATCH") for f in found):
831
+ failures.append(f"an old quote under a new projection version was not REDACTION_VERSION_MISMATCH: {found}")
832
+ again = make(run_dir, sha, record["line"], record["json_pointer"], record["char_span"], "in_window", "rt")
833
+ if verify(run_dir, again, current="rt") or again["redaction_version"] != "rt" or again["evidence_id"] == record["evidence_id"]:
834
+ failures.append("the re-projected quote did not pass under the new version as a new record")
835
+ projection.VERSIONS["rt"] = lambda value, home=None: projection.project_r22(value, home).replace("plain", "simple")
836
+ if not any(f.startswith("QUOTE_MISMATCH") for f in verify(run_dir, again, current="rt")):
837
+ failures.append("a record whose version is current but whose text the projection no longer gives was not QUOTE_MISMATCH")
838
+ finally:
839
+ del projection.VERSIONS["rt"]
840
+
841
+ # SOURCE_TAMPERED: the copy is edited in place (the O2 altered-source plant); a missing copy is named too
842
+ os.chmod(copy, 0o644)
843
+ original = copy.read_bytes()
844
+ copy.write_bytes(original.replace(b"plain version", b"plain versiom", 1))
845
+ found = verify(run_dir, record)
846
+ if not any(f.startswith("SOURCE_TAMPERED") for f in found):
847
+ failures.append(f"an edited source copy was not SOURCE_TAMPERED: {found}")
848
+ try:
849
+ make(run_dir, sha, record["line"], record["json_pointer"], record["char_span"], "in_window")
850
+ failures.append("evidence was made over an edited copy")
851
+ except Refused as exc:
852
+ if "SOURCE_TAMPERED" not in str(exc):
853
+ failures.append(f"making evidence over an edited copy was refused unnamed: {exc}")
854
+ copy.write_bytes(original)
855
+ os.chmod(copy, 0o444)
856
+ if verify(run_dir, record):
857
+ failures.append("restoring the copy's bytes did not restore the evidence")
858
+ os.chmod(copy, 0o644)
859
+ copy.rename(copy.with_name("moved"))
860
+ if not any(f.startswith("SOURCE_MISSING") for f in verify(run_dir, record)):
861
+ failures.append("a missing copy was not SOURCE_MISSING")
862
+ copy.with_name("moved").rename(copy)
863
+ os.chmod(copy, 0o444)
864
+ # the projection file is not trusted: evidence is checked against the copy, so a doctored projection changes nothing
865
+ projected = pathlib.Path(run_dir) / main["redacted"]
866
+ text = projected.read_text(encoding="utf-8")
867
+ projected.write_text(text.replace("plain version", "plain wersion"), encoding="utf-8")
868
+ if verify(run_dir, record):
869
+ failures.append("evidence depended on the projection file instead of the copy")
870
+ projected.write_text(text, encoding="utf-8")
871
+ # a lone surrogate in a block: the projection replaces it, the quote around it still verifies
872
+ if projection.project(json.loads('"a\\ud83dz"')) != "a?z":
873
+ failures.append("a lone surrogate was not replaced")
874
+
875
+ for failure in failures:
876
+ print(f"evidence --self-test [FAIL] {failure}")
877
+ if failures:
878
+ return 1
879
+ print("evidence --self-test: OK (a quote read from a window verifies, stores once, resolves and opens at its source; a changed "
880
+ "character, a moved span, the raw bytes where a mask stands and a quote not shown are QUOTE_MISMATCH; an ambiguous quote, "
881
+ "an unknown pointer or line, an unknown role and a missing window_role are named; an old projection version fails "
882
+ "REDACTION_VERSION_MISMATCH and the quote made again passes; an edited copy is SOURCE_TAMPERED, a missing one SOURCE_MISSING, "
883
+ "and the projection file is never the authority)")
884
+ return 0
885
+
886
+
887
+ if __name__ == "__main__":
888
+ if "--self-test" not in sys.argv[1:]:
889
+ sys.exit("usage: evidence.py --self-test")
890
+ sys.exit(self_test())