@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,1458 @@
1
+ #!/usr/bin/env python3
2
+ """Deterministic-candidate analysis for Token Coach.
3
+
4
+ Finds the parts of a user's workflow that could be plain code instead of model
5
+ calls, using only the local session transcripts. No model calls, no network,
6
+ read-only (the single write is an optional result cache in Token Optimizer's own
7
+ data dir, holding redacted command shapes and counts, never file contents).
8
+
9
+ Four detectors, all measured from the transcripts:
10
+
11
+ repeated_sequence the same ordered run of 3+ tool calls in 3+ sessions
12
+ templated_subagent subagent launches whose normalised first 300 chars match (5+)
13
+ polling_loop one literal command run 4+ times with no edit in between
14
+ (or a wait/check pattern: `sleep` + a status command)
15
+ parameter_sweep one normalised command shape run 4+ times over distinct
16
+ literal parameters (run-0, run-1, ...) with no edit
17
+ check_only_turn a turn whose only tool call was a passing test/build/lint run
18
+ and whose reply was short: the exit code already answered
19
+
20
+ Transcript readers exist for Claude Code (also used by Cowork) and Codex, the two
21
+ runtimes whose transcripts carry ordered tool calls with their inputs. Every other
22
+ runtime gets an explicit "not measurable on <runtime>" entry (see RUNTIME_SUPPORT).
23
+
24
+ Reading the numbers: ``tokens`` and ``cost_usd`` are what the turns that ran
25
+ those calls used (whole-turn input including cache reads, plus output), priced at
26
+ API-equivalent rates. They are not what a script would save: moving a step to
27
+ code removes those turns, so the saving is at most this much. Every figure is
28
+ "measured on your transcripts".
29
+
30
+ An inline script (``python3 - <<'EOF'``, ``python3 -c``, ``bash -c``, ``node -e``,
31
+ ``ruby -e``, ``perl -e``, here-strings) is a different command when its body
32
+ differs: the call key carries a fingerprint of the redacted, literal-blanked body.
33
+
34
+ Pricing is injected (``price_fn``) so this module stays free of measure.py and the
35
+ numbers come from the same rate cards as every other dollar figure in the tool.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import hashlib
41
+ import json
42
+ import os
43
+ import re
44
+ import time
45
+ from collections import Counter, defaultdict
46
+ from pathlib import Path
47
+ from typing import Any, Callable, Iterable
48
+
49
+ from credential_patterns import CommandMarks, scrub_command_syntax
50
+
51
+ # Part of the cache key. Bump when the SHAPE of stored examples changes, so a cache
52
+ # written by an older algorithm (possibly holding an example the newer scrubbers would
53
+ # have blanked) is never served again. 3: command-shape secret scrubbers (review F4).
54
+ ALGO_VERSION = 3
55
+ BASIS = "measured on your transcripts"
56
+ USED_NOT_SAVED_NOTE = "Moving a step to code removes those turns; the saving is at most this much."
57
+ PROGRESS_MIN_INTERVAL_S = 2.0
58
+ INLINE_SNIPPET_CHARS = 60
59
+
60
+ MIN_SEQ_LEN = 3
61
+ MAX_SEQ_LEN = 8
62
+ MIN_SEQ_SESSIONS = 3
63
+ MIN_SUBAGENT_LAUNCHES = 5
64
+ MIN_POLL_RUNS = 4
65
+ MIN_CHECK_TURNS = 3
66
+ MAX_CANDIDATES = 10
67
+ SHORT_REPLY_CHARS = 200
68
+ EXAMPLE_CAP = 200
69
+ PROMPT_KEY_CHARS = 300
70
+ MAX_CALLS_PER_SESSION = 5000
71
+ INLINE_READ_CHARS = 8000
72
+ PARTIAL_CACHE_TTL_S = 600
73
+ MAX_PARSE_FILE_BYTES = 96 * 1024 * 1024
74
+ MAX_JSONL_LINE_CHARS = 8 * 1024 * 1024
75
+ _BIG_LINE_CHARS = 20000
76
+
77
+ WITHHELD = "[example withheld: credential redactor unavailable]"
78
+
79
+ # Which runtimes can be measured. Only Claude Code (and Cowork, which writes the
80
+ # same transcripts) and Codex keep ordered tool calls WITH their inputs in a
81
+ # transcript Token Optimizer can read. The others keep counts or names only.
82
+ RUNTIME_SUPPORT: dict[str, dict[str, Any]] = {
83
+ "claude": {"measurable": True, "reader": "claude_jsonl"},
84
+ "codex": {"measurable": True, "reader": "codex_jsonl"},
85
+ "opencode": {"measurable": False, "reason": "OpenCode runs Token Optimizer as a native TypeScript plugin; measure.py has no reader for its session store"},
86
+ "copilot": {"measurable": False, "reason": "Copilot adapters keep tool-call counts and names, not ordered tool inputs"},
87
+ "hermes": {"measurable": False, "reason": "Hermes sessions are read from state.db, which keeps a tool-call count, not ordered tool inputs"},
88
+ "cursor": {"measurable": False, "reason": "Cursor sessions are read from a hook tally of tool counts, not ordered tool inputs"},
89
+ "antigravity": {"measurable": False, "reason": "Antigravity sessions are read from a conversation store that keeps a tool-call count, not ordered tool inputs"},
90
+ "grok": {"measurable": False, "reason": "Grok Build sessions keep a tool-call count, not ordered tool inputs"},
91
+ "pi": {"measurable": False, "reason": "Pi runs Token Optimizer as a native TypeScript extension; measure.py has no reader for its session store"},
92
+ }
93
+
94
+
95
+ def not_measurable(runtime: str) -> dict[str, Any]:
96
+ info = RUNTIME_SUPPORT.get(runtime) or {}
97
+ reason = info.get("reason") or "this runtime does not keep ordered tool-call inputs in a transcript Token Optimizer reads"
98
+ return {"runtime": runtime, "measurable": False, "reason": f"not measurable on {runtime}: {reason}"}
99
+
100
+
101
+ def runtime_support_table() -> list[dict[str, Any]]:
102
+ out = []
103
+ for name, info in RUNTIME_SUPPORT.items():
104
+ if info["measurable"]:
105
+ out.append({"runtime": name, "measurable": True})
106
+ else:
107
+ out.append(not_measurable(name))
108
+ return out
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # Normalisation
113
+ # ---------------------------------------------------------------------------
114
+
115
+ _HEREDOC_RE = re.compile(r"<<-?\s*['\"]?\w+")
116
+ _QUOTED_RE = re.compile(r'"(?:[^"\\]|\\.)*"|\'[^\']*\'')
117
+ _ENV_SECRET_RE = re.compile(
118
+ r"\b([A-Za-z][A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|PWD|CREDENTIAL)[A-Za-z0-9_]*)"
119
+ r"=(?:\[CREDENTIAL REDACTED[^\]]*\]|\"[^\"]*\"|'[^']*'|\S+)",
120
+ re.I,
121
+ )
122
+
123
+ # Email addresses identify a person. `git@host` (the ssh remote user) is not one.
124
+ _EMAIL_RE = re.compile(r"(?<![\w.+-])(?!git@)[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b")
125
+
126
+
127
+ # Placeholders for the shaping step: short tokens, not labeled redaction text.
128
+ _SHAPE_MARKS = CommandMarks(creds="<creds>", arg="<arg>", secret="<secret>", user="<user>")
129
+
130
+
131
+ def scrub_command_secrets(text: str) -> str:
132
+ """Blank credentials and personal identifiers that live in a command's syntax.
133
+
134
+ The credential rules live in credential_patterns.scrub_command_syntax (one
135
+ engine, also used to redact stored command text); this adds the email rule,
136
+ which is shaping-only.
137
+ """
138
+ text = scrub_command_syntax(text, _SHAPE_MARKS)
139
+ text = _EMAIL_RE.sub("<email>", text)
140
+ return text
141
+
142
+
143
+ _WIN_PATH_RE = re.compile(
144
+ r"(?<![\w\\])(?:[A-Za-z]:[\\/]+|\\{2,}[^\s\\/\"'|;&<>()]+[\\/]+)(?:[^\s\\/\"'|;&<>()]+[\\/]+)*[^\s\\/\"'|;&<>()]*"
145
+ )
146
+ _POSIX_PATH_RE = re.compile(
147
+ r"(?<![\w/.\-:<>$\\])(?:~|\$\{?HOME\}?)?/(?!(?:dev|proc|sys)/)(?:[^\s/\"'|;&<>()=]+/+)+[^\s/\"'|;&<>()=]+"
148
+ )
149
+ _UUID_RE = re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")
150
+ _DATETIME_RE = re.compile(
151
+ r"\b\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?\b"
152
+ )
153
+ _TIME_RE = re.compile(r"\b\d{1,2}:\d{2}:\d{2}\b")
154
+ _HASH_RE = re.compile(r"\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{7,64}\b")
155
+ _TOKEN_RE = re.compile(r"\b(?=[A-Za-z0-9_\-]*\d)(?=[A-Za-z0-9_\-]*[A-Za-z])[A-Za-z0-9_\-]{24,}\b")
156
+ _NUMBER_RE = re.compile(r"(?<![A-Za-z0-9])\d+(?:\.\d+)*(?![A-Za-z0-9])")
157
+ _CD_PREFIX_RE = re.compile(r"^(?:cd\s+\S+\s*(?:&&|;)\s*)+")
158
+ _WS_RE = re.compile(r"\s+")
159
+
160
+
161
+ def _path_to_placeholder(match: "re.Match[str]") -> str:
162
+ text = match.group(0)
163
+ base = re.split(r"[\\/]+", text.rstrip("\\/"))[-1] if text.rstrip("\\/") else ""
164
+ return f"<dir>/{base}" if base else "<dir>"
165
+
166
+
167
+ def _blank_literals(text: str, max_chars: int) -> str:
168
+ """Whitespace, secrets, quoted strings, paths, ids and numbers reduced to placeholders."""
169
+ text = text[:max_chars * 4]
170
+ text = _WS_RE.sub(" ", text).strip()
171
+ text = _ENV_SECRET_RE.sub(lambda mm: f"{mm.group(1)}=<secret>", text)
172
+ text = scrub_command_secrets(text)
173
+ text = _QUOTED_RE.sub(lambda mm: "<str:long>" if len(mm.group(0)) > 80 else "<str>", text)
174
+ text = _WIN_PATH_RE.sub(_path_to_placeholder, text)
175
+ text = _POSIX_PATH_RE.sub(_path_to_placeholder, text)
176
+ text = _UUID_RE.sub("<uuid>", text)
177
+ text = _DATETIME_RE.sub("<date>", text)
178
+ text = _TIME_RE.sub("<time>", text)
179
+ text = _HASH_RE.sub("<hash>", text)
180
+ text = _TOKEN_RE.sub("<token>", text)
181
+ text = _NUMBER_RE.sub("<n>", text)
182
+ text = _CD_PREFIX_RE.sub("", text)
183
+ return text[:max_chars]
184
+
185
+
186
+ def normalise_command(text: Any, *, max_chars: int = 600) -> str:
187
+ """Reduce a command (or prompt) to its reusable shape.
188
+
189
+ Quoted strings, numbers, hashes, UUIDs, dates, long opaque tokens and the
190
+ directory part of absolute paths (POSIX and Windows) become placeholders, so
191
+ two runs of the same command on different days, commits or checkouts compare
192
+ equal. Secret-looking env assignments are blanked. A leading ``cd <dir> &&``
193
+ is dropped. Heredoc bodies are cut. The result is one line, never the input.
194
+ """
195
+ if not isinstance(text, str):
196
+ return ""
197
+ text = text[:max_chars * 4]
198
+ m = _HEREDOC_RE.search(text)
199
+ if m and m.start() > 0:
200
+ text = text[:m.start()]
201
+ return _blank_literals(text, max_chars)
202
+
203
+
204
+ # ---------------------------------------------------------------------------
205
+ # Inline scripts (heredoc, -c / -e, here-string): the launcher is not the command
206
+ # ---------------------------------------------------------------------------
207
+
208
+ _INTERPRETERS = frozenset({
209
+ "python", "py", "pypy", "node", "nodejs", "ruby", "perl", "php", "bash", "sh", "zsh", "dash", "ksh",
210
+ "deno", "bun", "rscript", "pwsh", "powershell",
211
+ })
212
+ _LAUNCH_WRAPPERS = frozenset({"sudo", "env", "command", "exec", "time", "nohup", "uv", "poetry", "pipenv", "pdm",
213
+ "hatch", "rye", "run"})
214
+ _ENV_ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
215
+ _SEGMENT_SPLIT_RE = re.compile(r"&&|\|\||;|\|")
216
+ _HEREDOC_FULL_RE = re.compile(r"<<<|<<(-?)\s*(['\"]?)(\w+)\2")
217
+ _WORD_RE = re.compile(r"\s*(\"(?:[^\"\\]|\\.)*\"|'[^']*'|\S+)")
218
+ _INTERP_TOKEN_RE = re.compile(r"(?:^|(?<=[\s;&|(]))((?:\S*[\\/])?[A-Za-z][A-Za-z0-9._]*)(?=\s)")
219
+ _INLINE_QUOTED_RE = re.compile(r'"(?:[^"\\]|\\.)*"|\'[^\']*\'')
220
+
221
+
222
+ def _interp_family(word: str) -> str:
223
+ base = re.split(r"[\\/]", word)[-1].lower()
224
+ if base.endswith(".exe"):
225
+ base = base[:-4]
226
+ base = re.sub(r"[\d.]+$", "", base) if re.match(r"^(?:python|pypy)[\d.]*$", base) else base
227
+ return base if base in _INTERPRETERS else ""
228
+
229
+
230
+ def _inline_flag(family: str, flag: str) -> bool:
231
+ low = flag.lower()
232
+ if family in ("node", "nodejs"):
233
+ return low in ("--eval", "--print") or bool(re.fullmatch(r"-[ep]+", flag))
234
+ if family in ("ruby", "perl"):
235
+ return bool(re.fullmatch(r"-[A-Za-z]*[eE][A-Za-z]*", flag))
236
+ if family == "php":
237
+ return flag == "-r"
238
+ if family == "rscript":
239
+ return flag == "-e"
240
+ if family in ("pwsh", "powershell"):
241
+ return low in ("-c", "-command")
242
+ if family in ("deno", "bun"):
243
+ return False
244
+ return bool(re.fullmatch(r"-[A-Za-z]*c[A-Za-z]*", flag)) # python / shells: -c, -lc, -ec, -Bc
245
+
246
+
247
+ def _launcher_of_segment(segment: str) -> str:
248
+ for tok in segment.split():
249
+ if _ENV_ASSIGN_RE.match(tok) or tok.lower() in _LAUNCH_WRAPPERS or tok.startswith("-"):
250
+ continue
251
+ return _interp_family(tok)
252
+ return ""
253
+
254
+
255
+ def _unquote(body: str) -> str:
256
+ if len(body) >= 2 and body[0] == body[-1] and body[0] in "\"'":
257
+ return body[1:-1]
258
+ return body
259
+
260
+
261
+ def split_inline_script(text: str) -> "tuple[str, str] | None":
262
+ """Return (text with the script body removed, script body) for an interpreter given a script inline.
263
+
264
+ Recognises ``python3 - <<'EOF'`` style heredocs, ``-c`` / ``-e`` style flags
265
+ (python, bash/sh/zsh, node, ruby, perl, php, Rscript, PowerShell) and
266
+ ``<<<`` here-strings. Anything else, including ``cat <<EOF > file``, is not a script.
267
+ """
268
+ for m in _INTERP_TOKEN_RE.finditer(text):
269
+ family = _interp_family(m.group(1))
270
+ if not family:
271
+ continue
272
+ pos = m.end()
273
+ while True:
274
+ w = _WORD_RE.match(text, pos)
275
+ if not w or not w.group(1).startswith("-") or w.group(1) in ("-", "--"):
276
+ break
277
+ flag = w.group(1)
278
+ pos = w.end()
279
+ if _inline_flag(family, flag):
280
+ b = _WORD_RE.match(text, pos)
281
+ if b:
282
+ body = _unquote(b.group(1))
283
+ if body.strip():
284
+ return text[:b.start(1)] + '""' + text[b.end(1):], body
285
+ break
286
+ h = _HEREDOC_FULL_RE.search(text)
287
+ if not h:
288
+ return None
289
+ segment = _SEGMENT_SPLIT_RE.split(text[:h.start()])[-1]
290
+ if not _launcher_of_segment(segment):
291
+ return None
292
+ if h.group(0) == "<<<":
293
+ b = _WORD_RE.match(text, h.end())
294
+ if not b:
295
+ return None
296
+ body = _unquote(b.group(1))
297
+ return (text[:b.start(1)] + '""' + text[b.end(1):], body) if body.strip() else None
298
+ nl = text.find("\n", h.end())
299
+ if nl < 0:
300
+ return None
301
+ tag = h.group(3)
302
+ lines = []
303
+ for line in text[nl + 1:].split("\n"):
304
+ if line.strip() == tag:
305
+ break
306
+ lines.append(line)
307
+ body = "\n".join(lines)
308
+ return (text[:h.end()], body) if body.strip() else None
309
+
310
+
311
+ def inline_script_fingerprint(body: str) -> str:
312
+ """Stable id of a script body after literal blanking (ids, numbers, strings, paths)."""
313
+ shaped = _blank_literals(body, 4000)
314
+ return hashlib.sha1(shaped.encode("utf-8", "replace")).hexdigest()[:10]
315
+
316
+
317
+ def inline_script_snippet(body: str) -> str:
318
+ flat = scrub_command_secrets(_WS_RE.sub(" ", body).strip())
319
+ return flat if len(flat) <= INLINE_SNIPPET_CHARS else flat[:INLINE_SNIPPET_CHARS].rstrip() + "..."
320
+
321
+
322
+ # ---------------------------------------------------------------------------
323
+ # Check-command classification (tests, builds, linters)
324
+ # ---------------------------------------------------------------------------
325
+
326
+ _CHECK_PREFIX = (
327
+ r"^(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*"
328
+ r"(?:(?:uv|poetry|pipenv|pdm|hatch|rye)\s+run\s+|npx\s+|pnpx\s+|bunx\s+|pnpm\s+exec\s+|yarn\s+|"
329
+ r"python3?(?:\.\d+)?\s+-m\s+|py\s+-3\s+-m\s+)?"
330
+ )
331
+ _CHECK_RE = re.compile(
332
+ _CHECK_PREFIX
333
+ + r"(?:pytest|py\.test|tox|nox|unittest|flake8|mypy|pyright|pylint|tsc|eslint|jest|vitest|mocha|"
334
+ r"playwright\s+test|golangci-lint|rspec|rubocop|phpunit|"
335
+ r"(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|t|build|lint|typecheck|type-check|check|tsc|ci|test:\S+|lint:\S+|build:\S+|check:\S+)|"
336
+ r"cargo\s+(?:test|build|check|clippy|nextest)|"
337
+ r"go\s+(?:test|build|vet)|"
338
+ r"(?:\./)?gradlew?\s+(?:test|build|check|\S*test\S*)|mvnw?\s+(?:test|verify|package|compile)|"
339
+ r"dotnet\s+(?:test|build)|swift\s+(?:test|build)|"
340
+ r"bundle\s+exec\s+(?:rspec|rake\s+test|rubocop)|rake\s+test|"
341
+ r"ruff(?:\s+check)?|"
342
+ r"(?:\./|bash\s+|sh\s+)[^\s]*(?:test|check|lint)[^\s]*)(?=\s|$)"
343
+ )
344
+ # Formatters only count as a check when they do not rewrite files.
345
+ _FORMAT_CHECK_RE = re.compile(
346
+ _CHECK_PREFIX + r"(?:black|isort|prettier|biome(?:\s+(?:check|ci))?|ruff\s+format|cargo\s+fmt)(?=\s|$)"
347
+ )
348
+ _MUTATING_FLAG_RE = re.compile(r"(?:^|\s)(?:--fix|--write|--apply|--unsafe-fixes|-w|--update-snapshots?|-u)(?=\s|$)")
349
+ _NONMUTATING_FLAG_RE = re.compile(r"(?:^|\s)(?:--check|--diff|-check|--dry-run)(?=\s|$)")
350
+ _MAKE_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*g?make(?P<rest>(?:\s+\S+)*)$")
351
+ _MAKE_OK_TARGET_WORDS = frozenset({"test", "tests", "check", "lint", "build", "verify", "ci", "typecheck", "all", "compile"})
352
+ _FILTER_CMDS = ("tail", "head", "grep", "wc", "tee", "cat", "sed", "awk", "cut", "sort", "uniq", "tr")
353
+ _TRAILING_REDIRECT_RE = re.compile(r"\s*(?:\d?>\s*/dev/null|2>&1|&>\s*\S+)\s*$")
354
+ _TRIVIAL_SEGMENTS = {"true", "echo", ":", "exit"}
355
+
356
+
357
+ def _is_check_segment(seg: str) -> bool:
358
+ seg = seg.strip()
359
+ while True:
360
+ new = _TRAILING_REDIRECT_RE.sub("", seg)
361
+ if new == seg:
362
+ break
363
+ seg = new
364
+ if not seg:
365
+ return False
366
+ mk = _MAKE_RE.match(seg)
367
+ if mk:
368
+ words = [w for w in mk.group("rest").split() if not w.startswith("-") and "=" not in w]
369
+ return all(_MAKE_OK_TARGET_WORDS & set(re.split(r"[-_:./]+", w.lower())) for w in words)
370
+ if _FORMAT_CHECK_RE.match(seg):
371
+ return bool(_NONMUTATING_FLAG_RE.search(seg)) and not _MUTATING_FLAG_RE.search(seg)
372
+ if _CHECK_RE.match(seg):
373
+ return not _MUTATING_FLAG_RE.search(seg)
374
+ return False
375
+
376
+
377
+ def is_check_command(cmd: str) -> bool:
378
+ """True when the whole command is a test/build/lint run (exit code is the answer)."""
379
+ norm = _CD_PREFIX_RE.sub("", _WS_RE.sub(" ", cmd or "").strip())
380
+ if not norm:
381
+ return False
382
+ found = False
383
+ for chunk in re.split(r"\s*(?:&&|;)\s*", norm):
384
+ parts = [p.strip() for p in re.split(r"(?<!\|)\|(?!\|)", chunk)]
385
+ head, filters = parts[0], parts[1:]
386
+ if not head:
387
+ continue
388
+ if head.split()[0] in _TRIVIAL_SEGMENTS:
389
+ continue
390
+ if not _is_check_segment(head):
391
+ return False
392
+ for f in filters:
393
+ if not f or f.split()[0] not in _FILTER_CMDS:
394
+ return False
395
+ found = True
396
+ return found
397
+
398
+
399
+ # ---------------------------------------------------------------------------
400
+ # Data model
401
+ # ---------------------------------------------------------------------------
402
+
403
+ class Call:
404
+ __slots__ = ("key", "shape", "kind", "turn", "ut", "ok", "prompt_key", "cmd_ok_check", "lit")
405
+
406
+ def __init__(self, key, shape, kind, turn, ut, prompt_key=None, cmd_ok_check=False, lit=None):
407
+ self.key = key
408
+ self.shape = shape
409
+ self.kind = kind # bash | read | grep | glob | edit | agent | other
410
+ self.turn = turn # index into Trace.turns
411
+ self.ut = ut # index into Trace.uturns
412
+ self.ok = None # None unknown, True success, False failure
413
+ self.prompt_key = prompt_key
414
+ self.cmd_ok_check = cmd_ok_check
415
+ self.lit = lit # redacted literal command (no placeholder collapse)
416
+
417
+
418
+ class Turn:
419
+ __slots__ = ("fresh", "cr", "cc", "cc1h", "cc5m", "out", "model", "reply_chars", "ut")
420
+
421
+ def __init__(self, ut):
422
+ self.fresh = self.cr = self.cc = self.cc1h = self.cc5m = self.out = 0
423
+ self.model = "unknown"
424
+ self.reply_chars = 0
425
+ self.ut = ut
426
+
427
+
428
+ class Trace:
429
+ __slots__ = ("session", "calls", "turns", "uturns", "path")
430
+
431
+ def __init__(self, session, path=""):
432
+ self.session = session
433
+ self.path = path
434
+ self.calls: list[Call] = []
435
+ self.turns: list[Turn] = []
436
+ self.uturns: list[dict[str, list[int]]] = [] # {"turns": [...], "calls": [...]}
437
+
438
+ def new_uturn(self) -> int:
439
+ self.uturns.append({"turns": [], "calls": []})
440
+ return len(self.uturns) - 1
441
+
442
+ def current_uturn(self) -> int:
443
+ return len(self.uturns) - 1 if self.uturns else self.new_uturn()
444
+
445
+ def new_turn(self) -> int:
446
+ ut = self.current_uturn()
447
+ self.turns.append(Turn(ut))
448
+ idx = len(self.turns) - 1
449
+ self.uturns[ut]["turns"].append(idx)
450
+ return idx
451
+
452
+ def add_call(self, call: Call) -> None:
453
+ self.calls.append(call)
454
+ self.uturns[call.ut]["calls"].append(len(self.calls) - 1)
455
+
456
+
457
+ class BudgetExceeded(Exception):
458
+ pass
459
+
460
+
461
+ class Redactor:
462
+ """Wraps the credential redactor; remembers if it ever failed (fail closed)."""
463
+
464
+ def __init__(self, fn: Callable[[str], str] | None):
465
+ self.fn = fn
466
+ self.failed = fn is None
467
+
468
+ def __call__(self, text: str) -> str:
469
+ if self.fn is None:
470
+ self.failed = True
471
+ return text
472
+ try:
473
+ return self.fn(text)
474
+ except Exception:
475
+ self.failed = True
476
+ return text
477
+
478
+
479
+ class Throttle:
480
+ """Wrap a progress callback so it fires at most once per ``interval_s`` (first call always passes)."""
481
+
482
+ def __init__(self, fn: "Callable[[str], None] | None", interval_s: float = PROGRESS_MIN_INTERVAL_S,
483
+ clock: Callable[[], float] = time.monotonic):
484
+ self.fn = fn
485
+ self.interval_s = interval_s
486
+ self.clock = clock
487
+ self._last: float | None = None
488
+
489
+ def __call__(self, msg: str) -> None:
490
+ if self.fn is None:
491
+ return
492
+ now = self.clock()
493
+ if self._last is not None and now - self._last < self.interval_s:
494
+ return
495
+ self._last = now
496
+ self.fn(msg)
497
+
498
+
499
+ def default_redactor() -> Redactor:
500
+ try:
501
+ from credential_patterns import redact_credentials
502
+ return Redactor(redact_credentials)
503
+ except Exception:
504
+ return Redactor(None)
505
+
506
+
507
+ # ---------------------------------------------------------------------------
508
+ # Tool-call keys
509
+ # ---------------------------------------------------------------------------
510
+
511
+ _BOOKKEEPING = frozenset({
512
+ "TodoWrite", "TaskCreate", "TaskUpdate", "TaskList", "TaskGet", "TaskOutput", "TaskStop",
513
+ "ExitPlanMode", "EnterPlanMode", "AskUserQuestion", "ToolSearch", "SendMessage",
514
+ "update_plan", "wait_agent", "close_agent", "ListAgents", "ReadNotifications",
515
+ })
516
+ _EDIT_TOOLS = frozenset({"Edit", "Write", "MultiEdit", "NotebookEdit", "apply_patch"})
517
+ _READ_TOOLS = frozenset({"Read", "NotebookRead", "view_image"})
518
+ _AGENT_TOOLS = frozenset({"Agent", "Task", "spawn_agent"})
519
+ _BASH_TOOLS = frozenset({"Bash", "exec_command", "shell", "shell_command", "container.exec", "local_shell", "write_stdin"})
520
+
521
+
522
+ def _ext_of(path: Any) -> str:
523
+ if not isinstance(path, str) or not path:
524
+ return "?"
525
+ base = re.split(r"[\\/]+", path.rstrip("\\/"))[-1]
526
+ ext = os.path.splitext(base)[1].lower()
527
+ return ext or (base.lower() if base else "?")
528
+
529
+
530
+ class _KeyMaker:
531
+ """Turns a tool call into (key, shape, kind). Memoised; redacts before shaping."""
532
+
533
+ def __init__(self, redact: Redactor):
534
+ self.redact = redact
535
+ self._cmd_memo: dict[str, tuple[str, str, bool]] = {}
536
+
537
+ def command(self, raw: str) -> tuple[str, str, bool, str]:
538
+ hit = self._cmd_memo.get(raw)
539
+ if hit is None:
540
+ clean = self.redact(raw[:INLINE_READ_CHARS])
541
+ inline = split_inline_script(clean)
542
+ if inline is not None:
543
+ head, body = inline
544
+ norm = normalise_command(head)
545
+ key = f"B:{norm}#{inline_script_fingerprint(body)}"
546
+ shape = f"Bash: {norm} [script: {inline_script_snippet(body)}]"
547
+ else:
548
+ norm = normalise_command(clean)
549
+ key, shape = "B:" + norm, "Bash: " + norm
550
+ # The literal form keeps every parameter: polling means re-running
551
+ # ONE literal command; a normalised shape that hides several
552
+ # literals is a parameter sweep.
553
+ lit = _CD_PREFIX_RE.sub("", _WS_RE.sub(" ", clean).strip())
554
+ hit = (key, shape, is_check_command(clean), lit)
555
+ if len(self._cmd_memo) < 20000:
556
+ self._cmd_memo[raw] = hit
557
+ return hit
558
+
559
+ def prompt(self, raw: str) -> str:
560
+ clean = self.redact(raw[:1500])
561
+ return normalise_command(clean, max_chars=PROMPT_KEY_CHARS)
562
+
563
+ def generic(self, name: str, inp: dict) -> tuple[str, str]:
564
+ parts = []
565
+ for k in sorted(inp):
566
+ v = inp[k]
567
+ if isinstance(v, (int, float, bool)) and not isinstance(v, bool):
568
+ parts.append(f"{k}=<n>")
569
+ elif isinstance(v, bool):
570
+ parts.append(f"{k}={str(v).lower()}")
571
+ elif isinstance(v, str):
572
+ s = normalise_command(self.redact(v[:300]), max_chars=60)
573
+ parts.append(f"{k}={s}")
574
+ else:
575
+ parts.append(f"{k}=<{type(v).__name__}>")
576
+ body = ",".join(parts)[:160]
577
+ return f"O:{name}({body})", f"{name}({body})"
578
+
579
+ def build(self, name: str, inp: dict) -> tuple[str, str, str, str | None, bool, str | None]:
580
+ """Return (key, shape, kind, prompt_key, is_check, lit)."""
581
+ if name in _BASH_TOOLS:
582
+ cmd = inp.get("command") if "command" in inp else inp.get("cmd")
583
+ if isinstance(cmd, list):
584
+ cmd = cmd[-1] if cmd and isinstance(cmd[-1], str) and len(cmd) >= 3 and cmd[1] in ("-c", "-lc") else " ".join(str(c) for c in cmd)
585
+ if name == "write_stdin":
586
+ polling = not inp.get("chars")
587
+ label = "write_stdin <poll>" if polling else "write_stdin <input>"
588
+ return "B:" + label, "Bash: " + label, "bash", None, False, label
589
+ if not isinstance(cmd, str) or not cmd.strip():
590
+ return "B:?", "Bash: ?", "bash", None, False, "?"
591
+ key, shape, chk, lit = self.command(cmd)
592
+ return key, shape, "bash", None, chk, lit
593
+ if name in _READ_TOOLS:
594
+ ext = _ext_of(inp.get("file_path") or inp.get("path") or inp.get("notebook_path"))
595
+ return f"R:{ext}", f"Read *{ext}", "read", None, False, None
596
+ if name in _EDIT_TOOLS:
597
+ if name == "apply_patch":
598
+ ext = _ext_of(inp.get("_patch_path"))
599
+ else:
600
+ ext = _ext_of(inp.get("file_path") or inp.get("path") or inp.get("notebook_path"))
601
+ return f"E:{name}:{ext}", f"{name} *{ext}", "edit", None, False, None
602
+ if name == "Grep":
603
+ pat = normalise_command(self.redact(str(inp.get("pattern") or "")[:200]), max_chars=80)
604
+ scope = inp.get("glob") or inp.get("type") or ""
605
+ scope = _ext_of(scope) if isinstance(scope, str) and scope else ""
606
+ return f"G:{pat}|{scope}", f'Grep "{pat}" {scope}'.strip(), "grep", None, False, None
607
+ if name == "Glob":
608
+ pat = normalise_command(self.redact(str(inp.get("pattern") or "")[:200]), max_chars=80)
609
+ return f"L:{pat}", f"Glob {pat}", "glob", None, False, None
610
+ if name in _AGENT_TOOLS:
611
+ prompt = inp.get("prompt") or inp.get("message") or inp.get("task") or inp.get("description") or ""
612
+ if not isinstance(prompt, str):
613
+ prompt = ""
614
+ pk = self.prompt(prompt)
615
+ return f"A:{pk}", f"Agent: {pk}", "agent", pk, False, None
616
+ key, shape = self.generic(name, inp)
617
+ return key, shape, "other", None, False, None
618
+
619
+
620
+ # ---------------------------------------------------------------------------
621
+ # Claude Code transcript reader
622
+ # ---------------------------------------------------------------------------
623
+
624
+ _TOOL_USE_ID_RE = re.compile(r'"tool_use_id"\s*:\s*"([^"]+)"')
625
+ _IS_ERROR_TRUE_RE = re.compile(r'"is_error"\s*:\s*true')
626
+
627
+
628
+ def _safe_int(value: Any) -> int:
629
+ try:
630
+ return int(float(value or 0))
631
+ except (TypeError, ValueError, OverflowError):
632
+ return 0
633
+
634
+
635
+ def _iter_lines(path: Path, deadline: float | None):
636
+ try:
637
+ if os.stat(path).st_size > MAX_PARSE_FILE_BYTES:
638
+ return
639
+ except OSError:
640
+ return
641
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
642
+ for n, line in enumerate(fh):
643
+ if deadline is not None and (n & 1023) == 0 and time.monotonic() >= deadline:
644
+ raise BudgetExceeded()
645
+ if len(line) > MAX_JSONL_LINE_CHARS:
646
+ continue
647
+ yield line
648
+
649
+
650
+ def _human_user_text(rec: dict) -> bool:
651
+ """True for a record a human authored (not tool output, not injected meta)."""
652
+ if rec.get("isMeta") or rec.get("isCompactSummary"):
653
+ return False
654
+ msg = rec.get("message")
655
+ content = msg.get("content") if isinstance(msg, dict) else msg
656
+ if isinstance(content, str):
657
+ return bool(content.strip())
658
+ if isinstance(content, list):
659
+ has_text = False
660
+ for b in content:
661
+ if isinstance(b, dict):
662
+ if b.get("type") == "tool_result":
663
+ return False
664
+ if b.get("type") == "text" and str(b.get("text") or "").strip():
665
+ has_text = True
666
+ elif isinstance(b, str) and b.strip():
667
+ has_text = True
668
+ return has_text
669
+ return False
670
+
671
+
672
+ def extract_claude(path: Path | str, keys: _KeyMaker, seen_ids: set,
673
+ deadline: float | None = None) -> Trace | None:
674
+ """Read one Claude Code transcript into a Trace (None if it holds nothing usable).
675
+
676
+ Records already seen in a newer transcript (a resumed or forked session copies
677
+ its history, including requestIds and tool_use ids) are skipped so history is
678
+ counted once. ``seen_ids`` is updated only when the whole file was read.
679
+ """
680
+ path = Path(path)
681
+ trace = Trace(path.stem, str(path))
682
+ turn_by_req: dict[str, int] = {}
683
+ call_by_id: dict[str, Call] = {}
684
+ local_ids: set[str] = set()
685
+ for line in _iter_lines(path, deadline):
686
+ if '"assistant"' not in line and '"user"' not in line:
687
+ continue
688
+ if len(line) > _BIG_LINE_CHARS and '"type":"user"' in line[:2000] and '"tool_result"' in line:
689
+ ids = _TOOL_USE_ID_RE.findall(line)
690
+ if len(ids) == 1:
691
+ call = call_by_id.get(ids[0])
692
+ if call is not None:
693
+ call.ok = not _IS_ERROR_TRUE_RE.search(line)
694
+ continue
695
+ try:
696
+ rec = json.loads(line)
697
+ except (json.JSONDecodeError, ValueError):
698
+ continue
699
+ if not isinstance(rec, dict) or rec.get("isSidechain") is True:
700
+ continue
701
+ rtype = rec.get("type")
702
+ if rtype == "assistant":
703
+ msg = rec.get("message")
704
+ if not isinstance(msg, dict):
705
+ continue
706
+ rid = rec.get("requestId") or msg.get("id")
707
+ if isinstance(rid, str) and rid in seen_ids:
708
+ continue
709
+ tidx = turn_by_req.get(rid) if isinstance(rid, str) else None
710
+ if tidx is None:
711
+ tidx = trace.new_turn()
712
+ if isinstance(rid, str):
713
+ turn_by_req[rid] = tidx
714
+ local_ids.add(rid)
715
+ turn = trace.turns[tidx]
716
+ usage = msg.get("usage")
717
+ if isinstance(usage, dict):
718
+ cc_obj = usage.get("cache_creation")
719
+ cc_obj = cc_obj if isinstance(cc_obj, dict) else {}
720
+ cc1 = _safe_int(cc_obj.get("ephemeral_1h_input_tokens") or usage.get("ephemeral_1h_input_tokens"))
721
+ cc5 = _safe_int(cc_obj.get("ephemeral_5m_input_tokens") or usage.get("ephemeral_5m_input_tokens"))
722
+ cc = _safe_int(usage.get("cache_creation_input_tokens")) or (cc1 + cc5)
723
+ turn.fresh = max(turn.fresh, _safe_int(usage.get("input_tokens")))
724
+ turn.out = max(turn.out, _safe_int(usage.get("output_tokens")))
725
+ turn.cr = max(turn.cr, _safe_int(usage.get("cache_read_input_tokens")))
726
+ turn.cc = max(turn.cc, cc)
727
+ turn.cc1h = max(turn.cc1h, cc1)
728
+ turn.cc5m = max(turn.cc5m, cc5)
729
+ model = msg.get("model")
730
+ if isinstance(model, str) and model and model != "<synthetic>":
731
+ turn.model = model
732
+ content = msg.get("content")
733
+ if isinstance(content, str):
734
+ turn.reply_chars += len(content)
735
+ elif isinstance(content, list):
736
+ for block in content:
737
+ if not isinstance(block, dict):
738
+ continue
739
+ btype = block.get("type")
740
+ if btype == "text":
741
+ turn.reply_chars += len(str(block.get("text") or ""))
742
+ elif btype == "tool_use":
743
+ name = block.get("name")
744
+ cid = block.get("id")
745
+ if not isinstance(name, str) or name in _BOOKKEEPING:
746
+ continue
747
+ if isinstance(cid, str) and (cid in seen_ids or cid in call_by_id):
748
+ continue
749
+ if len(trace.calls) >= MAX_CALLS_PER_SESSION:
750
+ continue
751
+ inp = block.get("input")
752
+ inp = inp if isinstance(inp, dict) else {}
753
+ key, shape, kind, pkey, chk, lit = keys.build(name, inp)
754
+ call = Call(key, shape, kind, tidx, turn.ut, pkey, chk, lit)
755
+ trace.add_call(call)
756
+ if isinstance(cid, str):
757
+ call_by_id[cid] = call
758
+ local_ids.add(cid)
759
+ elif rtype == "user":
760
+ msg = rec.get("message")
761
+ content = msg.get("content") if isinstance(msg, dict) else None
762
+ if isinstance(content, list):
763
+ for block in content:
764
+ if isinstance(block, dict) and block.get("type") == "tool_result":
765
+ call = call_by_id.get(block.get("tool_use_id"))
766
+ if call is not None:
767
+ call.ok = not bool(block.get("is_error"))
768
+ if _human_user_text(rec):
769
+ if not trace.uturns or trace.uturns[-1]["turns"] or trace.uturns[-1]["calls"]:
770
+ trace.new_uturn()
771
+ if not trace.turns:
772
+ return None
773
+ seen_ids.update(local_ids)
774
+ return trace
775
+
776
+
777
+ # ---------------------------------------------------------------------------
778
+ # Codex transcript reader
779
+ # ---------------------------------------------------------------------------
780
+
781
+ _CODEX_EXIT_RE = re.compile(r"(?:exited with code|exit code:?)\s*(-?\d+)", re.I)
782
+ _CODEX_PATCH_FILE_RE = re.compile(r"^\*\*\* (?:Add|Update|Delete) File: (.+)$", re.M)
783
+ _CODEX_ENV_PREFIXES = ("<environment_context>", "<user_instructions>", "<user_action>", "# AGENTS.md", "<permissions")
784
+
785
+
786
+ def _codex_args(payload: dict) -> dict:
787
+ raw = payload.get("arguments")
788
+ if isinstance(raw, dict):
789
+ return raw
790
+ if isinstance(raw, str) and raw.strip():
791
+ try:
792
+ parsed = json.loads(raw)
793
+ except (json.JSONDecodeError, ValueError):
794
+ return {}
795
+ return parsed if isinstance(parsed, dict) else {}
796
+ return {}
797
+
798
+
799
+ def _codex_text(payload: dict) -> str:
800
+ if payload.get("type") in ("user_message", "agent_message"):
801
+ return str(payload.get("message") or "")
802
+ content = payload.get("content")
803
+ if isinstance(content, str):
804
+ return content
805
+ if isinstance(content, list):
806
+ return "\n".join(str(i.get("text") or "") if isinstance(i, dict) else str(i) for i in content)
807
+ return ""
808
+
809
+
810
+ def _codex_exit_from_output(output: Any) -> int | None:
811
+ if isinstance(output, str):
812
+ stripped = output.lstrip()
813
+ if stripped.startswith("{"):
814
+ try:
815
+ obj = json.loads(stripped)
816
+ except (json.JSONDecodeError, ValueError):
817
+ obj = None
818
+ if isinstance(obj, dict):
819
+ meta = obj.get("metadata")
820
+ if isinstance(meta, dict) and isinstance(meta.get("exit_code"), int):
821
+ return meta["exit_code"]
822
+ m = _CODEX_EXIT_RE.search(output[:4000])
823
+ if m:
824
+ return int(m.group(1))
825
+ return None
826
+
827
+
828
+ def extract_codex(path: Path | str, keys: _KeyMaker, seen_ids: set,
829
+ deadline: float | None = None) -> Trace | None:
830
+ path = Path(path)
831
+ trace = Trace(path.stem, str(path))
832
+ call_by_id: dict[str, Call] = {}
833
+ local_ids: set[str] = set()
834
+ open_turn: int | None = None
835
+ agent_msg_chars = 0
836
+ message_chars = 0
837
+ model = "unknown"
838
+ prev_total: dict[str, int] | None = None
839
+ uturn_reply: dict[int, list[int]] = {}
840
+
841
+ def ensure_turn() -> int:
842
+ nonlocal open_turn
843
+ if open_turn is None:
844
+ open_turn = trace.new_turn()
845
+ trace.turns[open_turn].model = model
846
+ return open_turn
847
+
848
+ def add_reply(n_agent: int, n_msg: int) -> None:
849
+ ut = trace.current_uturn()
850
+ acc = uturn_reply.setdefault(ut, [0, 0])
851
+ acc[0] += n_agent
852
+ acc[1] += n_msg
853
+
854
+ for line in _iter_lines(path, deadline):
855
+ try:
856
+ rec = json.loads(line)
857
+ except (json.JSONDecodeError, ValueError):
858
+ continue
859
+ if not isinstance(rec, dict):
860
+ continue
861
+ payload = rec.get("payload")
862
+ if not isinstance(payload, dict):
863
+ continue
864
+ ptype = payload.get("type")
865
+ rtype = rec.get("type")
866
+ m = payload.get("model")
867
+ if isinstance(m, str) and m.strip():
868
+ model = m.strip()
869
+ if open_turn is not None:
870
+ trace.turns[open_turn].model = model
871
+
872
+ if rtype == "session_meta":
873
+ sid = payload.get("id")
874
+ if isinstance(sid, str) and sid:
875
+ trace.session = sid
876
+ continue
877
+
878
+ if ptype == "user_message" or (rtype == "response_item" and ptype == "message" and payload.get("role") == "user"):
879
+ text = _codex_text(payload).lstrip()
880
+ if ptype == "message" and (not text or text.startswith(_CODEX_ENV_PREFIXES)):
881
+ continue
882
+ if not trace.uturns or trace.uturns[-1]["turns"] or trace.uturns[-1]["calls"]:
883
+ trace.new_uturn()
884
+ open_turn = None
885
+ elif ptype == "agent_message":
886
+ ensure_turn()
887
+ add_reply(len(_codex_text(payload)), 0)
888
+ elif ptype == "message" and payload.get("role") == "assistant":
889
+ ensure_turn()
890
+ add_reply(0, len(_codex_text(payload)))
891
+ elif ptype in ("function_call", "custom_tool_call", "local_shell_call"):
892
+ raw_name = str(payload.get("name") or ("local_shell" if ptype == "local_shell_call" else "unknown"))
893
+ cid = payload.get("call_id") or payload.get("id")
894
+ if raw_name in _BOOKKEEPING:
895
+ continue
896
+ if isinstance(cid, str) and (cid in seen_ids or cid in call_by_id):
897
+ continue
898
+ if len(trace.calls) >= MAX_CALLS_PER_SESSION:
899
+ continue
900
+ args = _codex_args(payload)
901
+ if ptype == "local_shell_call":
902
+ action = payload.get("action")
903
+ if isinstance(action, dict):
904
+ args = {"command": action.get("command")}
905
+ if raw_name == "apply_patch":
906
+ patch = payload.get("input") if isinstance(payload.get("input"), str) else str(args.get("input") or "")
907
+ pm = _CODEX_PATCH_FILE_RE.search(patch or "")
908
+ args = {"_patch_path": pm.group(1) if pm else ""}
909
+ tidx = ensure_turn()
910
+ key, shape, kind, pkey, chk, lit = keys.build(raw_name, args)
911
+ call = Call(key, shape, kind, tidx, trace.turns[tidx].ut, pkey, chk, lit)
912
+ trace.add_call(call)
913
+ if isinstance(cid, str):
914
+ call_by_id[cid] = call
915
+ local_ids.add(cid)
916
+ elif ptype == "collab_agent_spawn_end":
917
+ cid = payload.get("call_id")
918
+ if isinstance(cid, str) and (cid in call_by_id or cid in seen_ids):
919
+ continue
920
+ prompt = payload.get("prompt")
921
+ if isinstance(prompt, str) and prompt.strip():
922
+ tidx = ensure_turn()
923
+ key, shape, kind, pkey, chk, lit = keys.build("spawn_agent", {"prompt": prompt})
924
+ call = Call(key, shape, kind, tidx, trace.turns[tidx].ut, pkey, chk, lit)
925
+ call.ok = True
926
+ trace.add_call(call)
927
+ if isinstance(cid, str):
928
+ call_by_id[cid] = call
929
+ local_ids.add(cid)
930
+ elif ptype in ("function_call_output", "custom_tool_call_output"):
931
+ call = call_by_id.get(payload.get("call_id"))
932
+ if call is not None and call.ok is None:
933
+ code = _codex_exit_from_output(payload.get("output"))
934
+ if code is not None:
935
+ call.ok = code == 0
936
+ elif ptype == "exec_command_end":
937
+ call = call_by_id.get(payload.get("call_id"))
938
+ code = payload.get("exit_code")
939
+ if call is not None and isinstance(code, int):
940
+ call.ok = code == 0
941
+ elif ptype == "token_count":
942
+ info = payload.get("info")
943
+ if not isinstance(info, dict):
944
+ continue
945
+ total = info.get("total_token_usage")
946
+ last = info.get("last_token_usage")
947
+ use = None
948
+ if isinstance(total, dict):
949
+ cur = {k: _safe_int(total.get(k)) for k in ("input_tokens", "cached_input_tokens", "output_tokens")}
950
+ if prev_total is not None and cur["input_tokens"] >= prev_total["input_tokens"]:
951
+ use = {k: max(0, cur[k] - prev_total[k]) for k in cur}
952
+ prev_total = cur
953
+ elif prev_total is not None:
954
+ # Cumulative went backwards (compaction/resume): the per-call figure is the only safe one.
955
+ if isinstance(last, dict):
956
+ use = {k: _safe_int(last.get(k)) for k in cur}
957
+ else:
958
+ use = {k: _safe_int(last.get(k)) for k in cur} if isinstance(last, dict) else cur
959
+ prev_total = cur
960
+ elif isinstance(last, dict):
961
+ use = {k: _safe_int(last.get(k)) for k in ("input_tokens", "cached_input_tokens", "output_tokens")}
962
+ if not use or not (use["input_tokens"] or use["output_tokens"]):
963
+ continue
964
+ tidx = ensure_turn()
965
+ t = trace.turns[tidx]
966
+ cached = min(use["cached_input_tokens"], use["input_tokens"])
967
+ t.fresh += use["input_tokens"] - cached
968
+ t.cr += cached
969
+ t.out += use["output_tokens"]
970
+ open_turn = None
971
+
972
+ if not trace.turns:
973
+ return None
974
+ for ut, (agent_chars, msg_chars) in uturn_reply.items():
975
+ # response_item messages repeat the event_msg text; take the larger, never the sum.
976
+ if ut < len(trace.uturns) and trace.uturns[ut]["turns"]:
977
+ trace.turns[trace.uturns[ut]["turns"][-1]].reply_chars += max(agent_chars, msg_chars)
978
+ seen_ids.update(local_ids)
979
+ return trace
980
+
981
+
982
+ EXTRACTORS = {"claude": extract_claude, "codex": extract_codex}
983
+
984
+
985
+ # ---------------------------------------------------------------------------
986
+ # Detectors
987
+ # ---------------------------------------------------------------------------
988
+
989
+ _SUGGESTIONS = {
990
+ "repeated_sequence": "Wrap this exact sequence in one script (or a skill/hook that runs it) and let the model read only the result.",
991
+ "templated_subagent": "Same prompt shape launched repeatedly: if the work is mechanical, make it a parameterised script or scheduled job; keep a subagent only for the judgment step.",
992
+ "polling_loop": "Replace the model re-check loop with a script that waits (until <condition>; exit code) or a hook/scheduled job that notifies on completion.",
993
+ "parameter_sweep": "Same command shape run with different parameters: drive the values from one script loop (for x in ...; do cmd \"$x\"; done) or a matrix/table run, and let the model read only the results.",
994
+ "check_only_turn": "Run it from a hook, pre-commit or make target and read the exit code; the model does not need a turn to learn that it passed.",
995
+ }
996
+
997
+
998
+ class _Cand:
999
+ __slots__ = ("kind", "example", "times", "sessions", "turns", "extra")
1000
+
1001
+ def __init__(self, kind, example):
1002
+ self.kind = kind
1003
+ self.example = example
1004
+ self.times = 0
1005
+ self.sessions: set[int] = set()
1006
+ self.turns: set[tuple[int, int]] = set() # (trace index, turn index)
1007
+ self.extra: dict[str, Any] = {}
1008
+
1009
+
1010
+ def _distinct_ok(calls: list[Call]) -> bool:
1011
+ return len({c.key for c in calls}) >= 2 and any(c.kind in ("bash", "grep", "glob", "agent", "other") for c in calls)
1012
+
1013
+
1014
+ def detect_sequences(traces: list[Trace], deadline: float | None) -> tuple[list[_Cand], bool]:
1015
+ """Ordered runs of 3+ calls seen in 3+ sessions. Apriori-pruned so memory stays small."""
1016
+ intern: dict[str, int] = {}
1017
+ seqs: list[list[int]] = []
1018
+ seq_calls: list[list[Call]] = []
1019
+ for tr in traces:
1020
+ ids = []
1021
+ for c in tr.calls:
1022
+ ids.append(intern.setdefault(c.key, len(intern)))
1023
+ seqs.append(ids)
1024
+ seq_calls.append(tr.calls)
1025
+ partial = False
1026
+
1027
+ def over() -> bool:
1028
+ return deadline is not None and time.monotonic() >= deadline
1029
+
1030
+ # k = 1: keys in 3+ sessions
1031
+ sess_count: Counter = Counter()
1032
+ for ids in seqs:
1033
+ sess_count.update(set(ids))
1034
+ good_prev = {(k,) for k, c in sess_count.items() if c >= MIN_SEQ_SESSIONS}
1035
+ good_by_k: dict[int, set] = {}
1036
+ k = 1
1037
+ while good_prev and k < MAX_SEQ_LEN:
1038
+ k += 1
1039
+ counts: Counter = Counter()
1040
+ for ids in seqs:
1041
+ if over():
1042
+ return [], True
1043
+ if len(ids) < k:
1044
+ continue
1045
+ grams = set(zip(*[ids[j:] for j in range(k)]))
1046
+ counts.update(g for g in grams if g[:-1] in good_prev and g[1:] in good_prev)
1047
+ good_prev = {g for g, c in counts.items() if c >= MIN_SEQ_SESSIONS}
1048
+ if k >= MIN_SEQ_LEN and good_prev:
1049
+ good_by_k[k] = good_prev
1050
+ if not good_by_k:
1051
+ return [], partial
1052
+
1053
+ # Occurrences for the surviving n-grams only.
1054
+ occ: dict[tuple, list[tuple[int, int]]] = defaultdict(list)
1055
+ for si, ids in enumerate(seqs):
1056
+ if over():
1057
+ return [], True
1058
+ for k, good in good_by_k.items():
1059
+ if len(ids) < k:
1060
+ continue
1061
+ for pos, g in enumerate(zip(*[ids[j:] for j in range(k)])):
1062
+ if g in good:
1063
+ occ[g].append((si, pos))
1064
+
1065
+ rev = {v: k for k, v in intern.items()}
1066
+ ranked = []
1067
+ for g, places in occ.items():
1068
+ sessions = {si for si, _ in places}
1069
+ if len(sessions) < MIN_SEQ_SESSIONS:
1070
+ continue
1071
+ si0, pos0 = places[0]
1072
+ calls0 = seq_calls[si0][pos0:pos0 + len(g)]
1073
+ if not _distinct_ok(calls0):
1074
+ continue
1075
+ ranked.append((len(g), len(sessions), g, places, sessions))
1076
+ # Longest first; a shorter run that lives inside an accepted longer run in the same sessions is noise.
1077
+ ranked.sort(key=lambda r: (-r[0], -r[1]))
1078
+ covered: dict[tuple, int] = {}
1079
+ cands: list[_Cand] = []
1080
+ for k, nsess, g, places, sessions in ranked:
1081
+ if covered.get(g) == nsess:
1082
+ continue
1083
+ for kk in range(MIN_SEQ_LEN, k + 1):
1084
+ for s in range(0, k - kk + 1):
1085
+ covered.setdefault(g[s:s + kk], nsess)
1086
+ si0, pos0 = places[0]
1087
+ calls0 = seq_calls[si0][pos0:pos0 + k]
1088
+ cand = _Cand("repeated_sequence", " -> ".join(c.shape for c in calls0))
1089
+ by_session: dict[int, list[int]] = defaultdict(list)
1090
+ for si, pos in places:
1091
+ by_session[si].append(pos)
1092
+ for si, plist in by_session.items():
1093
+ last_end = -1
1094
+ for pos in sorted(plist):
1095
+ if pos < last_end:
1096
+ continue
1097
+ last_end = pos + k
1098
+ cand.times += 1
1099
+ cand.sessions.add(si)
1100
+ for c in seq_calls[si][pos:pos + k]:
1101
+ cand.turns.add((si, c.turn))
1102
+ cand.extra["sequence_length"] = k
1103
+ cands.append(cand)
1104
+ if len(cands) >= 400:
1105
+ break
1106
+ return cands, partial
1107
+
1108
+
1109
+ def detect_subagents(traces: list[Trace]) -> list[_Cand]:
1110
+ groups: dict[str, _Cand] = {}
1111
+ for si, tr in enumerate(traces):
1112
+ for c in tr.calls:
1113
+ if c.kind != "agent" or not c.prompt_key:
1114
+ continue
1115
+ cand = groups.get(c.prompt_key)
1116
+ if cand is None:
1117
+ cand = groups[c.prompt_key] = _Cand("templated_subagent", c.prompt_key)
1118
+ cand.times += 1
1119
+ cand.sessions.add(si)
1120
+ cand.turns.add((si, c.turn))
1121
+ return [c for c in groups.values() if c.times >= MIN_SUBAGENT_LAUNCHES]
1122
+
1123
+
1124
+ # A `sleep` segment is the model waiting for state to change: that is a
1125
+ # re-check loop even when the checked target's parameters differ each run.
1126
+ _SLEEP_SEGMENT_RE = re.compile(r"(?:^|&&|\|\||;|\|)\s*sleep(?=\s|$)")
1127
+
1128
+
1129
+ def detect_polling(traces: list[Trace]) -> list[_Cand]:
1130
+ groups: dict[tuple[str, str], _Cand] = {}
1131
+ for si, tr in enumerate(traces):
1132
+ runs: dict[str, list[Call]] = defaultdict(list)
1133
+
1134
+ def flush():
1135
+ for key, calls in runs.items():
1136
+ if len(calls) < MIN_POLL_RUNS:
1137
+ continue
1138
+ by_lit: dict[str, list[Call]] = defaultdict(list)
1139
+ for c in calls:
1140
+ by_lit[c.lit or c.shape].append(c)
1141
+ # a normalised shape collapses digits/strings/paths,
1142
+ # so `run-0`..`run-5` lands in one group. A polling loop
1143
+ # re-runs ONE literal command; several distinct literals is
1144
+ # a parameter sweep and needs different advice.
1145
+ loops = [lc for lc in by_lit.values() if len(lc) >= MIN_POLL_RUNS]
1146
+ if not loops:
1147
+ waiting = [c for c in calls if _SLEEP_SEGMENT_RE.search(c.lit or "")]
1148
+ if len(waiting) >= MIN_POLL_RUNS:
1149
+ loops = [waiting]
1150
+ if loops:
1151
+ loop_calls = [c for lc in loops for c in lc]
1152
+ cand = groups.get((key, "polling_loop"))
1153
+ if cand is None:
1154
+ cand = groups[(key, "polling_loop")] = _Cand("polling_loop", loop_calls[0].shape)
1155
+ cand.times += len(loop_calls)
1156
+ cand.sessions.add(si)
1157
+ for c in loop_calls:
1158
+ cand.turns.add((si, c.turn))
1159
+ elif len(by_lit) >= 2:
1160
+ cand = groups.get((key, "parameter_sweep"))
1161
+ if cand is None:
1162
+ cand = groups[(key, "parameter_sweep")] = _Cand("parameter_sweep", calls[0].shape)
1163
+ cand.times += len(calls)
1164
+ cand.sessions.add(si)
1165
+ for c in calls:
1166
+ cand.turns.add((si, c.turn))
1167
+ runs.clear()
1168
+
1169
+ for c in tr.calls:
1170
+ if c.kind == "edit":
1171
+ flush()
1172
+ elif c.kind == "bash":
1173
+ runs[c.key].append(c)
1174
+ flush()
1175
+ return list(groups.values())
1176
+
1177
+
1178
+ def detect_check_turns(traces: list[Trace]) -> list[_Cand]:
1179
+ groups: dict[str, _Cand] = {}
1180
+ for si, tr in enumerate(traces):
1181
+ for ut in tr.uturns:
1182
+ if len(ut["calls"]) != 1:
1183
+ continue
1184
+ call = tr.calls[ut["calls"][0]]
1185
+ if call.kind != "bash" or not call.cmd_ok_check or call.ok is not True:
1186
+ continue
1187
+ if sum(tr.turns[t].reply_chars for t in ut["turns"]) > SHORT_REPLY_CHARS:
1188
+ continue
1189
+ cand = groups.get(call.key)
1190
+ if cand is None:
1191
+ cand = groups[call.key] = _Cand("check_only_turn", call.shape)
1192
+ cand.times += 1
1193
+ cand.sessions.add(si)
1194
+ for t in ut["turns"]:
1195
+ cand.turns.add((si, t))
1196
+ return [c for c in groups.values() if c.times >= MIN_CHECK_TURNS]
1197
+
1198
+
1199
+ # ---------------------------------------------------------------------------
1200
+ # Assembly
1201
+ # ---------------------------------------------------------------------------
1202
+
1203
+ PriceFn = Callable[[str, int, int, int, int, int, int], "float | None"]
1204
+
1205
+
1206
+ def _price_turns(traces: list[Trace], turns: Iterable[tuple[int, int]], price: PriceFn) -> dict[str, Any]:
1207
+ fresh = cr = cc = out = 0
1208
+ cost = 0.0
1209
+ priced = unpriced = 0
1210
+ for si, ti in turns:
1211
+ t = traces[si].turns[ti]
1212
+ fresh += t.fresh
1213
+ cr += t.cr
1214
+ cc += t.cc
1215
+ out += t.out
1216
+ c = price(t.model, t.fresh, t.out, t.cr, t.cc, t.cc1h, t.cc5m)
1217
+ if c is None or (c == 0 and (t.fresh or t.cr or t.cc or t.out)):
1218
+ unpriced += 1
1219
+ else:
1220
+ cost += c
1221
+ priced += 1
1222
+ input_tokens = fresh + cr + cc
1223
+ return {
1224
+ "input_tokens": input_tokens,
1225
+ "cache_read_tokens": cr,
1226
+ "output_tokens": out,
1227
+ "total_tokens": input_tokens + out,
1228
+ "cost_usd": round(cost, 4),
1229
+ "cost_complete": unpriced == 0,
1230
+ "turns": priced + unpriced,
1231
+ }
1232
+
1233
+
1234
+ def _finish_example(text: str, redact: Redactor) -> str:
1235
+ if redact.failed:
1236
+ return WITHHELD
1237
+ out = redact(text)
1238
+ if redact.failed:
1239
+ return WITHHELD
1240
+ out = _WS_RE.sub(" ", out).strip()
1241
+ return out if len(out) <= EXAMPLE_CAP else out[:EXAMPLE_CAP - 3] + "..."
1242
+
1243
+
1244
+ def analyse(traces: list[Trace], price: PriceFn, redact: Redactor,
1245
+ deadline: float | None = None) -> tuple[list[dict], dict[str, Any], bool]:
1246
+ """Run all detectors. Returns (candidates, union totals, partial)."""
1247
+ cands = detect_check_turns(traces) + detect_polling(traces) + detect_subagents(traces)
1248
+ partial = False
1249
+ try:
1250
+ seq, seq_partial = detect_sequences(traces, deadline)
1251
+ cands += seq
1252
+ partial = partial or seq_partial
1253
+ except MemoryError:
1254
+ partial = True
1255
+ scored = []
1256
+ for c in cands:
1257
+ stats = _price_turns(traces, c.turns, price)
1258
+ scored.append((stats["total_tokens"], stats["cost_usd"], c, stats))
1259
+ scored.sort(key=lambda r: (-r[0], -r[1], -r[2].times))
1260
+ top = scored[:MAX_CANDIDATES]
1261
+ out = []
1262
+ union: set[tuple[int, int]] = set()
1263
+ for _, _, c, stats in top:
1264
+ union |= c.turns
1265
+ entry = {
1266
+ "kind": c.kind,
1267
+ "example": _finish_example(c.example, redact),
1268
+ "times_seen": c.times,
1269
+ "sessions_seen": len(c.sessions),
1270
+ "tokens": {k: stats[k] for k in ("input_tokens", "cache_read_tokens", "output_tokens", "total_tokens")},
1271
+ "cost_usd": stats["cost_usd"],
1272
+ "cost_complete": stats["cost_complete"],
1273
+ "suggestion": _SUGGESTIONS[c.kind],
1274
+ "basis": BASIS,
1275
+ }
1276
+ if "sequence_length" in c.extra:
1277
+ entry["sequence_length"] = c.extra["sequence_length"]
1278
+ if c.kind == "templated_subagent":
1279
+ entry["tokens_scope"] = "launching turns only; subagent transcripts are not attributed"
1280
+ out.append(entry)
1281
+ totals = _price_turns(traces, union, price)
1282
+ return out, totals, partial
1283
+
1284
+
1285
+ def summary_line(result: dict[str, Any]) -> str:
1286
+ """One human line for `coach` output."""
1287
+ status = result.get("status")
1288
+ if status == "not_measurable":
1289
+ return f"Deterministic candidates: {result.get('reason') or 'not measurable on this runtime'}"
1290
+ if status == "error":
1291
+ return "Deterministic candidates: unavailable (analysis error, coach output unaffected)"
1292
+ window = f"last {result.get('days', 30)}d, {result.get('sessions_scanned', 0)} sessions"
1293
+ cands = result.get("candidates") or []
1294
+ suffix = " (partial: time budget reached)" if result.get("partial") else ""
1295
+ if not cands:
1296
+ return f"Deterministic candidates: none found ({window}; {BASIS}){suffix}"
1297
+ tot = result.get("totals") or {}
1298
+ top = cands[0]
1299
+ return (
1300
+ f"Deterministic candidates: {len(cands)} workflow pattern(s) that could be plain code; "
1301
+ f"the turns that ran them used {tot.get('total_tokens', 0):,} tokens "
1302
+ f"(~${tot.get('cost_usd', 0):.2f} API-equivalent) "
1303
+ f"({window}; {BASIS}). Top: {top['kind']} x{top['times_seen']}: {top['example'][:80]}{suffix}"
1304
+ )
1305
+
1306
+
1307
+ # ---------------------------------------------------------------------------
1308
+ # Cache (Token Optimizer's own data dir; redacted shapes and counts only)
1309
+ # ---------------------------------------------------------------------------
1310
+
1311
+ CACHE_NAME = "deterministic-candidates-cache.json"
1312
+ _CACHE_MAX_ENTRIES = 6
1313
+
1314
+
1315
+ def cache_key(runtime: str, days: int, cap: int, tier: str, files: list[tuple[Path, float]]) -> str:
1316
+ newest = 0
1317
+ for _, mt in files:
1318
+ newest = max(newest, int(mt * 1e9))
1319
+ raw = f"{ALGO_VERSION}|{runtime}|{days}|{cap}|{tier}|{newest}|{len(files)}"
1320
+ return hashlib.sha256(raw.encode()).hexdigest()[:24]
1321
+
1322
+
1323
+ def cache_load(cache_dir: Path | None, key: str, now: float | None = None) -> dict | None:
1324
+ if cache_dir is None:
1325
+ return None
1326
+ try:
1327
+ data = json.loads((Path(cache_dir) / CACHE_NAME).read_text(encoding="utf-8"))
1328
+ entry = data.get("entries", {}).get(key)
1329
+ if not isinstance(entry, dict) or not isinstance(entry.get("result"), dict):
1330
+ return None
1331
+ result = entry["result"]
1332
+ if result.get("partial"):
1333
+ if (now if now is not None else time.time()) - float(entry.get("saved_at") or 0) > PARTIAL_CACHE_TTL_S:
1334
+ return None
1335
+ return result
1336
+ except (OSError, ValueError, TypeError, AttributeError):
1337
+ return None
1338
+
1339
+
1340
+ def cache_store(cache_dir: Path | None, key: str, result: dict, now: float | None = None) -> bool:
1341
+ if cache_dir is None:
1342
+ return False
1343
+ try:
1344
+ directory = Path(cache_dir)
1345
+ directory.mkdir(parents=True, exist_ok=True)
1346
+ path = directory / CACHE_NAME
1347
+ try:
1348
+ data = json.loads(path.read_text(encoding="utf-8"))
1349
+ entries = data.get("entries") if isinstance(data, dict) else None
1350
+ except (OSError, ValueError):
1351
+ entries = None
1352
+ entries = entries if isinstance(entries, dict) else {}
1353
+ entries[key] = {"saved_at": now if now is not None else time.time(), "result": result}
1354
+ if len(entries) > _CACHE_MAX_ENTRIES:
1355
+ for old in sorted(entries, key=lambda k: float(entries[k].get("saved_at") or 0))[:len(entries) - _CACHE_MAX_ENTRIES]:
1356
+ entries.pop(old, None)
1357
+ tmp = path.with_name(path.name + f".{os.getpid()}.tmp")
1358
+ tmp.write_text(json.dumps({"entries": entries}), encoding="utf-8")
1359
+ os.replace(tmp, path)
1360
+ return True
1361
+ except (OSError, TypeError, ValueError):
1362
+ return False
1363
+
1364
+
1365
+ # ---------------------------------------------------------------------------
1366
+ # Orchestration
1367
+ # ---------------------------------------------------------------------------
1368
+
1369
+ def run(
1370
+ runtime: str,
1371
+ files: list[tuple[Path, float]],
1372
+ price: PriceFn,
1373
+ *,
1374
+ days: int = 30,
1375
+ budget_s: float = 8.0,
1376
+ max_sessions: int = 60,
1377
+ cache_dir: Path | None = None,
1378
+ tier: str = "",
1379
+ use_cache: bool = True,
1380
+ redact: Redactor | None = None,
1381
+ progress: Callable[[str], None] | None = None,
1382
+ ) -> dict[str, Any]:
1383
+ """Scan ``files`` (newest first) and return the deterministic_candidates block.
1384
+
1385
+ Never raises: any internal failure comes back as ``status: "error"`` so
1386
+ ``coach --json`` cannot fail because of this block.
1387
+ """
1388
+ started = time.monotonic()
1389
+ base: dict[str, Any] = {
1390
+ "runtime": runtime, "days": days, "basis": BASIS, "tokens_note": USED_NOT_SAVED_NOTE, "partial": False,
1391
+ "candidates": [], "runtime_support": runtime_support_table(),
1392
+ }
1393
+ try:
1394
+ if not RUNTIME_SUPPORT.get(runtime, {}).get("measurable"):
1395
+ nm = not_measurable(runtime)
1396
+ base.update(status="not_measurable", reason=nm["reason"], sessions_scanned=0, not_measurable=[nm])
1397
+ base["summary"] = summary_line(base)
1398
+ return base
1399
+ files = sorted(files, key=lambda f: f[1], reverse=True)
1400
+ considered = files[:max(1, max_sessions)]
1401
+ key = cache_key(runtime, days, max_sessions, tier, considered)
1402
+ if use_cache:
1403
+ hit = cache_load(cache_dir, key)
1404
+ if hit is not None:
1405
+ hit = dict(hit)
1406
+ hit["cached"] = True
1407
+ return hit
1408
+ redact = redact or default_redactor()
1409
+ keys = _KeyMaker(redact)
1410
+ progress = Throttle(progress) if progress else None
1411
+ extract = EXTRACTORS[runtime]
1412
+ parse_deadline = started + budget_s * 0.7
1413
+ total_deadline = started + budget_s
1414
+ seen_ids: set = set()
1415
+ traces: list[Trace] = []
1416
+ partial = False
1417
+ scanned = 0
1418
+ for i, (path, _mt) in enumerate(considered):
1419
+ # >=: a spent budget (0.0 included) must stop even when the clock has
1420
+ # not ticked since `started`. Windows' monotonic clock moves in ~15 ms
1421
+ # steps, so a strict > let a zero budget scan every file.
1422
+ if time.monotonic() >= parse_deadline:
1423
+ partial = True
1424
+ break
1425
+ if progress:
1426
+ progress(f"deterministic-candidates: reading session {i + 1}/{len(considered)}")
1427
+ try:
1428
+ tr = extract(path, keys, seen_ids, parse_deadline)
1429
+ except BudgetExceeded:
1430
+ partial = True
1431
+ break
1432
+ except OSError:
1433
+ continue
1434
+ scanned += 1
1435
+ if tr is not None:
1436
+ traces.append(tr)
1437
+ if len(files) > len(considered):
1438
+ base["sessions_not_scanned_cap"] = len(files) - len(considered)
1439
+ cands, totals, a_partial = analyse(traces, price, redact, total_deadline)
1440
+ partial = partial or a_partial
1441
+ base.update(
1442
+ status="ok" if cands else "no_data",
1443
+ candidates=cands,
1444
+ totals=totals,
1445
+ partial=partial,
1446
+ sessions_scanned=scanned,
1447
+ sessions_found=len(files),
1448
+ elapsed_s=round(time.monotonic() - started, 2),
1449
+ cached=False,
1450
+ )
1451
+ base["summary"] = summary_line(base)
1452
+ if use_cache:
1453
+ cache_store(cache_dir, key, base)
1454
+ return base
1455
+ except Exception as exc: # the coach must never fail because of this block
1456
+ base.update(status="error", error=f"{type(exc).__name__}: {str(exc)[:120]}", partial=True,
1457
+ sessions_scanned=0, summary="Deterministic candidates: unavailable (analysis error, coach output unaffected)")
1458
+ return base