@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,504 @@
1
+ """Cache instability detector: flags CLAUDE.md patterns that break Anthropic prompt cache prefix stability."""
2
+
3
+ from runtime_env import detect_runtime
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ import tempfile
9
+ import time
10
+ from pathlib import Path
11
+
12
+ _TIMESTAMP_PATTERNS = [
13
+ re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}"), # ISO datetime
14
+ re.compile(r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s+\w+\s+\d{1,2}"), # Day, Month DD
15
+ re.compile(r"Updated:\s*\d{4}-\d{2}-\d{2}"), # Updated: YYYY-MM-DD
16
+ re.compile(r"Last (?:updated|modified|synced):\s*\d"), # Last updated: ...
17
+ re.compile(r"^(?:>?\s*)?As of \d{4}-\d{2}"), # As of 2026-04 (month-level = volatile, year-level = stable)
18
+ ]
19
+
20
+ _DYNAMIC_SECTION_MARKERS = [
21
+ "TOKEN_OPTIMIZER:MODEL_ROUTING",
22
+ "AUTO-GENERATED",
23
+ "DO NOT EDIT",
24
+ "Generated by",
25
+ "Synced from",
26
+ ]
27
+
28
+ _IMPORT_RE = re.compile(r"@import\s+[\"']([^\"']+)[\"']")
29
+
30
+ # Volatile token indicators for @import paths in CLAUDE.md. Used ONLY by Signal
31
+ # 3 (the @import path scan), NOT by the MCP scan: MCP env/args/url VALUES never
32
+ # reach the model-facing prompt (only tool schemas do), so scanning them for
33
+ # these substrings produced pervasive false positives (any --log-level, a
34
+ # /status URL, a current-site path tripped it). The MCP signal now targets the
35
+ # server SET instead; see _scan_mcp_servers.
36
+ _VOLATILE_TOKENS = ("status", "log", "daily", "current", "temp", "cache")
37
+
38
+ # Module-level caches keyed by resolved cwd so the 10-session loop in
39
+ # run_all_detectors reads each surface file at most once per measure run.
40
+ _MCP_SCAN_CACHE: dict = {}
41
+ _PROCESS_SCAN_CACHE: dict = {}
42
+
43
+ # Bound on the number of process-library prefix files scanned, to keep the
44
+ # detector cheap even in repos with very large process trees.
45
+ _PROCESS_FILE_CAP = 40
46
+
47
+ # Cap on a single config/prefix file read, so a huge ~/.claude.json or a
48
+ # symlinked /dev/zero cannot hang or OOM a measure run. 1 MiB is far above any
49
+ # legitimate .mcp.json/.claude.json or process prefix file.
50
+ _READ_CAP_BYTES = 1_000_000
51
+
52
+ # State filename for the MCP server-set diff (Signal 4). Records the set of MCP
53
+ # server names per resolved cwd so a later run can detect add/remove -- the
54
+ # config-detectable proxy for tool-schema churn in the cached prefix.
55
+ _MCP_STATE_FILENAME = "cache_instability_mcp_state.json"
56
+
57
+
58
+ def _has_timestamp(text):
59
+ """Return True if *text* matches any timestamp pattern."""
60
+ return any(pat.search(text) for pat in _TIMESTAMP_PATTERNS)
61
+
62
+
63
+ def _safe_read_text(path):
64
+ """Read up to ``_READ_CAP_BYTES`` from *path* without following symlinks.
65
+
66
+ Returns the text (errors replaced) or ``None`` when the file is absent, a
67
+ symlink, too large, or unreadable. Symlink rejection matters: a symlink in
68
+ .claude/processes or a project .mcp.json must not be followed into
69
+ /dev/zero or an attacker-chosen huge file. The cap matters for
70
+ ~/.claude.json, which accumulates per-project history and can run to many
71
+ MB. Fail-open: callers treat None as "no signal".
72
+ """
73
+ try:
74
+ if not path.exists() or path.is_symlink():
75
+ return None
76
+ if path.stat().st_size > _READ_CAP_BYTES:
77
+ return None
78
+ return path.read_text(encoding="utf-8", errors="replace")
79
+ except (PermissionError, OSError, ValueError):
80
+ return None
81
+
82
+
83
+ def _state_dir():
84
+ """Resolve a writable state dir for the detector, mirroring
85
+ plugin_env.resolve_snapshot_dir()'s CLAUDE_PLUGIN_DATA handling.
86
+ TOKEN_OPTIMIZER_SNAPSHOT_DIR wins (tests/sandbox); else the
87
+ identity-checked CLAUDE_PLUGIN_DATA (via plugin_env.resolve_claude_plugin_data_env
88
+ -- this detector WRITES state, so a foreign
89
+ plugin's CLAUDE_PLUGIN_DATA sharing the same shared plugins/data root must
90
+ never redirect that write into another plugin's directory, unlike the
91
+ pre-fix raw env read this duplicated); else ~/.claude/token-optimizer/data.
92
+ Returns None only if HOME itself is unresolvable, in which case the
93
+ snapshot diff is skipped (no finding, no crash).
94
+ """
95
+ override = os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip()
96
+ if override:
97
+ return Path(override).expanduser()
98
+ try:
99
+ from plugin_env import resolve_claude_plugin_data_env
100
+ plugin_data = resolve_claude_plugin_data_env()
101
+ except Exception:
102
+ plugin_data = None
103
+ if plugin_data is not None:
104
+ return plugin_data / "data"
105
+ try:
106
+ return Path.home() / ".claude" / "token-optimizer" / "data"
107
+ except (RuntimeError, OSError):
108
+ return None
109
+
110
+
111
+ def _scan_prefix_lines(lines, surface_label, cutoff_ratio=0.6):
112
+ """Run the timestamp-pattern scan and the auto-gen-marker scan over *lines*.
113
+
114
+ Returns the same finding dicts the CLAUDE.md path produces today, with the
115
+ surface label parameterised so the helper can be reused for other
116
+ cache-prefix-resident surfaces. When *surface_label* is ``"CLAUDE.md"`` the
117
+ output is byte-identical to the pre-refactor CLAUDE.md signals.
118
+ """
119
+ if not lines:
120
+ return []
121
+
122
+ findings = []
123
+ prefix_cutoff = int(len(lines) * cutoff_ratio)
124
+
125
+ # Signal 1: Timestamps or dates in the first 60% of the surface
126
+ early_timestamps = []
127
+ for i, line in enumerate(lines[:prefix_cutoff]):
128
+ for pat in _TIMESTAMP_PATTERNS:
129
+ if pat.search(line):
130
+ early_timestamps.append((i + 1, line.strip()[:80]))
131
+ break
132
+
133
+ if early_timestamps:
134
+ # Tokens wasted = everything after the first timestamp that could be cached
135
+ first_ts_line = early_timestamps[0][0]
136
+ chars_after = sum(len(lines[i]) for i in range(first_ts_line, len(lines)))
137
+ wasted_tokens = chars_after // 4
138
+ if wasted_tokens > 500:
139
+ evidence_lines = "; ".join(f"L{ln}" for ln, _ in early_timestamps[:3])
140
+ findings.append({
141
+ "name": "cache_instability",
142
+ "confidence": 0.75,
143
+ "evidence": (
144
+ f"Timestamps in {surface_label} prefix ({evidence_lines}) invalidate prompt cache "
145
+ f"for ~{wasted_tokens:,} tokens of stable content below them"
146
+ ),
147
+ "savings_tokens": wasted_tokens,
148
+ "suggestion": (
149
+ f"Move timestamped content to the bottom of {surface_label}. "
150
+ f"Anthropic's prompt cache is prefix-based: everything before the first "
151
+ f"changing line gets cached. ~{wasted_tokens:,} tokens of stable rules "
152
+ f"could get cache hits (90% cost reduction) if timestamps move to the end."
153
+ ),
154
+ "occurrence_count": len(early_timestamps),
155
+ })
156
+
157
+ # Signal 2: Auto-generated sections in the first 60%
158
+ dynamic_sections = []
159
+ for i, line in enumerate(lines[:prefix_cutoff]):
160
+ for marker in _DYNAMIC_SECTION_MARKERS:
161
+ if marker in line:
162
+ dynamic_sections.append((i + 1, marker))
163
+ break
164
+
165
+ if dynamic_sections:
166
+ first_dynamic = dynamic_sections[0][0]
167
+ chars_after = sum(len(lines[i]) for i in range(first_dynamic, len(lines)))
168
+ wasted_tokens = chars_after // 4
169
+ if wasted_tokens > 500:
170
+ markers_found = ", ".join(m for _, m in dynamic_sections[:3])
171
+ findings.append({
172
+ "name": "cache_instability",
173
+ "confidence": 0.7,
174
+ "evidence": (
175
+ f"Auto-generated sections in {surface_label} prefix ({markers_found} at "
176
+ f"L{first_dynamic}) change between sessions, breaking cache"
177
+ ),
178
+ "savings_tokens": wasted_tokens,
179
+ "suggestion": (
180
+ f"Move auto-generated sections to the end of {surface_label}. "
181
+ "Content that changes per-session should be after stable content "
182
+ "to preserve prompt cache hits on the prefix."
183
+ ),
184
+ "occurrence_count": len(dynamic_sections),
185
+ })
186
+
187
+ return findings
188
+
189
+
190
+ def _mcp_candidate_files(cwd):
191
+ """Return the ordered list of MCP config files to inspect for *cwd*.
192
+
193
+ Project-local files first, then the home fallback. Order matters: the
194
+ project-local ``.claude.json`` overrides the home one for the server-set
195
+ scan.
196
+ """
197
+ cwd_path = Path(cwd)
198
+ return [
199
+ cwd_path / ".mcp.json",
200
+ cwd_path / ".claude.json",
201
+ Path.home() / ".claude.json",
202
+ ]
203
+
204
+
205
+ def _read_mcp_server_set(cwd):
206
+ """Return the set of MCP server names configured for *cwd*.
207
+
208
+ Union of the ``mcpServers`` keys across the candidate config files.
209
+ ``env``/``args``/``url``/``command`` VALUES are deliberately NOT inspected:
210
+ they never reach the model-facing prompt (the host loads them to spawn
211
+ servers; the model receives tool SCHEMAS, not the env values), so their
212
+ churn does not invalidate the prompt cache. The server SET is the
213
+ config-detectable proxy for tool-schema churn: adding or removing a server
214
+ changes the set of tool schemas injected into the cached prefix.
215
+ """
216
+ servers = set()
217
+ for path in _mcp_candidate_files(cwd):
218
+ text = _safe_read_text(path)
219
+ if text is None:
220
+ continue
221
+ try:
222
+ data = json.loads(text)
223
+ except (json.JSONDecodeError, ValueError):
224
+ continue
225
+ if not isinstance(data, dict):
226
+ continue
227
+ s = data.get("mcpServers")
228
+ if not isinstance(s, dict):
229
+ continue
230
+ for name, cfg in s.items():
231
+ if isinstance(cfg, dict):
232
+ servers.add(str(name))
233
+ return servers
234
+
235
+
236
+ def _load_mcp_state(state_path):
237
+ """Read the persisted server-set state, or {} on any error/missing file."""
238
+ if state_path is None:
239
+ return {}
240
+ text = _safe_read_text(state_path)
241
+ if text is None:
242
+ return {}
243
+ try:
244
+ data = json.loads(text)
245
+ except (json.JSONDecodeError, ValueError):
246
+ return {}
247
+ return data if isinstance(data, dict) else {}
248
+
249
+
250
+ def _save_mcp_state(state_path, state):
251
+ """Atomically persist the server-set state. Fail-open on any I/O error."""
252
+ if state_path is None:
253
+ return
254
+ try:
255
+ state_path.parent.mkdir(parents=True, exist_ok=True)
256
+ # Unique temp name (not a fixed ".tmp" sibling): two concurrent measure
257
+ # runs in different cwds would otherwise write the SAME ".tmp" and clobber
258
+ # each other, so one os.replace promotes the wrong content and the other
259
+ # raises FileNotFoundError. mkstemp gives each writer its own temp.
260
+ fd, tmp = tempfile.mkstemp(dir=str(state_path.parent), prefix=state_path.name + ".", suffix=".tmp")
261
+ try:
262
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
263
+ fh.write(json.dumps(state))
264
+ os.replace(tmp, state_path)
265
+ except BaseException:
266
+ try:
267
+ os.unlink(tmp)
268
+ except OSError:
269
+ pass
270
+ raise
271
+ except (PermissionError, OSError, ValueError):
272
+ pass
273
+
274
+
275
+ def _scan_mcp_servers(cwd):
276
+ """Signal 4: detect MCP server add/remove between measure runs.
277
+
278
+ The cached prompt prefix includes the tool-schema block the host builds from
279
+ the configured MCP servers. Adding or removing a server changes that block
280
+ and invalidates the cache for everything after it -- the same effect a
281
+ CLAUDE.md edit has. The server SET (the ``mcpServers`` keys in .mcp.json /
282
+ .claude.json) is the config-detectable proxy for that churn.
283
+
284
+ What this does NOT do, and why: it does not scan ``env``/``args``/``url``
285
+ VALUES. Those never reach the model-facing prompt (only tool schemas do), so
286
+ their churn does not break the prefix cache; scanning them for volatile
287
+ substrings was the old behaviour and produced pervasive false positives
288
+ (any ``--log-level``, a ``/status`` URL, a ``current-site`` path tripped
289
+ it). It also does not detect per-tool description/count churn, because that
290
+ is not visible in config files -- it requires runtime tool-list capture,
291
+ which is out of scope for a config-file detector.
292
+
293
+ State: one entry per resolved cwd in ``_MCP_STATE_FILENAME`` under the
294
+ snapshot dir. The first run for a cwd records a baseline and fires nothing
295
+ (there is no prior set to diff against); subsequent runs fire when the set
296
+ changes and update the baseline. Fail-open on any I/O error.
297
+ """
298
+ key = str(Path(cwd).resolve())
299
+ if key in _MCP_SCAN_CACHE:
300
+ return _MCP_SCAN_CACHE[key]
301
+
302
+ findings = []
303
+ current = _read_mcp_server_set(cwd)
304
+
305
+ state_dir = _state_dir()
306
+ state_path = (state_dir / _MCP_STATE_FILENAME) if state_dir is not None else None
307
+ state = _load_mcp_state(state_path)
308
+ prev_entry = state.get(key)
309
+ prev_servers = None
310
+ if isinstance(prev_entry, dict):
311
+ ps = prev_entry.get("servers")
312
+ if isinstance(ps, list):
313
+ prev_servers = set(ps)
314
+
315
+ # First run for this cwd: record baseline, no churn to report yet.
316
+ if prev_servers is None:
317
+ state[key] = {"servers": sorted(current), "ts": time.time()}
318
+ _save_mcp_state(state_path, state)
319
+ _MCP_SCAN_CACHE[key] = findings
320
+ return findings
321
+
322
+ added = current - prev_servers
323
+ removed = prev_servers - current
324
+
325
+ # Persist the new baseline regardless of whether we fire.
326
+ state[key] = {"servers": sorted(current), "ts": time.time()}
327
+ _save_mcp_state(state_path, state)
328
+
329
+ if added or removed:
330
+ parts = []
331
+ if added:
332
+ parts.append("+ " + ", ".join(sorted(added)[:5]))
333
+ if removed:
334
+ parts.append("- " + ", ".join(sorted(removed)[:5]))
335
+ findings.append({
336
+ "name": "cache_instability",
337
+ "confidence": 0.7,
338
+ "evidence": (
339
+ f"MCP server set changed since last measure ({'; '.join(parts)}): "
340
+ f"adding/removing a server changes the tool schemas in the cached "
341
+ f"prompt prefix, invalidating the cache for everything after them"
342
+ ),
343
+ "savings_tokens": 1500,
344
+ "suggestion": (
345
+ "MCP server add/remove changes the tool-schema block in the cached "
346
+ "prefix, so each rotation costs one uncached turn. Keep the server "
347
+ "set stable across sessions. (Per-tool description churn is not "
348
+ "detectable from config files alone and is not flagged here.)"
349
+ ),
350
+ "occurrence_count": len(added) + len(removed),
351
+ })
352
+
353
+ _MCP_SCAN_CACHE[key] = findings
354
+ return findings
355
+
356
+
357
+ def _process_prefix_dirs(cwd):
358
+ """Return the ordered list of process-library prefix directories to scan."""
359
+ cwd_path = Path(cwd)
360
+ home = Path.home()
361
+ return [
362
+ cwd_path / ".a5c" / "processes",
363
+ cwd_path / ".claude" / "processes",
364
+ home / ".a5c" / "processes",
365
+ home / ".claude" / "processes",
366
+ ]
367
+
368
+
369
+ def _scan_process_prefixes(cwd):
370
+ """Signal 5: scan process-library prompt prefix files for cache-prefix churn.
371
+
372
+ ``.a5c/processes`` and ``.claude/processes`` hold prompt prefix files that
373
+ are loaded into the cached prefix; timestamps or auto-gen markers in their
374
+ first 60% break the cache. Bounded by ``_PROCESS_FILE_CAP`` and
375
+ ``_READ_CAP_BYTES``; symlinks are not followed (a symlinked entry must not
376
+ pull in an arbitrary huge file). Fail-open.
377
+ """
378
+ key = str(Path(cwd).resolve())
379
+ if key in _PROCESS_SCAN_CACHE:
380
+ return _PROCESS_SCAN_CACHE[key]
381
+
382
+ findings = []
383
+ unstable_files = []
384
+ try:
385
+ scanned = 0
386
+ for directory in _process_prefix_dirs(cwd):
387
+ if not directory.exists() or not directory.is_dir() or directory.is_symlink():
388
+ continue
389
+ for path in sorted(directory.iterdir()):
390
+ if scanned >= _PROCESS_FILE_CAP:
391
+ break
392
+ if not path.is_file() or path.is_symlink() or path.suffix not in (".md", ".txt"):
393
+ continue
394
+ scanned += 1
395
+ text = _safe_read_text(path)
396
+ if text is None or len(text) < 50:
397
+ continue
398
+ lines = text.splitlines()
399
+ prefix_cutoff = int(len(lines) * 0.6) or 1
400
+ for line in lines[:prefix_cutoff]:
401
+ if _has_timestamp(line):
402
+ unstable_files.append(path.name)
403
+ break
404
+ if any(marker in line for marker in _DYNAMIC_SECTION_MARKERS):
405
+ unstable_files.append(path.name)
406
+ break
407
+ if scanned >= _PROCESS_FILE_CAP:
408
+ break
409
+ except (PermissionError, OSError):
410
+ pass
411
+
412
+ if unstable_files:
413
+ names = ", ".join(unstable_files[:5])
414
+ findings.append({
415
+ "name": "cache_instability",
416
+ "confidence": 0.6,
417
+ "evidence": (
418
+ f"Process-library prompt prefix files contain timestamps or auto-gen "
419
+ f"markers in their first 60% ({names}), breaking the cached prefix"
420
+ ),
421
+ "savings_tokens": 1500,
422
+ "suggestion": (
423
+ "Move timestamped or auto-generated content in .a5c/processes and "
424
+ ".claude/processes prefix files to the end of each file, or strip the "
425
+ "volatile header. These files load into the cached prompt prefix."
426
+ ),
427
+ "occurrence_count": len(unstable_files),
428
+ })
429
+
430
+ _PROCESS_SCAN_CACHE[key] = findings
431
+ return findings
432
+
433
+
434
+ def detect_cache_instability(session_data):
435
+ """Detect CLAUDE.md patterns that break Anthropic's prefix-based prompt cache.
436
+
437
+ Anthropic caches a byte-identical prefix. Content that changes between sessions
438
+ (timestamps, auto-generated sections, volatile imports) invalidates the cache
439
+ for everything after it. Moving volatile content to the end preserves cache hits
440
+ on the stable prefix.
441
+
442
+ Surfaces scanned (all additive to the original CLAUDE.md signals):
443
+ 1-3. CLAUDE.md prefix: timestamps, auto-gen markers, volatile @imports.
444
+ 4. MCP server add/remove in .mcp.json / .claude.json (the server set is
445
+ the config-detectable proxy for tool-schema churn in the cached
446
+ prefix; env/args/url values are NOT scanned -- they never reach the
447
+ model-facing prompt).
448
+ 5. Process-library prompt prefix files in .a5c/processes, .claude/processes.
449
+ """
450
+ if detect_runtime() not in ("claude", "hermes"):
451
+ # Every surface here is Claude-runtime-specific (CLAUDE.md prefix,
452
+ # .mcp.json/.claude.json server sets, .claude/processes), and the
453
+ # MCP server-set state defaults to ~/.claude/token-optimizer/data.
454
+ # Foreign runtimes (codex, cursor, antigravity, ...) must not trigger
455
+ # reads, recommendations, or state writes on foreign-runtime paths.
456
+ # Hermes is a Claude runtime and keeps the scans.
457
+ return []
458
+ claude_md = session_data.get("claude_md_content", "")
459
+ # New surfaces must still run when CLAUDE.md is absent/small. With an empty
460
+ # `lines` list every original prefix loop is a no-op, so the 3 original
461
+ # signals behave exactly as before when CLAUDE.md is missing.
462
+ lines = claude_md.splitlines() if (claude_md and len(claude_md) >= 200) else []
463
+
464
+ findings = []
465
+
466
+ # Signals 1 & 2: timestamps and auto-gen markers in the CLAUDE.md prefix.
467
+ # _scan_prefix_lines with surface_label="CLAUDE.md" is byte-identical to the
468
+ # pre-refactor CLAUDE.md path.
469
+ findings.extend(_scan_prefix_lines(lines, "CLAUDE.md"))
470
+
471
+ # Signal 3: @import of volatile files in the first 60%
472
+ if lines:
473
+ prefix_cutoff = int(len(lines) * 0.6)
474
+ volatile_imports = []
475
+ for i, line in enumerate(lines[:prefix_cutoff]):
476
+ match = _IMPORT_RE.search(line)
477
+ if match:
478
+ path = match.group(1)
479
+ if any(v in path.lower() for v in _VOLATILE_TOKENS):
480
+ volatile_imports.append((i + 1, path))
481
+
482
+ if volatile_imports:
483
+ findings.append({
484
+ "name": "cache_instability",
485
+ "confidence": 0.6,
486
+ "evidence": (
487
+ "@import of volatile files in CLAUDE.md prefix: "
488
+ + ", ".join(p for _, p in volatile_imports[:3])
489
+ ),
490
+ "savings_tokens": 2000,
491
+ "suggestion": (
492
+ "Move @import of volatile files to the end of CLAUDE.md, or use "
493
+ "path-scoped rules files instead (which only load when relevant)."
494
+ ),
495
+ "occurrence_count": len(volatile_imports),
496
+ })
497
+
498
+ # Signal 4: MCP server add/remove (cached-prefix tool-schema churn).
499
+ findings.extend(_scan_mcp_servers(Path.cwd()))
500
+
501
+ # Signal 5: process-library prompt prefix files (cached-prefix-resident).
502
+ findings.extend(_scan_process_prefixes(Path.cwd()))
503
+
504
+ return findings
@@ -0,0 +1,88 @@
1
+ """Looping detector: high user-message similarity with low progress."""
2
+
3
+ import json
4
+
5
+
6
+ def _word_set(text):
7
+ """Extract lowercase word set for rough similarity."""
8
+ return set(text.lower().split())
9
+
10
+
11
+ def _similarity(a, b):
12
+ """Jaccard similarity between two word sets."""
13
+ if not a or not b:
14
+ return 0.0
15
+ intersection = len(a & b)
16
+ union = len(a | b)
17
+ return intersection / union if union else 0.0
18
+
19
+
20
+ def detect_looping(session_data):
21
+ """Detect sessions where user keeps asking similar things with low progress.
22
+
23
+ Scans JSONL for sequences of 4+ user messages with >75% word overlap,
24
+ indicating the model is stuck in a loop.
25
+ """
26
+ jsonl_path = session_data.get("jsonl_path")
27
+ if not jsonl_path:
28
+ return []
29
+
30
+ user_messages = []
31
+
32
+ try:
33
+ with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
34
+ for line in f:
35
+ try:
36
+ record = json.loads(line)
37
+ except json.JSONDecodeError:
38
+ continue
39
+
40
+ if record.get("type") != "user":
41
+ continue
42
+
43
+ msg = record.get("message", {})
44
+ content = msg.get("content") if isinstance(msg, dict) else msg
45
+ if isinstance(content, str) and len(content) > 10:
46
+ user_messages.append(content[:500])
47
+ elif isinstance(content, list):
48
+ for block in content:
49
+ if isinstance(block, dict) and block.get("type") == "text":
50
+ text = block.get("text", "")
51
+ if len(text) > 10:
52
+ user_messages.append(text[:500])
53
+ break
54
+
55
+ except (OSError, PermissionError):
56
+ return []
57
+
58
+ if len(user_messages) < 4:
59
+ return []
60
+
61
+ # Find runs of similar messages
62
+ findings = []
63
+ word_sets = [_word_set(m) for m in user_messages]
64
+ streak = 1
65
+ max_streak = 1
66
+
67
+ for i in range(1, len(word_sets)):
68
+ if _similarity(word_sets[i], word_sets[i - 1]) > 0.75:
69
+ streak += 1
70
+ max_streak = max(max_streak, streak)
71
+ else:
72
+ streak = 1
73
+
74
+ if max_streak >= 4:
75
+ est_tokens = max_streak * 5000
76
+ findings.append({
77
+ "name": "looping",
78
+ "confidence": 0.6,
79
+ "evidence": f"{max_streak} similar consecutive user messages detected",
80
+ "savings_tokens": est_tokens,
81
+ "suggestion": (
82
+ f"You sent {max_streak} similar messages in a row, suggesting the model was stuck. "
83
+ "Try: restate the problem differently, provide a concrete example, or /clear and start fresh."
84
+ ),
85
+ "occurrence_count": max_streak,
86
+ })
87
+
88
+ return findings