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,454 @@
1
+ #!/usr/bin/env python3
2
+ """First-entrypoint classification and lineage over transcript records (design §5.1, §5.3).
3
+
4
+ Ports of the probe-8 classifiers (`claude-records/scripts/classify.py`, `features.py`,
5
+ `codex-records/scripts/classify.py`), made single-pass: a scan is fed one parsed record at a
6
+ time, so a transcript is never held in memory. Nothing here reads a timestamp to decide
7
+ ancestry: a rewritten clock hides a replay from a timestamp test, and record ids survive it.
8
+
9
+ A session is a **root** when it carries no inherited-history marker; Claude has no positive
10
+ marker, so a fork is recognized by a head that only an earlier life of the conversation writes.
11
+ Two sessions are linked by an explicit pointer (Codex `forked_from_id`, `history_base`; Claude
12
+ `continued-in`), by a shared host-minted record id, or by at least one identical (timestamp, human
13
+ text) turn: the id test survives a rewritten clock and the turn test survives rewritten ids. A
14
+ component is an **affirmed lineage** when exactly one member is a root; it counts once. Any other
15
+ component has unknown independence and counts toward nothing.
16
+
17
+ Identity is `(host, full session id)` (design §5.3), written `<host>:<id>` wherever one string is
18
+ needed (`identity`): a lineage node, a coverage key and an S3 result all use it, and nothing links
19
+ two sessions of different hosts.
20
+
21
+ `CODEX_COMPACTION_MEASURED` is False until WP-23's planted Codex compaction (design §14 check
22
+ 5) has shown whether compaction stays in one file. Until then a Codex transcript carrying a
23
+ compaction record is never a root: the classifier does not guess its file behavior.
24
+
25
+ lineage.py --self-test
26
+ """
27
+ import re
28
+ import sys
29
+
30
+ CODEX_COMPACTION_MEASURED = False
31
+ HOSTS = ("claude", "codex")
32
+ HEAD_INHERIT = {"ai-title", "last-prompt"} # written only after a turn, so only an earlier life leaves them in a head
33
+ ID_KEYS = ("turn_id", "response_id") # `root_turn_id` is absent on purpose: a child carries its parent's there
34
+ CODEX_ID = re.compile(r"^(msg|fc|fco|amsg|cmp|rs)_")
35
+ # A record id is kept as the interpreter's 64-bit string hash: only equality between ids matters, and a
36
+ # transcript can hold hundreds of thousands of them.
37
+
38
+
39
+ def identity(host, sid):
40
+ """The one string that stands for `(host, full session id)`."""
41
+ return f"{host}:{sid}"
42
+
43
+
44
+ def split_identity(ident):
45
+ host, _, sid = ident.partition(":")
46
+ return host, sid
47
+
48
+
49
+ def turn_of(stamp, text):
50
+ """The fingerprint of one human turn: its timestamp and its text, or None when either is missing."""
51
+ text = text.strip() if isinstance(text, str) else ""
52
+ return hash((stamp, text)) if text and isinstance(stamp, str) else None
53
+
54
+
55
+ class ClaudeScan:
56
+ """One pass over the records of a Claude Code session file."""
57
+
58
+ host = "claude"
59
+
60
+ def __init__(self):
61
+ self.entrypoint = None # the FIRST recorded one: a session resumed headlessly keeps its class
62
+ self.ids = set() # record `uuid`s, which a fork copies under a new sessionId
63
+ self.turns = set() # (timestamp, human text) fingerprints
64
+ self.continued_in = [] # `continued-in` pointers: explicit forward links to a successor session
65
+ self.pre_user = [] # record types before the first `user` record
66
+ self.seen_user = False
67
+ self.session_id = None # the first `sessionId`: a child's records carry its parent's
68
+ self.marker = None # (isSidechain, agentId) of the first record that carries either
69
+
70
+ def feed(self, rec, index=0):
71
+ kind = rec.get("type")
72
+ if self.entrypoint is None and rec.get("entrypoint"):
73
+ self.entrypoint = rec["entrypoint"]
74
+ if self.session_id is None and isinstance(rec.get("sessionId"), str):
75
+ self.session_id = rec["sessionId"]
76
+ if self.marker is None and ("isSidechain" in rec or "agentId" in rec):
77
+ self.marker = (rec.get("isSidechain") is True, rec.get("agentId"))
78
+ if rec.get("uuid"):
79
+ self.ids.add(hash(rec["uuid"]))
80
+ if kind == "user" and not rec.get("isMeta") and rec.get("isSidechain") is not True:
81
+ turn = turn_of(rec.get("timestamp"), self.human_text(rec))
82
+ if turn is not None:
83
+ self.turns.add(turn)
84
+ if kind == "continued-in" and rec.get("continuedInSessionId"):
85
+ self.continued_in.append(rec["continuedInSessionId"])
86
+ if kind == "user":
87
+ self.seen_user = True
88
+ elif not self.seen_user and len(self.pre_user) < 200:
89
+ self.pre_user.append(kind)
90
+
91
+ @staticmethod
92
+ def human_text(rec):
93
+ """What the person typed in a `user` record: its string content, or its text blocks when no block is a tool result."""
94
+ message = rec.get("message")
95
+ content = message.get("content") if isinstance(message, dict) else None
96
+ if isinstance(content, str):
97
+ return content
98
+ if isinstance(content, list) and not any(isinstance(b, dict) and b.get("type") == "tool_result" for b in content):
99
+ return "".join(b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text")
100
+ return None
101
+
102
+ def child(self):
103
+ """True when this file's own thread is a sidechain: its first record that says so is `isSidechain` or names an `agentId`
104
+ (design §5.1). Inline sidechain records further into an ordinary session do not make it a child."""
105
+ return bool(self.marker and (self.marker[0] or self.marker[1]))
106
+
107
+ def inherited_head(self):
108
+ """The in-file markers that the head of this file was written by an earlier life of the conversation."""
109
+ pre = self.pre_user if self.seen_user else self.pre_user[:12]
110
+ marked = sorted(HEAD_INHERIT & set(pre))
111
+ queued = "mode" in pre and "queue-operation" in pre and pre.index("mode") < pre.index("queue-operation")
112
+ return [*([f"head-has:{','.join(marked)}"] if marked else []),
113
+ *(["fhs>=2-before-first-user"] if pre.count("file-history-snapshot") >= 2 else []),
114
+ *(["mode-before-queue-operation"] if queued else [])]
115
+
116
+ def lineage_node(self, sid):
117
+ return {"id": identity(self.host, sid), "host": self.host, "root": not self.inherited_head(), "ids": self.ids, "turns": self.turns,
118
+ "links": [(identity(self.host, t), "continued_in") for t in self.continued_in]}
119
+
120
+
121
+ class CodexScan:
122
+ """One pass over the records of a Codex rollout."""
123
+
124
+ host = "codex"
125
+
126
+ def __init__(self, stem=""):
127
+ self.meta = None # the first record's session_meta payload
128
+ self.first_ordinal = None
129
+ self.ids = set()
130
+ self.turns = set() # (timestamp, human text) fingerprints
131
+ self.compacted = False
132
+ self.stem = stem
133
+
134
+ def feed(self, rec, index=0):
135
+ if index == 0:
136
+ self.first_ordinal = rec.get("ordinal", 0)
137
+ if rec.get("type") == "session_meta" and isinstance(rec.get("payload"), dict):
138
+ self.meta = rec["payload"]
139
+ if rec.get("type") == "compacted":
140
+ self.compacted = True
141
+ payload = rec.get("payload")
142
+ if isinstance(payload, dict):
143
+ if rec.get("type") == "response_item" and payload.get("type") == "message" and payload.get("role") == "user":
144
+ content = payload.get("content")
145
+ turn = turn_of(rec.get("timestamp"), "".join(b.get("text", "") for b in content if isinstance(b, dict))
146
+ if isinstance(content, list) else None)
147
+ if turn is not None:
148
+ self.turns.add(turn)
149
+ for key in ID_KEYS:
150
+ if isinstance(payload.get(key), str):
151
+ self.ids.add(hash(payload[key]))
152
+ if isinstance(payload.get("id"), str) and CODEX_ID.match(payload["id"]):
153
+ self.ids.add(hash(payload["id"]))
154
+ retained = (rec.get("metadata") or {}).get("retained_source") if isinstance(rec.get("metadata"), dict) else None
155
+ if isinstance(retained, dict) and isinstance(retained.get("revision"), str):
156
+ self.ids.add(hash(retained["revision"]))
157
+
158
+ def absorb(self, later):
159
+ """This scan with the lineage evidence of a later rollout file of the same thread added: its record ids, its turns
160
+ and whether it was compacted. The later file's `session_meta` is not taken: the thread's kind and pointer are its
161
+ first file's, and a later file's `history_base` names the thread it continues, which is no edge to another
162
+ (D-20261103-a7128a)."""
163
+ self.ids |= later.ids
164
+ self.turns |= later.turns
165
+ self.compacted = self.compacted or later.compacted
166
+ return self
167
+
168
+ def kind(self):
169
+ """`subagent` (a child), `fork`, `continuation`, `root` or `unknown`, and the parent id it points at."""
170
+ meta = self.meta
171
+ if meta is None:
172
+ return "unknown", None
173
+ sub = meta.get("source", {}).get("subagent") if isinstance(meta.get("source"), dict) else None
174
+ if meta.get("parent_thread_id") or sub is not None:
175
+ spawn = sub.get("thread_spawn") if isinstance(sub, dict) else None
176
+ return "subagent", meta.get("parent_thread_id") or (spawn or {}).get("parent_thread_id")
177
+ if meta.get("forked_from_id"):
178
+ return "fork", meta["forked_from_id"]
179
+ base = meta.get("history_base")
180
+ stem = re.sub(r"\.(zst|jsonl)$", "", re.sub(r"\.zst$", "", self.stem))
181
+ if base or "_" in stem[len("rollout-"):]:
182
+ return "continuation", (base or {}).get("thread_id") if isinstance(base, dict) else None
183
+ return ("root", None) if self.first_ordinal == 0 else ("unknown", None)
184
+
185
+ def lineage_node(self, sid):
186
+ kind, target = self.kind()
187
+ pending = self.compacted and not CODEX_COMPACTION_MEASURED
188
+ return {"id": identity(self.host, sid), "host": self.host, "root": kind == "root" and not pending, "ids": self.ids, "turns": self.turns,
189
+ "pending": pending,
190
+ "links": [(identity(self.host, target), "forked_from_id" if kind == "fork" else "history_base")]
191
+ if target and kind in ("fork", "continuation") else []}
192
+
193
+
194
+ def classify_claude(entrypoint):
195
+ """(status, reason, source class) from the FIRST recorded entrypoint."""
196
+ if entrypoint is None:
197
+ return "unknown_provenance", "no_entrypoint", None
198
+ if entrypoint == "cli":
199
+ return "eligible", None, "claude-cli"
200
+ if entrypoint == "claude-desktop":
201
+ return "eligible", None, "claude-desktop"
202
+ if entrypoint.startswith("sdk"):
203
+ return "excluded", entrypoint, None # automated
204
+ return "unknown_provenance", f"entrypoint:{entrypoint}", None
205
+
206
+
207
+ def classify_codex(source, originator, pinned, table):
208
+ """(status, reason, source class) from `session_meta.source` for a top-level rollout.
209
+
210
+ `vscode` is written by every app-server client, so it is split first by the pin join (an
211
+ activated session is codex-cli) and then by the originator table; an originator the table
212
+ does not name is unknown, never silently one class."""
213
+ if source == "cli":
214
+ return "eligible", None, "codex-cli"
215
+ if source == "exec":
216
+ return "excluded", "exec", None
217
+ if source != "vscode":
218
+ return "unknown_provenance", f"source:{source if isinstance(source, str) else 'unrecognized'}", None
219
+ if pinned:
220
+ return "eligible", None, "codex-cli"
221
+ mapped = table.get(originator)
222
+ if originator == "agent-bios":
223
+ return "unknown_provenance", "agent-bios:unpinned", None
224
+ if mapped in ("codex-cli", "codex-desktop"):
225
+ return "eligible", None, mapped
226
+ if mapped == "excluded":
227
+ return "excluded", f"originator:{originator}", None
228
+ return "unknown_provenance", f"originator:{originator}", None
229
+
230
+
231
+ def components(nodes):
232
+ """Per node id: `{component, root, unique_root, affirmed}` over `nodes`, each
233
+ `{id, host, root, ids, turns, links}` (a link is `(target id, via)`; a target that is not a node is no edge).
234
+
235
+ Two nodes of one host are linked by a shared record id or a shared (timestamp, human text) turn;
236
+ nodes of different hosts never are. `component` is the smallest member id, `root` the one root
237
+ member when the component has exactly one (else None), and `affirmed` the edges that touch the node
238
+ when it does."""
239
+ known = {n["id"]: n for n in nodes}
240
+ parent = {i: i for i in known}
241
+
242
+ def find(x):
243
+ while parent[x] != x:
244
+ parent[x] = parent[parent[x]]
245
+ x = parent[x]
246
+ return x
247
+
248
+ edges, owner = {}, {}
249
+
250
+ def link(a, b, via):
251
+ parent[find(a)] = find(b)
252
+ edges.setdefault((a, b), set()).add(via)
253
+
254
+ for node in nodes:
255
+ for kind, via, shared in (("id", "record_ids", node["ids"]), ("turn", "timestamp_text", node.get("turns", ()))):
256
+ for evidence in shared:
257
+ first = owner.setdefault((node["host"], kind, evidence), node["id"])
258
+ if first != node["id"]:
259
+ link(first, node["id"], via)
260
+ for target, via in node["links"]:
261
+ if target in known and target != node["id"]:
262
+ link(node["id"], target, via)
263
+ # a `continued-in` pointer names its target a continuation, whatever the target's own head looks like
264
+ continued = {t for n in nodes for t, via in n["links"] if via == "continued_in" and t in known}
265
+ members = {}
266
+ for i in known:
267
+ members.setdefault(find(i), []).append(i)
268
+ touching = {}
269
+ for (a, b), via in sorted(edges.items()):
270
+ for end in (a, b):
271
+ touching.setdefault(end, []).append({"from": a, "to": b, "via": sorted(via)})
272
+ result = {}
273
+ for group in members.values():
274
+ roots = [i for i in group if known[i]["root"] and i not in continued]
275
+ unique = len(roots) == 1
276
+ for i in group:
277
+ mine = touching.get(i, [])
278
+ if unique: # an edge reads from the member to the root, whichever way it was found
279
+ mine = [e if e["to"] == roots[0] or e["from"] != roots[0] else {**e, "from": e["to"], "to": e["from"]} for e in mine]
280
+ result[i] = {"component": min(group), "root": roots[0] if unique else None, "unique_root": unique,
281
+ "affirmed": mine if unique else []}
282
+ return result
283
+
284
+
285
+ def self_test():
286
+ failures = []
287
+
288
+ def expect(label, got, want):
289
+ if got != want:
290
+ failures.append(f"{label}: expected {want!r}, got {got!r}")
291
+
292
+ def claude(types, entrypoint="cli", ids=()):
293
+ scan = ClaudeScan()
294
+ for n, kind in enumerate(types):
295
+ scan.feed({"type": kind, "entrypoint": entrypoint if kind in ("user", "assistant") else None,
296
+ "uuid": ids[n] if n < len(ids) else None}, n)
297
+ return scan
298
+
299
+ # Claude: positive control first (a fresh interactive head), then each inherited-head marker by name
300
+ fresh = ["mode", "permission-mode", "atis-latch", "file-history-snapshot", "user", "assistant"]
301
+ expect("fresh interactive head is a root", claude(fresh).inherited_head(), [])
302
+ expect("ai-title before the first user", claude(["ai-title", "user"]).inherited_head(), ["head-has:ai-title"])
303
+ expect("last-prompt before the first user", claude(["last-prompt", "user"]).inherited_head(), ["head-has:last-prompt"])
304
+ expect("two snapshots before the first user", claude(["file-history-snapshot"] * 2 + ["user"]).inherited_head(), ["fhs>=2-before-first-user"])
305
+ expect("mode before queue-operation", claude(["mode", "queue-operation", "user"]).inherited_head(), ["mode-before-queue-operation"])
306
+ expect("queue-operation before mode is not a marker", claude(["queue-operation", "mode", "user"]).inherited_head(), [])
307
+ expect("a marker after the first user is not a head marker", claude(["user", "ai-title"]).inherited_head(), [])
308
+ expect("first entrypoint wins over a later headless one",
309
+ (lambda s: (s.feed({"type": "assistant", "entrypoint": "sdk-cli"}), s.entrypoint)[1])(claude(fresh)), "cli")
310
+ for entrypoint, want in (("cli", ("eligible", None, "claude-cli")), ("claude-desktop", ("eligible", None, "claude-desktop")),
311
+ ("sdk-cli", ("excluded", "sdk-cli", None)), ("sdk-py", ("excluded", "sdk-py", None)),
312
+ (None, ("unknown_provenance", "no_entrypoint", None)),
313
+ ("mcp", ("unknown_provenance", "entrypoint:mcp", None))):
314
+ expect(f"claude entrypoint {entrypoint}", classify_claude(entrypoint), want)
315
+
316
+ # Codex kinds, from the markers of probe 8
317
+ def codex(meta, ordinal=0, stem="rollout-2026-10-01T00-00-00-aaaa", compacted=False):
318
+ scan = CodexScan(stem + ".jsonl.zst")
319
+ scan.feed({"type": "session_meta", "ordinal": ordinal, "payload": {"id": "x", **meta}}, 0)
320
+ if compacted:
321
+ scan.feed({"type": "compacted", "payload": {}}, 1)
322
+ return scan
323
+
324
+ expect("fresh rollout is a root", codex({"source": "cli"}).kind(), ("root", None))
325
+ expect("forked_from_id is a fork", codex({"forked_from_id": "p"}).kind(), ("fork", "p"))
326
+ expect("history_base is a continuation", codex({"history_base": {"thread_id": "p"}}, ordinal=5).kind(), ("continuation", "p"))
327
+ expect("a suffixed file name is a continuation", codex({}, stem="rollout-2026-10-01T00-00-00-aaaa_bbbb").kind()[0], "continuation")
328
+ expect("parent_thread_id is a child", codex({"parent_thread_id": "p"}).kind(), ("subagent", "p"))
329
+ expect("thread_spawn names its parent", codex({"source": {"subagent": {"thread_spawn": {"parent_thread_id": "q"}}}}).kind(), ("subagent", "q"))
330
+ expect("a review child has no parent", codex({"source": {"subagent": "review"}}).kind(), ("subagent", None))
331
+ expect("a first ordinal past zero with no pointer is unknown", codex({}, ordinal=3).kind(), ("unknown", None))
332
+ expect("no session_meta is unknown", CodexScan("rollout-x.jsonl").kind(), ("unknown", None))
333
+ table = {"Codex Desktop": "codex-desktop", "Claude Code": "excluded", "codex_vscode": "unknown_provenance"}
334
+ for label, args, want in (
335
+ ("cli", ("cli", "codex-tui", False, table), ("eligible", None, "codex-cli")),
336
+ ("exec", ("exec", "codex_exec", False, table), ("excluded", "exec", None)),
337
+ ("vscode desktop", ("vscode", "Codex Desktop", False, table), ("eligible", None, "codex-desktop")),
338
+ ("vscode Claude Code", ("vscode", "Claude Code", False, table), ("excluded", "originator:Claude Code", None)),
339
+ ("vscode table says unknown", ("vscode", "codex_vscode", False, table), ("unknown_provenance", "originator:codex_vscode", None)),
340
+ ("vscode unnamed originator", ("vscode", "NewClient", False, table), ("unknown_provenance", "originator:NewClient", None)),
341
+ ("vscode no originator", ("vscode", None, False, table), ("unknown_provenance", "originator:None", None)),
342
+ ("activated vscode with its pin", ("vscode", "agent-bios", True, table), ("eligible", None, "codex-cli")),
343
+ ("activated vscode without a pin", ("vscode", "agent-bios", False, table), ("unknown_provenance", "agent-bios:unpinned", None)),
344
+ ("a source the census does not know", ("custom", "x", False, table), ("unknown_provenance", "source:custom", None))):
345
+ expect(f"codex {label}", classify_codex(*args), want)
346
+
347
+ # the counting rule: components with one root, none, several; edges oriented to the root
348
+ def node(i, root, ids=(), links=(), turns=(), host="claude"):
349
+ return {"id": identity(host, i), "host": host, "root": root, "ids": set(ids), "turns": set(turns),
350
+ "links": [(identity(host, t), via) for t, via in links]}
351
+
352
+ cl = lambda i: identity("claude", i) # noqa: E731
353
+ got = components([node("A", True, [1, 2]), node("B", False, [2, 3]), node("C", True, [9])])
354
+ expect("fork sharing an id with its root is affirmed", (got[cl("A")]["unique_root"], got[cl("B")]["unique_root"], got[cl("B")]["root"]),
355
+ (True, True, cl("A")))
356
+ expect("the fork's edge reads from the fork to its source", got[cl("B")]["affirmed"], [{"from": cl("B"), "to": cl("A"), "via": ["record_ids"]}])
357
+ expect("an unrelated root is its own lineage", (got[cl("C")]["unique_root"], got[cl("C")]["component"], got[cl("C")]["affirmed"]), (True, cl("C"), []))
358
+ expect("the two lineages are two components", got[cl("A")]["component"] != got[cl("C")]["component"], True)
359
+ got = components([node("A", True, [1, 2]), node("A2", True, [1, 2])])
360
+ expect("a copy of a root beside its original has two roots", (got[cl("A")]["unique_root"], got[cl("A")]["root"], got[cl("A")]["affirmed"]),
361
+ (False, None, []))
362
+ got = components([node("F1", False, [5]), node("F2", False, [5])])
363
+ expect("members that all look inherited have no root", (got[cl("F1")]["unique_root"], got[cl("F1")]["root"]), (False, None))
364
+ got = components([node("N", False, [], [("P", "forked_from_id")]), node("P", True, [])])
365
+ expect("an explicit pointer links without a shared id", (got[cl("N")]["unique_root"], got[cl("N")]["root"], got[cl("N")]["affirmed"]),
366
+ (True, cl("P"), [{"from": cl("N"), "to": cl("P"), "via": ["forked_from_id"]}]))
367
+ got = components([node("N", False, [], [("absent", "forked_from_id")])])
368
+ expect("a pointer to a session that is not here links nothing", (got[cl("N")]["unique_root"], got[cl("N")]["root"]), (False, None))
369
+ got = components([node("P", True, [1]), node("K1", False, [1, 2]), node("K2", False, [2])])
370
+ expect("a fork of a fork stays in one lineage", (got[cl("K2")]["unique_root"], got[cl("K2")]["root"]), (True, cl("P")))
371
+ got = components([node("A", True, [], [("B", "continued_in")]), node("B", True, [])])
372
+ expect("a continued-in pointer makes its target a continuation, not a second root", (got[cl("B")]["unique_root"], got[cl("B")]["root"]), (True, cl("A")))
373
+
374
+ # the third link of design §5.3: an identical (timestamp, human text) turn, with no pointer and no shared record id
375
+ mark = turn_of("2026-10-02T10:00:00.000Z", "summarize the weekly report")
376
+ got = components([node("R", True, [1], turns=[mark]), node("Q", False, [2], turns=[mark])])
377
+ expect("an identical (timestamp, human text) turn links two sessions whose record ids were rewritten",
378
+ (got[cl("Q")]["unique_root"], got[cl("Q")]["root"], got[cl("Q")]["affirmed"]),
379
+ (True, cl("R"), [{"from": cl("Q"), "to": cl("R"), "via": ["timestamp_text"]}]))
380
+ got = components([node("R", True, [1], turns=[mark]), node("Q", False, [2], turns=[turn_of("2026-10-02T10:00:01.000Z", "summarize the weekly report")])])
381
+ expect("the same text at another time links nothing", (got[cl("Q")]["unique_root"], got[cl("R")]["component"] == got[cl("Q")]["component"]), (False, False))
382
+ got = components([node("R", True, [1], turns=[mark]), node("Q", False, [2], turns=[turn_of("2026-10-02T10:00:00.000Z", "something else")])])
383
+ expect("the same time with other text links nothing", got[cl("R")]["component"] == got[cl("Q")]["component"], False)
384
+ expect("a turn without a timestamp or without text has no fingerprint", (turn_of(None, "x"), turn_of("t", " "), turn_of("t", None)), (None, None, None))
385
+ got = components([node("R", True, [1], turns=[mark]), node("Q", True, [2], turns=[mark])])
386
+ expect("two roots sharing a turn are a copy: unknown independence", (got[cl("R")]["unique_root"], got[cl("R")]["affirmed"]), (False, []))
387
+
388
+ # identity is (host, id): the same string on two hosts is two sessions, and no evidence links them
389
+ both = components([node("same", True, [1], host="claude"), node("same", True, [1], turns=[mark], host="codex"),
390
+ node("other", True, [], turns=[mark], host="claude")])
391
+ expect("one id on two hosts survives as two nodes", sorted(both), [cl("other"), cl("same"), identity("codex", "same")])
392
+ expect("shared evidence across hosts links nothing", len({v["component"] for v in both.values()}), 3)
393
+ expect("identity round-trips", split_identity(identity("codex", "a:b")), ("codex", "a:b"))
394
+
395
+ # scans: what each host's records contribute to the evidence
396
+ scan = ClaudeScan()
397
+ for n, rec in enumerate([
398
+ {"type": "user", "timestamp": "t1", "message": {"role": "user", "content": "plan the release"}, "uuid": "u1", "sessionId": "S"},
399
+ {"type": "user", "timestamp": "t2", "message": {"role": "user", "content": [{"type": "tool_result", "content": "plan the release"}]}},
400
+ {"type": "user", "timestamp": "t3", "isMeta": True, "message": {"role": "user", "content": "caveat text"}},
401
+ {"type": "user", "timestamp": "t4", "isSidechain": True, "message": {"role": "user", "content": "side text"}},
402
+ {"type": "user", "timestamp": "t5", "message": {"role": "user", "content": [{"type": "text", "text": "two"}, {"type": "text", "text": " parts"}]}},
403
+ {"type": "assistant", "timestamp": "t6", "message": {"role": "assistant", "content": "plan the release"}}]):
404
+ scan.feed(rec, n)
405
+ expect("Claude human turns are typed text only: not a tool result, a meta record, a sidechain or an assistant",
406
+ scan.turns, {turn_of("t1", "plan the release"), turn_of("t5", "two parts")})
407
+ cx = CodexScan("rollout-x.jsonl")
408
+ for n, rec in enumerate([
409
+ {"type": "session_meta", "payload": {"id": "x"}},
410
+ {"type": "response_item", "timestamp": "t1", "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "plan the release"}]}},
411
+ {"type": "response_item", "timestamp": "t2", "payload": {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "ok"}]}},
412
+ {"type": "event_msg", "timestamp": "t3", "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "not a response item"}]}}]):
413
+ cx.feed(rec, n)
414
+ expect("Codex human turns are the user-role messages of response items", cx.turns, {turn_of("t1", "plan the release")})
415
+
416
+ # a Claude child is a file whose own thread is a sidechain, however it is laid out on disk
417
+ def marked(*recs):
418
+ sc = ClaudeScan()
419
+ for n, rec in enumerate(recs):
420
+ sc.feed(rec, n)
421
+ return sc
422
+
423
+ expect("isSidechain on the first marked record makes a child", marked({"type": "user", "isSidechain": True, "sessionId": "P"}).child(), True)
424
+ expect("an agentId makes a child", marked({"type": "user", "isSidechain": False, "agentId": "a1", "sessionId": "P"}).child(), True)
425
+ expect("a child's records carry its parent's session id", marked({"type": "user", "isSidechain": True, "sessionId": "P"}).session_id, "P")
426
+ expect("an ordinary session is not a child", marked({"type": "user", "isSidechain": False}, {"type": "assistant", "isSidechain": False}).child(), False)
427
+ expect("inline sidechain records further in do not make the session a child", marked({"type": "user", "isSidechain": False}, {"type": "user", "isSidechain": True}).child(), False)
428
+ expect("a session whose records say nothing about sidechains is not a child", marked({"type": "user"}).child(), False)
429
+
430
+ # Codex compaction: not a root until WP-23 has measured its file behavior
431
+ pending = codex({"source": "cli"}, compacted=True).lineage_node("x")
432
+ expect("a Codex node is host-qualified", (pending["id"], pending["host"]), ("codex:x", "codex"))
433
+ expect("compaction unmeasured: not a root", (pending["root"], pending["pending"]), (False, True))
434
+ global CODEX_COMPACTION_MEASURED
435
+ CODEX_COMPACTION_MEASURED = True
436
+ try:
437
+ measured = codex({"source": "cli"}, compacted=True).lineage_node("x")
438
+ expect("compaction measured: classified as any other root", (measured["root"], measured["pending"]), (True, False))
439
+ finally:
440
+ CODEX_COMPACTION_MEASURED = False
441
+ for failure in failures:
442
+ print(f"lineage --self-test [FAIL] {failure}")
443
+ if failures:
444
+ return 1
445
+ print("lineage --self-test: OK (3 inherited-head markers and their counterparts, first entrypoint wins, 6 Claude and 10 Codex "
446
+ "classes, 9 kinds, one/none/several roots, pointers, shared record ids, identical (timestamp, human text) turns and their "
447
+ "negatives, host-qualified identity, Claude sidechain children, copies, fork of a fork, compaction pending until measured)")
448
+ return 0
449
+
450
+
451
+ if __name__ == "__main__":
452
+ if "--self-test" not in sys.argv[1:]:
453
+ sys.exit("usage: lineage.py --self-test")
454
+ sys.exit(self_test())