agent-bios 0.19.4 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/DEPENDENCIES.md +19 -5
  2. package/README.md +14 -19
  3. package/claude/agents/frontier.md +1 -1
  4. package/claude/guides/claude-prompting.md +475 -234
  5. package/claude/guides/cli-multi-model-workflow.md +4 -3
  6. package/claude/guides/gpt-prompting.md +235 -136
  7. package/claude/guides/session-distill-workflow.md +93 -43
  8. package/claude/guides/tooling-gotchas.md +3 -1
  9. package/codex/guides/claude-prompting.md +475 -234
  10. package/codex/guides/cli-multi-model-workflow.md +4 -3
  11. package/codex/guides/gpt-prompting.md +235 -136
  12. package/codex/guides/session-distill-workflow.md +93 -43
  13. package/codex/guides/tooling-gotchas.md +3 -1
  14. package/compose/assemble.py +4 -1
  15. package/compose/canary.sh +8 -6
  16. package/compose/host_platform.py +158 -15
  17. package/compose/instructions-state.py +183 -41
  18. package/compose/instructions_install.py +222 -27
  19. package/compose/instructions_session.py +250 -75
  20. package/compose/instructions_setup_cli.py +2 -36
  21. package/compose/instructions_store.py +160 -3
  22. package/compose/instructions_transaction.py +29 -5
  23. package/docs/advanced-launch.md +4 -0
  24. package/docs/releases/0.20.0.md +102 -0
  25. package/install.sh +42 -14
  26. package/launch/agent-launch.py +152 -18
  27. package/launch/agent-launch.toml +17 -7
  28. package/launch/agent-launch.zsh +104 -13
  29. package/launch/claude_subcommands.py +179 -0
  30. package/launch/shell_integration.py +7 -1
  31. package/learn/collect-learning.py +60 -9
  32. package/learn/migrate-learnings.py +70 -4
  33. package/learn/redact.py +2 -1
  34. package/package.json +36 -3
  35. package/provenance.json +1 -1
  36. package/session-cost.py +80 -9
  37. package/session-distill/coverage.json +6 -0
  38. package/session-distill/distill.py +2575 -0
  39. package/session-distill/grammar/__init__.py +0 -0
  40. package/session-distill/grammar/owner_lines.py +874 -0
  41. package/session-distill/originators.json +9 -0
  42. package/session-distill/packets/cross_review.md +31 -0
  43. package/session-distill/packets/form.md +86 -0
  44. package/session-distill/packets/judge.md +81 -0
  45. package/session-distill/packets/placement_contract.md +90 -0
  46. package/session-distill/packets/propose.md +124 -0
  47. package/session-distill/packets/read.md +57 -0
  48. package/session-distill/packets/reconsider.md +53 -0
  49. package/session-distill/packets/s7b.md +65 -0
  50. package/session-distill/packets/s9b.md +39 -0
  51. package/session-distill/packets/stitch.md +35 -0
  52. package/session-distill/packets/sweep.md +33 -0
  53. package/session-distill/runlib/__init__.py +0 -0
  54. package/session-distill/runlib/bound.py +1102 -0
  55. package/session-distill/runlib/breaker.py +467 -0
  56. package/session-distill/runlib/census.py +2347 -0
  57. package/session-distill/runlib/claims.py +420 -0
  58. package/session-distill/runlib/controls.py +902 -0
  59. package/session-distill/runlib/coverage.py +881 -0
  60. package/session-distill/runlib/declare.py +888 -0
  61. package/session-distill/runlib/delivery_evidence.py +1145 -0
  62. package/session-distill/runlib/derive.py +812 -0
  63. package/session-distill/runlib/destinations.py +3072 -0
  64. package/session-distill/runlib/dispatch.py +7939 -0
  65. package/session-distill/runlib/drift.py +1077 -0
  66. package/session-distill/runlib/entry.py +401 -0
  67. package/session-distill/runlib/evidence.py +890 -0
  68. package/session-distill/runlib/exposure.py +1162 -0
  69. package/session-distill/runlib/gate.py +2727 -0
  70. package/session-distill/runlib/gitread.py +79 -0
  71. package/session-distill/runlib/inventory.py +19624 -0
  72. package/session-distill/runlib/journal.py +1919 -0
  73. package/session-distill/runlib/ledger.py +3210 -0
  74. package/session-distill/runlib/ledger_compat.py +101 -0
  75. package/session-distill/runlib/ledger_migration.py +190 -0
  76. package/session-distill/runlib/lifecycle_intake.py +693 -0
  77. package/session-distill/runlib/lineage.py +454 -0
  78. package/session-distill/runlib/measures.py +249 -0
  79. package/session-distill/runlib/monitor.py +1180 -0
  80. package/session-distill/runlib/operations.py +522 -0
  81. package/session-distill/runlib/packet.py +838 -0
  82. package/session-distill/runlib/placement.py +1769 -0
  83. package/session-distill/runlib/projection.py +4090 -0
  84. package/session-distill/runlib/ranking.py +740 -0
  85. package/session-distill/runlib/receipts.py +200 -0
  86. package/session-distill/runlib/records.py +1965 -0
  87. package/session-distill/runlib/search.py +249 -0
  88. package/session-distill/runlib/sequencing.py +829 -0
  89. package/session-distill/runlib/sources.py +641 -0
  90. package/session-distill/runlib/stage_adjudicate.py +845 -0
  91. package/session-distill/runlib/stage_apply.py +1378 -0
  92. package/session-distill/runlib/stage_approvals.py +758 -0
  93. package/session-distill/runlib/stage_close.py +1220 -0
  94. package/session-distill/runlib/stage_confirm.py +929 -0
  95. package/session-distill/runlib/stage_delivery.py +3080 -0
  96. package/session-distill/runlib/stage_form.py +2576 -0
  97. package/session-distill/runlib/stage_judge.py +4248 -0
  98. package/session-distill/runlib/stage_propose.py +3307 -0
  99. package/session-distill/runlib/stage_read.py +5179 -0
  100. package/session-distill/runlib/stage_render.py +2739 -0
  101. package/session-distill/runlib/stage_retrieve.py +924 -0
  102. package/session-distill/runlib/stage_review_korean.py +1002 -0
  103. package/session-distill/runlib/stage_review_proposals.py +1292 -0
  104. package/session-distill/runlib/stagelock.py +412 -0
  105. package/session-distill/runlib/stop.py +1061 -0
  106. package/session-distill/runlib/targets.py +809 -0
  107. package/session-distill/runlib/usage.py +280 -0
  108. package/session-distill/runlib/validate.py +319 -0
  109. package/session-distill/runlib/views.py +4327 -0
  110. package/session-distill/schemas/adjudication.schema.json +35 -0
  111. package/session-distill/schemas/approval.schema.json +35 -0
  112. package/session-distill/schemas/census.schema.json +128 -0
  113. package/session-distill/schemas/checks.schema.json +207 -0
  114. package/session-distill/schemas/claim.schema.json +16 -0
  115. package/session-distill/schemas/confirmation.schema.json +24 -0
  116. package/session-distill/schemas/coverage.schema.json +66 -0
  117. package/session-distill/schemas/cross_review.schema.json +24 -0
  118. package/session-distill/schemas/event.schema.json +20 -0
  119. package/session-distill/schemas/evidence.schema.json +20 -0
  120. package/session-distill/schemas/expected_observation.schema.json +18 -0
  121. package/session-distill/schemas/form.schema.json +103 -0
  122. package/session-distill/schemas/intake.schema.json +71 -0
  123. package/session-distill/schemas/inventory.schema.json +872 -0
  124. package/session-distill/schemas/judge.schema.json +77 -0
  125. package/session-distill/schemas/ledger.schema.json +313 -0
  126. package/session-distill/schemas/observation.schema.json +16 -0
  127. package/session-distill/schemas/propose.schema.json +555 -0
  128. package/session-distill/schemas/read.schema.json +76 -0
  129. package/session-distill/schemas/reconsider.schema.json +122 -0
  130. package/session-distill/schemas/run.schema.json +150 -0
  131. package/session-distill/schemas/s7b.schema.json +200 -0
  132. package/session-distill/schemas/s9b.schema.json +28 -0
  133. package/session-distill/schemas/stitch.schema.json +25 -0
  134. package/session-distill/schemas/sweep.schema.json +25 -0
  135. package/session-distill/seats.json +149 -0
  136. package/session-distill/tables/allowed_pairs.json +257 -0
  137. package/session-distill/tables/controls.json +30 -0
  138. package/session-distill/tables/delivery_evidence.json +36 -0
  139. package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
  140. package/session-distill/tables/destinations.json +684 -0
  141. package/session-distill/tables/drift_layers.json +68 -0
  142. package/session-distill/tables/exposure_rules.json +192 -0
  143. package/session-distill/tables/placement_rules.json +148 -0
  144. package/session-distill/tables/propose_fixtures.json +154 -0
  145. package/session-distill/tables/ranking.json +194 -0
  146. package/session-distill/tables/redundancy.json +10 -0
  147. package/session-distill/tables/structural_rules.json +44 -0
  148. package/session-distill/tables/transition_fixtures.json +398 -0
  149. package/session-distill/tables/transitions.json +69 -0
  150. package/session-distill/tables/unit_outcome.json +67 -0
  151. package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
  152. package/wrappers/claude-run.sh +481 -33
  153. package/wrappers/claude_hermetic_evidence.py +1423 -0
  154. package/wrappers/codex-helm.sh +38 -7
  155. package/wrappers/codex-run.sh +183 -20
  156. package/wrappers/codex_frame_filter.py +1199 -0
  157. package/wrappers/codex_protocol.py +737 -0
  158. package/wrappers/jsonl_lines.py +65 -0
@@ -0,0 +1,641 @@
1
+ #!/usr/bin/env python3
2
+ """Readers for the S1 census: transcripts, the host indexes, activation pins (design §5.1, §5.3).
3
+
4
+ Every function here reads and none writes under the owner's homes. A transcript is opened
5
+ `rb`, or decompressed by the `zstd` the run declares by absolute path (`.jsonl.zst` is what
6
+ the host leaves behind after indexing a rollout); a missing `zstd` makes each such file
7
+ `Unreadable` by name instead of skipping it. The host indexes are the one place reading is
8
+ not obvious:
9
+
10
+ * `state_5.sqlite` is a WAL database, and the host has it open while a census runs. A read-only
11
+ connection that sees uncheckpointed threads is `mode=ro` (never `immutable=1`, which ignores
12
+ the WAL), but any connection to the host's own files can write: SQLite keeps its read marks in
13
+ the `-shm` file and creates `-wal`/`-shm` when they are absent. So `open_threads` never opens
14
+ the host's database. It clones the database and its `-wal` (`cp -c`, copy on write) into a
15
+ directory of its own (made fresh by `mkdtemp` under a parent the caller has confined, never a
16
+ directory that was already there) and opens the clone; SQLite rebuilds the `-shm` there. The directory is
17
+ removed afterwards, and only that directory: if it is no longer the real directory that was made
18
+ (swapped for a link, say) nothing is removed and the read fails as `SNAPSHOT_DIR_CHANGED`.
19
+ The clones are taken at different instants, so each capture is bracketed by the size, mtime
20
+ and inode of both host files and repeated (`SNAPSHOT_ATTEMPTS`) if the host wrote in between;
21
+ a database that never settles is `INDEX_UNSTABLE`, not a guess.
22
+ * `history.jsonl` and the Desktop `local_*.json` files are plain files.
23
+
24
+ Failures are named by their first word: ZSTD_UNAVAILABLE, ZSTD_FAILED, READ_FAILED,
25
+ INDEX_UNREADABLE, INDEX_UNSTABLE, INDEX_SHAPE, SNAPSHOT_DIR_CHANGED.
26
+
27
+ sources.py --self-test
28
+ """
29
+ import contextlib
30
+ import hashlib
31
+ import json
32
+ import os
33
+ import pathlib
34
+ import re
35
+ import shutil
36
+ import sqlite3
37
+ import subprocess
38
+ import sys
39
+ import tempfile
40
+ import time
41
+
42
+ # The names a run declares in `run.json` `sources[]` (design §4.1). The census reads these and
43
+ # no others; a name it needs that the run does not declare is reported undeclared, never zero.
44
+ TRANSCRIPT_SOURCES = ("claude_projects", "codex_sessions", "codex_archived_sessions")
45
+ INDEX_SOURCES = ("claude_desktop_index", "claude_history", "codex_state")
46
+ SOURCE_NAMES = TRANSCRIPT_SOURCES + INDEX_SOURCES + ("agent_bios_state", "zstd")
47
+ # What §5.3 reads from `threads`; a table without one of them is a changed shape (§14 check 7).
48
+ THREAD_COLUMNS = ("id", "rollout_path", "source", "created_at", "updated_at")
49
+ ROLLOUT = re.compile(r"^rollout-.*\.jsonl(\.zst)?$")
50
+ SNAPSHOT_ATTEMPTS = 5 # captures of the host database before it is called unstable
51
+
52
+
53
+ class Unreadable(Exception):
54
+ """A source or transcript that could not be read; the message starts with the named code."""
55
+
56
+
57
+ def declared(run):
58
+ """`{name: path}` of the sources a run declares that the census reads."""
59
+ return {s["name"]: s["path"] for s in run.get("sources", []) if s["name"] in SOURCE_NAMES}
60
+
61
+
62
+ def state_of(path, want_dir):
63
+ """`undeclared`, `missing` or `present`: an absent source is unknown coverage, not zero."""
64
+ if path is None:
65
+ return "undeclared"
66
+ p = pathlib.Path(path)
67
+ return "present" if (p.is_dir() if want_dir else p.is_file()) else "missing"
68
+
69
+
70
+ def checked_zstd(zstd):
71
+ """`zstd` when it is an absolute path whose resolved file is named zstd, else ValueError: every
72
+ caller that runs the declared zstd runs it through here, so never another program."""
73
+ if not zstd or not os.path.isabs(zstd) or os.path.basename(os.path.realpath(zstd)) != "zstd":
74
+ raise ValueError("the declared zstd is not an absolute path to a file named zstd")
75
+ return zstd
76
+
77
+
78
+ def read_lines(path, zstd, limit=None):
79
+ """The raw lines (bytes, newline kept) of a transcript, at most `limit` of them.
80
+
81
+ A `.zst` file goes through `zstd -dcq`; a decoder that fails after producing lines raises
82
+ `Unreadable` once those lines are consumed, so the caller never mistakes a truncated
83
+ stream for a short file."""
84
+ path = str(path)
85
+ if not path.endswith(".zst"):
86
+ try:
87
+ with open(path, "rb") as handle:
88
+ for count, line in enumerate(handle):
89
+ if limit is not None and count >= limit:
90
+ return
91
+ yield line
92
+ except OSError as exc:
93
+ raise Unreadable(f"READ_FAILED {path}: {exc.strerror or exc}") from exc
94
+ return
95
+ try:
96
+ # close_fds=False lets the interpreter spawn without forking itself (descriptors are non-inheritable
97
+ # by default); a census starts tens of thousands of these, and a fork of a large heap each time dominates it
98
+ proc = subprocess.Popen([checked_zstd(zstd), "-dcq", path], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=False)
99
+ except (OSError, ValueError) as exc:
100
+ raise Unreadable(f"ZSTD_UNAVAILABLE {zstd}: {path}: {getattr(exc, 'strerror', None) or exc}") from exc
101
+ done = False
102
+ try:
103
+ for count, line in enumerate(proc.stdout):
104
+ if limit is not None and count >= limit:
105
+ return
106
+ yield line
107
+ done = True
108
+ finally:
109
+ if not done:
110
+ proc.kill()
111
+ proc.stdout.close()
112
+ code = proc.wait()
113
+ if done and code != 0:
114
+ raise Unreadable(f"ZSTD_FAILED {path}: zstd exited {code}")
115
+
116
+
117
+ def walk_files(root):
118
+ """Every regular file under `root`, symlinks not followed, in a stable order."""
119
+ for base, dirs, names in os.walk(root, followlinks=False):
120
+ dirs.sort()
121
+ for name in sorted(names):
122
+ path = os.path.join(base, name)
123
+ if os.path.isfile(path) and not os.path.islink(path):
124
+ yield path
125
+
126
+
127
+ def discover_codex(root):
128
+ """(rollout paths, count of files that are not rollouts) under a Codex transcript directory."""
129
+ found, other = [], 0
130
+ for path in walk_files(root):
131
+ if ROLLOUT.match(os.path.basename(path)):
132
+ found.append(path)
133
+ else:
134
+ other += 1
135
+ return found, other
136
+
137
+
138
+ def discover_claude(root):
139
+ """(top-level, children, other) under `claude_projects`: `<project>/<id>.jsonl` is a session,
140
+ `<project>/<id>/subagents/**/agent-*.jsonl` is a child of session `<id>`; any other file is counted
141
+ and not read. `top` is `[(id, path)]`, `children` is `[(parent_id, path)]`.
142
+
143
+ Only an `agent-*` file under `subagents/` is a subagent's transcript. The host writes other JSONL
144
+ there too - a workflow's `journal.jsonl` records the workflow's steps, not a conversation - and
145
+ such a file is no child: it is counted with the files that are not read."""
146
+ root = os.path.abspath(root)
147
+ top, children, other = [], [], 0
148
+ for path in walk_files(root):
149
+ parts = pathlib.Path(os.path.relpath(path, root)).parts
150
+ if not path.endswith(".jsonl"):
151
+ other += 1
152
+ elif len(parts) == 2:
153
+ top.append((parts[1][:-len(".jsonl")], path))
154
+ elif len(parts) >= 4 and parts[2] == "subagents" and parts[-1].startswith("agent-"):
155
+ children.append((parts[1], path))
156
+ else:
157
+ other += 1
158
+ return top, children, other
159
+
160
+
161
+ def _signature(path):
162
+ """What a write to a file changes: size, mtime and inode. None when it is absent."""
163
+ try:
164
+ st = os.stat(path)
165
+ except FileNotFoundError:
166
+ return None
167
+ return st.st_size, st.st_mtime_ns, st.st_ino
168
+
169
+
170
+ def _clone(src, dst):
171
+ if subprocess.run(["/bin/cp", "-c", src, dst], capture_output=True).returncode != 0:
172
+ shutil.copyfile(src, dst) # not an APFS volume, or another one
173
+
174
+
175
+ def capture(path, directory, between=None):
176
+ """Clone the database `path` and its `-wal` into `directory`; returns the clone's path.
177
+
178
+ The two clones are taken at different instants, so the capture counts only when neither host file
179
+ changed while it ran. `between` is called after the clones, where a concurrent host write would land."""
180
+ copy = os.path.join(directory, "index.sqlite")
181
+ for attempt in range(SNAPSHOT_ATTEMPTS):
182
+ for suffix in ("", "-wal", "-shm"):
183
+ pathlib.Path(copy + suffix).unlink(missing_ok=True)
184
+ before = (_signature(path), _signature(path + "-wal"))
185
+ _clone(path, copy)
186
+ if before[1] is not None:
187
+ try:
188
+ _clone(path + "-wal", copy + "-wal")
189
+ except FileNotFoundError:
190
+ pass # the host checkpointed it away: the signature check below sees that and captures again
191
+ if between:
192
+ between()
193
+ if (_signature(path), _signature(path + "-wal")) == before:
194
+ return copy
195
+ time.sleep(0.05 * (attempt + 1))
196
+ raise Unreadable(f"INDEX_UNSTABLE {path}: the host changed it during each of {SNAPSHOT_ATTEMPTS} captures")
197
+
198
+
199
+ def discard(directory, made):
200
+ """Remove the snapshot directory this reader made, and nothing else: `made` is the real path it had when it
201
+ was made, and it must still be that real directory (not a link, not another directory) when it is removed."""
202
+ if os.path.islink(directory) or not os.path.isdir(directory) or os.path.realpath(directory) != made:
203
+ raise Unreadable(f"SNAPSHOT_DIR_CHANGED {directory}: it is no longer the directory this reader made ({made}); nothing was removed")
204
+ shutil.rmtree(directory)
205
+
206
+
207
+ @contextlib.contextmanager
208
+ def open_threads(path, scratch=None, between=None):
209
+ """A read-only connection to a private snapshot of the Codex `threads` database: it sees the host's
210
+ uncheckpointed write-ahead log and touches nothing of the host's (see the module docstring).
211
+ The snapshot lives in a directory of its own, made fresh under `scratch` (the caller's confined parent,
212
+ a run's `private/`) and removed afterwards by `discard`; `between` is a test seam."""
213
+ path = os.path.abspath(path)
214
+ directory = tempfile.mkdtemp(prefix="census-index-", dir=scratch)
215
+ made = os.path.realpath(directory)
216
+ try:
217
+ conn = sqlite3.connect(f"file:{capture(path, directory, between)}?mode=ro", uri=True, timeout=5)
218
+ try:
219
+ yield conn
220
+ finally:
221
+ conn.close()
222
+ except sqlite3.Error as exc:
223
+ raise Unreadable(f"INDEX_UNREADABLE {path}: {exc}") from exc
224
+ except OSError as exc:
225
+ raise Unreadable(f"INDEX_UNREADABLE {path}: {exc.strerror or exc}") from exc
226
+ finally:
227
+ discard(directory, made)
228
+
229
+
230
+ def read_threads(path, scratch=None, between=None):
231
+ """`{id: {rollout_path, source, originator, created_at, updated_at}}` of the Codex index."""
232
+ with open_threads(path, scratch, between) as conn:
233
+ try:
234
+ columns = [row[1] for row in conn.execute("pragma table_info(threads)")]
235
+ missing = [c for c in THREAD_COLUMNS if c not in columns]
236
+ if missing:
237
+ raise Unreadable(f"INDEX_SHAPE {path}: threads lacks {missing}")
238
+ extra = "originator" if "originator" in columns else "null"
239
+ query = f"select id, rollout_path, source, {extra}, created_at, updated_at from threads"
240
+ return {row[0]: {"rollout_path": row[1], "source": row[2], "originator": row[3],
241
+ "created_at": row[4], "updated_at": row[5]} for row in conn.execute(query)}
242
+ except sqlite3.Error as exc:
243
+ raise Unreadable(f"INDEX_UNREADABLE {path}: {exc}") from exc
244
+
245
+
246
+ def read_history(path):
247
+ """(`{sessionId: [first, last]}` in epoch ms, count of lines that did not parse) of
248
+ `history.jsonl`. A session id counts as indexed on any entry that carries it; the times come
249
+ from prompt entries only. A torn last line is the host mid-write, counted and not fatal."""
250
+ seen, bad = {}, 0
251
+ try:
252
+ with open(path, "rb") as handle:
253
+ for line in handle:
254
+ try:
255
+ entry = json.loads(line)
256
+ sid = entry["sessionId"]
257
+ except (ValueError, KeyError, TypeError):
258
+ bad += 1
259
+ continue
260
+ span = seen.setdefault(sid, [None, None])
261
+ ts = entry.get("timestamp")
262
+ if isinstance(ts, (int, float)):
263
+ span[0] = ts if span[0] is None else min(span[0], ts)
264
+ span[1] = ts if span[1] is None else max(span[1], ts)
265
+ except OSError as exc:
266
+ raise Unreadable(f"INDEX_UNREADABLE {path}: {exc.strerror or exc}") from exc
267
+ return seen, bad
268
+
269
+
270
+ def read_desktop_index(root):
271
+ """`{cliSessionId: [createdAt, lastActivityAt]}` (epoch ms) of the Desktop session index.
272
+ One file that does not parse makes the whole index unreadable: a session it might have named
273
+ would otherwise read as `not_indexed` and be judged on a guess."""
274
+ found = {}
275
+ for path in walk_files(root):
276
+ if not re.fullmatch(r"local_.*\.json", os.path.basename(path)):
277
+ continue
278
+ try:
279
+ entry = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
280
+ sid = entry.get("cliSessionId")
281
+ if sid:
282
+ found[sid] = [entry.get("createdAt"), entry.get("lastActivityAt")]
283
+ except (OSError, ValueError, AttributeError) as exc:
284
+ raise Unreadable(f"INDEX_UNREADABLE {path}: {getattr(exc, 'strerror', None) or exc}") from exc
285
+ return found
286
+
287
+
288
+ def pin_identity(record, host, stem):
289
+ """Is this record a pin OF `host`/`stem`? The one identity rule, so two readers of one state cannot
290
+ disagree about which files are pins (X r2 F4). `(True, rollout id or None)` for a pin whose
291
+ activation resolved a rollout, `(True, None)` for one that did not or predates the binding."""
292
+ if not isinstance(record, dict) or record.get("host") != host or record.get("session_id") != stem:
293
+ return False, None
294
+ rollout_id = record.get("rollout_id")
295
+ return True, rollout_id if isinstance(rollout_id, str) and rollout_id else None
296
+
297
+
298
+ def read_pins(state_root):
299
+ """`(lookup, bad count, {rollout id: [pin ids]}, {(host, pin id): content_ref})` of the activation pins.
300
+
301
+ A pin is read for its `content_ref` only; one that is not a JSON object naming its own host and id
302
+ is ignored and counted. A Codex pin names the app-server's thread id, which no rollout carries
303
+ (F-22): when its activation also resolved the rollout the host wrote, the pin is reachable by that
304
+ id too, because that is the id a transcript carries.
305
+
306
+ The two lookups are SEPARATE maps (X r2 F3). `lookup` is what a census row is answered from: a
307
+ Claude key is the session's own id, and a Codex key is a rollout id some pin NAMES -- never a thread
308
+ id, because a Codex transcript is named by its rollout and a pin whose own id happens to equal
309
+ another thread's rollout was attributing its snapshot to that rollout. `threads` keys every pin by
310
+ its own id for a reader that has one, and no alias ever writes into it.
311
+
312
+ A rollout id claimed by two or more pins is reported in `claims` and keyed in NEITHER map: a reader
313
+ that picked one picked it by file name, and two readers picked differently (X r1 F5).
314
+ """
315
+ threads, bad, claims, aliases = {}, 0, {}, {}
316
+ base = pathlib.Path(state_root) / "sessions" / "pins"
317
+ for host in ("codex", "claude"):
318
+ for path in sorted((base / host).glob("*.json")) if (base / host).is_dir() else []:
319
+ try:
320
+ record = json.loads(path.read_text(encoding="utf-8"))
321
+ except (OSError, ValueError):
322
+ bad += 1
323
+ continue
324
+ ok, rollout_id = pin_identity(record, host, path.stem)
325
+ if not ok:
326
+ bad += 1
327
+ continue
328
+ threads[(host, path.stem)] = record.get("content_ref")
329
+ if host == "codex" and rollout_id:
330
+ aliases.setdefault(rollout_id, []).append((path.stem, record.get("content_ref")))
331
+ lookup = {key: value for key, value in threads.items() if key[0] == "claude"}
332
+ for rollout_id, claimed in sorted(aliases.items()):
333
+ if len(claimed) > 1:
334
+ claims[rollout_id] = [stem for stem, _ref in claimed]
335
+ continue
336
+ lookup[("codex", rollout_id)] = claimed[0][1]
337
+ return lookup, bad, claims, threads
338
+
339
+
340
+ def self_test():
341
+ failures = []
342
+ zstd = "/opt/homebrew/bin/zstd"
343
+ if not os.access(zstd, os.X_OK):
344
+ print(f"sources --self-test [FAIL] ZSTD_UNAVAILABLE {zstd}: the fixtures are compressed with the declared zstd")
345
+ return 1
346
+
347
+ def raises(label, fn, code):
348
+ try:
349
+ fn()
350
+ failures.append(f"{label}: nothing was raised")
351
+ except Unreadable as exc:
352
+ if code not in str(exc):
353
+ failures.append(f"{label}: expected {code}, got {exc}")
354
+
355
+ def compress(src, dst):
356
+ subprocess.run([zstd, "-q", "-f", str(src), "-o", str(dst)], check=True)
357
+
358
+ with tempfile.TemporaryDirectory() as td:
359
+ root = pathlib.Path(td)
360
+ text = b"".join(b'{"n": %d}\n' % n for n in range(50))
361
+ plain, packed = root / "rollout-a.jsonl", root / "rollout-b.jsonl.zst"
362
+ plain.write_bytes(text)
363
+ compress(plain, packed)
364
+ # positive controls first: a plain and a compressed file give the same lines, a limit stops early
365
+ if list(read_lines(plain, zstd)) != text.splitlines(keepends=True):
366
+ failures.append("a plain file did not read back")
367
+ if list(read_lines(packed, zstd)) != text.splitlines(keepends=True):
368
+ failures.append("a compressed file did not read back")
369
+ if len(list(read_lines(packed, zstd, limit=3))) != 3:
370
+ failures.append("a limit did not stop a compressed read")
371
+ # negative controls: each unreadable cause is named, and the file with it
372
+ raises("zstd path that does not exist", lambda: list(read_lines(packed, "/nonexistent/zstd")), f"ZSTD_UNAVAILABLE /nonexistent/zstd: {packed}")
373
+ raises("no zstd declared", lambda: list(read_lines(packed, None)), "ZSTD_UNAVAILABLE")
374
+ raises("a declared zstd that is another program", lambda: list(read_lines(packed, "/bin/cat")), "ZSTD_UNAVAILABLE /bin/cat")
375
+ (root / "cut.jsonl.zst").write_bytes(packed.read_bytes()[:-12])
376
+ raises("truncated stream", lambda: list(read_lines(root / "cut.jsonl.zst", zstd)), "ZSTD_FAILED")
377
+ (root / "junk.jsonl.zst").write_bytes(b"not zstd at all")
378
+ raises("not a zstd file", lambda: list(read_lines(root / "junk.jsonl.zst", zstd)), "ZSTD_FAILED")
379
+ raises("absent file", lambda: list(read_lines(root / "absent.jsonl", zstd)), "READ_FAILED")
380
+
381
+ # discovery: a layout the census does not recognise is counted, not read and not dropped silently
382
+ proj = root / "claude" / "-proj"
383
+ # a workflow's journal under subagents/ records the workflow's steps: it is no child (C0, 2026-11-03)
384
+ for rel in ("s1.jsonl", "s1/subagents/agent-a.jsonl", "s1/subagents/workflows/w/agent-b.jsonl", "s1/other/x.jsonl", "notes.md",
385
+ "s1/subagents/workflows/w/journal.jsonl"):
386
+ (proj / rel).parent.mkdir(parents=True, exist_ok=True)
387
+ (proj / rel).write_text("{}\n")
388
+ top, kids, other = discover_claude(root / "claude")
389
+ if [t[0] for t in top] != ["s1"] or sorted(os.path.basename(k[1]) for k in kids) != ["agent-a.jsonl", "agent-b.jsonl"] or other != 3:
390
+ failures.append(f"claude discovery (a workflow journal is not a child): {top} {kids} {other}")
391
+ (root / "cx" / "2026").mkdir(parents=True)
392
+ for name in ("rollout-1.jsonl", "rollout-2.jsonl.zst", "readme.md", "rollout-3.json"):
393
+ (root / "cx" / "2026" / name).write_text("{}\n")
394
+ found, other = discover_codex(root / "cx")
395
+ if [os.path.basename(f) for f in found] != ["rollout-1.jsonl", "rollout-2.jsonl.zst"] or other != 2:
396
+ failures.append(f"codex discovery: {found} {other}")
397
+ if (state_of(None, True), state_of(root / "nope", True), state_of(root / "cx", True),
398
+ state_of(root / "cx", False)) != ("undeclared", "missing", "present", "missing"):
399
+ failures.append("a source state was not undeclared, missing, present, missing")
400
+
401
+ # the Codex index (done-when 6): an uncheckpointed thread in the WAL is found, and not one byte of the host's files moves
402
+ def listing(directory):
403
+ return sorted((p.name, p.stat().st_size) for p in pathlib.Path(directory).iterdir())
404
+
405
+ def host_bytes(directory):
406
+ """Every file of the host's directory by name: size, modification time and the hash of its bytes."""
407
+ return sorted((p.name, p.stat().st_size, p.stat().st_mtime_ns, hashlib.sha256(p.read_bytes()).hexdigest())
408
+ for p in pathlib.Path(directory).iterdir())
409
+
410
+ def make_index(directory, rows, keep_open):
411
+ db = pathlib.Path(directory) / "state_5.sqlite"
412
+ conn = sqlite3.connect(db)
413
+ conn.execute("pragma journal_mode=wal")
414
+ conn.execute("create table threads(id text, rollout_path text, source text, originator text, created_at integer, updated_at integer)")
415
+ conn.execute("insert into threads values('checkpointed', '/x/a.jsonl', 'cli', 'codex-tui', 1, 2)")
416
+ conn.commit()
417
+ conn.execute("pragma wal_checkpoint(truncate)")
418
+ conn.execute("pragma wal_autocheckpoint=0")
419
+ for row in rows:
420
+ conn.execute("insert into threads values(?, ?, ?, ?, ?, ?)", row)
421
+ conn.commit()
422
+ if not keep_open:
423
+ conn.close()
424
+ return db, None
425
+ return db, conn
426
+
427
+ wal_row = ("in-wal-only", "/x/b.jsonl", "vscode", "Codex Desktop", 3, 4)
428
+ live = root / "live"
429
+ live.mkdir()
430
+ scratch = root / "scratch"
431
+ scratch.mkdir()
432
+ db, writer = make_index(live, [wal_row], keep_open=True) # the host has the database open
433
+ names = [n for n, *_ in host_bytes(live)]
434
+ if names != ["state_5.sqlite", "state_5.sqlite-shm", "state_5.sqlite-wal"]:
435
+ failures.append(f"instrument control: the fixture host did not leave a -wal and a -shm: {names}")
436
+ before = host_bytes(live)
437
+ made, real = [], tempfile.mkdtemp
438
+ tempfile.mkdtemp = lambda *a, **k: made.append(1) or real(*a, **k)
439
+ try:
440
+ threads = read_threads(db, scratch)
441
+ finally:
442
+ tempfile.mkdtemp = real
443
+ if set(threads) != {"checkpointed", "in-wal-only"}:
444
+ failures.append(f"the uncheckpointed thread was not found through the WAL: {sorted(threads)}")
445
+ if host_bytes(live) != before:
446
+ failures.append(f"reading the live index changed the host's db, -wal or -shm (size, mtime or bytes): {before} -> {host_bytes(live)}")
447
+ if len(made) != 1:
448
+ failures.append(f"a database the host has open (-wal and -shm present) was not read from a private snapshot ({len(made)} made)")
449
+ if listing(scratch):
450
+ failures.append(f"the private snapshot was not deleted: {listing(scratch)}")
451
+ direct = root / "direct"
452
+ direct.mkdir()
453
+ db_direct, writer_direct = make_index(direct, [wal_row], keep_open=True)
454
+ before = host_bytes(direct)
455
+ sqlite3.connect(f"file:{db_direct}?mode=ro", uri=True).execute("select 1 from threads").fetchall()
456
+ if host_bytes(direct) == before:
457
+ failures.append("instrument control: a direct mode=ro open of the host's database moved nothing, so the byte comparison cannot tell a reader that writes")
458
+ writer_direct.close()
459
+ lone = sqlite3.connect(f"file:{db}?immutable=1", uri=True)
460
+ if "in-wal-only" in {r[0] for r in lone.execute("select id from threads")}:
461
+ failures.append("instrument control: immutable=1 saw the WAL row, so the WAL control cannot tell the two apart")
462
+ lone.close()
463
+ # the host writes while the capture runs: the capture is repeated and sees the write; one that never settles is named
464
+ calls = []
465
+
466
+ def host_writes_once():
467
+ calls.append(1)
468
+ if len(calls) == 1:
469
+ writer.execute("insert into threads values('written-during-capture', '/x/c.jsonl', 'cli', 'codex-tui', 5, 6)")
470
+ writer.commit()
471
+
472
+ if "written-during-capture" not in read_threads(db, scratch, between=host_writes_once) or len(calls) != 2:
473
+ failures.append(f"a host write during the capture was not followed by a second capture ({len(calls)} captures)")
474
+
475
+ def host_always_writing():
476
+ writer.execute("insert into threads values(?, '/x/d.jsonl', 'cli', 'codex-tui', 7, 8)", (f"churn-{time.monotonic_ns()}",))
477
+ writer.commit()
478
+
479
+ raises("a host that changes the index during every capture", lambda: read_threads(db, scratch, between=host_always_writing), "INDEX_UNSTABLE")
480
+ if listing(scratch):
481
+ failures.append(f"a failed capture left its snapshot behind: {listing(scratch)}")
482
+ # every read gets a fresh directory of its own, and two reads leave nothing behind
483
+ names = []
484
+ read_threads(db, scratch, between=lambda: names.append(sorted(os.listdir(scratch))))
485
+ read_threads(db, scratch, between=lambda: names.append(sorted(os.listdir(scratch))))
486
+ if len(names) != 2 or any(len(n) != 1 for n in names) or names[0] == names[1] or listing(scratch):
487
+ failures.append(f"two reads did not each get a fresh snapshot directory and remove it: {names} {listing(scratch)}")
488
+ # the snapshot directory swapped for a link to someone else's directory before it is removed: refused by name, nothing removed
489
+ victim, parked = root / "victim", root / "parked"
490
+ victim.mkdir()
491
+ (victim / "artifact.txt").write_text("someone else's")
492
+
493
+ def swapped():
494
+ before = set(os.listdir(scratch))
495
+ with open_threads(db, scratch):
496
+ made = next(p for p in pathlib.Path(scratch).iterdir() if p.name not in before)
497
+ made.rename(parked)
498
+ os.symlink(victim, made)
499
+
500
+ raises("a snapshot directory swapped for a link before cleanup", swapped, "SNAPSHOT_DIR_CHANGED")
501
+ if [p.name for p in victim.iterdir()] != ["artifact.txt"] or not parked.is_dir() or not (parked / "index.sqlite").exists():
502
+ failures.append(f"a refused cleanup removed something: victim {sorted(p.name for p in victim.iterdir())} parked {parked.is_dir()}")
503
+ for leftover in pathlib.Path(scratch).iterdir(): # the planted link and the moved-away directory are the test's to clean
504
+ if leftover.is_symlink():
505
+ leftover.unlink()
506
+ shutil.rmtree(parked, ignore_errors=True)
507
+ # the host's -wal without its -shm: the snapshot still finds the row
508
+ torn = root / "torn"
509
+ torn.mkdir()
510
+ for suffix in ("", "-wal"):
511
+ shutil.copyfile(str(db) + suffix, torn / f"state_5.sqlite{suffix}")
512
+ before = host_bytes(torn)
513
+ if "in-wal-only" not in read_threads(torn / "state_5.sqlite", scratch):
514
+ failures.append("the snapshot of a database with a -wal and no -shm lost the WAL row")
515
+ if host_bytes(torn) != before:
516
+ failures.append(f"reading a database with no -shm created or changed files: {before} -> {host_bytes(torn)}")
517
+ naive = root / "naive"
518
+ naive.mkdir()
519
+ for suffix in ("", "-wal"):
520
+ shutil.copyfile(str(db) + suffix, naive / f"state_5.sqlite{suffix}")
521
+ before = listing(naive)
522
+ sqlite3.connect(f"file:{naive / 'state_5.sqlite'}?mode=ro", uri=True).execute("select 1 from threads").fetchall()
523
+ if listing(naive) == before:
524
+ failures.append("instrument control: a plain mode=ro open created nothing, so the listing cannot tell a reader that does")
525
+ writer.close()
526
+ # a cleanly closed database: no -wal, no -shm, and still nothing created by the reader
527
+ idle = root / "idle"
528
+ idle.mkdir()
529
+ db2, _ = make_index(idle, [wal_row], keep_open=False)
530
+ for suffix in ("-wal", "-shm"):
531
+ pathlib.Path(str(db2) + suffix).unlink(missing_ok=True)
532
+ before = host_bytes(idle)
533
+ if set(read_threads(db2, scratch)) != {"checkpointed", "in-wal-only"}:
534
+ failures.append("an idle database did not read back")
535
+ if host_bytes(idle) != before:
536
+ failures.append(f"reading an idle index created or changed files: {before} -> {host_bytes(idle)}")
537
+ # the shape the design reads: a missing column and a file that is not a database are named
538
+ shape = root / "shape.sqlite"
539
+ conn = sqlite3.connect(shape)
540
+ conn.execute("create table threads(id text, rollout_path text)")
541
+ conn.commit()
542
+ conn.close()
543
+ raises("threads without the fields §5.3 uses", lambda: read_threads(shape), "INDEX_SHAPE")
544
+ (root / "garbage.sqlite").write_bytes(b"not a database" * 100)
545
+ raises("a file that is not a database", lambda: read_threads(root / "garbage.sqlite"), "INDEX_UNREADABLE")
546
+ raises("an index that is absent", lambda: read_threads(root / "absent.sqlite"), "INDEX_UNREADABLE")
547
+ real_connect = sqlite3.connect
548
+
549
+ def refusing_connect(*a, **k):
550
+ raise sqlite3.OperationalError("unable to open database file")
551
+
552
+ sqlite3.connect = refusing_connect
553
+ try:
554
+ raises("a snapshot that SQLite will not open", lambda: read_threads(db), "INDEX_UNREADABLE")
555
+ finally:
556
+ sqlite3.connect = real_connect
557
+ locked = root / "locked"
558
+ locked.mkdir()
559
+ shutil.copyfile(db, locked / "state_5.sqlite")
560
+ for suffix in ("-wal", "-shm"):
561
+ (locked / f"state_5.sqlite{suffix}").write_bytes(b"")
562
+ os.chmod(locked / "state_5.sqlite", 0)
563
+ try:
564
+ raises("an index the reader may not open", lambda: read_threads(locked / "state_5.sqlite"), "INDEX_UNREADABLE")
565
+ finally:
566
+ os.chmod(locked / "state_5.sqlite", 0o600)
567
+
568
+ # history and the Desktop index
569
+ (root / "history.jsonl").write_text('{"sessionId": "a", "timestamp": 10}\n{"sessionId": "a", "timestamp": 30}\n'
570
+ '{"sessionId": "b", "ts": 5, "type": "history-suppression"}\n{"sessionId": "c", "timest')
571
+ seen, bad = read_history(root / "history.jsonl")
572
+ if seen != {"a": [10, 30], "b": [None, None]} or bad != 1:
573
+ failures.append(f"history read: {seen} {bad}")
574
+ raises("history that is absent", lambda: read_history(root / "no-history.jsonl"), "INDEX_UNREADABLE")
575
+ desk = root / "desk" / "x" / "y"
576
+ desk.mkdir(parents=True)
577
+ (desk / "local_1.json").write_text('{"cliSessionId": "d1", "createdAt": 5, "lastActivityAt": 9}')
578
+ (desk / "local_2.json").write_text('{"sessionId": "local_2"}')
579
+ (desk / "notes.json").write_text("not json")
580
+ if read_desktop_index(root / "desk") != {"d1": [5, 9]}:
581
+ failures.append("the Desktop index did not read back")
582
+ (desk / "local_3.json").write_text("{broken")
583
+ raises("one Desktop index file that does not parse", lambda: read_desktop_index(root / "desk"), "INDEX_UNREADABLE")
584
+
585
+ pins = root / "state" / "sessions" / "pins"
586
+ (pins / "codex").mkdir(parents=True)
587
+ (pins / "codex" / "t1.json").write_text('{"host": "codex", "session_id": "t1", "content_ref": "sha256:ab"}')
588
+ (pins / "codex" / "t2.json").write_text('{"host": "codex", "session_id": "other"}')
589
+ (pins / "codex" / "t3.json").write_text("{")
590
+ if read_pins(root / "state") != ({}, 2, {}, {("codex", "t1"): "sha256:ab"}):
591
+ failures.append(f"pins read: {read_pins(root / 'state')}")
592
+ # F-22: a Codex pin that names the rollout the host wrote is reachable by that id too, which is
593
+ # the id a transcript carries; one that resolved none, and one written before the binding
594
+ # existed, stay reachable by their thread id alone.
595
+ (pins / "codex" / "t4.json").write_text('{"host": "codex", "session_id": "t4", "content_ref": "sha256:cd",'
596
+ ' "rollout_id": "r4", "rollout_path": "/s/rollout-r4.jsonl"}')
597
+ (pins / "codex" / "t5.json").write_text('{"host": "codex", "session_id": "t5", "content_ref": "sha256:ef",'
598
+ ' "rollout_id": null, "rollout_path": null}')
599
+ joined, _bad, claimed, threads = read_pins(root / "state")
600
+ if joined.get(("codex", "r4")) != "sha256:cd" or threads.get(("codex", "t4")) != "sha256:cd":
601
+ failures.append(f"a pin naming a rollout answers its rollout lookup and its own: {sorted(joined)} {sorted(threads)}")
602
+ if ("codex", "t4") in joined or ("codex", "t1") in joined:
603
+ failures.append(f"a thread id is a key of the census lookup, where only rollout ids belong: {sorted(joined)}")
604
+ if ("codex", "r5") in joined or threads.get(("codex", "t5")) != "sha256:ef" or ("codex", "r1") in joined:
605
+ failures.append(f"an unresolved or pre-binding pin gained a rollout key: {sorted(joined)}")
606
+ if claimed:
607
+ failures.append(f"a rollout claimed once was reported as claimed twice: {claimed}")
608
+ # Two pins naming one rollout: neither is chosen, and the ambiguity is named with both pin ids.
609
+ (pins / "codex" / "t6.json").write_text('{"host": "codex", "session_id": "t6", "content_ref": "sha256:66",'
610
+ ' "rollout_id": "r9"}')
611
+ (pins / "codex" / "t7.json").write_text('{"host": "codex", "session_id": "t7", "content_ref": "sha256:77",'
612
+ ' "rollout_id": "r9"}')
613
+ # And a pin whose own id equals another pin's rollout id answers neither for the other: the
614
+ # census asks the rollout lookup, where t1 is not a key, and t1 keeps its own (X r2 F3).
615
+ (pins / "codex" / "t8.json").write_text('{"host": "codex", "session_id": "t8", "content_ref": "sha256:88",'
616
+ ' "rollout_id": "t1"}')
617
+ twice, _bad, claimed, threads = read_pins(root / "state")
618
+ if claimed != {"r9": ["t6", "t7"]}:
619
+ failures.append(f"two pins naming one rollout were not named as an ambiguity: {claimed}")
620
+ if ("codex", "r9") in twice or ("codex", "r9") in threads:
621
+ failures.append("a rollout two pins claim was keyed to one of them")
622
+ if twice.get(("codex", "t1")) != "sha256:88" or threads.get(("codex", "t1")) != "sha256:ab":
623
+ failures.append(f"a rollout lookup and a thread lookup were answered from one map: "
624
+ f"{twice.get(('codex', 't1'))} {threads.get(('codex', 't1'))}")
625
+ for failure in failures:
626
+ print(f"sources --self-test [FAIL] {failure}")
627
+ if failures:
628
+ return 1
629
+ print("sources --self-test: OK (plain and compressed reads agree; a missing zstd, a truncated stream and a non-zstd file are "
630
+ "named with the file; a WAL-only thread is found from a private snapshot while the host's db, -wal and -shm keep their "
631
+ "bytes and mtimes, a write during the capture is captured again and one that never settles is named, and the snapshot is "
632
+ "removed (a swapped directory is refused by name and nothing is removed); immutable=1 misses the row and a direct read-only open moves the -shm; missing columns, a non-database, a "
633
+ "torn history line, an unparseable Desktop file and bad pins are handled by name; a pin naming a rollout is keyed by "
634
+ "that id in the census lookup, one that resolved none is not, two pins claiming one rollout are named rather than chosen in either map, and a thread lookup is a map of its own)")
635
+ return 0
636
+
637
+
638
+ if __name__ == "__main__":
639
+ if "--self-test" not in sys.argv[1:]:
640
+ sys.exit("usage: sources.py --self-test")
641
+ sys.exit(self_test())