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,1180 @@
1
+ #!/usr/bin/env python3
2
+ """The live monitor of one model call (design §13.2, §13.3): a request ledger fed from what the
3
+ host emits, both caps evaluated at every stream event and every transcript record, and the
4
+ check that no request was sent after the stop took effect.
5
+
6
+ Claude: stdout `--output-format stream-json --verbose --include-partial-messages` gives the
7
+ main thread (`system/status requesting`, `message_start`, `message_delta`), the compaction
8
+ markers (`compact_boundary`), `rate_limit_event` and `result`; the transcripts under
9
+ `<cfg>/projects/` give one `api-request` record per HTTP attempt (its timestamp is the host's
10
+ send instant) and the subagents' usage. Records reach the disk 73-108 ms after their
11
+ timestamp, so a hint with no record is "not sent" only when the kill came at least
12
+ FLUSH_WINDOW_S after it; inside that window whether it was sent stays unknown.
13
+
14
+ Codex: stderr under `RUST_LOG=tungstenite::protocol=trace,codex_otel.log_only=info` gives the
15
+ server frames ("Received message"), the client frames (permessage-deflate payloads, decoded by
16
+ `SentDecoder`, whose turn metadata names the request kind and the agent) and the otel rows. The
17
+ records are reduced to the whitelisted form the gate reads as capture/frames.jsonl.
18
+
19
+ Each request is measured, provisional (at `usage.estimate`: the same agent's previous request
20
+ plus the new content since it — Claude's user and tool-result blocks, a Codex request's input
21
+ items — never the class's highest) or unresolved (design §13.3). A compaction marker counts a
22
+ provisional compaction request at twice the previous main request (the safety factor; probe 9
23
+ measured 1.42-2.11x). Codex otel completions enter the ledger as they arrive, reconciled with
24
+ the requests already there before the caps are evaluated: one a frame response already accounts
25
+ for (same thread, same usage) is that request, one with a sent request of its thread still
26
+ outstanding measures that request until its frame arrives, and any other is a request of unknown
27
+ kind measured from otel (frames_blind, design §13.3); an HTTPS response start is a request in
28
+ flight, and a responses_retry warning, which names no thread, is one failed post of unknown
29
+ usage, marking nothing else interrupted. The token cap trips when measured plus provisional reaches it; the
30
+ compaction cap when the markers pass it. A structured provider signal (breaker.py's parsers) is
31
+ passed to `on_signal` the moment its event or frame is read.
32
+
33
+ `boundary` holds the requests' host-recorded send instants against the verified freeze instant
34
+ of `stop.stop_tree`: a send after it is STOP_BOUNDARY_VIOLATED by request id; outgoing evidence
35
+ that cannot establish sending — a request that may have gone out unrecorded, a send record with
36
+ no host instant read after the freeze, an undecodable client frame or a frame header whose
37
+ payload never followed (the next record or the end of the trace came first) written after it — is
38
+ reported as uncertain, never counted clean; an unverified freeze is STOP_BOUNDARY_UNVERIFIED.
39
+ `boundary_verdict` folds both lists into the one value the stopped record carries: clean only when
40
+ both are empty, STOP_BOUNDARY_UNVERIFIED with anything uncertain, STOP_BOUNDARY_VIOLATED with a
41
+ violation.
42
+ CONTRACT names the predicate and its section; the self-test holds its codes against §13.2.
43
+
44
+ monitor.py --self-test
45
+ """
46
+ import datetime
47
+ import json
48
+ import os
49
+ import pathlib
50
+ import re
51
+ import sys
52
+ import threading
53
+ import time
54
+ import zlib
55
+
56
+ if __package__ in (None, ""): # run as a script: put session-distill/ on the import path
57
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
58
+ from runlib import breaker as breakers
59
+ from runlib import usage as usages
60
+
61
+ FLUSH_WINDOW_S = 0.25 # transcript records reach the disk 73-108 ms after their timestamp (probe 9)
62
+ RECV = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+TRACE tungstenite::protocol: Received message (\{.*\})\s*$')
63
+ WRITE = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+TRACE tungstenite::protocol::frame: writing frame')
64
+ STAMPED = re.compile(r'^\d{4}-\d\d-\d\dT[\d:.]+Z\s')
65
+ OTEL = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+INFO\s+.*?codex_otel\.log_only: (.*)$')
66
+ KV = re.compile(r'([A-Za-z_.]+)=("[^"]*"|\S+)')
67
+ ROOT_THREAD = re.compile(r'codex\.exec\{[^}]*thread\.id="([0-9a-f-]{36})"')
68
+ OTEL_KEYS = ("event.name", "event.kind", "input_token_count", "output_token_count", "cached_token_count",
69
+ "cache_write_token_count", "conversation.id", "model", "http.response.status_code", "attempt", "endpoint")
70
+ # the otel rows the gate's completion ledger and attempt coverage read (gate.codex_attempts); the rest is dropped
71
+ OTEL_KEPT = {"codex.websocket_request", "codex.websocket_connect", "codex.api_request"}
72
+ SSE_KINDS = ("response.created", "response.completed")
73
+ # a real warning is printed inside the turn's spans (`WARN session_loop{..}:turn{..}: codex_core::...`)
74
+ RETRY = re.compile(r'^(\d{4}-\d\d-\d\dT[\d:.]+Z)\s+WARN\s+.*?codex_core::responses_retry: ')
75
+ RESP_KEYS = ("id", "model", "status", "generate", "previous_response_id", "prompt_cache_key", "incomplete_details", "error")
76
+ CODEX_TOKENS = ("input_tokens", "cached_tokens", "cache_write_tokens", "output_tokens", "reasoning_tokens", "total_tokens")
77
+ TOOL_OUTPUTS = ("function_call_output", "custom_tool_call_output", "local_shell_call_output", "mcp_tool_call_output")
78
+ CONTRACT = {"$comment": "design §13.2: no request is sent after the stop takes effect, checked on outgoing evidence "
79
+ "against the verified freeze, uncertain where a host record cannot establish sending (boundary)",
80
+ "predicate": "boundary"}
81
+
82
+
83
+ def iso_epoch(text):
84
+ return datetime.datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()
85
+
86
+
87
+ def claude_tokens(u):
88
+ return {"input": u.get("input_tokens") or 0, "output": u.get("output_tokens") or 0,
89
+ "cache_read": u.get("cache_read_input_tokens") or 0, "cache_creation": u.get("cache_creation_input_tokens") or 0}
90
+
91
+
92
+ def otel_usage(rec):
93
+ """An otel completion's token counts in the frame response's form."""
94
+ return {"input_tokens": int(rec.get("input_token_count") or 0), "output_tokens": int(rec.get("output_token_count") or 0),
95
+ "cached_tokens": int(rec.get("cached_token_count") or 0),
96
+ "cache_write_tokens": int(rec.get("cache_write_token_count") or 0)}
97
+
98
+
99
+ def claude_content(message):
100
+ """(characters, tool_result) of a Claude user message: its text and tool-result blocks."""
101
+ content = (message or {}).get("content") if isinstance(message, dict) else None
102
+ if isinstance(content, str):
103
+ return len(content), False
104
+ chars, tool = 0, False
105
+ for block in content if isinstance(content, list) else []:
106
+ if not isinstance(block, dict):
107
+ continue
108
+ if block.get("type") == "tool_result":
109
+ tool, inner = True, block.get("content")
110
+ chars += len(inner) if isinstance(inner, str) else sum(
111
+ len(b.get("text") or "") for b in inner if isinstance(b, dict)) if isinstance(inner, list) else 0
112
+ elif block.get("type") == "text":
113
+ chars += len(block.get("text") or "")
114
+ return chars, tool
115
+
116
+
117
+ def codex_content(items):
118
+ """(characters, tool_result) of a Codex request's input items: tool outputs, messages, the rest."""
119
+ chars, tool = 0, False
120
+ for item in items if isinstance(items, list) else []:
121
+ if not isinstance(item, dict):
122
+ continue
123
+ if item.get("type") in TOOL_OUTPUTS:
124
+ tool, out = True, item.get("output")
125
+ chars += len(out) if isinstance(out, str) else len(json.dumps(out))
126
+ elif item.get("type") == "message" and isinstance(item.get("content"), list):
127
+ chars += sum(len(c.get("text") or "") for c in item["content"] if isinstance(c, dict))
128
+ else:
129
+ chars += len(json.dumps(item))
130
+ return chars, tool
131
+
132
+
133
+ def codex_tokens(u):
134
+ """Codex counts cached and cache-written tokens inside input_tokens; usage.json keeps them apart."""
135
+ cached, written = u.get("cached_tokens") or 0, u.get("cache_write_tokens") or 0
136
+ return {"input": max((u.get("input_tokens") or 0) - cached - written, 0), "output": u.get("output_tokens") or 0,
137
+ "cache_read": cached, "cache_creation": written}
138
+
139
+
140
+ class Ledger:
141
+ """The requests of one call, each in one of usage.STATES, with their send instants."""
142
+
143
+ def __init__(self):
144
+ self.requests, self.sends, self.events, self.compactions, self.result = [], [], [], 0, None
145
+ self.content = {} # agent -> [characters, tool_result] added since its last request opened
146
+
147
+ def previous(self, agent):
148
+ done = [r for r in self.requests if r["agent"] == agent and r["state"] == "measured" and r["role"] != "compaction"]
149
+ return usages.request_total(done[-1]) if done else None
150
+
151
+ def add_content(self, agent, chars, tool_result):
152
+ held = self.content.setdefault(agent, [0, False])
153
+ held[0] += chars
154
+ held[1] = held[1] or tool_result
155
+
156
+ def open(self, rid, role, agent, at, estimate=None):
157
+ if estimate is None:
158
+ chars, tool = self.content.pop(agent, (0, False))
159
+ est = estimate if estimate is not None else usages.estimate(self.previous(agent), chars, tool)
160
+ r = {"id": rid, "role": role, "agent": agent, "state": "provisional" if est is not None else "unresolved",
161
+ "estimate": est, "started_at": at, "sent_at": None, "msg_id": None,
162
+ **{key: None for key in usages.TOKEN_KEYS}}
163
+ self.requests.append(r)
164
+ return r
165
+
166
+ def measure(self, r, tokens):
167
+ r.update(tokens, state="measured", estimate=None)
168
+
169
+ def projected(self):
170
+ return sum(usages.request_total(r) if r["state"] == "measured" else (r["estimate"] or 0) for r in self.requests)
171
+
172
+ def record(self, call_id, stage, seat, observed, wall_ms, reconciled):
173
+ """The call's usage.json (usage.SCHEMA)."""
174
+ rows = [{"id": r["id"], "role": r["role"], "state": r["state"], "estimate": r["estimate"],
175
+ **{key: r[key] for key in usages.TOKEN_KEYS}} for r in self.requests]
176
+ return {"call_id": call_id, "stage": stage, "seat_requested": seat, "seat_observed": observed,
177
+ "requests": rows, "wall_ms": wall_ms, "attempts": len(rows), "reconciled": reconciled}
178
+
179
+
180
+ class ClaudeFeed:
181
+ """Claude's stream events and transcript records into the ledger."""
182
+
183
+ def __init__(self, ledger):
184
+ self.L, self.hints = ledger, 0
185
+
186
+ def _main(self, unbound):
187
+ return next((r for r in self.L.requests if r["role"] == "main" and r[unbound] is None and r["state"] != "measured"), None)
188
+
189
+ def stream(self, j, at):
190
+ kind = j.get("type")
191
+ if kind == "system" and j.get("subtype") == "status" and j.get("status") == "requesting":
192
+ self.hints += 1
193
+ # the transcript's record of the same send may have been read first
194
+ seen = next((r for r in self.L.requests if r["role"] == "main" and not r.get("hint") and r.get("send_seen")
195
+ and r["msg_id"] is None and r["state"] != "measured"), None)
196
+ (seen or self.L.open(f"main#{len(self.L.requests) + 1}", "main", "main", at))["hint"] = True
197
+ elif kind == "system" and j.get("subtype") == "compact_boundary":
198
+ self.L.compactions += 1
199
+ prev = self.L.previous("main")
200
+ self.L.open(f"compaction#{self.L.compactions}", "compaction", "main", at,
201
+ estimate=None if prev is None else usages.SAFETY_FACTOR * prev)
202
+ elif kind == "stream_event":
203
+ event = j.get("event") or {}
204
+ if event.get("type") == "message_start":
205
+ m = event.get("message") or {}
206
+ r = self._main("msg_id") or self.L.open(f"main#{len(self.L.requests) + 1}", "main", "main", at)
207
+ r["msg_id"], r["start_usage"] = m.get("id"), m.get("usage") or {}
208
+ # the response start carries the request's input: at least that much is spent
209
+ started = sum(claude_tokens(r["start_usage"]).values())
210
+ r.update(state="provisional", estimate=max(r["estimate"] or 0, started))
211
+ elif event.get("type") == "message_delta" and event.get("usage"):
212
+ r = next((x for x in reversed(self.L.requests) if x["role"] == "main" and x["msg_id"] and x["state"] != "measured"), None)
213
+ if r is not None:
214
+ self.L.measure(r, claude_tokens({**r.get("start_usage", {}), **event["usage"]}))
215
+ elif kind == "user" and not j.get("parent_tool_use_id"):
216
+ # the main thread's new content: tool results and text since its last request
217
+ self.L.add_content("main", *claude_content(j.get("message")))
218
+ elif kind in ("rate_limit_event", "result"):
219
+ self.L.events.append(j)
220
+ if kind == "result":
221
+ self.L.result = j
222
+
223
+ def transcript(self, agent, kind, rec, at):
224
+ """One record of a transcript file: `kind` main or subagent, `agent` the file's key."""
225
+ if rec.get("type") == "api-request":
226
+ # the host's send instant, or none: the observation time is not a send instant
227
+ sent = iso_epoch(rec["timestamp"]) if rec.get("timestamp") else None
228
+ if kind == "main":
229
+ # the first main request whose send record has not been read, measured or not: the
230
+ # stream may have been read to its end before the transcript record of the same send
231
+ r = next((x for x in self.L.requests if x["role"] == "main" and not x.get("send_seen")), None) \
232
+ or self.L.open(f"main#{len(self.L.requests) + 1}", "main", "main", sent if sent is not None else at)
233
+ else:
234
+ r = self.L.open(f"sub:{agent}#{sum(1 for x in self.L.requests if x['agent'] == agent) + 1}", "subagent", agent,
235
+ sent if sent is not None else at)
236
+ r.update(sent_at=sent, send_seen=True)
237
+ self.L.sends.append({"id": r["id"], "at": sent, "observed_at": at, "source": f"{kind} transcript api-request"})
238
+ elif rec.get("type") == "user" and kind == "subagent":
239
+ self.L.add_content(agent, *claude_content(rec.get("message")))
240
+ elif rec.get("type") == "assistant" and kind == "subagent":
241
+ m = rec.get("message") or {}
242
+ r = next((x for x in self.L.requests if x["agent"] == agent and x["state"] != "measured"), None)
243
+ if r is not None and m.get("stop_reason") is not None:
244
+ self.L.measure(r, claude_tokens(m.get("usage") or {}))
245
+
246
+
247
+ class SentDecoder:
248
+ """permessage-deflate with context takeover: one raw-deflate stream per websocket connection,
249
+ and the log does not say which connection a frame belongs to. A frame is inflated against
250
+ every live context and a fresh one; the context whose last response id equals the frame's
251
+ previous_response_id wins, else a fresh context for a warm-up or another thread, else the
252
+ context of the same thread (a history restart after compaction)."""
253
+
254
+ def __init__(self):
255
+ self.ctx = []
256
+
257
+ @staticmethod
258
+ def meta(j):
259
+ try:
260
+ return json.loads((j.get("client_metadata") or {}).get("x-codex-turn-metadata") or "{}")
261
+ except ValueError:
262
+ return {}
263
+
264
+ def decode(self, payload):
265
+ data = payload + b"\x00\x00\xff\xff"
266
+ candidates = []
267
+ for i, c in enumerate(self.ctx):
268
+ try:
269
+ copy = c["obj"].copy()
270
+ candidates.append((i, copy, json.loads(copy.decompress(data))))
271
+ except (zlib.error, ValueError):
272
+ continue
273
+ fresh = None
274
+ try:
275
+ copy = zlib.decompressobj(-15)
276
+ fresh = (None, copy, json.loads(copy.decompress(data)))
277
+ except (zlib.error, ValueError):
278
+ pass
279
+ exact = [c for c in candidates if c[2].get("previous_response_id") and c[2]["previous_response_id"] == self.ctx[c[0]]["last"]]
280
+ pick = exact[0] if exact else None
281
+ if pick is None and fresh is not None:
282
+ m = self.meta(fresh[2])
283
+ same = [c for c in candidates if self.ctx[c[0]]["thread"] and self.ctx[c[0]]["thread"] == m.get("thread_id")]
284
+ pick = fresh if m.get("request_kind") == "prewarm" or not same else same[0]
285
+ if pick is None and candidates:
286
+ pick = candidates[0]
287
+ if pick is None:
288
+ return None, None
289
+ i, copy, j = pick
290
+ if i is None:
291
+ self.ctx.append({"obj": copy, "thread": self.meta(j).get("thread_id"), "last": None})
292
+ i = len(self.ctx) - 1
293
+ else:
294
+ self.ctx[i]["obj"] = copy
295
+ return j, i
296
+
297
+ def note(self, i, response_id):
298
+ if i is not None and 0 <= i < len(self.ctx):
299
+ self.ctx[i]["last"] = response_id
300
+
301
+
302
+ def codes(value, keys):
303
+ """A diagnostic object reduced to its short structured codes; a message, which may quote the
304
+ prompt, the output or a credential, never survives (the capture keeps no body, design §3.2)."""
305
+ if not isinstance(value, dict):
306
+ return None
307
+ return {k: value[k] for k in keys if isinstance(value.get(k), (str, int)) and len(str(value[k])) <= 64}
308
+
309
+
310
+ class CodexFeed:
311
+ """Codex's trace lines into reduced records and the ledger. The records are the capture's
312
+ frames.jsonl only where the runner wrote none: under codex-run's capture its helper
313
+ (wrappers/codex_frame_filter.py, WP-04) writes them, and its reduction is the one owner; this
314
+ live reduction exists for the caps and the boundary, and the gate imports the helper's
315
+ reduce_lines/responses/join/attempts at integration instead of a third copy."""
316
+
317
+ def __init__(self, ledger):
318
+ self.L, self.dec, self.records, self.pending, self.root = ledger, SentDecoder(), [], None, None
319
+ self.by_response, self.undecoded, self.truncations, self.retries = {}, 0, 0, 0
320
+
321
+ def line(self, text, at):
322
+ text = text.rstrip("\n")
323
+ if self.root is None and ROOT_THREAD.search(text):
324
+ self.root = ROOT_THREAD.search(text).group(1)
325
+ self.records.append({"dir": "info", "type": "root_thread", "thread": self.root})
326
+ if self.pending is not None:
327
+ if text.startswith("opcode:"):
328
+ self.pending["opcode"] = text.split(":", 1)[1].strip()
329
+ return
330
+ if text.startswith("payload: 0x"):
331
+ ts, op = self.pending["ts"], self.pending.get("opcode", "TEXT")
332
+ self.pending = None
333
+ if op == "TEXT":
334
+ try:
335
+ payload = bytes.fromhex(text[len("payload: 0x"):])
336
+ except ValueError:
337
+ payload = None
338
+ self.sent(ts, payload, at)
339
+ return
340
+ if STAMPED.match(text):
341
+ self.truncated(at) # another record came before the payload: the header stays evidence
342
+ else:
343
+ return
344
+ if WRITE.match(text):
345
+ self.pending = {"ts": WRITE.match(text).group(1)}
346
+ elif OTEL.match(text):
347
+ m = OTEL.match(text)
348
+ kv = {k: v.strip('"') for k, v in KV.findall(m.group(2)) if k in OTEL_KEYS}
349
+ if kv.get("event.name") in OTEL_KEPT or (kv.get("event.name") == "codex.sse_event" and kv.get("event.kind") in SSE_KINDS):
350
+ self.records.append({"dir": "otel", "ts": m.group(1), **kv})
351
+ self.otel(self.records[-1])
352
+ elif RETRY.match(text):
353
+ self.records.append({"dir": "warn", "type": "responses_retry", "ts": RETRY.match(text).group(1)})
354
+ self.retry(self.records[-1]["ts"])
355
+ elif RECV.match(text):
356
+ m = RECV.match(text)
357
+ try:
358
+ self.received(m.group(1), json.loads(m.group(2)))
359
+ except ValueError:
360
+ self.records.append({"dir": "recv", "type": "unparsable", "ts": m.group(1)})
361
+
362
+ def truncated(self, at=None):
363
+ """A TEXT (or not yet typed) client frame header whose payload never followed — another
364
+ record came first, or the trace ended: written, not readable, and uncertain at the boundary."""
365
+ held, self.pending = self.pending, None
366
+ if held is None or held.get("opcode", "TEXT") != "TEXT":
367
+ return
368
+ self.truncations += 1
369
+ self.records.append({"dir": "info", "type": "truncated_frame", "ts": held["ts"]})
370
+ self.L.sends.append({"id": f"truncated#{self.truncations}", "at": iso_epoch(held["ts"]), "decoded": False,
371
+ "what": "a client frame header whose payload was never read",
372
+ "observed_at": time.time() if at is None else at, "source": "client frame, truncated"})
373
+
374
+ def finish(self, at=None):
375
+ """The trace ended: a frame header still waiting for its payload is kept as evidence."""
376
+ self.truncated(at)
377
+
378
+ def retry(self, ts):
379
+ """A codex_core::responses_retry warning (design §3.2). It names no thread or request, so it
380
+ marks nothing interrupted — a retried send does that, on its own thread — and is one failed
381
+ post of unknown usage, unresolved (whether it was billed is unknown, §13.3); which thread it
382
+ belongs to is the closing reconciliation's (gate.codex_attempts), never decided here."""
383
+ self.retries += 1
384
+ self.L.open(f"retry#{self.retries}", "unknown", None, iso_epoch(ts))
385
+
386
+ def sent(self, ts, payload, at=None):
387
+ j, ctx = self.dec.decode(payload) if payload is not None else (None, None)
388
+ if j is None:
389
+ # written, but not readable as a request or anything else: kept, and uncertain at the boundary
390
+ self.undecoded += 1
391
+ self.records.append({"dir": "info", "type": "undecodable_frame", "ts": ts})
392
+ self.L.sends.append({"id": f"undecoded#{self.undecoded}", "at": iso_epoch(ts), "decoded": False,
393
+ "what": "an undecodable client frame",
394
+ "observed_at": time.time() if at is None else at, "source": "client frame, undecodable"})
395
+ return
396
+ if j.get("type") != "response.create":
397
+ return
398
+ m = SentDecoder.meta(j)
399
+ child = bool(m.get("parent_thread_id") or (m.get("agent_name") or "/root") != "/root")
400
+ role = {"prewarm": "warmup", "compaction": "compaction"}.get(m.get("request_kind"), "child" if child else "main")
401
+ rec = {"dir": "send", "type": "response.create", "ts": ts, "thread_id": m.get("thread_id"),
402
+ "agent_name": m.get("agent_name"), "request_kind": m.get("request_kind"),
403
+ "parent_thread_id": m.get("parent_thread_id"), "previous_response_id": j.get("previous_response_id"),
404
+ "prompt_cache_key": j.get("prompt_cache_key"), "model": j.get("model"),
405
+ "reasoning_effort": (j.get("reasoning") or {}).get("effort")}
406
+ self.records.append(rec)
407
+ if role == "compaction":
408
+ self.L.compactions += 1
409
+ self.L.add_content(m.get("thread_id"), *codex_content(j.get("input")))
410
+ key = (rec["prompt_cache_key"], rec["previous_response_id"])
411
+ for x in self.L.requests: # a send asking again what an unanswered one asked is its retry: that one failed
412
+ if x.get("key") == key and x["state"] != "measured" and x["agent"] == m.get("thread_id"):
413
+ x["interrupted"] = True
414
+ r = self.L.open(f"send#{len(self.L.sends) + 1}", role, m.get("thread_id"), iso_epoch(ts))
415
+ r.update(sent_at=iso_epoch(ts), send_seen=True, ctx=ctx, key=key)
416
+ self.L.sends.append({"id": r["id"], "at": iso_epoch(ts), "observed_at": time.time() if at is None else at,
417
+ "source": "client frame"})
418
+
419
+ def otel(self, rec):
420
+ """An otel row into the ledger (design §13.3), reconciled before the caps are evaluated: a
421
+ completion a frame response of the same thread already accounts for, by full usage, is
422
+ that request; an HTTPS completion is its open stream's; any other completion is the
423
+ thread's oldest sent request still waiting for its usage — measured from otel until its
424
+ frame arrives (pre_otel keeps what it was), never an attempt a retry warning or
425
+ a retried send showed failed —, and with none outstanding a request of
426
+ unknown kind measured from otel (frames_blind). An HTTPS response start is a request in
427
+ flight until its completion arrives."""
428
+ if rec.get("event.name") != "codex.sse_event":
429
+ return
430
+ thread, at = rec.get("conversation.id"), iso_epoch(rec["ts"])
431
+ if rec.get("event.kind") == "response.created":
432
+ self.L.open(f"otel#{len(self.L.requests) + 1}", "unknown", thread, at)["otel_open"] = True
433
+ return
434
+ if rec.get("event.kind") != "response.completed" or rec.get("input_token_count") is None:
435
+ return
436
+ joined = next((x for x in self.L.requests if x.get("frame_usage") is not None and not x.get("otel_joined")
437
+ and x["agent"] == thread and usages.same_usage(rec, x["frame_usage"])), None)
438
+ if joined is not None:
439
+ joined["otel_joined"] = True
440
+ return
441
+ pending = [x for x in self.L.requests if x.get("otel_open") and x["agent"] == thread and x["state"] != "measured"]
442
+ waiting = [x for x in self.L.requests if x.get("send_seen") and x["agent"] == thread and x["state"] != "measured"
443
+ and x.get("frame_usage") is None and not x.get("interrupted")] # a failed attempt answers nothing
444
+ if pending:
445
+ r = pending[-1]
446
+ r["otel_only"] = True
447
+ elif waiting:
448
+ r = waiting[0]
449
+ r["pre_otel"] = {key: r[key] for key in ("state", "estimate", *usages.TOKEN_KEYS)}
450
+ else:
451
+ r = self.L.open(f"otel#{len(self.L.requests) + 1}", "unknown", thread, at)
452
+ r["otel_only"] = True
453
+ self.L.measure(r, codex_tokens(otel_usage(rec)))
454
+ r["otel_usage"] = rec
455
+
456
+ def received(self, ts, j):
457
+ kind, resp = j.get("type"), j.get("response")
458
+ rec = {"dir": "recv", "type": kind, "ts": ts}
459
+ if isinstance(resp, dict):
460
+ rec["response"] = {k: resp.get(k) for k in RESP_KEYS}
461
+ rec["response"]["error"] = codes(resp.get("error"), ("code", "type"))
462
+ rec["response"]["incomplete_details"] = codes(resp.get("incomplete_details"), ("reason",))
463
+ rec["response"]["reasoning_effort"] = (resp.get("reasoning") or {}).get("effort")
464
+ u = resp.get("usage") if isinstance(resp.get("usage"), dict) else None
465
+ rec["response"]["usage"] = None if u is None else {
466
+ "input_tokens": u.get("input_tokens"), "cached_tokens": (u.get("input_tokens_details") or {}).get("cached_tokens"),
467
+ "cache_write_tokens": (u.get("input_tokens_details") or {}).get("cache_write_tokens"),
468
+ "output_tokens": u.get("output_tokens"), "reasoning_tokens": (u.get("output_tokens_details") or {}).get("reasoning_tokens"),
469
+ "total_tokens": u.get("total_tokens")}
470
+ r = self.by_response.get(resp.get("id"))
471
+ if r is None:
472
+ key = (resp.get("prompt_cache_key"), resp.get("previous_response_id"))
473
+ r = next((x for x in self.L.requests if x.get("key") == key and not x.get("response_id")
474
+ and not x.get("interrupted")), None)
475
+ if r is not None:
476
+ r["response_id"] = resp.get("id")
477
+ self.by_response[resp.get("id")] = r
478
+ self.dec.note(r.get("ctx"), resp.get("id"))
479
+ if r is not None and kind == "response.completed" and rec["response"]["usage"]:
480
+ held = r.get("otel_usage")
481
+ if held is not None and not usages.same_usage(held, rec["response"]["usage"]):
482
+ # the otel completion this request was measured from answered another request
483
+ stray = self.L.open(f"otel#{len(self.L.requests) + 1}", "unknown", r["agent"], iso_epoch(held["ts"]))
484
+ self.L.measure(stray, codex_tokens(otel_usage(held)))
485
+ stray.update(otel_usage=held, otel_only=True)
486
+ r.pop("otel_usage")
487
+ elif held is not None:
488
+ r["otel_joined"] = True
489
+ self.L.measure(r, codex_tokens(rec["response"]["usage"]))
490
+ r["frame_usage"] = rec["response"]["usage"]
491
+ # its otel completion read first, while nothing was outstanding: that row was this request
492
+ early = next((x for x in self.L.requests if x.get("otel_only") and not x.get("frame_usage")
493
+ and not x.get("otel_joined") and x["agent"] == r["agent"]
494
+ and usages.same_usage(x["otel_usage"], r["frame_usage"])), None)
495
+ if early is not None:
496
+ self.L.requests.remove(early)
497
+ r["otel_joined"] = True
498
+ elif kind == "codex.rate_limits":
499
+ rl = j.get("rate_limits") or {}
500
+ rec["rate_limits"] = {"allowed": rl.get("allowed"), "limit_reached": rl.get("limit_reached")}
501
+ elif kind == "error":
502
+ err = j.get("error") if isinstance(j.get("error"), dict) else {}
503
+ rec["detail"] = {"status": j.get("status"), "error": codes(err, ("code", "type"))}
504
+ elif not (isinstance(kind, str) and "refusal" in kind): # a refusal frame is kept by its type alone
505
+ return
506
+ self.records.append(rec)
507
+
508
+
509
+ class Monitor:
510
+ """Feeds one call's ledger and evaluates both caps at every event and record; at a cap it
511
+ calls `on_trip(reason)` once."""
512
+
513
+ def __init__(self, host, caps, on_trip=None, on_signal=None, output_cap=None):
514
+ self.host, self.caps, self.on_trip, self.on_signal = host, caps, on_trip, on_signal
515
+ self.output_cap = output_cap # the call's declared output-token cap: an overrun of it is no provider signal
516
+ self.ledger, self.lock, self.trip, self.closed = Ledger(), threading.Lock(), None, False
517
+ self.feed = ClaudeFeed(self.ledger) if host == "claude" else CodexFeed(self.ledger)
518
+ self._read = 0 # how many events (Claude) or records (Codex) the signal check has seen
519
+
520
+ def line(self, text, at=None):
521
+ at = time.time() if at is None else at
522
+ with self.lock:
523
+ if self.closed: # read after the call was accounted: it belongs to no verdict
524
+ return
525
+ if self.host == "claude":
526
+ try:
527
+ self.feed.stream(json.loads(text), at)
528
+ except ValueError:
529
+ return
530
+ else:
531
+ self.feed.line(text, at)
532
+ self._caps(at)
533
+ self._signals()
534
+
535
+ def transcript(self, agent, kind, rec, at=None):
536
+ at = time.time() if at is None else at
537
+ with self.lock:
538
+ if self.closed:
539
+ return
540
+ self.feed.transcript(agent, kind, rec, at)
541
+ self._caps(at)
542
+
543
+ def finish(self, at=None):
544
+ """The readers drained, or given up on: what the trace left half-written is kept
545
+ (CodexFeed.finish), and nothing read after this reaches the ledger."""
546
+ with self.lock:
547
+ if self.host == "codex" and not self.closed:
548
+ self.feed.finish(time.time() if at is None else at)
549
+ self.closed = True
550
+
551
+ def _signals(self):
552
+ """The structured provider signals among what was read since the last line, at once."""
553
+ held = self.ledger.events if self.host == "claude" else self.feed.records
554
+ fresh, self._read = held[self._read:], len(held)
555
+ found = breakers.claude_signals(fresh, self.output_cap) if self.host == "claude" else breakers.codex_signals(fresh)
556
+ stopping = [sig for sig in found if sig["kind"] in ("limit", "unrecognised")]
557
+ if stopping and self.on_signal is not None:
558
+ self.on_signal(stopping)
559
+
560
+ def _caps(self, at):
561
+ if self.trip is not None:
562
+ return
563
+ projected = self.ledger.projected()
564
+ if projected >= self.caps["tokens"]:
565
+ self.trip = {"why": f"token cap: measured and provisional {projected} >= {self.caps['tokens']}", "at": at}
566
+ elif self.ledger.compactions > self.caps["compactions"]:
567
+ self.trip = {"why": f"compaction cap: {self.ledger.compactions} compactions > {self.caps['compactions']}", "at": at}
568
+ if self.trip is not None and self.on_trip is not None:
569
+ self.on_trip(self.trip["why"])
570
+
571
+
572
+ class StreamTail(threading.Thread):
573
+ """Follows the stream file a runner appends to (capture/stream.jsonl) and feeds every new
574
+ complete line to `monitor.line`, once."""
575
+
576
+ def __init__(self, path, monitor, interval=0.005):
577
+ super().__init__(daemon=True)
578
+ self.path, self.monitor, self.interval = pathlib.Path(path), monitor, interval
579
+ self.pos, self.halt, self.poll_lock = 0, threading.Event(), threading.Lock()
580
+
581
+ def run(self):
582
+ while not self.halt.wait(self.interval):
583
+ self.poll()
584
+
585
+ def poll(self):
586
+ with self.poll_lock:
587
+ size = self.path.stat().st_size if self.path.is_file() else 0
588
+ if size <= self.pos:
589
+ return
590
+ with open(self.path, "rb") as handle:
591
+ handle.seek(self.pos)
592
+ data = handle.read(size - self.pos)
593
+ cut = data.rfind(b"\n")
594
+ if cut < 0:
595
+ return
596
+ self.pos += cut + 1
597
+ for raw in data[:cut].split(b"\n"):
598
+ if raw.strip():
599
+ self.monitor.line(raw.decode("utf-8", "replace"))
600
+
601
+
602
+ class TranscriptTail(threading.Thread):
603
+ """Polls `<cfg>/projects` and feeds every new complete record to `monitor.transcript`."""
604
+
605
+ def __init__(self, cfg_dir, monitor, interval=0.005):
606
+ super().__init__(daemon=True)
607
+ self.root, self.monitor, self.interval = pathlib.Path(cfg_dir) / "projects", monitor, interval
608
+ self.pos, self.halt, self.poll_lock = {}, threading.Event(), threading.Lock()
609
+
610
+ def run(self):
611
+ while not self.halt.wait(self.interval):
612
+ self.poll()
613
+
614
+ def poll(self):
615
+ with self.poll_lock:
616
+ for path in sorted(self.root.rglob("*.jsonl")) if self.root.is_dir() else []:
617
+ size, offset = path.stat().st_size, self.pos.get(path, 0)
618
+ if size <= offset:
619
+ continue
620
+ with open(path, "rb") as handle:
621
+ handle.seek(offset)
622
+ data = handle.read(size - offset)
623
+ cut = data.rfind(b"\n")
624
+ if cut < 0:
625
+ continue
626
+ self.pos[path] = offset + cut + 1
627
+ kind = "subagent" if "subagents" in path.parts else "main"
628
+ agent = path.stem[len("agent-"):] if kind == "subagent" else "main"
629
+ for raw in data[:cut].split(b"\n"):
630
+ try:
631
+ self.monitor.transcript(agent, kind, json.loads(raw))
632
+ except ValueError:
633
+ continue
634
+
635
+
636
+ BOUNDARY_VERDICTS = ("clean", "STOP_BOUNDARY_UNVERIFIED", "STOP_BOUNDARY_VIOLATED")
637
+
638
+
639
+ def boundary_verdict(problems, uncertain):
640
+ """The one value a stop's boundary is read by (design §13.2's guarantee): a violation names
641
+ it VIOLATED; else anything uncertain leaves it UNVERIFIED, never clean; clean only when both
642
+ lists are empty."""
643
+ if any(p.startswith("STOP_BOUNDARY_VIOLATED") for p in problems):
644
+ return "STOP_BOUNDARY_VIOLATED"
645
+ if problems or uncertain:
646
+ return "STOP_BOUNDARY_UNVERIFIED"
647
+ return "clean"
648
+
649
+
650
+ def boundary(ledger, freeze_at, kill_at):
651
+ """(problems, uncertain): sends after the verified freeze instant, and requests whose sending
652
+ no host record can establish either way."""
653
+ problems, uncertain = [], []
654
+ if freeze_at is None:
655
+ problems.append("STOP_BOUNDARY_UNVERIFIED the freeze was not verified, so no send can be held against it")
656
+ return problems, uncertain
657
+ for send in ledger.sends:
658
+ if send.get("decoded") is False:
659
+ if send["at"] > freeze_at:
660
+ uncertain.append(f"{send['id']}: {send['what']} written at {send['at']:.6f}, after the "
661
+ f"verified freeze at {freeze_at:.6f}; whether it was a request is unknown")
662
+ elif send["at"] is None:
663
+ if send["observed_at"] > freeze_at:
664
+ uncertain.append(f"{send['id']}: a send record with no host instant, read after the verified freeze at "
665
+ f"{freeze_at:.6f} ({send['source']}); whether it was sent before it is unknown")
666
+ elif send["at"] > freeze_at:
667
+ problems.append(f"STOP_BOUNDARY_VIOLATED {send['id']} sent at {send['at']:.6f}, after the verified freeze at "
668
+ f"{freeze_at:.6f} ({send['source']})")
669
+ for r in ledger.requests:
670
+ if r.get("hint") and not r.get("send_seen") and kill_at - r["started_at"] < FLUSH_WINDOW_S:
671
+ uncertain.append(f"{r['id']}: requested {kill_at - r['started_at']:.3f} s before the kill, inside the "
672
+ f"{FLUSH_WINDOW_S} s flush window; whether it was sent is unknown")
673
+ return problems, uncertain
674
+
675
+
676
+ def self_test():
677
+ from runlib import records
678
+ try:
679
+ replay_root = records.fixture_root("replay")
680
+ except records.Refused as exc: # a tree without fixtures/ ends the suite by name, never by a traceback
681
+ print(f"monitor --self-test: {exc}")
682
+ return 1
683
+ import ast
684
+ import tempfile
685
+ failures, ran = [], []
686
+
687
+ def control(name, condition, detail):
688
+ ran.append(name)
689
+ if not condition:
690
+ failures.append(f"{name}: {detail}")
691
+
692
+ def status():
693
+ return json.dumps({"type": "system", "subtype": "status", "status": "requesting"})
694
+
695
+ def start(mid, inp=2):
696
+ return json.dumps({"type": "stream_event", "event": {"type": "message_start", "message": {"id": mid, "model": "m",
697
+ "usage": {"input_tokens": inp, "cache_read_input_tokens": 2800, "cache_creation_input_tokens": 350}}}})
698
+
699
+ def delta(out):
700
+ return json.dumps({"type": "stream_event", "event": {"type": "message_delta", "usage": {"output_tokens": out}}})
701
+
702
+ # positive control first: one main request, measured at its delta, under both caps
703
+ m = Monitor("claude", {"tokens": 10_000, "compactions": 2})
704
+ for line in (status(), start("msg_1"), delta(48)):
705
+ m.line(line, 1.0)
706
+ r = m.ledger.requests[0]
707
+ control("claude-main-request-measured", r["state"] == "measured" and usages.request_total(r) == 3200 and m.trip is None,
708
+ f"{r}, trip {m.trip}")
709
+ # the next request is provisional at the same agent's previous request, and trips the token cap
710
+ trips = []
711
+ m = Monitor("claude", {"tokens": 6_000, "compactions": 2}, on_trip=trips.append)
712
+ for line in (status(), start("msg_1"), delta(48), status()):
713
+ m.line(line, 1.0)
714
+ control("claude-in-flight-request-is-provisional-at-the-previous", m.ledger.requests[1]["state"] == "provisional"
715
+ and m.ledger.requests[1]["estimate"] == 3200, f"{m.ledger.requests[1]}")
716
+ control("token-cap-trips-on-the-provisional-estimate", len(trips) == 1 and trips[0].startswith("token cap: measured and provisional 6400"),
717
+ f"{trips}")
718
+ m.line(status(), 1.1)
719
+ control("cap-trips-once", len(trips) == 1, f"{trips}")
720
+ # compaction markers: a provisional estimate each, and the compaction cap
721
+ trips = []
722
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 2}, on_trip=trips.append)
723
+ m.line(status(), 1.0)
724
+ m.line(start("msg_1"), 1.0)
725
+ m.line(delta(48), 1.0)
726
+ for n in range(3):
727
+ m.line(json.dumps({"type": "system", "subtype": "compact_boundary", "compact_metadata": {"trigger": "auto"}}), 2.0 + n)
728
+ compactions = [x for x in m.ledger.requests if x["role"] == "compaction"]
729
+ control("compaction-marker-counts-a-provisional-estimate", len(compactions) == 3 and compactions[0]["estimate"] == 6400
730
+ and compactions[0]["state"] == "provisional", f"{compactions}")
731
+ control("compaction-cap-trips-past-the-cap", trips == ["compaction cap: 3 compactions > 2"], f"{trips}")
732
+ trips = []
733
+ m = Monitor("claude", {"tokens": 3000, "compactions": 2}, on_trip=trips.append)
734
+ m.line(status(), 1.0)
735
+ control("first-request-unresolved-until-its-response-starts", m.ledger.requests[0]["state"] == "unresolved" and not trips,
736
+ f"{m.ledger.requests[0]} {trips}")
737
+ m.line(start("msg_1"), 1.0)
738
+ control("response-start-input-trips-the-cap-mid-stream", m.ledger.requests[0]["estimate"] == 3152
739
+ and trips == ["token cap: measured and provisional 3152 >= 3000"], f"{m.ledger.requests[0]} {trips}")
740
+ control("first-request-without-a-previous-is-unresolved", Monitor("claude", {"tokens": 1, "compactions": 0}).ledger.open(
741
+ "x", "main", "main", 0)["state"] == "unresolved", "estimated from nothing")
742
+ # subagents are seen only in their transcripts: started at api-request, measured at their final record
743
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
744
+ m.transcript("a1", "subagent", {"type": "api-request", "timestamp": "2026-10-21T00:00:01.000Z"}, 1792540801.1)
745
+ m.transcript("a1", "subagent", {"type": "assistant", "message": {"stop_reason": "end_turn", "usage": {"input_tokens": 10, "output_tokens": 5}}}, 1792540802.0)
746
+ sub = m.ledger.requests[0]
747
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
748
+ m.transcript("main", "main", {"type": "api-request", "timestamp": "2026-10-21T00:00:01.000Z"}, 1.0)
749
+ for line in (status(), start("msg_1"), delta(48)):
750
+ m.line(line, 1.0)
751
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
752
+ for line in (status(), start("msg_1"), delta(48)):
753
+ m.line(line, 1.0)
754
+ m.transcript("main", "main", {"type": "api-request", "timestamp": "2026-10-21T00:00:01.000Z"}, 1.0)
755
+ control("transcript-read-after-the-stream-binds-one-request", [(r["id"], r["state"], r["sent_at"] is not None)
756
+ for r in m.ledger.requests] == [("main#1", "measured", True)],
757
+ f"{m.ledger.requests}")
758
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
759
+ m.transcript("main", "main", {"type": "api-request", "timestamp": "2026-10-21T00:00:01.000Z"}, 1.0)
760
+ for line in (status(), start("msg_1"), delta(48)):
761
+ m.line(line, 1.0)
762
+ control("transcript-read-before-the-stream-binds-one-request", [(r["id"], r["state"], r.get("hint")) for r in m.ledger.requests]
763
+ == [("main#1", "measured", True)], f"{m.ledger.requests}")
764
+ control("subagent-measured-from-its-transcript", sub["role"] == "subagent" and sub["state"] == "measured"
765
+ and m.ledger.sends[0]["at"] == iso_epoch("2026-10-21T00:00:01.000Z"), f"{sub} {m.ledger.sends}")
766
+ # the usage record the dispatcher writes is a valid usage.json
767
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
768
+ for line in (status(), start("msg_1"), delta(48), status()):
769
+ m.line(line, 1.0)
770
+ record = m.ledger.record("r1-S6-c1-a1", "S6", "claude:claude-opus-5-5/high", {"main": ["m"]}, 900, False)
771
+ control("usage-record-valid", not usages.check(record) and usages.call_state(record) == "provisional", f"{usages.check(record)}")
772
+
773
+ # the boundary: sends against the verified freeze instant, on outgoing evidence
774
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
775
+ m.line(status(), 99.0)
776
+ m.transcript("main", "main", {"type": "api-request", "timestamp": datetime.datetime.fromtimestamp(99.001, datetime.timezone.utc).isoformat()}, 99.1)
777
+ m.line(start("msg_1"), 99.2)
778
+ m.line(delta(5), 99.3)
779
+ problems, uncertain = boundary(m.ledger, freeze_at=100.0, kill_at=100.05)
780
+ control("sends-before-the-freeze-are-clean", not problems and not uncertain, f"{problems} {uncertain}")
781
+ # a fault-injected send after the freeze that produced no response start: named by its request id
782
+ m.transcript("main", "main", {"type": "api-request", "timestamp": datetime.datetime.fromtimestamp(100.02, datetime.timezone.utc).isoformat()}, 100.3)
783
+ problems, uncertain = boundary(m.ledger, freeze_at=100.0, kill_at=100.05)
784
+ control("post-freeze-send-is-named", any(p.startswith("STOP_BOUNDARY_VIOLATED main#2 sent at 100.020000") for p in problems), f"{problems}")
785
+ starts_after = [r for r in m.ledger.requests if r.get("msg_id") and r["started_at"] > 100.0]
786
+ control("a-response-start-reading-misses-it", not starts_after, "the message_start-only reading saw a response start after the freeze")
787
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
788
+ m.line(status(), 100.0)
789
+ problems, uncertain = boundary(m.ledger, freeze_at=100.01, kill_at=100.1)
790
+ control("a-hint-inside-the-flush-window-is-uncertain", not problems and uncertain and uncertain[0].startswith("main#1: requested 0.100 s"),
791
+ f"{problems} {uncertain}")
792
+ problems, uncertain = boundary(m.ledger, freeze_at=100.01, kill_at=100.4)
793
+ control("a-hint-outside-the-flush-window-was-not-sent", not problems and not uncertain, f"{uncertain}")
794
+ control("unverified-freeze-is-named", boundary(m.ledger, None, 100.4)[0][0].startswith("STOP_BOUNDARY_UNVERIFIED"), "unnamed")
795
+ # the one value the boundary is read by: clean only when nothing is a problem and nothing uncertain
796
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
797
+ m.transcript("main", "main", {"type": "api-request", "timestamp": datetime.datetime.fromtimestamp(99.0, datetime.timezone.utc).isoformat()}, 99.1)
798
+ control("boundary-verdict-clean-when-every-send-precedes-the-freeze", boundary_verdict(*boundary(m.ledger, 100.0, 100.05)) == "clean",
799
+ f"{boundary(m.ledger, 100.0, 100.05)}")
800
+ m.transcript("main", "main", {"type": "api-request"}, 100.2)
801
+ control("boundary-verdict-a-post-freeze-send-without-an-instant-is-unverified",
802
+ boundary_verdict(*boundary(m.ledger, 100.0, 100.05)) == "STOP_BOUNDARY_UNVERIFIED", f"{boundary(m.ledger, 100.0, 100.05)}")
803
+ m.transcript("main", "main", {"type": "api-request", "timestamp": datetime.datetime.fromtimestamp(100.02, datetime.timezone.utc).isoformat()}, 100.3)
804
+ control("boundary-verdict-a-timestamped-post-freeze-send-is-violated",
805
+ boundary_verdict(*boundary(m.ledger, 100.0, 100.05)) == "STOP_BOUNDARY_VIOLATED", f"{boundary(m.ledger, 100.0, 100.05)}")
806
+ control("boundary-verdict-an-unverified-freeze-is-not-clean", boundary_verdict(*boundary(m.ledger, None, 100.05)) == "STOP_BOUNDARY_UNVERIFIED",
807
+ "clean")
808
+
809
+ # Codex: trace lines, with client frames deflated per connection as codex-cli 0.163.0 writes them
810
+ def deflater():
811
+ return zlib.compressobj(wbits=-15)
812
+
813
+ def payload(comp, obj):
814
+ return (comp.compress(json.dumps(obj).encode()) + comp.flush(zlib.Z_SYNC_FLUSH))[:-4]
815
+
816
+ root, kid = "01a1587a-0000-7000-8000-00000000000a", "01a1587a-0000-7000-8000-00000000000b"
817
+
818
+ def create(thread, agent, kind, prev, parent=None):
819
+ meta = {"thread_id": thread, "agent_name": agent, "request_kind": kind, "parent_thread_id": parent}
820
+ return {"type": "response.create", "model": "gpt-6-luna", "previous_response_id": prev, "prompt_cache_key": root,
821
+ "reasoning": {"effort": "low"}, "client_metadata": {"x-codex-turn-metadata": json.dumps(meta)}}
822
+
823
+ def written(ts, comp, obj):
824
+ return [f"{ts} TRACE tungstenite::protocol::frame: writing frame", "opcode: TEXT", "reserved: true false false",
825
+ "payload: 0x" + payload(comp, obj).hex()]
826
+
827
+ def received(ts, kind, rid, prev, usage=None):
828
+ resp = {"id": rid, "model": "gpt-6-luna", "status": "completed" if usage else "in_progress", "previous_response_id": prev,
829
+ "prompt_cache_key": root, "reasoning": {"effort": "low"},
830
+ "usage": None if usage is None else {"input_tokens": usage, "input_tokens_details": {"cached_tokens": 1000},
831
+ "output_tokens": 15, "total_tokens": usage + 15}}
832
+ return f"{ts} TRACE tungstenite::protocol: Received message {json.dumps({'type': kind, 'response': resp})}"
833
+
834
+ c_root, c_kid = deflater(), deflater()
835
+ lines = [f'2026-10-21T00:00:00.000001Z INFO codex.exec{{thread.id="{root}"}}: started']
836
+ lines += written("2026-10-21T00:00:00.100000Z", c_root, create(root, "/root", "prewarm", None))
837
+ lines += [received("2026-10-21T00:00:00.200000Z", "response.created", "resp_w", None),
838
+ received("2026-10-21T00:00:00.300000Z", "response.completed", "resp_w", None, 11814)]
839
+ lines += written("2026-10-21T00:00:00.400000Z", c_root, create(root, "/root", "turn", "resp_w"))
840
+ lines += written("2026-10-21T00:00:00.410000Z", c_kid, create(kid, "/root/kid", "turn", None, parent=root))
841
+ lines += [received("2026-10-21T00:00:00.500000Z", "response.created", "resp_m", "resp_w"),
842
+ received("2026-10-21T00:00:00.600000Z", "response.completed", "resp_m", "resp_w", 13595),
843
+ '2026-10-21T00:00:00.610000Z INFO session_loop: codex_otel.log_only: event.name="codex.sse_event" event.kind=response.completed '
844
+ f'input_token_count=13595 output_token_count=15 cached_token_count=1000 cache_write_token_count=0 '
845
+ f'conversation.id={root} model=gpt-6-luna']
846
+ trips = []
847
+ m = Monitor("codex", {"tokens": 50_000, "compactions": 2}, on_trip=trips.append)
848
+ for line in lines:
849
+ m.line(line, 1.0)
850
+ sends = [r for r in m.feed.records if r["dir"] == "send"]
851
+ control("codex-client-frames-decoded-per-connection", [(s["request_kind"], s["thread_id"]) for s in sends]
852
+ == [("prewarm", root), ("turn", root), ("turn", kid)] and m.feed.undecoded == 0, f"{sends} undecoded {m.feed.undecoded}")
853
+ roles = {r["id"]: (r["role"], r["state"]) for r in m.ledger.requests}
854
+ control("codex-roles-and-states", roles == {"send#1": ("warmup", "measured"), "send#2": ("main", "measured"),
855
+ "send#3": ("child", "unresolved")}, f"{roles}")
856
+ control("codex-cached-tokens-kept-apart", m.ledger.requests[0]["cache_read"] == 1000 and m.ledger.requests[0]["input"] == 10814,
857
+ f"{m.ledger.requests[0]}")
858
+ control("codex-records-in-the-gate-form", any(r["dir"] == "otel" and r.get("input_token_count") == "13595" for r in m.feed.records)
859
+ and any(r["dir"] == "info" and r["thread"] == root for r in m.feed.records), f"{m.feed.records[:3]}")
860
+ control("codex-under-the-cap", not trips, f"{trips}")
861
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 9})
862
+ for line in ('2026-10-21T00:00:02.000000Z INFO session_loop: codex_otel.log_only: event.name="codex.sse_event" '
863
+ f'event.kind=response.output_text.delta conversation.id={root}',
864
+ '2026-10-21T00:00:02.100000Z INFO session_loop: codex_otel.log_only: event.name="codex.api_request" '
865
+ 'http.response.status_code=200 attempt=0 endpoint=/models',
866
+ "2026-10-21T00:00:02.200000Z WARN codex_core::responses_retry: stream disconnected - retrying sampling "
867
+ "request (1/5 in 190ms)",
868
+ '2026-10-21T00:00:02.300000Z WARN session_loop{thread_id=th}:turn{turn.id="t1"}: codex_core::responses_retry: '
869
+ "stream disconnected - retrying sampling request (2/5 in 380ms)",
870
+ '2026-10-21T00:00:02.400000Z TRACE tungstenite::protocol: Received message '
871
+ '{"type":"response.refusal.done","refusal":"BODY-CANARY-refusal-text"}',
872
+ '2026-10-21T00:00:02.500000Z TRACE tungstenite::protocol: Received message '
873
+ '{"type":"error","status":400,"error":{"code":"bad","type":"t","message":"BODY-CANARY-error-text"}}'):
874
+ m.line(line, 1.0)
875
+ control("codex-otel-whitelist-retry-warnings-bare-and-in-spans-and-refusals",
876
+ [(r["dir"], r.get("event.name") or r.get("type"), r.get("endpoint")) for r in m.feed.records]
877
+ == [("otel", "codex.api_request", "/models"), ("warn", "responses_retry", None), ("warn", "responses_retry", None),
878
+ ("recv", "response.refusal.done", None), ("recv", "error", None)]
879
+ and "BODY-CANARY" not in json.dumps(m.feed.records), f"{m.feed.records}")
880
+ m = Monitor("codex", {"tokens": 20_000, "compactions": 2}, on_trip=trips.append)
881
+ for line in lines:
882
+ m.line(line, 1.0)
883
+ control("codex-cap-trips-at-a-send", trips and trips[0].startswith("token cap: measured and provisional 23658"), f"{trips}")
884
+ trips.clear()
885
+ c = deflater()
886
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 0}, on_trip=trips.append)
887
+ for line in written("2026-10-21T00:00:01.000000Z", c, create(root, "/root", "compaction", None)):
888
+ m.line(line, 1.0)
889
+ control("codex-compaction-request-counts-against-the-cap", trips == ["compaction cap: 1 compactions > 0"], f"{trips}")
890
+
891
+ # otel usage enters the live ledger (design §13.3): a fallback capture's otel-only completion
892
+ # (replay, its trace lines rebuilt from the retained rows) is measured and counts toward the cap
893
+ replay = replay_root / "codex-accounting"
894
+
895
+ def otel_lines(case):
896
+ rows = [json.loads(x) for x in (replay / case / "frames.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()]
897
+ lines = [f'{rows[0].get("ts", "2026-10-20T00:00:00.000000Z")} INFO codex.exec{{thread.id="{rows[0]["thread"]}"}}: started']
898
+ return lines + [f'{r["ts"]} INFO session_loop: codex_otel.log_only: ' + " ".join(
899
+ f"{k}={v}" for k, v in r.items() if k not in ("dir", "ts")) for r in rows if r.get("dir") == "otel"]
900
+ trips = []
901
+ m = Monitor("codex", {"tokens": 1002, "compactions": 2}, on_trip=trips.append)
902
+ for line in otel_lines("f-ws-refuse-always-fallback"):
903
+ m.line(line, 1.0)
904
+ rows = [(r["role"], r["state"], usages.request_total(r) if r["state"] == "measured" else r["estimate"]) for r in m.ledger.requests]
905
+ control("otel-only-completion-measured-and-counted-toward-the-cap", rows == [("unknown", "measured", 1002)]
906
+ and trips == ["token cap: measured and provisional 1002 >= 1002"], f"{rows} {trips}")
907
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2})
908
+ for line in otel_lines("f-http-sse-drop"):
909
+ m.line(line, 1.0)
910
+ control("dropped-https-stream-stays-an-unmeasured-attempt", [r["state"] for r in m.ledger.requests] == ["unresolved", "measured"],
911
+ f"{m.ledger.requests}")
912
+ # mixed coverage (golden): one request over websocket, the next over HTTPS after a fallback
913
+ https = [f'2026-10-21T00:00:00.700000Z INFO session_loop: codex_otel.log_only: event.name="codex.sse_event" '
914
+ f'event.kind=response.created conversation.id={root} model=gpt-6-luna',
915
+ '2026-10-21T00:00:00.800000Z INFO session_loop: codex_otel.log_only: event.name="codex.sse_event" '
916
+ f'event.kind=response.completed input_token_count=14000 output_token_count=20 cached_token_count=1000 '
917
+ f'cache_write_token_count=0 conversation.id={root} model=gpt-6-luna']
918
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2})
919
+ for line in lines + https:
920
+ m.line(line, 1.0)
921
+ measured = sum(usages.request_total(r) for r in m.ledger.requests if r["state"] == "measured")
922
+ control("mixed-coverage-counts-the-frames-and-the-otel-only-request-once-each", measured == 11829 + 13610 + 14020
923
+ and [r["role"] for r in m.ledger.requests if r["state"] == "measured"] == ["warmup", "main", "unknown"], f"{m.ledger.requests}")
924
+ trips = []
925
+ m = Monitor("codex", {"tokens": 11829 + 13610 + 14020, "compactions": 2}, on_trip=trips.append)
926
+ for line in lines[:-1] + https: # the cap lies past the frames' total: only the otel-only completion reaches it
927
+ m.line(line, 1.0)
928
+ control("mixed-coverage-otel-only-completion-trips-the-cap", trips == ["token cap: measured and provisional 39459 >= 39459"],
929
+ f"{trips}")
930
+ early = lines[:-3] + [lines[-1], lines[-3], lines[-2]] # resp_m's otel completion read before its frames
931
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2})
932
+ for line in early:
933
+ m.line(line, 1.0)
934
+ control("otel-completion-read-before-its-frame-is-one-request", [(r["id"], r["state"]) for r in m.ledger.requests
935
+ if r["state"] == "measured"] == [("send#1", "measured"), ("send#2", "measured")],
936
+ f"{m.ledger.requests}")
937
+ # the caps see the reconciled ledger at the otel row itself: 11829 + 13610 spent, never that
938
+ # plus send#2's estimate (37268), so a cap between the two holds and one at the total trips
939
+ for name, cap, want in (("cap-between-the-total-and-a-double-count-holds", 30_000, []),
940
+ ("cap-at-the-reconciled-total-trips", 25_439, ["token cap: measured and provisional 25439 >= 25439"])):
941
+ trips = []
942
+ m = Monitor("codex", {"tokens": cap, "compactions": 2}, on_trip=trips.append)
943
+ for line in early:
944
+ m.line(line, 1.0)
945
+ control(f"otel-before-frame-{name}", trips == want, f"{trips} {m.ledger.requests}")
946
+ # a failed websocket attempt (its response started, then the stream dropped), its retry, and the
947
+ # retry's otel completion read before the retry's frames: the completion is the retry's, never
948
+ # the failed attempt's, so the cap sees warm-up + the failed attempt's estimate + the retry once
949
+ def failed_then_retried(warned):
950
+ c = deflater()
951
+ out = [lines[0], *written("2026-10-21T00:00:00.100000Z", c, create(root, "/root", "prewarm", None)),
952
+ received("2026-10-21T00:00:00.200000Z", "response.created", "resp_w", None),
953
+ received("2026-10-21T00:00:00.300000Z", "response.completed", "resp_w", None, 11814),
954
+ *written("2026-10-21T00:00:00.400000Z", c, create(root, "/root", "turn", "resp_w")),
955
+ received("2026-10-21T00:00:00.450000Z", "response.created", "resp_x", "resp_w")]
956
+ if warned:
957
+ out.append("2026-10-21T00:00:00.480000Z WARN codex_core::responses_retry: stream disconnected - retrying sampling request")
958
+ return out + [*written("2026-10-21T00:00:00.500000Z", c, create(root, "/root", "turn", "resp_w")),
959
+ '2026-10-21T00:00:00.610000Z INFO session_loop: codex_otel.log_only: event.name="codex.sse_event" '
960
+ f'event.kind=response.completed input_token_count=13595 output_token_count=15 cached_token_count=1000 '
961
+ f'cache_write_token_count=0 conversation.id={root} model=gpt-6-luna',
962
+ received("2026-10-21T00:00:00.620000Z", "response.created", "resp_m", "resp_w"),
963
+ received("2026-10-21T00:00:00.630000Z", "response.completed", "resp_m", "resp_w", 13595)]
964
+ for warned in (True, False):
965
+ how = "with-its-retry-warning" if warned else "known-only-by-its-retried-send"
966
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2})
967
+ for line in failed_then_retried(warned):
968
+ m.line(line, 1.0)
969
+ rows = [(r["id"], r["role"], r["state"], usages.request_total(r) if r["state"] == "measured" else r["estimate"])
970
+ for r in m.ledger.requests]
971
+ control(f"failed-attempt-{how}-never-takes-the-retrys-early-completion", rows == [
972
+ ("send#1", "warmup", "measured", 11829), ("send#2", "main", "provisional", 11829),
973
+ *([("retry#1", "unknown", "unresolved", None)] if warned else []), ("send#3", "main", "measured", 13610)], f"{rows}")
974
+ trips = []
975
+ m = Monitor("codex", {"tokens": 11829 + 11829 + 13610 + 1, "compactions": 2}, on_trip=trips.append)
976
+ for line in failed_then_retried(warned):
977
+ m.line(line, 1.0)
978
+ control(f"failed-attempt-{how}-cap-between-the-total-and-a-double-count-holds", trips == [], f"{trips}")
979
+ # two threads: B's attempt fails and is retried (the unscoped warning between) while A's turn
980
+ # completes otel-before-frame; the warning marks nothing, so A's early completion is A's, and
981
+ # the cap sees each request once
982
+ def two_threads():
983
+ a, b = deflater(), deflater()
984
+ return [lines[0], *written("2026-10-21T00:00:00.100000Z", a, create(root, "/root", "prewarm", None)),
985
+ received("2026-10-21T00:00:00.200000Z", "response.created", "resp_w", None),
986
+ received("2026-10-21T00:00:00.300000Z", "response.completed", "resp_w", None, 11814),
987
+ *written("2026-10-21T00:00:00.400000Z", a, create(root, "/root", "turn", "resp_w")),
988
+ *written("2026-10-21T00:00:00.410000Z", b, create(kid, "/root/kid", "turn", None, parent=root)),
989
+ "2026-10-21T00:00:00.480000Z WARN codex_core::responses_retry: stream disconnected - retrying sampling request",
990
+ *written("2026-10-21T00:00:00.490000Z", b, create(kid, "/root/kid", "turn", None, parent=root)),
991
+ '2026-10-21T00:00:00.610000Z INFO session_loop: codex_otel.log_only: event.name="codex.sse_event" '
992
+ f'event.kind=response.completed input_token_count=13595 output_token_count=15 cached_token_count=1000 '
993
+ f'cache_write_token_count=0 conversation.id={root} model=gpt-6-luna',
994
+ received("2026-10-21T00:00:00.620000Z", "response.created", "resp_m", "resp_w"),
995
+ received("2026-10-21T00:00:00.630000Z", "response.completed", "resp_m", "resp_w", 13595)]
996
+ m, peak = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2}), 0
997
+ for line in two_threads():
998
+ m.line(line, 1.0)
999
+ peak = max(peak, m.ledger.projected())
1000
+ rows = [(r["id"], r["role"], (r["agent"] or "")[-2:], r["state"], r.get("interrupted", False)) for r in m.ledger.requests]
1001
+ control("unscoped-retry-warning-marks-no-other-threads-request", rows == [
1002
+ ("send#1", "warmup", "0a", "measured", False), ("send#2", "main", "0a", "measured", False),
1003
+ ("send#3", "child", "0b", "unresolved", True), ("retry#1", "unknown", "", "unresolved", False),
1004
+ ("send#4", "child", "0b", "unresolved", False)] and peak == 11829 + 13610, f"{rows} peak {peak}")
1005
+ trips = []
1006
+ m = Monitor("codex", {"tokens": peak + 1, "compactions": 2}, on_trip=trips.append)
1007
+ for line in two_threads():
1008
+ m.line(line, 1.0)
1009
+ control("unscoped-retry-warning-cap-between-the-total-and-a-double-count-holds", trips == [], f"{trips}")
1010
+ # an otel completion measured onto the outstanding send, whose frame then reports other usage:
1011
+ # the otel row answered a request no frame shows (unknown kind), and the send is the frame's
1012
+ other = early[:-3] + [early[-3].replace("input_token_count=13595", "input_token_count=13000"), early[-2], early[-1]]
1013
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2})
1014
+ for line in other:
1015
+ m.line(line, 1.0)
1016
+ control("otel-completion-the-frame-contradicts-is-another-request", [(r["id"], r["role"], r["state"], usages.request_total(r))
1017
+ for r in m.ledger.requests if r["state"] == "measured"]
1018
+ == [("send#1", "warmup", "measured", 11829), ("send#2", "main", "measured", 13610), ("otel#4", "unknown", "measured", 13015)],
1019
+ f"{m.ledger.requests}")
1020
+ # a retry warning (design §3.2) is one failed post of unknown usage, whatever is in flight:
1021
+ # f-http-500-once's first post; beside f-http-sse-drop's dropped stream, a post of its own
1022
+ for case, at, want in (("f-http-500-once", 1, [("retry#1", "unresolved"), ("otel#2", "measured")]),
1023
+ ("f-http-sse-drop", 3, [("otel#1", "unresolved"), ("retry#1", "unresolved"), ("otel#3", "measured")])):
1024
+ lines_of = otel_lines(case)
1025
+ warned = lines_of[:at] + [lines_of[at][:27] + " WARN codex_core::responses_retry: retrying sampling request (1/5)"] + lines_of[at:]
1026
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 2})
1027
+ for line in warned:
1028
+ m.line(line, 1.0)
1029
+ control(f"retry-warning-in-the-live-ledger-{case}", [(r["id"], r["state"]) for r in m.ledger.requests] == want
1030
+ and sum(1 for r in m.feed.records if r["dir"] == "warn") == 1, f"{m.ledger.requests}")
1031
+
1032
+ # the estimate adds the new content since the agent's previous request (design §13.3)
1033
+ def tool_result(chars):
1034
+ return json.dumps({"type": "user", "message": {"role": "user", "content": [
1035
+ {"type": "tool_result", "tool_use_id": "t1", "content": "r" * chars}]}})
1036
+ for name, extra, tripped in (("without-new-content-under-the-cap", [], False),
1037
+ ("tool-result-content-trips-the-cap", [tool_result(3000)], True)):
1038
+ trips = []
1039
+ m = Monitor("claude", {"tokens": 7000, "compactions": 2}, on_trip=trips.append)
1040
+ for line in [status(), start("msg_1"), delta(48), *extra, status()]:
1041
+ m.line(line, 1.0)
1042
+ want = 3200 + (2 * 1000 if extra else 0)
1043
+ control(f"claude-estimate-{name}", m.ledger.requests[1]["estimate"] == want and bool(trips) == tripped,
1044
+ f"{m.ledger.requests[1]} {trips}")
1045
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
1046
+ m.transcript("a1", "subagent", {"type": "api-request", "timestamp": "2026-10-21T00:00:01.000Z"}, 1.0)
1047
+ m.transcript("a1", "subagent", {"type": "assistant", "message": {"stop_reason": "tool_use", "usage": {"input_tokens": 900, "output_tokens": 100}}}, 1.1)
1048
+ m.transcript("a1", "subagent", {"type": "user", "message": {"content": [{"type": "tool_result", "content": [{"type": "text", "text": "s" * 300}]}]}}, 1.2)
1049
+ m.transcript("a1", "subagent", {"type": "api-request", "timestamp": "2026-10-21T00:00:02.000Z"}, 1.3)
1050
+ control("subagent-estimate-adds-its-tool-result", m.ledger.requests[1]["estimate"] == 1000 + 2 * 100, f"{m.ledger.requests[1]}")
1051
+ c = deflater()
1052
+ turn = create(root, "/root", "turn", "resp_w")
1053
+ turn["input"] = [{"type": "function_call_output", "call_id": "c1", "output": "o" * 3000}]
1054
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 9})
1055
+ for line in [lines[0], *written("2026-10-21T00:00:00.100000Z", c, create(root, "/root", "prewarm", None)),
1056
+ received("2026-10-21T00:00:00.200000Z", "response.created", "resp_w", None),
1057
+ received("2026-10-21T00:00:00.300000Z", "response.completed", "resp_w", None, 11814),
1058
+ *written("2026-10-21T00:00:00.400000Z", c, turn)]:
1059
+ m.line(line, 1.0)
1060
+ control("codex-estimate-adds-the-request-input", [r["estimate"] for r in m.ledger.requests] == [None, 11829 + 2 * 1000],
1061
+ f"{m.ledger.requests}")
1062
+
1063
+ # outgoing evidence that cannot establish sending stays uncertain (design §13.2)
1064
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
1065
+ m.transcript("main", "main", {"type": "api-request"}, 99.0)
1066
+ problems, uncertain = boundary(m.ledger, freeze_at=100.0, kill_at=100.05)
1067
+ control("send-record-without-an-instant-read-before-the-freeze-is-clean", not problems and not uncertain, f"{problems} {uncertain}")
1068
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
1069
+ m.transcript("main", "main", {"type": "api-request"}, 100.2)
1070
+ problems, uncertain = boundary(m.ledger, freeze_at=100.0, kill_at=100.05)
1071
+ control("send-record-without-an-instant-read-after-the-freeze-is-uncertain", not problems and uncertain
1072
+ and uncertain[0].startswith("main#1: a send record with no host instant") and m.ledger.requests[0]["sent_at"] is None,
1073
+ f"{problems} {uncertain} {m.ledger.requests}")
1074
+ junk = ["2026-10-21T00:00:05.000000Z TRACE tungstenite::protocol::frame: writing frame", "opcode: TEXT",
1075
+ "reserved: true false false", "payload: 0x" + os.urandom(48).hex()]
1076
+ for name, freeze, want in (("before", 1792540806.0, False), ("after", 1792540804.0, True)):
1077
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 9})
1078
+ for line in junk:
1079
+ m.line(line, 1.0)
1080
+ problems, uncertain = boundary(m.ledger, freeze_at=freeze, kill_at=freeze + 0.05)
1081
+ control(f"undecodable-client-frame-written-{name}-the-freeze", not problems and bool(uncertain) == want
1082
+ and (not want or uncertain[0].startswith("undecoded#1: an undecodable client frame"))
1083
+ and any(r.get("type") == "undecodable_frame" for r in m.feed.records), f"{problems} {uncertain} {m.feed.records}")
1084
+ # a frame header whose payload never followed: the next timestamped record came first, or the
1085
+ # trace ended (the readers drained, Monitor.finish); kept as a record and uncertain past the freeze
1086
+ header = junk[:3]
1087
+ interrupted = header + ["2026-10-21T00:00:05.100000Z INFO session_loop: codex_otel.log_only: event.name=\"codex.api_request\" "
1088
+ "http.response.status_code=200 attempt=0 endpoint=/models"]
1089
+ for name, trace, finish in (("interrupted-by-a-timestamped-record", interrupted, False), ("cut-at-the-end-of-the-trace", header, True)):
1090
+ for side, freeze, want in (("before", 1792540806.0, False), ("after", 1792540804.0, True)):
1091
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 9})
1092
+ for line in trace:
1093
+ m.line(line, 1.0)
1094
+ if finish:
1095
+ m.finish(1.0)
1096
+ problems, uncertain = boundary(m.ledger, freeze_at=freeze, kill_at=freeze + 0.05)
1097
+ control(f"frame-header-{name}-written-{side}-the-freeze", not problems and bool(uncertain) == want
1098
+ and (not want or uncertain[0].startswith("truncated#1: a client frame header whose payload was never read "
1099
+ "written at 1792540805.000000"))
1100
+ and [r["type"] for r in m.feed.records if r["dir"] == "info"] == ["truncated_frame"],
1101
+ f"{problems} {uncertain} {m.feed.records}")
1102
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 9})
1103
+ for line in ["2026-10-21T00:00:05.000000Z TRACE tungstenite::protocol::frame: writing frame", "opcode: PING"]:
1104
+ m.line(line, 1.0)
1105
+ m.finish(1.0)
1106
+ control("non-text-frame-header-cut-at-the-end-is-no-request", not m.ledger.sends and not m.feed.records, f"{m.ledger.sends}")
1107
+
1108
+ # a structured provider signal is passed on the moment it is read
1109
+ seen = []
1110
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9}, on_signal=seen.append)
1111
+ m.line(json.dumps({"type": "rate_limit_event", "rate_limit_info": {"status": "allowed"}}), 1.0)
1112
+ control("allowed-rate-limit-signals-nothing", seen == [], f"{seen}")
1113
+ m.line(json.dumps({"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": 5}}), 1.0)
1114
+ control("claude-limit-signalled-as-read", [[s["source"] for s in batch] for batch in seen] == [["rate_limit_event"]], f"{seen}")
1115
+ # the host's cap overrun read in flight (WP-03v dw5, the recorded cap16 result): no signal at the
1116
+ # call's own declared cap; without its api_error_status field, or with no cap passed, a provider stop
1117
+ overrun = json.loads((replay_root / "claude-runner"
1118
+ / "cap16-overrun" / "result.json").read_text(encoding="utf-8"))
1119
+ for name, result, cap, want in (("cap-overrun-at-the-declared-cap-signals-nothing-in-flight", overrun, 16, []),
1120
+ ("cap-overrun-without-its-status-field-signals-in-flight",
1121
+ {k: v for k, v in overrun.items() if k != "api_error_status"}, 16, [["result.api_error"]]),
1122
+ ("cap-overrun-without-a-passed-cap-signals-in-flight", overrun, None, [["result.api_error"]])):
1123
+ seen = []
1124
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9}, on_signal=seen.append, output_cap=cap)
1125
+ m.line(json.dumps(result), 1.0)
1126
+ control(name, [[s["source"] for s in batch] for batch in seen] == want, f"{seen}")
1127
+ seen = []
1128
+ m = Monitor("codex", {"tokens": 10 ** 9, "compactions": 9}, on_signal=seen.append)
1129
+ m.line('2026-10-21T00:00:01.000000Z TRACE tungstenite::protocol: Received message '
1130
+ + json.dumps({"type": "error", "status": 429, "error": {"type": "usage_limit_reached", "code": "usage_limit_reached"}}), 1.0)
1131
+ control("codex-limit-signalled-as-read", [[s["source"] for s in batch] for batch in seen] == [["error frame"]], f"{seen}")
1132
+
1133
+ # contract fidelity: the boundary's codes, copied here once from design §13.2 and plan WP-02
1134
+ # done-when 5: a send after the verified freeze, and a freeze that was not verified
1135
+ from runlib import stop
1136
+ source = pathlib.Path(__file__).read_text(encoding="utf-8")
1137
+ design = {"STOP_BOUNDARY_VIOLATED", "STOP_BOUNDARY_UNVERIFIED"}
1138
+ control("contract-cites-design-13-2", CONTRACT["$comment"].startswith("design §13.2"), CONTRACT["$comment"])
1139
+ control("boundary-codes-are-design-13-2", stop.problem_codes(source, "boundary") == design
1140
+ and "uncertain" in {n.func.value.id for n in ast.walk(ast.parse(source)) if isinstance(n, ast.Call)
1141
+ and isinstance(n.func, ast.Attribute) and n.func.attr == "append" and isinstance(n.func.value, ast.Name)},
1142
+ f"{stop.problem_codes(source, 'boundary')}")
1143
+ planted = source.replace(' problems.append("STOP_BOUNDARY_UNVERIFIED', ' problems.append(f"STOP_PLANTED {kill_at}")\n'
1144
+ ' problems.append("STOP_BOUNDARY_UNVERIFIED', 1)
1145
+ dropped = source.replace('problems.append(f"STOP_BOUNDARY_VIOLATED', 'uncertain.append(f"STOP_BOUNDARY_VIOLATED', 1)
1146
+ control("an-added-boundary-code-is-detected", planted != source and stop.problem_codes(planted, "boundary") - design == {"STOP_PLANTED"},
1147
+ f"{stop.problem_codes(planted, 'boundary')}")
1148
+ control("a-removed-boundary-code-is-detected", dropped != source
1149
+ and design - stop.problem_codes(dropped, "boundary") == {"STOP_BOUNDARY_VIOLATED"}, f"{stop.problem_codes(dropped, 'boundary')}")
1150
+
1151
+ # the transcript tail reads complete records only, once each
1152
+ with tempfile.TemporaryDirectory() as td:
1153
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
1154
+ tail = TranscriptTail(td, m)
1155
+ sub = pathlib.Path(td) / "projects" / "cell" / "s1" / "subagents" / "agent-a7.jsonl"
1156
+ sub.parent.mkdir(parents=True)
1157
+ sub.write_text(json.dumps({"type": "api-request", "timestamp": "2026-10-21T00:00:01.000Z"}) + "\n{\"type\": \"assis", encoding="utf-8")
1158
+ tail.poll()
1159
+ tail.poll()
1160
+ control("tail-feeds-complete-records-once", [r["agent"] for r in m.ledger.requests] == ["a7"], f"{m.ledger.requests}")
1161
+ m = Monitor("claude", {"tokens": 10 ** 9, "compactions": 9})
1162
+ stream = StreamTail(pathlib.Path(td) / "stream.jsonl", m)
1163
+ stream.poll()
1164
+ (pathlib.Path(td) / "stream.jsonl").write_text(status() + "\n" + start("msg_1")[:20], encoding="utf-8")
1165
+ stream.poll()
1166
+ stream.poll()
1167
+ control("stream-tail-feeds-complete-lines-once", [r["id"] for r in m.ledger.requests] == ["main#1"], f"{m.ledger.requests}")
1168
+
1169
+ for failure in failures:
1170
+ print(f"monitor --self-test [FAIL] {failure}")
1171
+ if failures:
1172
+ return 1
1173
+ print(f"monitor --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + ")")
1174
+ return 0
1175
+
1176
+
1177
+ if __name__ == "__main__":
1178
+ if "--self-test" not in sys.argv[1:]:
1179
+ sys.exit("usage: monitor.py --self-test")
1180
+ sys.exit(self_test())