@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,1186 @@
1
+ #!/usr/bin/env python3
2
+ """Codex session JSONL adapter for Token Optimizer.
3
+
4
+ Codex stores session logs in a different JSONL shape than Claude Code. This
5
+ module normalizes the parts Token Optimizer needs so the mature quality,
6
+ trends, and dashboard pipeline can stay shared.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import heapq
12
+ import itertools
13
+ import json
14
+ import sqlite3
15
+ import re
16
+ from collections import deque
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from runtime_env import codex_home
22
+
23
+ CHARS_PER_TOKEN = 4
24
+ MAX_PARSE_FILE_BYTES = 96 * 1024 * 1024
25
+ LARGE_FILE_TAIL_BYTES = 8 * 1024 * 1024
26
+ MAX_JSONL_LINE_CHARS = 8 * 1024 * 1024
27
+ _UNKNOWN_MODEL = "unknown"
28
+ _DEFAULT_MODEL = "codex"
29
+ TOOL_ALIASES = {
30
+ "exec_command": "Bash",
31
+ "apply_patch": "Edit",
32
+ "write_stdin": "Bash",
33
+ "spawn_agent": "Task",
34
+ "wait_agent": "Task",
35
+ "close_agent": "Task",
36
+ "view_image": "ViewImage",
37
+ }
38
+
39
+ READ_CMD_RE = re.compile(r"\b(?:cat|sed|nl|head|tail|less|rg|grep)\b")
40
+ PATCH_FILE_RE = re.compile(r"^\*\*\* (?:Add|Update|Delete) File: (.+)$", re.MULTILINE)
41
+ _ERROR_RE = re.compile(r"\b(error|failed|traceback|exception|permission denied|not found)\b", re.IGNORECASE)
42
+
43
+
44
+ def _payload(record: dict[str, Any]) -> dict[str, Any]:
45
+ payload = record.get("payload")
46
+ return payload if isinstance(payload, dict) else {}
47
+
48
+
49
+ def _parse_ts(value: Any) -> datetime | None:
50
+ if not value:
51
+ return None
52
+ try:
53
+ if isinstance(value, (int, float)):
54
+ return datetime.fromtimestamp(value, tz=timezone.utc)
55
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
56
+ except (OSError, ValueError, TypeError):
57
+ return None
58
+
59
+
60
+ def _extract_text(payload: dict[str, Any]) -> str:
61
+ payload_type = payload.get("type")
62
+ if payload_type in {"user_message", "agent_message"}:
63
+ return str(payload.get("message") or "")
64
+ content = payload.get("content")
65
+ if isinstance(content, str):
66
+ return content
67
+ if isinstance(content, list):
68
+ parts = []
69
+ for item in content:
70
+ if isinstance(item, str):
71
+ parts.append(item)
72
+ elif isinstance(item, dict):
73
+ text = item.get("text")
74
+ if isinstance(text, str):
75
+ parts.append(text)
76
+ return "\n".join(parts)
77
+ return ""
78
+
79
+
80
+ def _parse_arguments(payload: dict[str, Any]) -> dict[str, Any]:
81
+ raw = payload.get("arguments")
82
+ if isinstance(raw, dict):
83
+ return raw
84
+ if not isinstance(raw, str) or not raw.strip():
85
+ return {}
86
+ try:
87
+ parsed = json.loads(raw)
88
+ except json.JSONDecodeError:
89
+ return {}
90
+ return parsed if isinstance(parsed, dict) else {}
91
+
92
+
93
+ def _tool_name(name: str) -> str:
94
+ return TOOL_ALIASES.get(name, name or "unknown")
95
+
96
+
97
+ def _extract_model(payload: dict[str, Any]) -> str | None:
98
+ model = payload.get("model")
99
+ if isinstance(model, str) and model.strip():
100
+ return model.strip()
101
+ settings = payload.get('thread_settings')
102
+ if isinstance(settings, dict):
103
+ model = settings.get('model')
104
+ if isinstance(model, str) and model.strip():
105
+ return model.strip()
106
+ collaboration = payload.get("collaboration_mode")
107
+ if isinstance(collaboration, dict):
108
+ settings = collaboration.get("settings")
109
+ if isinstance(settings, dict):
110
+ model = settings.get("model")
111
+ if isinstance(model, str) and model.strip():
112
+ return model.strip()
113
+ return None
114
+
115
+
116
+ def _estimate_tokens(text: str | int) -> int:
117
+ if isinstance(text, int):
118
+ return max(0, text // CHARS_PER_TOKEN)
119
+ return max(0, len(text.encode("utf-8", errors="replace")) // CHARS_PER_TOKEN)
120
+
121
+
122
+ def _safe_int(value: Any) -> int:
123
+ try:
124
+ return int(float(value or 0))
125
+ except (TypeError, ValueError, OverflowError):
126
+ return 0
127
+
128
+
129
+ def _iter_json_records(filepath: str | Path, *, skip_large_file: bool = True):
130
+ """Yield parsed JSONL records without letting pathological logs dominate.
131
+
132
+ Codex can occasionally leave multi-GB session files or individual records
133
+ with enormous embedded tool output. Dashboard and hook refresh paths need
134
+ bounded work more than perfect telemetry from those outlier transcripts.
135
+ """
136
+ path = Path(filepath)
137
+ try:
138
+ with path.open("rb") as handle:
139
+ size = path.stat().st_size
140
+ if skip_large_file and size > MAX_PARSE_FILE_BYTES:
141
+ # Keep identity, but never attribute the omitted interval to
142
+ # the model from the first turn. Only recent usage is sampled.
143
+ head = handle.readline(65536)
144
+ try:
145
+ meta = json.loads(head)
146
+ if isinstance(meta, dict) and meta.get('type') == 'session_meta':
147
+ yield meta
148
+ except (ValueError, UnicodeError):
149
+ pass
150
+ offset = max(handle.tell(), size - LARGE_FILE_TAIL_BYTES)
151
+ handle.seek(max(0, offset - 1))
152
+ if offset and handle.read(1) != b'\n':
153
+ while True:
154
+ fragment = handle.readline(65536)
155
+ if not fragment or fragment.endswith(b'\n'):
156
+ break
157
+ while True:
158
+ line = handle.readline(MAX_JSONL_LINE_CHARS + 1)
159
+ if not line:
160
+ break
161
+ if len(line) > MAX_JSONL_LINE_CHARS:
162
+ while line and not line.endswith(b'\n'):
163
+ line = handle.readline(65536)
164
+ continue
165
+ try:
166
+ record = json.loads(line)
167
+ except (ValueError, UnicodeError):
168
+ continue
169
+ if isinstance(record, dict):
170
+ yield record
171
+ except (PermissionError, OSError):
172
+ return
173
+
174
+
175
+ def _token_usage(payload: dict[str, Any], *, cumulative: bool = True) -> dict[str, int] | None:
176
+ info = payload.get("info")
177
+ if not isinstance(info, dict):
178
+ return None
179
+ usage_key = "total_token_usage" if cumulative else "last_token_usage"
180
+ fallback_key = "last_token_usage" if cumulative else "total_token_usage"
181
+ usage = info.get(usage_key) or info.get(fallback_key)
182
+ if not isinstance(usage, dict):
183
+ return None
184
+ return {
185
+ "input_tokens": _safe_int(usage.get("input_tokens")),
186
+ "cached_input_tokens": _safe_int(usage.get("cached_input_tokens")),
187
+ "output_tokens": _safe_int(usage.get("output_tokens")),
188
+ "reasoning_output_tokens": _safe_int(usage.get("reasoning_output_tokens")),
189
+ "total_tokens": _safe_int(usage.get("total_tokens")),
190
+ "model_context_window": _safe_int(info.get("model_context_window")),
191
+ }
192
+
193
+
194
+ _TOPIC_PREFIXES = (
195
+ "implement the following plan:",
196
+ "please implement",
197
+ "can you help me",
198
+ "i need help with",
199
+ "help me",
200
+ "i want to",
201
+ "i'd like to",
202
+ )
203
+
204
+
205
+ def _extract_topic(text: str) -> str | None:
206
+ text = " ".join(text.split())
207
+ if not text:
208
+ return None
209
+ lower = text.lower()
210
+ for prefix in _TOPIC_PREFIXES:
211
+ if lower.startswith(prefix):
212
+ text = text[len(prefix):].strip()
213
+ break
214
+ if text.startswith("# "):
215
+ first_line = text.split("\n", 1)[0]
216
+ text = first_line.lstrip("# ").strip()
217
+ if not text:
218
+ return None
219
+ # User-derived text that is persisted (session_log/quality cache) and
220
+ # rendered into checkpoints — redact credentials, or drop the topic if
221
+ # the shared redactor is unavailable/refuses. Redact BEFORE truncating:
222
+ # a secret straddling the cut is a prefix no pattern recognises.
223
+ try:
224
+ from credential_patterns import redact_credentials as _topic_redact
225
+ text = _topic_redact(text)
226
+ except Exception:
227
+ return None
228
+ if len(text) > 120:
229
+ text = text[:117] + "..."
230
+ return text
231
+
232
+
233
+ def _safe_session_id(value: str | None) -> str:
234
+ if not value:
235
+ return ""
236
+ sanitized = re.sub(r"[^a-zA-Z0-9_-]", "", value)
237
+ match = re.fullmatch(r'rollout-.*-([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})', sanitized)
238
+ if match:
239
+ return match.group(1)
240
+ return sanitized if len(sanitized) >= 6 else ""
241
+
242
+
243
+ def resolve_session(transcript_path=None, session_id=None):
244
+ """Resolve a known task without ever substituting another active task."""
245
+ sid = _safe_session_id(session_id)
246
+ if transcript_path:
247
+ p = Path(transcript_path)
248
+ if p.is_file():
249
+ if not sid or _safe_session_id(p.stem) == sid or _session_meta_id(p) == sid:
250
+ return p
251
+ # The transcript exists but names a different session: falling
252
+ # through to find_session_jsonl_by_id would substitute another
253
+ # task's log and attribute its costs to this hook. Refuse.
254
+ return None
255
+ if sid:
256
+ return find_session_jsonl_by_id(sid)
257
+ return None
258
+
259
+
260
+ def _looks_like_error_text(text: str) -> bool:
261
+ return bool(_ERROR_RE.search(text))
262
+
263
+
264
+ def session_roots() -> tuple[Path, ...]:
265
+ home = codex_home()
266
+ return (home / "sessions", home / "archived_sessions")
267
+
268
+
269
+ def is_codex_session_path(path: str | Path) -> bool:
270
+ p = Path(path).expanduser()
271
+ try:
272
+ resolved = p.resolve(strict=False)
273
+ return any(resolved.is_relative_to(root.resolve(strict=False)) for root in session_roots())
274
+ except (OSError, ValueError):
275
+ return False
276
+
277
+
278
+ def find_all_jsonl_files(days: int = 30, max_files: int = 500) -> list[tuple[Path, float, str]]:
279
+ cutoff = datetime.now(timezone.utc).timestamp() - (days * 86400)
280
+ results: list[tuple[Path, float]] = []
281
+ for root in session_roots():
282
+ if not root.exists():
283
+ continue
284
+ for jf in root.rglob("*.jsonl"):
285
+ try:
286
+ mtime = jf.stat().st_mtime
287
+ except OSError:
288
+ continue
289
+ if mtime < cutoff:
290
+ continue
291
+ results.append((jf, mtime))
292
+ # Limit after ordering, not before: rglob often returns old date folders
293
+ # first. Read metadata only for the selected files.
294
+ newest = heapq.nlargest(max_files, results, key=lambda item: item[1])
295
+ return [(jf, mtime, _project_name_from_file(jf)) for jf, mtime in newest]
296
+
297
+
298
+ def find_session_jsonl_by_id(session_id: str) -> Path | None:
299
+ safe_id = _safe_session_id(session_id)
300
+ if not safe_id:
301
+ return None
302
+ exact_matches: list[Path] = []
303
+ for root in session_roots():
304
+ if not root.exists():
305
+ continue
306
+ for jf in itertools.islice(root.rglob(f"*{safe_id}*.jsonl"), 50):
307
+ meta_id = _session_meta_id(jf)
308
+ if _safe_session_id(jf.stem) == safe_id or meta_id == safe_id:
309
+ exact_matches.append(jf)
310
+ if not exact_matches:
311
+ return None
312
+ exact_matches.sort(key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True)
313
+ return exact_matches[0]
314
+
315
+
316
+ _ROLLOUT_STEM_RE = re.compile(
317
+ r'rollout-.*-([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})'
318
+ )
319
+
320
+
321
+ def _raw_session_meta_id(path: Path) -> str | None:
322
+ """session_meta id exactly as written (no normalization)."""
323
+ for record in _iter_json_records(path, skip_large_file=True):
324
+ if record.get("type") != "session_meta":
325
+ continue
326
+ value = _payload(record).get("id")
327
+ return str(value) if value else None
328
+ return None
329
+
330
+
331
+ def find_session_jsonl_exact(thread_id: str) -> Path | None:
332
+ """Resolve the transcript for exactly ``thread_id``; never normalized.
333
+
334
+ Unlike ``find_session_jsonl_by_id`` (an explicit-session convenience that
335
+ strips ``rollout-`` prefixes and illegal characters), this is for the
336
+ invoking-thread identity, where silently changing the id would bind to a
337
+ different thread. A candidate is accepted only when:
338
+ * it is a regular file inside a sessions root (no symlinks out),
339
+ * its raw ``session_meta`` id equals ``thread_id``; a file with no
340
+ readable ``session_meta`` falls back to its exact stem / the UUID
341
+ suffix of a ``rollout-<ts>-<uuid>`` stem, and
342
+ * its name is not a ``rollout-UNKNOWN-`` placeholder.
343
+ Ties resolve deterministically (newest mtime, then path).
344
+ """
345
+ if not thread_id or not re.fullmatch(r"[A-Za-z0-9_-]{6,128}", thread_id):
346
+ return None
347
+ matches: list[tuple[float, str, Path]] = []
348
+ for root in session_roots():
349
+ if not root.exists():
350
+ continue
351
+ try:
352
+ root_real = root.resolve()
353
+ except OSError:
354
+ continue
355
+ for jf in root.rglob(f"*{thread_id}*.jsonl"):
356
+ try:
357
+ if jf.is_symlink() or not jf.is_file():
358
+ continue
359
+ if root_real not in jf.resolve().parents:
360
+ continue
361
+ if jf.stem.startswith("rollout-UNKNOWN-"):
362
+ continue
363
+ meta_id = _raw_session_meta_id(jf)
364
+ if meta_id is not None:
365
+ ok = meta_id == thread_id
366
+ else:
367
+ m = _ROLLOUT_STEM_RE.fullmatch(jf.stem)
368
+ ok = (m.group(1) if m else jf.stem) == thread_id
369
+ if ok:
370
+ matches.append((jf.stat().st_mtime, str(jf), jf))
371
+ except OSError:
372
+ continue
373
+ if not matches:
374
+ return None
375
+ matches.sort(key=lambda t: (-t[0], t[1]))
376
+ return matches[0][2]
377
+
378
+
379
+ def _session_meta_id(path: Path) -> str | None:
380
+ for record in _iter_json_records(path, skip_large_file=True):
381
+ if record.get("type") != "session_meta":
382
+ continue
383
+ value = _payload(record).get("id")
384
+ return _safe_session_id(str(value)) if value else None
385
+ return None
386
+
387
+
388
+ def _project_name_from_file(path: Path) -> str:
389
+ for record in _iter_json_records(path, skip_large_file=True):
390
+ if record.get("type") != "session_meta":
391
+ continue
392
+ cwd = _payload(record).get("cwd")
393
+ if cwd:
394
+ return Path(str(cwd)).name or str(cwd)
395
+ break
396
+ return path.parent.name
397
+
398
+
399
+ def parse_session_jsonl(filepath: str | Path) -> dict[str, Any] | None:
400
+ try:
401
+ large = Path(filepath).stat().st_size > MAX_PARSE_FILE_BYTES
402
+ except OSError:
403
+ return None
404
+ if large:
405
+ try:
406
+ import codex_log_index
407
+ records, info = codex_log_index.records(filepath)
408
+ result = _parse_session_records(records, incomplete=info['incomplete'])
409
+ if result:
410
+ result.update(info)
411
+ return result
412
+ except (OSError, ValueError, sqlite3.Error):
413
+ # Contention must not stall a hook. A tail fallback remains labelled.
414
+ return _parse_session_records(_iter_json_records(filepath), incomplete=True, sampled=True)
415
+ return _parse_session_records(_iter_json_records(filepath))
416
+
417
+
418
+ def _parse_session_records(records, incomplete=False, sampled=False):
419
+ skills_used: dict[str, int] = {}
420
+ subagents_used: dict[str, int] = {}
421
+ tool_calls: dict[str, int] = {}
422
+ model_usage: dict[str, int] = {}
423
+ model_usage_breakdown: dict[str, dict[str, int]] = {}
424
+ version = None
425
+ slug = None
426
+ topic = None
427
+ first_ts = None
428
+ last_ts = None
429
+ message_count = 0
430
+ api_calls = 0
431
+ input_text_chars = 0
432
+ output_text_chars = 0
433
+ tool_output_chars = 0
434
+ last_usage: dict[str, int] | None = None
435
+ previous_usage: dict[str, int] | None = None
436
+ current_model = _UNKNOWN_MODEL
437
+ per_model_usage: dict[str, dict[str, int]] = {}
438
+ rate_limits_latest: dict[str, Any] | None = None
439
+ effort_counts: dict[str, int] = {}
440
+ tool_durations_ms: list[float] = []
441
+ task_durations_ms: list[float] = []
442
+ ttft_ms: list[float] = []
443
+
444
+ for record in records:
445
+ payload = _payload(record)
446
+ payload_type = payload.get("type")
447
+
448
+ ts = _parse_ts(record.get("timestamp") or payload.get("timestamp"))
449
+ if ts:
450
+ first_ts = first_ts or ts
451
+ last_ts = ts
452
+
453
+ if record.get("type") == "session_meta":
454
+ version = version or payload.get("cli_version")
455
+ slug = slug or payload.get("id")
456
+ elif record.get("type") == "turn_context":
457
+ effort = payload.get("effort")
458
+ if isinstance(effort, str) and effort.strip():
459
+ effort_counts[effort.strip()] = effort_counts.get(effort.strip(), 0) + 1
460
+
461
+ model = _extract_model(payload)
462
+ if model:
463
+ current_model = model
464
+
465
+ if payload_type == "token_count":
466
+ usage = _token_usage(payload, cumulative=True)
467
+ if usage:
468
+ last_usage = usage
469
+ rl = _extract_rate_limits(payload)
470
+ if rl:
471
+ rate_limits_latest = rl
472
+ rate_limits_latest['observed_at'] = record.get('timestamp')
473
+ turn_usage = _token_usage(payload, cumulative=False)
474
+ # token_count also repeats the previous usage when only rate
475
+ # limits change. Cumulative deltas count each API response once.
476
+ info = payload.get('info') or {}
477
+ if usage and info.get('total_token_usage'):
478
+ has_last = isinstance(info.get('last_token_usage'), dict)
479
+ if previous_usage and usage['input_tokens'] < previous_usage['input_tokens']:
480
+ # Cumulative decreased (compaction reset, session resume
481
+ # boundary, or a Codex quirk). The cumulative total is NOT
482
+ # this call's work — it includes tokens from before the
483
+ # reset. If last_token_usage is available, use it (per-
484
+ # call, correct). If not, skip this record entirely rather
485
+ # than attributing the full cumulative to one call (which
486
+ # would over-count by the entire pre-reset total).
487
+ # Keep previous_usage at the pre-decrease baseline so the
488
+ # next delta is computed against the correct reference.
489
+ if not has_last:
490
+ turn_usage = None
491
+ # Do NOT update previous_usage on decrease.
492
+ else:
493
+ if previous_usage and usage['input_tokens'] >= previous_usage['input_tokens']:
494
+ turn_usage = {k: max(0, usage[k] - previous_usage[k])
495
+ for k in ('input_tokens', 'cached_input_tokens', 'output_tokens', 'reasoning_output_tokens')}
496
+ elif not has_last:
497
+ # First record seen with no last_token_usage (resumed
498
+ # session, or a tail pass that begins mid-stream):
499
+ # cumulative totals are not this call's usage, but we
500
+ # have no per-request value. Fall back to the full
501
+ # cumulative figure as the best available estimate.
502
+ turn_usage = usage
503
+ previous_usage = usage
504
+ if turn_usage:
505
+ model_key = current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL
506
+ bucket = per_model_usage.setdefault(
507
+ model_key,
508
+ {"fresh_input": 0, "cache_read": 0, "cache_create": 0, "output": 0},
509
+ )
510
+ bucket["fresh_input"] += max(0, turn_usage["input_tokens"] - turn_usage["cached_input_tokens"])
511
+ bucket["cache_read"] += max(0, turn_usage["cached_input_tokens"])
512
+ bucket["output"] += max(0, turn_usage["output_tokens"])
513
+ if turn_usage['input_tokens'] or turn_usage['output_tokens']:
514
+ bucket.setdefault('requests', []).append({
515
+ 'fresh_input': max(0, turn_usage['input_tokens'] - turn_usage['cached_input_tokens']),
516
+ 'cache_read': max(0, turn_usage['cached_input_tokens']),
517
+ 'output': max(0, turn_usage['output_tokens']),
518
+ })
519
+
520
+ elif payload_type == "collab_agent_spawn_end":
521
+ # Modern subagent spawn. The legacy spawn_agent function_call path
522
+ # below also counts subagents; a session that spans a mid-session
523
+ # Codex upgrade (rare) could emit both and double-count.
524
+ role = str(payload.get("new_agent_role") or payload.get("new_agent_nickname") or "subagent")
525
+ subagents_used[role] = subagents_used.get(role, 0) + 1
526
+ tool_calls["Task"] = tool_calls.get("Task", 0) + 1
527
+
528
+ elif payload_type == "task_complete":
529
+ _append_positive(task_durations_ms, payload.get("duration_ms"))
530
+ _append_positive(ttft_ms, payload.get("time_to_first_token_ms"))
531
+
532
+ elif payload_type in {"user_message", "message", "agent_message"}:
533
+ text = _extract_text(payload)
534
+ text_chars = payload.get('_optimizer_chars', len(text))
535
+ role = payload.get("role")
536
+ if payload_type == "user_message" or role == "user":
537
+ topic = topic or _extract_topic(text)
538
+ input_text_chars += text_chars
539
+ elif payload_type == "agent_message" or role == "assistant":
540
+ output_text_chars += text_chars
541
+ else:
542
+ input_text_chars += text_chars
543
+ message_count += 1
544
+
545
+ elif payload_type in {"function_call", "custom_tool_call"}:
546
+ raw_name = str(payload.get("name") or "unknown")
547
+ name = _tool_name(raw_name)
548
+ tool_calls[name] = tool_calls.get(name, 0) + 1
549
+ api_calls += 1
550
+ if raw_name == "spawn_agent":
551
+ args = _parse_arguments(payload)
552
+ agent_type = str(args.get("agent_type") or "default")
553
+ subagents_used[agent_type] = subagents_used.get(agent_type, 0) + 1
554
+
555
+ elif payload_type in {"function_call_output", "custom_tool_call_output"}:
556
+ tool_output_chars += payload.get('_optimizer_output_chars', len(str(payload.get("output") or "")))
557
+ elif payload_type in {"exec_command_end", "patch_apply_end"}:
558
+ tool_output_chars += payload.get('_optimizer_output_chars', len(_event_output_text(payload)))
559
+ _append_duration(tool_durations_ms, payload.get("duration"))
560
+ elif payload_type == "mcp_tool_call_end":
561
+ _append_duration(tool_durations_ms, payload.get("duration"))
562
+
563
+ if message_count == 0 and api_calls == 0 and not last_usage:
564
+ return None
565
+
566
+ wall_duration_minutes = 0
567
+ if first_ts and last_ts:
568
+ wall_duration_minutes = max(0, (last_ts - first_ts).total_seconds() / 60)
569
+ # Resumed tasks can span weeks. Elapsed wall time is not active work.
570
+ if task_durations_ms:
571
+ duration_minutes = sum(task_durations_ms) / 60000
572
+ duration_source = "task_complete"
573
+ elif wall_duration_minutes:
574
+ duration_minutes = wall_duration_minutes
575
+ duration_source = "wall"
576
+ else:
577
+ duration_minutes = 0
578
+ duration_source = "unavailable"
579
+
580
+ if last_usage:
581
+ fresh_input = sum(p['fresh_input'] for p in per_model_usage.values())
582
+ cache_read = sum(p['cache_read'] for p in per_model_usage.values())
583
+ estimated_input = fresh_input + cache_read
584
+ estimated_output = sum(p['output'] for p in per_model_usage.values())
585
+ token_source = "codex_token_count"
586
+ else:
587
+ fresh_input = _estimate_tokens(input_text_chars + tool_output_chars)
588
+ cache_read = 0
589
+ estimated_input = fresh_input
590
+ estimated_output = _estimate_tokens(output_text_chars)
591
+ token_source = "char_estimate"
592
+
593
+ if per_model_usage:
594
+ model_usage_breakdown = per_model_usage
595
+ for model, parts in model_usage_breakdown.items():
596
+ model_usage[model] = parts["fresh_input"] + parts["cache_create"] + parts["output"]
597
+ else:
598
+ model = current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL
599
+ billable_estimate = fresh_input + estimated_output
600
+ model_usage[model] = billable_estimate
601
+ model_usage_breakdown[model] = {
602
+ "fresh_input": fresh_input,
603
+ "cache_read": cache_read,
604
+ "cache_create": 0,
605
+ "output": estimated_output,
606
+ }
607
+
608
+ return {
609
+ "incomplete": incomplete,
610
+ "scan_mode": "recent_tail" if incomplete else "full",
611
+ "version": version,
612
+ "slug": slug,
613
+ "topic": topic,
614
+ "duration_minutes": duration_minutes,
615
+ "wall_duration_minutes": wall_duration_minutes,
616
+ "duration_source": duration_source,
617
+ "total_input_tokens": estimated_input,
618
+ "total_output_tokens": estimated_output,
619
+ "total_cache_read": cache_read,
620
+ "total_cache_create": 0,
621
+ "total_cache_create_1h": 0,
622
+ "total_cache_create_5m": 0,
623
+ "model_context_window": last_usage["model_context_window"] if last_usage else None,
624
+ "cache_hit_rate": max(0.0, min(1.0, cache_read / estimated_input)) if estimated_input else 0.0,
625
+ "avg_call_gap_seconds": None,
626
+ "max_call_gap_seconds": None,
627
+ "p95_call_gap_seconds": None,
628
+ "model_usage": model_usage,
629
+ "model_usage_breakdown": model_usage_breakdown,
630
+ "skills_used": skills_used,
631
+ "subagents_used": subagents_used,
632
+ "tool_calls": tool_calls,
633
+ "message_count": message_count,
634
+ "api_calls": api_calls,
635
+ "first_ts": first_ts.isoformat() if first_ts else None,
636
+ "estimated": token_source != "codex_token_count",
637
+ "runtime": "codex",
638
+ "token_source": token_source,
639
+ "rate_limits": rate_limits_latest,
640
+ "effort": max(effort_counts, key=effort_counts.get) if effort_counts else None,
641
+ "effort_breakdown": dict(effort_counts),
642
+ "tool_duration_p90_ms": _percentile(tool_durations_ms, 90),
643
+ "task_duration_ms_max": max(task_durations_ms) if task_durations_ms else None,
644
+ "ttft_ms_avg": round(sum(ttft_ms) / len(ttft_ms), 1) if ttft_ms else None,
645
+ }
646
+
647
+
648
+ def parse_session_turns(filepath: str | Path) -> list[dict[str, Any]]:
649
+ turns: list[dict[str, Any]] = []
650
+ pending_tools: list[str] = []
651
+ pending_usage: dict[str, int] | None = None
652
+ current_model = _UNKNOWN_MODEL
653
+ turn_index = 0
654
+ for record in _iter_json_records(filepath):
655
+ payload = _payload(record)
656
+ payload_type = payload.get("type")
657
+ model = _extract_model(payload)
658
+ if model:
659
+ current_model = model
660
+ if payload_type in {"function_call", "custom_tool_call"}:
661
+ pending_tools.append(_tool_name(str(payload.get("name") or "unknown")))
662
+ elif payload_type == "token_count":
663
+ usage = _token_usage(payload, cumulative=False)
664
+ if usage:
665
+ if turns:
666
+ turn = turns[-1]
667
+ turn["input_tokens"] = usage["input_tokens"]
668
+ turn["output_tokens"] = usage["output_tokens"]
669
+ turn["cache_read"] = usage["cached_input_tokens"]
670
+ turn["estimated"] = False
671
+ else:
672
+ pending_usage = usage
673
+ elif payload_type == "agent_message":
674
+ text = _extract_text(payload)
675
+ turn = {
676
+ "turn_index": turn_index,
677
+ "role": "assistant",
678
+ "input_tokens": 0,
679
+ "output_tokens": _estimate_tokens(text),
680
+ "cache_read": 0,
681
+ "cache_creation": 0,
682
+ "cache_creation_1h": 0,
683
+ "cache_creation_5m": 0,
684
+ "model": current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL,
685
+ "timestamp": record.get("timestamp"),
686
+ "gap_since_prev_seconds": None,
687
+ "tools_used": pending_tools,
688
+ "cost_usd": 0.0,
689
+ "estimated": True,
690
+ }
691
+ if pending_usage:
692
+ turn["input_tokens"] = pending_usage["input_tokens"]
693
+ turn["output_tokens"] = pending_usage["output_tokens"]
694
+ turn["cache_read"] = pending_usage["cached_input_tokens"]
695
+ turn["estimated"] = False
696
+ pending_usage = None
697
+ turns.append(turn)
698
+ pending_tools = []
699
+ turn_index += 1
700
+ return turns
701
+
702
+
703
+ def parse_jsonl_for_quality(filepath: str | Path) -> dict[str, Any] | None:
704
+ reads: list[tuple[int, str, str]] = []
705
+ writes: list[tuple[int, str, str]] = []
706
+ tool_results: list[tuple[int, str, int, bool]] = []
707
+ system_reminders: list[tuple[int, str, int]] = []
708
+ messages: list[tuple[int, str, int, bool]] = []
709
+ compactions = 0
710
+ agent_dispatches: list[tuple[int, int, int]] = []
711
+ decisions: list[tuple[int, str]] = []
712
+ compaction_ratios: list[dict[str, Any]] = []
713
+ last_usage: dict[str, int] | None = None
714
+ current_model = _UNKNOWN_MODEL
715
+ topic = None
716
+ idx = 0
717
+ prev_was_compacted = False
718
+ last_turn_context: int | None = None
719
+
720
+ for record in _iter_json_records(filepath):
721
+ payload = _payload(record)
722
+ payload_type = payload.get("type")
723
+ ts = str(record.get("timestamp") or "")
724
+
725
+ model = _extract_model(payload)
726
+ if model:
727
+ current_model = model
728
+
729
+ # Per compaction: the `compacted` rollout record (which carries
730
+ # replacement_history) is authoritative — count it and capture the ratio.
731
+ # Its paired `context_compacted` event_msg fires immediately after, so
732
+ # count that ONLY when standalone (older Codex with no `compacted`
733
+ # record), detected by the previous record not being a `compacted`. This
734
+ # keeps the count==len(ratios) invariant even for back-to-back compactions.
735
+ is_compacted_record = record.get("type") == "compacted"
736
+ if is_compacted_record or payload_type == "context_compacted":
737
+ if is_compacted_record:
738
+ compactions += 1
739
+ rh = payload.get("replacement_history")
740
+ # Codex total_token_usage is cumulative (monotonic), so it does
741
+ # not drop at compaction. The meaningful "before" is the context
742
+ # occupancy of the last turn (per-turn input+cache); the "after"
743
+ # is the size of the replacement history that becomes the new
744
+ # context. ratio < 1 means compaction shrank the context; ratio is
745
+ # None for a degenerate empty/missing replacement_history.
746
+ after_tokens = _replacement_content_tokens(rh) if isinstance(rh, list) else None
747
+ ratio = round(after_tokens / last_turn_context, 3) if after_tokens and last_turn_context else None
748
+ compaction_ratios.append({
749
+ "before_context_tokens": last_turn_context,
750
+ "after_context_tokens": after_tokens,
751
+ "replacement_msgs": len(rh) if isinstance(rh, list) else None,
752
+ "ratio": ratio,
753
+ })
754
+ elif not prev_was_compacted:
755
+ compactions += 1
756
+ prev_was_compacted = is_compacted_record
757
+ reads = []
758
+ writes = []
759
+ tool_results = []
760
+ system_reminders = []
761
+ messages = []
762
+ agent_dispatches = []
763
+ decisions = []
764
+ idx += 1
765
+ continue
766
+ prev_was_compacted = False
767
+
768
+ if payload_type == "token_count":
769
+ usage = _token_usage(payload, cumulative=True)
770
+ if usage:
771
+ last_usage = usage
772
+ turn = _token_usage(payload, cumulative=False)
773
+ if turn:
774
+ # input already includes cached input; cumulative session
775
+ # usage is not the occupancy of this response's context.
776
+ last_turn_context = turn["input_tokens"] + turn["output_tokens"]
777
+
778
+ elif payload_type == "collab_agent_spawn_end":
779
+ prompt = str(payload.get("prompt") or "")
780
+ agent_dispatches.append((idx, len(prompt), 0))
781
+
782
+ elif payload_type in {"user_message", "message", "agent_message"}:
783
+ text = _extract_text(payload)
784
+ role = "assistant" if payload_type == "agent_message" else str(payload.get("role") or "user")
785
+ if role == "user":
786
+ topic = topic or _extract_topic(text)
787
+ substantive = len(text.split()) > (20 if role == "assistant" else 10)
788
+ messages.append((idx, role, len(text), substantive))
789
+ if re.search(r"\b(chose|decided|because|switched|going with)\b", text, re.IGNORECASE):
790
+ decisions.append((idx, text[:200].strip()))
791
+
792
+ elif payload_type in {"function_call", "custom_tool_call"}:
793
+ name = str(payload.get("name") or "")
794
+ args = _parse_arguments(payload)
795
+ if name == "exec_command":
796
+ cmd = str(args.get("cmd") or "")
797
+ if READ_CMD_RE.search(cmd):
798
+ for path in _extract_shell_paths(cmd):
799
+ reads.append((idx, path, ts))
800
+ elif name == "apply_patch":
801
+ patch = str(args.get("patch") or "")
802
+ for path in PATCH_FILE_RE.findall(patch):
803
+ writes.append((idx, path.strip(), ts))
804
+ elif name == "spawn_agent":
805
+ prompt = str(args.get("message") or args.get("prompt") or "")
806
+ agent_dispatches.append((idx, len(prompt), 0))
807
+
808
+ elif payload_type in {"function_call_output", "custom_tool_call_output"}:
809
+ text = str(payload.get("output") or "")
810
+ call_id = str(payload.get("call_id") or idx)
811
+ tool_results.append((idx, call_id, len(text), False))
812
+ if agent_dispatches and agent_dispatches[-1][2] == 0:
813
+ last = agent_dispatches[-1]
814
+ agent_dispatches[-1] = (last[0], last[1], len(text))
815
+ elif payload_type in {"exec_command_end", "patch_apply_end"}:
816
+ text = _event_output_text(payload)
817
+ if text:
818
+ call_id = str(payload.get("call_id") or idx)
819
+ tool_results.append((idx, call_id, len(text), False))
820
+
821
+ idx += 1
822
+
823
+ if not messages:
824
+ return None
825
+
826
+ return {
827
+ "reads": reads,
828
+ "writes": writes,
829
+ "tool_results": tool_results,
830
+ "system_reminders": system_reminders,
831
+ "messages": messages,
832
+ "compactions": compactions,
833
+ "agent_dispatches": agent_dispatches,
834
+ "decisions": decisions,
835
+ "compaction_ratios": compaction_ratios,
836
+ "total_entries": idx,
837
+ "estimated": True,
838
+ "context_tokens": last_turn_context or None,
839
+ "model_context_window": last_usage["model_context_window"] if last_usage else None,
840
+ "model": current_model if current_model != _UNKNOWN_MODEL else _DEFAULT_MODEL,
841
+ "topic": topic,
842
+ }
843
+
844
+
845
+ def iter_tool_outputs(
846
+ filepath: str | Path,
847
+ *,
848
+ min_chars: int = 4096,
849
+ max_outputs: int = 20,
850
+ ) -> list[dict[str, Any]]:
851
+ """Return large/high-signal Codex tool outputs from a session JSONL.
852
+
853
+ Balanced Codex hooks do not receive every PostToolUse payload. This
854
+ bounded transcript pass lets the Stop worker backfill the same durable
855
+ pointers Claude gets from PostToolUse archive hooks, without keeping tool
856
+ hooks enabled in the noisy default profile.
857
+ """
858
+ call_meta: dict[str, dict[str, str]] = {}
859
+ outputs: deque[dict[str, Any]] = deque(maxlen=max_outputs)
860
+ synthetic_index = 0
861
+
862
+ for record in _iter_json_records(filepath):
863
+ payload = _payload(record)
864
+ payload_type = payload.get("type")
865
+
866
+ if payload_type in {"function_call", "custom_tool_call"}:
867
+ call_id = str(payload.get("call_id") or payload.get("id") or synthetic_index)
868
+ raw_name = str(payload.get("name") or "unknown")
869
+ args = _parse_arguments(payload)
870
+ command_or_path = ""
871
+ if raw_name == "exec_command":
872
+ command_or_path = str(args.get("cmd") or args.get("command") or "")
873
+ elif raw_name == "apply_patch":
874
+ command_or_path = "apply_patch"
875
+ call_meta[call_id] = {
876
+ "tool_name": _tool_name(raw_name),
877
+ "raw_name": raw_name,
878
+ "command_or_path": command_or_path,
879
+ }
880
+
881
+ elif payload_type in {"function_call_output", "custom_tool_call_output"}:
882
+ call_id = str(payload.get("call_id") or synthetic_index)
883
+ text = str(payload.get("output") or "")
884
+ meta = call_meta.get(call_id, {})
885
+ if len(text) >= min_chars or _looks_like_error_text(text):
886
+ outputs.append({
887
+ "tool_use_id": call_id,
888
+ "tool_name": meta.get("tool_name", "Tool"),
889
+ "tool_type": meta.get("raw_name", "function_call"),
890
+ "command_or_path": meta.get("command_or_path", ""),
891
+ "output": text,
892
+ "timestamp": record.get("timestamp") or payload.get("timestamp"),
893
+ })
894
+
895
+ elif payload_type in {"exec_command_end", "patch_apply_end"}:
896
+ call_id = str(payload.get("call_id") or f"event-{synthetic_index}")
897
+ text = _event_output_text(payload)
898
+ exit_code = payload.get("exit_code")
899
+ status = str(payload.get("status") or "").lower()
900
+ high_signal = exit_code not in (None, 0) or "error" in status or _looks_like_error_text(text)
901
+ if text and (len(text) >= min_chars or high_signal):
902
+ outputs.append({
903
+ "tool_use_id": call_id,
904
+ "tool_name": "Bash" if payload_type == "exec_command_end" else "Edit",
905
+ "tool_type": payload_type,
906
+ "command_or_path": str(payload.get("cmd") or payload.get("command") or ""),
907
+ "output": text,
908
+ "timestamp": record.get("timestamp") or payload.get("timestamp"),
909
+ })
910
+
911
+ synthetic_index += 1
912
+
913
+ return list(outputs)
914
+
915
+
916
+ def extract_session_state(filepath: str | Path, tail_lines: int = 500, max_files: int = 10) -> dict[str, Any] | None:
917
+ """Extract checkpoint-ready continuity state from a Codex JSONL session.
918
+
919
+ Every transcript string is redacted where it enters the state, before the
920
+ width cuts (200/300/500...): a secret straddling a cut would otherwise
921
+ survive as a prefix no pattern recognises. No redactor means no state.
922
+ """
923
+ question_re = re.compile(r"\?|TODO|FIXME|HACK|XXX", re.IGNORECASE)
924
+ try:
925
+ from credential_patterns import redact_credentials as _ingest_redact
926
+ except Exception:
927
+ return None
928
+ active_files: list[tuple[str, str, str]] = []
929
+ recent_reads: list[str] = []
930
+ decisions: list[str] = []
931
+ open_questions: list[str] = []
932
+ agent_state: list[tuple[str, str]] = []
933
+ error_context: list[tuple[str, str]] = []
934
+ todos: list[tuple[str, str]] = []
935
+ active_plan = None
936
+ last_user_msg = ""
937
+ last_assistant_msg = ""
938
+ seen_files: set[str] = set()
939
+ recent_errors: list[str] = []
940
+
941
+ records: deque[dict[str, Any]] = deque(maxlen=tail_lines)
942
+ for record in _iter_json_records(filepath):
943
+ records.append(record)
944
+
945
+ if not records:
946
+ return None
947
+
948
+ for record in records:
949
+ payload = _payload(record)
950
+ payload_type = payload.get("type")
951
+
952
+ if payload_type in {"user_message", "message", "agent_message"}:
953
+ role = payload.get("role")
954
+ if payload_type == "user_message":
955
+ role = "user"
956
+ elif payload_type == "agent_message":
957
+ role = "assistant"
958
+ text = _ingest_redact(_extract_text(payload)).strip()
959
+ if not text:
960
+ continue
961
+ if role == "user":
962
+ last_user_msg = text
963
+ elif role == "assistant":
964
+ last_assistant_msg = text
965
+ _append_decisions(text, decisions)
966
+ if recent_errors and _looks_like_fix(text):
967
+ error_context.append((recent_errors[-1][:200], text[:200]))
968
+ recent_errors = []
969
+ if question_re.search(text):
970
+ _append_question(text, open_questions)
971
+
972
+ elif payload_type in {"function_call", "custom_tool_call"}:
973
+ name = str(payload.get("name") or "")
974
+ args = _parse_arguments(payload)
975
+ if name == "exec_command":
976
+ cmd = str(args.get("cmd") or args.get("command") or "")
977
+ if READ_CMD_RE.search(cmd):
978
+ for path in _extract_shell_paths(cmd):
979
+ _append_file_path(path, "read", "", active_files, recent_reads, seen_files, max_files)
980
+ if _is_plan_path(path):
981
+ active_plan = path
982
+ for path in _extract_probable_write_paths(cmd):
983
+ _append_file_path(path, "modified", "", active_files, recent_reads, seen_files, max_files)
984
+ if _is_plan_path(path):
985
+ active_plan = path
986
+ elif name == "apply_patch":
987
+ patch = str(args.get("patch") or "")
988
+ for path in PATCH_FILE_RE.findall(patch):
989
+ clean_path = path.strip()
990
+ _append_file_path(clean_path, "modified", "", active_files, recent_reads, seen_files, max_files)
991
+ if _is_plan_path(clean_path):
992
+ active_plan = clean_path
993
+ elif name == "spawn_agent":
994
+ agent_type = str(args.get("agent_type") or "default")
995
+ desc = _ingest_redact(str(args.get("message") or args.get("prompt") or ""))[:100]
996
+ agent_state.append((agent_type, desc))
997
+ elif name == "update_plan":
998
+ plan = args.get("plan")
999
+ if isinstance(plan, list):
1000
+ todos = [
1001
+ (_ingest_redact(str(item.get("step") or item.get("content") or ""))[:120], str(item.get("status") or ""))
1002
+ for item in plan
1003
+ if isinstance(item, dict) and (item.get("step") or item.get("content"))
1004
+ ]
1005
+
1006
+ elif payload_type in {"function_call_output", "custom_tool_call_output"}:
1007
+ text = _ingest_redact(str(payload.get("output") or ""))
1008
+ if _looks_like_error_text(text):
1009
+ recent_errors.append(text[:300].strip())
1010
+ elif payload_type in {"exec_command_end", "patch_apply_end"}:
1011
+ text = _ingest_redact(_event_output_text(payload))
1012
+ exit_code = payload.get("exit_code")
1013
+ status = str(payload.get("status") or "").lower()
1014
+ if exit_code not in (None, 0) or "error" in status or _looks_like_error_text(text):
1015
+ recent_errors.append(text[:300].strip())
1016
+
1017
+ return {
1018
+ "active_files": active_files[-max_files:],
1019
+ "recent_reads": recent_reads[-max_files:],
1020
+ "decisions": decisions[-10:],
1021
+ "open_questions": open_questions[-5:],
1022
+ "agent_state": agent_state[-10:],
1023
+ "error_context": error_context[-5:],
1024
+ "todos": todos,
1025
+ "active_plan": active_plan,
1026
+ "current_step": {
1027
+ "last_user": last_user_msg[:500],
1028
+ "last_assistant": last_assistant_msg[:500],
1029
+ },
1030
+ }
1031
+
1032
+
1033
+ def _append_file_path(
1034
+ path: str,
1035
+ action: str,
1036
+ line_range: str,
1037
+ active_files: list[tuple[str, str, str]],
1038
+ recent_reads: list[str],
1039
+ seen_files: set[str],
1040
+ max_files: int,
1041
+ ) -> None:
1042
+ if not path:
1043
+ return
1044
+ if path in seen_files:
1045
+ if action == "modified" and all(existing[0] != path for existing in active_files):
1046
+ if len(active_files) < max_files:
1047
+ active_files.append((path, action, line_range))
1048
+ try:
1049
+ recent_reads.remove(path)
1050
+ except ValueError:
1051
+ pass
1052
+ return
1053
+ seen_files.add(path)
1054
+ if action == "modified":
1055
+ if len(active_files) < max_files:
1056
+ active_files.append((path, action, line_range))
1057
+ else:
1058
+ recent_reads.append(path)
1059
+
1060
+
1061
+ def _append_decisions(text: str, decisions: list[str]) -> None:
1062
+ if not re.search(r"\b(chose|decided|because|instead of|went with|going with|switched|prefer|should use|will use)\b", text, re.IGNORECASE):
1063
+ return
1064
+ for sentence in re.split(r"[.!?\n]", text):
1065
+ if re.search(r"\b(chose|decided|because|instead of|went with|going with|switched|prefer|should use|will use)\b", sentence, re.IGNORECASE):
1066
+ snippet = sentence.strip()[:200]
1067
+ if snippet and snippet not in decisions:
1068
+ decisions.append(snippet)
1069
+ return
1070
+
1071
+
1072
+ def _append_question(text: str, open_questions: list[str]) -> None:
1073
+ for sentence in re.split(r"[.!?\n]", text):
1074
+ snippet = sentence.strip()[:200]
1075
+ if snippet and ("?" in snippet or re.search(r"\bTODO\b|\bFIXME\b", snippet, re.IGNORECASE)):
1076
+ if snippet not in open_questions:
1077
+ open_questions.append(snippet)
1078
+ return
1079
+
1080
+
1081
+ def _extract_probable_write_paths(command: str) -> list[str]:
1082
+ if not re.search(r">\s*|tee\s+|mv\s+|cp\s+|touch\s+|mkdir\s+-p\s+", command):
1083
+ return []
1084
+ return _extract_shell_paths(command)
1085
+
1086
+
1087
+ def _is_plan_path(path: str) -> bool:
1088
+ return "/docs/plans/" in path and path.endswith(".md")
1089
+
1090
+
1091
+ def _looks_like_fix(text: str) -> bool:
1092
+ return bool(re.search(r"\b(fix|fixed|instead|switched|resolved|retry|rerun|passing)\b", text, re.IGNORECASE))
1093
+
1094
+
1095
+ def _extract_shell_paths(command: str) -> list[str]:
1096
+ paths: list[str] = []
1097
+ for token in re.findall(r"(?:[./~][^\s'\";|&<>]+|[A-Za-z0-9_.-]+/[^\s'\";|&<>]+)", command):
1098
+ if any(ch in token for ch in "*?$(){}[]"):
1099
+ continue
1100
+ paths.append(token.rstrip(":,"))
1101
+ return paths[:10]
1102
+
1103
+
1104
+ def _event_output_text(payload: dict[str, Any]) -> str:
1105
+ parts = []
1106
+ for key in ("aggregated_output", "formatted_output", "stdout", "stderr", "output"):
1107
+ value = payload.get(key)
1108
+ if value:
1109
+ parts.append(str(value))
1110
+ return "\n".join(parts)
1111
+
1112
+
1113
+ def _append_positive(bucket: list[float], value: Any) -> None:
1114
+ if isinstance(value, (int, float)) and value > 0:
1115
+ bucket.append(float(value))
1116
+
1117
+
1118
+ def _append_duration(bucket: list[float], duration: Any) -> None:
1119
+ ms = _secs_nanos_to_ms(duration)
1120
+ if ms is not None and ms > 0: # match _append_positive: ignore zero-duration noise
1121
+ bucket.append(ms)
1122
+
1123
+
1124
+ def _secs_nanos_to_ms(value: Any) -> float | None:
1125
+ """Convert a Codex ``{secs, nanos}`` duration to milliseconds.
1126
+
1127
+ Observed Codex wire format for tool durations is always the ``{secs, nanos}``
1128
+ dict. A bare number is a defensive fallback assumed to already be in
1129
+ milliseconds; if a future Codex emits bare seconds, durations would read
1130
+ 1000x low (the dict form is unaffected)."""
1131
+ if isinstance(value, dict):
1132
+ secs = value.get("secs")
1133
+ nanos = value.get("nanos")
1134
+ if isinstance(secs, (int, float)) or isinstance(nanos, (int, float)):
1135
+ return (float(secs or 0) * 1000.0) + (float(nanos or 0) / 1_000_000.0)
1136
+ return None
1137
+ if isinstance(value, (int, float)) and value >= 0:
1138
+ return float(value)
1139
+ return None
1140
+
1141
+
1142
+ def _percentile(values: list[float], pct: float) -> float | None:
1143
+ if not values:
1144
+ return None
1145
+ ordered = sorted(values)
1146
+ k = (len(ordered) - 1) * (pct / 100.0)
1147
+ lo = int(k)
1148
+ hi = min(lo + 1, len(ordered) - 1)
1149
+ return round(ordered[lo] + (ordered[hi] - ordered[lo]) * (k - lo), 1)
1150
+
1151
+
1152
+ def _extract_rate_limits(payload: dict[str, Any]) -> dict[str, Any] | None:
1153
+ """Capture the rate_limits block from a token_count payload, defensively.
1154
+
1155
+ Scalars are copied as-is; ``primary``/``secondary`` window objects are kept
1156
+ whole so downstream consumers can read whatever fields Codex exposes without
1157
+ this parser guessing the window schema.
1158
+ """
1159
+ rl = payload.get("rate_limits")
1160
+ if not isinstance(rl, dict):
1161
+ return None
1162
+ out: dict[str, Any] = {}
1163
+ for key, value in rl.items():
1164
+ if value is None or isinstance(value, (str, int, float, bool, dict)):
1165
+ out[key] = value
1166
+ return out or None
1167
+
1168
+
1169
+ def _replacement_content_tokens(replacement_history: list[Any]) -> int:
1170
+ """Approximate the token size of a compaction's replacement_history messages."""
1171
+ total_chars = 0
1172
+ for item in replacement_history:
1173
+ if not isinstance(item, dict):
1174
+ continue
1175
+ content = item.get("content")
1176
+ if isinstance(content, str):
1177
+ total_chars += len(content)
1178
+ elif isinstance(content, list):
1179
+ for part in content:
1180
+ if isinstance(part, dict):
1181
+ text = part.get("text")
1182
+ if isinstance(text, str):
1183
+ total_chars += len(text)
1184
+ elif isinstance(part, str):
1185
+ total_chars += len(part)
1186
+ return total_chars // CHARS_PER_TOKEN