@alexgreensh/token-optimizer 5.13.65 → 5.13.67

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 (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +0 -10
  4. package/hooks/module_runner.py +62 -13
  5. package/hooks/userpromptsubmit_runner.py +13 -1
  6. package/package.json +1 -1
  7. package/skills/token-optimizer/examples/hooks-starter.json +0 -10
  8. package/skills/token-optimizer/scripts/_measure/__init__.py +16 -0
  9. package/skills/token-optimizer/scripts/_measure/_compat.py +200 -0
  10. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +9 -0
  11. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +23 -0
  12. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
  13. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +8 -0
  14. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_parser.py +770 -0
  15. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +112 -0
  16. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +10 -0
  17. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +6949 -0
  19. package/skills/token-optimizer/scripts/_measure/cache_policy.py +7050 -0
  20. package/skills/token-optimizer/scripts/_measure/cli.py +2722 -0
  21. package/skills/token-optimizer/scripts/_measure/continuity.py +4630 -0
  22. package/skills/token-optimizer/scripts/_measure/daemon.py +6773 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +4358 -0
  24. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6145 -0
  25. package/skills/token-optimizer/scripts/_measure/pricing.py +2101 -0
  26. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7138 -0
  27. package/skills/token-optimizer/scripts/_measure/runtime.py +1231 -0
  28. package/skills/token-optimizer/scripts/_measure/savings.py +7702 -0
  29. package/skills/token-optimizer/scripts/_measure/sessions.py +4784 -0
  30. package/skills/token-optimizer/scripts/_measure/trends.py +2432 -0
  31. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
  32. package/skills/token-optimizer/scripts/bash_compress.py +3 -3
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
  34. package/skills/token-optimizer/scripts/cloud_kit.py +7 -8
  35. package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
  36. package/skills/token-optimizer/scripts/codex_doctor.py +14 -0
  37. package/skills/token-optimizer/scripts/command_filters.py +630 -19
  38. package/skills/token-optimizer/scripts/devin_source.py +2 -1
  39. package/skills/token-optimizer/scripts/hermes_doctor.py +13 -0
  40. package/skills/token-optimizer/scripts/hermes_install.py +11 -0
  41. package/skills/token-optimizer/scripts/measure.py +2430 -60930
  42. package/skills/token-optimizer/scripts/read_cache.py +20 -21
  43. package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
  44. package/skills/token-optimizer/scripts/session_store.py +11 -48
@@ -0,0 +1,4358 @@
1
+ """Definition-only implementations; mutable state belongs to measure."""
2
+ from __future__ import annotations
3
+ from . import _compat
4
+
5
+
6
+ def _daemon_is_running():
7
+ """Return True iff the dashboard daemon identity probe passes.
8
+
9
+ Uses the same magic-string check as `daemon-status` so a foreign
10
+ process on 24842 is never mistaken for ours. Short timeout (0.5s)
11
+ because this is called from interactive paths where users are
12
+ waiting for a browser to open.
13
+ """
14
+ _measure_facade = _compat.facade()
15
+ import urllib.error
16
+ import urllib.request
17
+
18
+ magic = _measure_facade.DAEMON_IDENTITY_MAGIC.encode("utf-8")
19
+ for host in ("127.0.0.1", "[::1]"):
20
+ url = f"http://{host}:{_measure_facade.DAEMON_PORT}/__to_ping"
21
+ try:
22
+ with urllib.request.urlopen(url, timeout=0.5) as resp:
23
+ if resp.read(len(magic) + 8).strip() == magic:
24
+ return True
25
+ except (urllib.error.URLError, OSError, ValueError):
26
+ continue
27
+ return False
28
+
29
+
30
+ def _launch_opener(argv):
31
+ """Run a browser opener detached from our terminal (#199).
32
+
33
+ The opener and the browser it starts must not inherit our stdin/stdout/
34
+ stderr: Chrome logs freely to whatever stderr it gets, which painted over
35
+ TUI hosts like OpenCode. A new session keeps a TUI's Ctrl-C from reaching
36
+ the browser. We still wait briefly so a failing opener (bad exit code)
37
+ falls back to printing the URL; a slow opener is assumed to have launched.
38
+ """
39
+ _measure_facade = _compat.facade()
40
+ proc = _measure_facade.subprocess.Popen(
41
+ argv,
42
+ stdin=_measure_facade.subprocess.DEVNULL,
43
+ stdout=_measure_facade.subprocess.DEVNULL,
44
+ stderr=_measure_facade.subprocess.DEVNULL,
45
+ start_new_session=(_measure_facade.os.name == "posix"),
46
+ creationflags=_measure_facade._NO_WINDOW,
47
+ )
48
+ try:
49
+ rc = proc.wait(timeout=10)
50
+ except _measure_facade.subprocess.TimeoutExpired:
51
+ # A slow or hung opener: reap it in the background (no zombie, no
52
+ # ResourceWarning) and say where the page is, so a hang is never silent.
53
+ import threading
54
+ threading.Thread(target=proc.wait, daemon=True).start()
55
+ print(f" Browser is slow to open. If nothing appears, open: {argv[-1]}")
56
+ return
57
+ if rc != 0:
58
+ raise _measure_facade.subprocess.CalledProcessError(rc, argv)
59
+
60
+
61
+ def _open_in_browser(filepath):
62
+ """Open a file in the default browser. Cross-platform.
63
+
64
+ Kept for non-dashboard callers. For dashboard flows use
65
+ _open_dashboard() which prefers the bookmarkable URL when the
66
+ daemon is live.
67
+ """
68
+ _measure_facade = _compat.facade()
69
+ filepath = str(filepath)
70
+ system = _measure_facade.platform.system()
71
+ try:
72
+ if system == "Darwin":
73
+ _measure_facade._launch_opener(["open", filepath])
74
+ elif system == "Linux":
75
+ _measure_facade._launch_opener(["xdg-open", filepath])
76
+ elif system == "Windows":
77
+ _measure_facade.os.startfile(filepath)
78
+ else:
79
+ raise OSError(f"Unsupported platform: {system}")
80
+ except (_measure_facade.subprocess.CalledProcessError, OSError, FileNotFoundError):
81
+ url = _measure_facade.Path(filepath).as_uri()
82
+ print("\n Could not auto-open browser. Open manually:")
83
+ print(f" {url}")
84
+
85
+
86
+ def _open_dashboard(fallback_filepath):
87
+ """Open the dashboard, preferring the bookmarkable URL.
88
+
89
+ When the daemon is live, open http://localhost:24842/token-optimizer
90
+ so the user lands on their bookmark-ready URL instead of a
91
+ throwaway file:// path. The caller must still have written the
92
+ freshest content to DASHBOARD_PATH so the daemon serves current
93
+ data -- this helper doesn't touch files, only decides which
94
+ address to open.
95
+
96
+ Falls back to opening the file directly when the daemon isn't
97
+ live or the identity probe fails.
98
+ """
99
+ _measure_facade = _compat.facade()
100
+ if _measure_facade._daemon_is_running():
101
+ url = f"http://localhost:{_measure_facade.DAEMON_PORT}/token-optimizer"
102
+ system = _measure_facade.platform.system()
103
+ try:
104
+ if system == "Darwin":
105
+ _measure_facade._launch_opener(["open", url])
106
+ elif system == "Linux":
107
+ _measure_facade._launch_opener(["xdg-open", url])
108
+ elif system == "Windows":
109
+ _measure_facade.os.startfile(url)
110
+ else:
111
+ raise OSError(f"Unsupported platform: {system}")
112
+ print(f" Opened: {url}")
113
+ return
114
+ except (_measure_facade.subprocess.CalledProcessError, OSError, FileNotFoundError):
115
+ print(f"\n Could not auto-open browser. Open manually:\n {url}")
116
+ return
117
+ # Daemon down: open the file directly
118
+ _measure_facade._open_in_browser(fallback_filepath)
119
+
120
+
121
+ def _serve_dashboard(filepath, port=None, host=None):
122
+ """Serve the dashboard over HTTP for headless/remote access."""
123
+ _measure_facade = _compat.facade()
124
+ import http.server
125
+ import socketserver
126
+ import socket
127
+
128
+ filepath = _measure_facade.Path(filepath).resolve()
129
+ serve_dir = str(filepath.parent)
130
+ filename = filepath.name
131
+
132
+ # Find an available port if the default is taken
133
+ for attempt_port in range(port, port + 20):
134
+ try:
135
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
136
+ s.bind((host, attempt_port))
137
+ port = attempt_port
138
+ break
139
+ except OSError:
140
+ continue
141
+ else:
142
+ print(f" Error: no available port in range {port}-{port + 19}")
143
+ _measure_facade.sys.exit(1)
144
+
145
+ handler = http.server.SimpleHTTPRequestHandler
146
+
147
+ class DashboardHandler(handler):
148
+ def __init__(self, *a, **kw):
149
+ _measure_facade = _compat.facade()
150
+ super().__init__(*a, directory=serve_dir, **kw)
151
+
152
+ def log_message(self, *args):
153
+ _measure_facade = _compat.facade()
154
+ pass # suppress per-request logs (overrides BaseHTTPRequestHandler)
155
+
156
+ def end_headers(self):
157
+ _measure_facade = _compat.facade()
158
+ self.send_header("X-Content-Type-Options", "nosniff")
159
+ self.send_header("X-Frame-Options", "DENY")
160
+ self.send_header("Referrer-Policy", "no-referrer")
161
+ self.send_header(
162
+ "Content-Security-Policy", _measure_facade._DASHBOARD_CSP,
163
+ )
164
+ super().end_headers()
165
+
166
+ def _is_dashboard_request(self):
167
+ _measure_facade = _compat.facade()
168
+ requested = self.path.lstrip("/").split("?")[0]
169
+ return requested in ("", "token-optimizer", filename)
170
+
171
+ def _redirect_root(self):
172
+ _measure_facade = _compat.facade()
173
+ if self._is_dashboard_request():
174
+ if self.path.lstrip("/").split("?")[0] != filename:
175
+ self.send_response(302)
176
+ self.send_header("Location", f"/{filename}")
177
+ self.end_headers()
178
+ return True
179
+ return False
180
+
181
+ def _check_allowed(self):
182
+ """Only serve the dashboard file itself, nothing else."""
183
+ _measure_facade = _compat.facade()
184
+ if not self._is_dashboard_request():
185
+ self.send_error(403, "Forbidden")
186
+ return False
187
+ return True
188
+
189
+ def do_GET(self):
190
+ _measure_facade = _compat.facade()
191
+ path_only = self.path.split("?")[0]
192
+ # API health probe (lets dashboard detect our server vs generic)
193
+ if path_only == "/api/health":
194
+ self._json_response(200, {"ok": True, "server": "token-optimizer"})
195
+ return
196
+ # v5.4.19 identity magic probe (defeats foreign-port masquerade)
197
+ if path_only == "/__to_ping":
198
+ self._json_response(200, {"ok": True, "magic": _measure_facade.DAEMON_IDENTITY_MAGIC})
199
+ return
200
+ # v5.4.19 per-install token endpoint (H-2/M-4). Only served to
201
+ # localhost Origin+Host so a foreign site cannot exfiltrate it.
202
+ if path_only == "/api/token":
203
+ origin = self.headers.get("Origin", "")
204
+ host = self.headers.get("Host", "")
205
+ origin_ok = (not origin) or any(
206
+ origin.startswith(p) for p in ("http://127.0.0.1:", "http://localhost:", "http://[::1]:")
207
+ )
208
+ if not origin_ok or not _measure_facade._is_localhost_host_header(host):
209
+ self.send_error(403, "Forbidden")
210
+ return
211
+ self._json_response(200, {"token": _measure_facade._read_daemon_token()})
212
+ return
213
+ # Live savings recompute. A browser refresh against the daemon shows
214
+ # current savings/cache numbers WITHOUT paying for a full (multi-second)
215
+ # dashboard regen: the page fetches this and patches the tiles in place.
216
+ # Read-only, localhost-guarded (same DNS-rebinding defense as the static
217
+ # assets below), fail-open (a slow/failed eval degrades to a safe shape).
218
+ if path_only == "/api/savings":
219
+ if not _measure_facade._is_localhost_host_header(self.headers.get("Host", "")):
220
+ self.send_error(421, "Misdirected Request")
221
+ return
222
+ try:
223
+ payload = _measure_facade._live_savings_payload(days=30)
224
+ except Exception:
225
+ self._json_response(500, {"ok": False})
226
+ return
227
+ self._json_response(200, payload)
228
+ return
229
+ if self._redirect_root():
230
+ return
231
+ if not self._check_allowed():
232
+ return
233
+ # H-1 DNS rebinding defense: GETs to static assets must come from localhost Host
234
+ if not _measure_facade._is_localhost_host_header(self.headers.get("Host", "")):
235
+ self.send_error(421, "Misdirected Request")
236
+ return
237
+ super().do_GET()
238
+
239
+ def do_HEAD(self):
240
+ _measure_facade = _compat.facade()
241
+ if self._redirect_root():
242
+ return
243
+ if not self._check_allowed():
244
+ return
245
+ if not _measure_facade._is_localhost_host_header(self.headers.get("Host", "")):
246
+ self.send_error(421, "Misdirected Request")
247
+ return
248
+ super().do_HEAD()
249
+
250
+ def do_POST(self):
251
+ """Handle API requests for skill/MCP management.
252
+
253
+ v5.4.19 hardening (C-2/H-1/M-4):
254
+ - Reject empty Origin (no more bypass via curl/fetch-no-cors).
255
+ - Enforce Host allowlist (defeats DNS rebinding).
256
+ - Require X-TO-Token matching per-install secret.
257
+ """
258
+ # C-2 fix: require a non-empty, localhost-prefixed Origin.
259
+ _measure_facade = _compat.facade()
260
+ origin = self.headers.get("Origin", "")
261
+ if not origin or not any(origin.startswith(p) for p in ("http://127.0.0.1:", "http://localhost:", "http://[::1]:")):
262
+ self.send_error(403, "Forbidden: invalid origin")
263
+ return
264
+
265
+ # H-1 fix: Host header allowlist (localhost / 127.0.0.1 / [::1]).
266
+ if not _measure_facade._is_localhost_host_header(self.headers.get("Host", "")):
267
+ self.send_error(421, "Misdirected Request")
268
+ return
269
+
270
+ # M-4 fix: constant-time per-install token check.
271
+ expected_tok = _measure_facade._read_daemon_token()
272
+ got_tok = self.headers.get("X-TO-Token", "")
273
+ if not expected_tok or not _measure_facade.hmac.compare_digest(expected_tok, got_tok):
274
+ self.send_error(403, "Forbidden: invalid token")
275
+ return
276
+
277
+ path = self.path.split("?")[0]
278
+
279
+ # Body size limit
280
+ MAX_BODY = 65536 # 64KB
281
+ content_len = int(self.headers.get("Content-Length", 0))
282
+ if content_len > MAX_BODY:
283
+ self.send_error(413, "Request body too large")
284
+ return
285
+
286
+ # Read JSON body
287
+ body = {}
288
+ if content_len > 0:
289
+ try:
290
+ body = _measure_facade.json.loads(self.rfile.read(content_len))
291
+ except (_measure_facade.json.JSONDecodeError, ValueError):
292
+ pass
293
+
294
+ if path == "/api/session-turns":
295
+ raw_path = body.get("jsonl_path", "")
296
+ if not raw_path:
297
+ self._json_response(400, {"error": "Missing 'jsonl_path' field"})
298
+ return
299
+ try:
300
+ jsonl_path = _measure_facade.Path(raw_path).expanduser().resolve()
301
+ allowed_root = (_measure_facade.CLAUDE_DIR / "projects").resolve()
302
+ jsonl_path.relative_to(allowed_root)
303
+ except (ValueError, OSError):
304
+ self._json_response(403, {"error": "Forbidden: invalid session path"})
305
+ return
306
+ if not jsonl_path.exists():
307
+ self._json_response(404, {"error": "Session log not found"})
308
+ return
309
+ turns = _measure_facade.parse_session_turns(jsonl_path)
310
+ self._json_response(200, {"ok": True, "turns": turns})
311
+ return
312
+
313
+ name = body.get("name", "")
314
+ if not name:
315
+ self._json_response(400, {"error": "Missing 'name' field"})
316
+ return
317
+
318
+ ok = False
319
+ msg = ""
320
+ if path == "/api/skill/archive":
321
+ if _measure_facade.detect_runtime() == "codex":
322
+ ok = _measure_facade._manage_codex_skill("disable", raw_path=name)
323
+ msg = f"Disabled Codex skill: {name}" if ok else f"Failed to disable Codex skill: {name}"
324
+ else:
325
+ ok = _measure_facade._manage_skill("archive", name)
326
+ msg = f"Archived skill: {name}" if ok else f"Failed to archive: {name}"
327
+ elif path == "/api/skill/restore":
328
+ if _measure_facade.detect_runtime() == "codex":
329
+ ok = _measure_facade._manage_codex_skill("enable", raw_path=name)
330
+ msg = f"Enabled Codex skill: {name}" if ok else f"Failed to enable Codex skill: {name}"
331
+ else:
332
+ ok = _measure_facade._manage_skill("restore", name)
333
+ msg = f"Restored skill: {name}" if ok else f"Failed to restore: {name}"
334
+ elif path == "/api/mcp/disable":
335
+ if _measure_facade.detect_runtime() == "codex":
336
+ ok = _measure_facade._manage_codex_mcp("disable", name)
337
+ msg = f"Disabled Codex MCP server: {name}" if ok else f"Failed to disable Codex MCP: {name}"
338
+ else:
339
+ ok = _measure_facade._manage_mcp("disable", name)
340
+ msg = f"Disabled MCP server: {name}" if ok else f"Failed to disable: {name}"
341
+ elif path == "/api/mcp/enable":
342
+ if _measure_facade.detect_runtime() == "codex":
343
+ ok = _measure_facade._manage_codex_mcp("enable", name)
344
+ msg = f"Enabled Codex MCP server: {name}" if ok else f"Failed to enable Codex MCP: {name}"
345
+ else:
346
+ ok = _measure_facade._manage_mcp("enable", name)
347
+ msg = f"Enabled MCP server: {name}" if ok else f"Failed to enable: {name}"
348
+ elif path == "/api/v5/toggle":
349
+ # v5 feature toggle: body has {"name": "feature_name", "enabled": true/false}
350
+ enabled = bool(body.get("enabled", False))
351
+ if name not in _measure_facade.V5_FEATURES:
352
+ self._json_response(400, {"error": f"Unknown v5 feature: {name}"})
353
+ return
354
+ # An env-managed feature can't be toggled from the dashboard: a
355
+ # config.json write would be silently shadowed by the env var,
356
+ # leaving the UI out of sync with runtime. Reject it honestly
357
+ # rather than pretend the toggle took effect.
358
+ if _measure_facade._resolve_feature_env(_measure_facade.V5_FEATURES[name]["env_var"]) is not None:
359
+ self._json_response(409, {
360
+ "ok": False,
361
+ "msg": f"{_measure_facade.V5_FEATURES[name]['label']} is set via an environment "
362
+ f"variable and cannot be toggled from the dashboard. "
363
+ f"Change {_measure_facade.V5_FEATURES[name]['env_var']} in your settings.",
364
+ })
365
+ return
366
+ ok = _measure_facade._set_v5_feature(name, enabled)
367
+ label = _measure_facade.V5_FEATURES[name]["label"]
368
+ msg = f"{'Enabled' if enabled else 'Disabled'}: {label}" if ok else f"Failed to toggle {name}"
369
+ # Strip internal implementation keys before returning over HTTP
370
+ public_status = {}
371
+ for fname, info in _measure_facade._get_v5_feature_status().items():
372
+ public_status[fname] = {k: v for k, v in info.items() if k not in ("env_var", "config_key")}
373
+ # Return updated status so dashboard refreshes
374
+ self._json_response(200 if ok else 500, {
375
+ "ok": ok,
376
+ "msg": msg,
377
+ "v5_features": public_status,
378
+ })
379
+ return
380
+ else:
381
+ self._json_response(404, {"error": "Unknown endpoint"})
382
+ return
383
+
384
+ # After state change, regenerate dashboard data for the manage tab
385
+ fresh_manage = None
386
+ if ok:
387
+ try:
388
+ fresh_manage = _measure_facade._collect_management_data()
389
+ except Exception:
390
+ pass
391
+
392
+ self._json_response(
393
+ 200 if ok else 500,
394
+ {"ok": ok, "message": msg, "manage": fresh_manage}
395
+ )
396
+
397
+ def _json_response(self, code, data):
398
+ _measure_facade = _compat.facade()
399
+ body = _measure_facade.json.dumps(data, default=str).encode("utf-8")
400
+ self.send_response(code)
401
+ self.send_header("Content-Type", "application/json")
402
+ self.send_header("Content-Length", str(len(body)))
403
+ origin = self.headers.get("Origin", "")
404
+ server_port = getattr(self.server, "server_port", None)
405
+ if server_port is None and getattr(self.server, "server_address", None):
406
+ server_port = self.server.server_address[1]
407
+ if origin in (f"http://127.0.0.1:{server_port}", f"http://localhost:{server_port}"):
408
+ self.send_header("Access-Control-Allow-Origin", origin)
409
+ self.end_headers()
410
+ self.wfile.write(body)
411
+
412
+ def do_OPTIONS(self):
413
+ """Handle CORS preflight."""
414
+ _measure_facade = _compat.facade()
415
+ self.send_response(204)
416
+ origin = self.headers.get("Origin", "")
417
+ server_port = getattr(self.server, "server_port", None)
418
+ if server_port is None and getattr(self.server, "server_address", None):
419
+ server_port = self.server.server_address[1]
420
+ if origin in (f"http://127.0.0.1:{server_port}", f"http://localhost:{server_port}"):
421
+ self.send_header("Access-Control-Allow-Origin", origin)
422
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
423
+ self.send_header("Access-Control-Allow-Headers", "Content-Type, X-TO-Token")
424
+ self.end_headers()
425
+
426
+ display_host = "localhost" if host == "127.0.0.1" else host
427
+ print("\n Serving dashboard at:")
428
+ print(f" http://{display_host}:{port}/")
429
+ if host == "0.0.0.0":
430
+ print(" (accessible from any machine on your network)")
431
+ print("\n Press Ctrl+C to stop.\n")
432
+
433
+ with socketserver.TCPServer((host, port), DashboardHandler) as httpd:
434
+ try:
435
+ httpd.serve_forever()
436
+ except KeyboardInterrupt:
437
+ print("\n Server stopped.")
438
+
439
+
440
+ def _sanitize_dashboard_paths(data):
441
+ """Redact home-directory prefixes from paths embedded in dashboard HTML.
442
+
443
+ Applies to ALL runtimes (Claude Code and Codex). Replaces /Users/xxx
444
+ or /home/xxx with ~ so the rendered dashboard doesn't expose the full
445
+ filesystem path. Paths that the daemon API needs (e.g. jsonl_path for
446
+ on-demand session-turn loading) are kept functional since ~ is only
447
+ cosmetic in the JSON, and the API endpoint resolves paths itself.
448
+ """
449
+ _measure_facade = _compat.facade()
450
+ trends = data.get("trends")
451
+ if isinstance(trends, dict):
452
+ for day in trends.get("daily", []) or []:
453
+ for session in day.get("session_details", []) or []:
454
+ path = session.get("jsonl_path")
455
+ if path:
456
+ session["jsonl_path"] = _measure_facade._display_path(path)
457
+
458
+ quality = data.get("quality")
459
+ if isinstance(quality, dict):
460
+ sf = quality.get("session_file")
461
+ if sf:
462
+ quality["session_file"] = _measure_facade.Path(sf).name
463
+
464
+ mr = data.get("memory_review")
465
+ if isinstance(mr, dict):
466
+ target = mr.get("target")
467
+ if target:
468
+ mr["target"] = _measure_facade._display_path(target)
469
+
470
+ return data
471
+
472
+
473
+ def _codex_state_summary():
474
+ """Collect Codex runtime-state metrics for display, or None unless Codex.
475
+
476
+ Combines read-only SQLite state (subagent costs, memory overhead, goal
477
+ budgets) with the current session's parsed signals (rate limits, effort,
478
+ compaction compression). Returns None on the Claude runtime so dashboard,
479
+ report, and doctor consumers can treat the key as optional (no Claude-path
480
+ behavior change). All sources degrade to empty rather than raising.
481
+ """
482
+ _measure_facade = _compat.facade()
483
+ if _measure_facade.detect_runtime() != "codex":
484
+ return None
485
+ # Resolve the invoking thread id ONCE (CODEX_THREAD_ID) and scope every
486
+ # thread-specific Codex-state metric to it: subagent and goal totals to
487
+ # its goal subtree. When the identity is unresolved, do NOT fall back to
488
+ # the whole-DB aggregation for those: that would present other threads'
489
+ # tokens and goals as the current thread's. Report an explicit unresolved
490
+ # state instead. Memory overhead is different: it is a machine-wide
491
+ # metric across all threads on this machine, so it is measured without a
492
+ # thread filter and needs no identity.
493
+ try:
494
+ current_tid = _measure_facade.codex_state.current_thread_id()
495
+ except Exception:
496
+ current_tid = None
497
+ res = _measure_facade._codex_thread_resolution()
498
+ if current_tid:
499
+ subagents = _measure_facade.codex_state.subagent_costs(root_thread_id=current_tid)
500
+ goals = _measure_facade.codex_state.goal_budgets(root_thread_id=current_tid)
501
+ else:
502
+ subagents = {**_measure_facade.codex_state._empty_subagents(), "unresolved": True}
503
+ goals = {**_measure_facade.codex_state._empty_goals(), "unresolved": True}
504
+ memory = _measure_facade.codex_state.memory_overhead()
505
+ summary = {
506
+ "subagents": subagents,
507
+ "memory": memory,
508
+ "goals": goals,
509
+ "selected_thread_id": current_tid,
510
+ "thread_resolution": res["status"],
511
+ "thread_resolution_reason": res["reason"],
512
+ "rate_limits": None,
513
+ "effort": None,
514
+ "compaction": None,
515
+ }
516
+ import codex_models
517
+ summary['available_models'] = codex_models.visible_models()
518
+ try:
519
+ # Session signals follow the same identity: never the newest-mtime file.
520
+ current = res["path"]
521
+ if current:
522
+ session = _measure_facade.codex_session.parse_session_jsonl(current)
523
+ if session:
524
+ summary.update({
525
+ "rate_limits": session.get("rate_limits"),
526
+ "effort": session.get("effort"),
527
+ "effort_breakdown": session.get("effort_breakdown"),
528
+ "tool_duration_p90_ms": session.get("tool_duration_p90_ms"),
529
+ "task_duration_ms_max": session.get("task_duration_ms_max"),
530
+ "ttft_ms_avg": session.get("ttft_ms_avg"),
531
+ })
532
+ quality = _measure_facade.codex_session.parse_jsonl_for_quality(current)
533
+ if quality and quality.get("compaction_ratios"):
534
+ ratios = [r["ratio"] for r in quality["compaction_ratios"] if r.get("ratio") is not None]
535
+ summary["compaction"] = {
536
+ "count": quality.get("compactions", 0),
537
+ "ratios": quality["compaction_ratios"],
538
+ "avg_ratio": round(sum(ratios) / len(ratios), 3) if ratios else None,
539
+ }
540
+ except Exception:
541
+ pass
542
+ return summary
543
+
544
+
545
+ def codex_state_report(as_json=None):
546
+ """Print the Codex runtime-state summary (subagents, memory, goals, signals)."""
547
+ _measure_facade = _compat.facade()
548
+ summary = _measure_facade._codex_state_summary()
549
+ if as_json:
550
+ print(_measure_facade.json.dumps(summary, indent=2, default=str))
551
+ return
552
+ if summary is None:
553
+ print("Codex runtime state is only available on the Codex runtime.")
554
+ return
555
+ print("\nToken Optimizer - Codex Runtime State")
556
+ print("=" * 38)
557
+
558
+ if summary.get("thread_resolution") == "unresolved":
559
+ reason = summary.get("thread_resolution_reason")
560
+ why = (f"no transcript found for {summary.get('selected_thread_id')}"
561
+ if reason == "transcript_not_found" else _measure_facade._codex_identity_reason())
562
+ print(f"\nCurrent thread: unresolved ({why}). "
563
+ + ("Session signals are not shown; thread-scoped subagent and goal totals are not shown."
564
+ if not summary.get("selected_thread_id")
565
+ else f"Session signals are not shown; totals below are for thread {summary.get('selected_thread_id')}, not its transcript."))
566
+
567
+ sub = summary["subagents"]
568
+ if sub.get("unresolved"):
569
+ print("\nSubagents: unresolved (no invoking thread id)")
570
+ elif sub.get("available"):
571
+ print(f"\nSubagents: {sub['total_subagents']} total "
572
+ f"({sub['open_subagents']} open, {sub['closed_subagents']} closed, "
573
+ f"{sub['leaked_subagents']} leaked)")
574
+ print(f" Subagent token cost: {sub['total_child_tokens']:,}")
575
+ for leak in sub.get("leaked", [])[:5]:
576
+ age = f"{leak['age_minutes']}min" if leak["age_minutes"] is not None else "unknown age"
577
+ print(f" ! leaked {leak['child_thread_id'][:16]} ({leak['tokens_used']:,} tokens, open {age})")
578
+ else:
579
+ print("\nSubagents: no state data yet (no spawn edges recorded)")
580
+
581
+ mem = summary["memory"]
582
+ if mem.get("available") and mem["thread_count"]:
583
+ print(f"\nMemory overhead: {mem['total_memory_tokens']:,} tokens across {mem['thread_count']}{'+' if mem.get('truncated') else ''} thread(s) on this machine"
584
+ f"{' (partial: scan cap reached)' if mem.get('truncated') else ''}; "
585
+ f"largest {mem['max_thread_memory_tokens']:,}")
586
+ else:
587
+ print("\nMemory overhead: none recorded")
588
+
589
+ goals = summary["goals"]
590
+ if goals.get("unresolved"):
591
+ print("\nGoals: unresolved (no invoking thread id)")
592
+ elif goals.get("available") and goals["total_goals"]:
593
+ print(f"\nGoals: {goals['total_goals']} ({goals['active_goals']} active)")
594
+ if goals["budget_limited"] or goals["usage_limited"] or goals["over_budget"]:
595
+ print(f" ! {goals['budget_limited']} budget-limited, {goals['usage_limited']} usage-limited, "
596
+ f"{goals['over_budget']} over budget")
597
+ else:
598
+ print("\nGoals: none active")
599
+
600
+ rl = summary.get("rate_limits") or {}
601
+ primary = rl.get("primary")
602
+ if isinstance(primary, dict) and primary.get("used_percent") is not None:
603
+ print(f"\nRate limit (primary): {primary['used_percent']:.0f}% used")
604
+ if summary.get("effort"):
605
+ print(f"Effort (dominant this session): {summary['effort']}")
606
+ if summary.get("task_duration_ms_max"):
607
+ print(f"Longest task: {summary['task_duration_ms_max'] / 1000:.0f}s"
608
+ + (f" (first token ~{summary['ttft_ms_avg'] / 1000:.0f}s avg)" if summary.get("ttft_ms_avg") else ""))
609
+ comp = summary.get("compaction")
610
+ if comp and comp.get("avg_ratio") is not None:
611
+ print(f"Compaction: {comp['count']} this session, "
612
+ f"avg compression to {comp['avg_ratio'] * 100:.0f}% of pre-compaction context")
613
+ print()
614
+
615
+
616
+ def generate_dashboard(coord_path):
617
+ """Generate an interactive HTML dashboard from audit results."""
618
+ _measure_facade = _compat.facade()
619
+ coord = _measure_facade.Path(coord_path)
620
+ if not coord.exists():
621
+ print(f"Error: coord-path does not exist: {coord_path}")
622
+ print(_measure_facade._hint("Usage: python3 measure.py dashboard --coord-path /tmp/token-optimizer-XXXXXXXXXX"))
623
+ _measure_facade.sys.exit(1)
624
+
625
+ # Locate the template
626
+ script_dir = _measure_facade.Path(_measure_facade.__file__).resolve().parent
627
+ template_path = script_dir.parent / "assets" / "dashboard.html"
628
+ if not template_path.exists():
629
+ print(f"Error: dashboard template not found at: {template_path}")
630
+ _measure_facade.sys.exit(1)
631
+
632
+ # Re-measure current state
633
+ print(" Measuring current token overhead...")
634
+ components = _measure_facade.measure_components()
635
+ totals = _measure_facade.calculate_totals(components)
636
+ baselines = _measure_facade.get_session_baselines(5)
637
+
638
+ calibration = _measure_facade.detect_calibration_gap(components, totals, baselines)
639
+
640
+ ctx_window, ctx_source = _measure_facade.detect_context_window()
641
+ snapshot = {
642
+ "components": components,
643
+ "totals": totals,
644
+ "session_baselines": baselines,
645
+ "calibration": calibration,
646
+ "context_window": ctx_window,
647
+ "context_source": ctx_source,
648
+ }
649
+
650
+ # Read audit files
651
+ audit_dir = coord / "audit"
652
+ audit = {}
653
+ audit_files = {
654
+ "claudemd": "claudemd.md",
655
+ "memorymd": "memorymd.md",
656
+ "skills": "skills.md",
657
+ "mcp": "mcp.md",
658
+ "commands": "commands.md",
659
+ "advanced": "advanced.md",
660
+ }
661
+ for key, filename in audit_files.items():
662
+ fpath = audit_dir / filename
663
+ if fpath.exists():
664
+ try:
665
+ audit[key] = fpath.read_text(encoding="utf-8")
666
+ except (OSError, UnicodeDecodeError):
667
+ audit[key] = None
668
+ else:
669
+ audit[key] = None
670
+
671
+ found = sum(1 for v in audit.values() if v)
672
+ print(f" Loaded {found}/{len(audit_files)} audit files")
673
+
674
+ # Read optimization plan
675
+ plan_path = coord / "analysis" / "optimization-plan.md"
676
+ plan = None
677
+ if plan_path.exists():
678
+ try:
679
+ plan = plan_path.read_text(encoding="utf-8")
680
+ print(f" Loaded optimization plan ({len(plan)} chars)")
681
+ except (OSError, UnicodeDecodeError):
682
+ pass
683
+
684
+ # Collect trends and health data
685
+ print(" Collecting usage trends...")
686
+ try:
687
+ trends = _measure_facade._collect_trends_data(days=30)
688
+ except Exception:
689
+ trends = None
690
+ print(" Checking session health...")
691
+ try:
692
+ health = _measure_facade._collect_health_data()
693
+ except Exception:
694
+ health = None
695
+
696
+ # Generate coach data for the Coach tab (reuse already-collected components/trends)
697
+ print(" Generating coach data...")
698
+ try:
699
+ coach = _measure_facade.generate_coach_data(components=components, trends=trends)
700
+ except Exception:
701
+ coach = None
702
+
703
+ # Collect context quality data (v2.0)
704
+ print(" Analyzing context quality...")
705
+ quality = _measure_facade._collect_quality_for_dashboard()
706
+
707
+ # Collect hook installation status for dashboard toggles
708
+ hook_status = _measure_facade._collect_hook_status_for_dashboard()
709
+
710
+ # Collect management data for Manage tab. The full audit dashboard should
711
+ # expose the same Codex skill/MCP controls as the standalone dashboard.
712
+ management = _measure_facade._collect_management_data(components=components, trends=trends)
713
+
714
+ # Savings data for dashboard. Merged view = measured runtime + realized
715
+ # structural + opportunity (unclaimed) + estimated uncaptured runtime, all
716
+ # tier-labelled. Wrapped so a slow/failed savings eval never blocks regen.
717
+ print(" Collecting savings data...")
718
+ savings_data = _measure_facade._dashboard_savings_data(days=30)
719
+
720
+ # U6: tiered compression-coverage diagnostic (kept separate from savings;
721
+ # shadow/opportunity ratios never feed the headline). Fail-open to empty.
722
+ try:
723
+ compression_coverage = _measure_facade._get_compression_coverage(days=30)
724
+ except Exception:
725
+ compression_coverage = {"available": False, "tiers": {}, "first_read_proxy": None}
726
+
727
+ # Tripwire verdict for the coverage panel (per-cohort live edit-rate +
728
+ # auto-demotions). Read-only; never recomputes/demotes here. Fail-open.
729
+ try:
730
+ cohort_tripwire = _measure_facade._cohort_tripwire_state()
731
+ except Exception:
732
+ cohort_tripwire = {"cohorts": [], "demoted": []}
733
+ compression_coverage["cohort_tripwire"] = cohort_tripwire
734
+
735
+ # Cache-TTL watchdog (opportunity tier — observed waste, potential recovery).
736
+ # Standalone analysis; never reaches the realized savings headline. Fail-open.
737
+ try:
738
+ cache_health = _measure_facade._cache_ttl_waste_cached(days=30)
739
+ except Exception:
740
+ cache_health = {"available": False, "tier": "opportunity"}
741
+
742
+ # U7: keep-warm cache-automation sub-block carried inside the cache-health
743
+ # payload (realized vs spend vs NET, tripwire ratio, the 5 tile states,
744
+ # predictor transparency). Fail-open so it never blocks dashboard regen.
745
+ try:
746
+ if isinstance(cache_health, dict):
747
+ cache_health["keepwarm"] = _measure_facade.keepwarm_cache_health_block(days=30)
748
+ except Exception:
749
+ pass
750
+
751
+ # Fall back to auto-recommendations if LLM plan is missing
752
+ auto_plan_flag = False
753
+ if not plan:
754
+ print(" No LLM plan found, generating auto-recommendations...")
755
+ plan, rec_count = _measure_facade.generate_auto_recommendations(components, trends=trends, days=30)
756
+ if plan:
757
+ auto_plan_flag = True
758
+ print(f" Generated {rec_count} auto-recommendations as fallback")
759
+ else:
760
+ plan = None
761
+
762
+ # Subscription runway: leads the savings surface for rate-limited plans,
763
+ # where a dollar figure is the wrong currency. None on API-billed setups or
764
+ # when the meter has never been read at all (a stale-but-present reading is
765
+ # kept and dated on the card), and the template simply omits the card.
766
+ try:
767
+ runway = _measure_facade.runway_snapshot(days=30)
768
+ except Exception:
769
+ runway = None
770
+
771
+ # Assemble data
772
+ data = {
773
+ "runway": runway,
774
+ "snapshot": snapshot,
775
+ "audit": audit,
776
+ "plan": plan,
777
+ "trends": trends,
778
+ "health": health,
779
+ "coach": coach,
780
+ "quality": quality,
781
+ "manage": management,
782
+ "hooks": hook_status,
783
+ "savings": savings_data,
784
+ "compression_coverage": compression_coverage,
785
+ "cache_health": cache_health,
786
+ "auto_plan": auto_plan_flag,
787
+ "generated_at": _measure_facade.datetime.now().isoformat(),
788
+ "version": _measure_facade.TOKEN_OPTIMIZER_VERSION,
789
+ "runtime": _measure_facade.detect_runtime(),
790
+ "runtime_label": _measure_facade.runtime_name_for_humans(),
791
+ "codex_state": _measure_facade._codex_state_summary(),
792
+ }
793
+ data = _measure_facade._sanitize_dashboard_paths(data)
794
+
795
+ # Load template and inject data
796
+ template = template_path.read_text(encoding="utf-8")
797
+ data_json = _measure_facade.json.dumps(data, ensure_ascii=True, default=str)
798
+ data_json = data_json.replace("</", "<\\/") # Prevent </script> injection
799
+ placeholder = "window.__TOKEN_DATA__ = null;"
800
+ injected = template.replace(placeholder, f"window.__TOKEN_DATA__ = {data_json};", 1)
801
+ if injected == template:
802
+ print(" [Warning] Data injection failed: placeholder not found in template.")
803
+
804
+ # Write audit output to the coord_path (historical behavior so
805
+ # audits keep a self-contained artifact per run).
806
+ out_dir = coord / "analysis"
807
+ out_dir.mkdir(parents=True, exist_ok=True)
808
+ out_path = out_dir / "dashboard.html"
809
+ fd = _measure_facade.os.open(str(out_path), _measure_facade.os.O_WRONLY | _measure_facade.os.O_CREAT | _measure_facade.os.O_TRUNC, 0o600)
810
+ with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as f:
811
+ f.write(injected)
812
+ print(f" Dashboard written to: {out_path}")
813
+
814
+ # v5.3.6 / v5.4.10: mirror the same HTML to BOTH dashboard paths so
815
+ # the daemon serves fresh audit content regardless of which path it
816
+ # was configured to use. Same dual-path pattern as v5.4.7 daemon script.
817
+ legacy_dashboard = _measure_facade.RUNTIME_DIR / "_backups" / "token-optimizer" / "dashboard.html"
818
+ wrote_mirror = False
819
+ skipped_all = True
820
+ for mirror_path in {_measure_facade.DASHBOARD_PATH, legacy_dashboard}:
821
+ # Version-downgrade guard: an older build's audit must not clobber a
822
+ # shared dashboard a newer build already wrote. The per-run audit artifact
823
+ # (out_path) is still written above; only the SHARED served copies are
824
+ # guarded. Fail-open (see _dashboard_on_disk_is_newer).
825
+ if _measure_facade._dashboard_on_disk_is_newer(mirror_path):
826
+ continue
827
+ skipped_all = False
828
+ try:
829
+ mirror_path.parent.mkdir(parents=True, exist_ok=True)
830
+ mirror_fd = _measure_facade.os.open(str(mirror_path), _measure_facade.os.O_WRONLY | _measure_facade.os.O_CREAT | _measure_facade.os.O_TRUNC, 0o600)
831
+ with _measure_facade.os.fdopen(mirror_fd, "w", encoding="utf-8") as f:
832
+ f.write(injected)
833
+ # The sidecar must name the build that wrote THIS HTML, or the guard
834
+ # reads a stale version and a middle build could clobber a newer file.
835
+ _measure_facade._write_dashboard_meta(mirror_path)
836
+ wrote_mirror = True
837
+ except OSError:
838
+ pass
839
+ # Only a real write FAILURE warrants the warning; an intentional guard skip
840
+ # (all shared copies are already newer) is not a failure.
841
+ if not wrote_mirror and not skipped_all:
842
+ print(" [Warning] Could not mirror dashboard to daemon paths.")
843
+
844
+ # Prefer the bookmarkable URL when the daemon is live; fall back to
845
+ # the coord-path file://. This removes the v5.3.5-era UX bug where
846
+ # users with a live daemon still got a /tmp/coord.../dashboard.html
847
+ # file:// URL instead of their bookmark.
848
+ _measure_facade._open_dashboard(fallback_filepath=out_path)
849
+ return str(out_path)
850
+
851
+
852
+ def _shell_script_path():
853
+ """This script's resolved path, quoted to paste into Bash, PowerShell and cmd.exe."""
854
+ _measure_facade = _compat.facade()
855
+ return _measure_facade.shell_path(_measure_facade.Path(_measure_facade.__file__).resolve())
856
+
857
+
858
+ def _measure_cli(*args):
859
+ """The command that runs this script, for hints a user will paste into a shell.
860
+
861
+ Always the resolved script path (quoted): a bare `python3 measure.py` only works
862
+ from inside the scripts directory, which is where nobody is. On Windows the
863
+ interpreter is `python`, and the path uses forward slashes and double quotes, the
864
+ one form cmd.exe, PowerShell and Git Bash all read as a single argument
865
+ (`runtime_env.shell_path`).
866
+ """
867
+ _measure_facade = _compat.facade()
868
+ parts = [_measure_facade.hint_python(), _measure_facade._shell_script_path()]
869
+ parts.extend(args)
870
+ return " ".join(parts)
871
+
872
+
873
+ def _runtime_cli(runtime, *args):
874
+ """`_measure_cli` pinned to a runtime for hints.
875
+
876
+ macOS/Linux: the Bash `TOKEN_OPTIMIZER_RUNTIME=NAME python3 <script>` prefix,
877
+ unchanged. cmd.exe and PowerShell cannot parse that, so on Windows it is
878
+ `python <script> --runtime NAME` (a leading global flag, see `consume_runtime_flag`).
879
+ """
880
+ _measure_facade = _compat.facade()
881
+ if _measure_facade._windows_hints():
882
+ parts = [_measure_facade.hint_python(), _measure_facade._shell_script_path(), "--runtime", runtime]
883
+ else:
884
+ parts = [f"TOKEN_OPTIMIZER_RUNTIME={runtime}", _measure_facade.hint_python(), _measure_facade._shell_script_path()]
885
+ parts.extend(args)
886
+ return " ".join(parts)
887
+
888
+
889
+ def _hint(text):
890
+ """Make a printed hint pasteable from any directory.
891
+
892
+ Hints are written as `python3 measure.py <subcommand>`; this swaps that
893
+ bare prefix for the resolved, quoted script path (`_measure_cli()`). A
894
+ `TOKEN_OPTIMIZER_RUNTIME=X` prefix (Bash only) becomes `--runtime X` on Windows.
895
+ """
896
+ _measure_facade = _compat.facade()
897
+ text = _measure_facade._ENV_PREFIXED_BARE_HINT.sub(lambda m: ((_measure_facade := _compat.facade()), _measure_facade._runtime_cli(m.group(1)))[1], text)
898
+ return text.replace("python3 measure.py", _measure_facade._measure_cli())
899
+
900
+
901
+ def _subagent_cache_cmd(action=None):
902
+ """The `subagent-cache [action]` command users are told to run (advice, enable, undo)."""
903
+ _measure_facade = _compat.facade()
904
+ return _measure_facade._measure_cli("subagent-cache", *([action] if action else []))
905
+
906
+
907
+ def _display_path(absolute_path):
908
+ """Replace the user's home directory with ~ for display purposes.
909
+
910
+ Avoids exposing full filesystem paths like /Users/alex/.claude/... in the UI.
911
+ """
912
+ _measure_facade = _compat.facade()
913
+ home = str(_measure_facade.Path.home())
914
+ s = str(absolute_path)
915
+ if s == home:
916
+ return "~"
917
+ if s.startswith(home + _measure_facade.os.sep):
918
+ return "~" + s[len(home):]
919
+ return s
920
+
921
+
922
+ def _collect_hook_status_for_dashboard():
923
+ """Collect hook installation status for dashboard toggle panel."""
924
+ _measure_facade = _compat.facade()
925
+ if _measure_facade.detect_runtime() == "codex":
926
+ return _measure_facade._collect_codex_hook_status_for_dashboard()
927
+ if _measure_facade.detect_runtime() == "hermes":
928
+ return _measure_facade._collect_hermes_hook_status_for_dashboard()
929
+ if _measure_facade.detect_runtime() == "copilot":
930
+ return _measure_facade._collect_copilot_hook_status_for_dashboard()
931
+ if _measure_facade.detect_runtime() == "cursor":
932
+ return _measure_facade._collect_cursor_hook_status_for_dashboard()
933
+ if _measure_facade.detect_runtime() == "antigravity":
934
+ return _measure_facade._collect_antigravity_hook_status_for_dashboard()
935
+ if _measure_facade.detect_runtime() == "grok":
936
+ return _measure_facade._collect_grok_hook_status_for_dashboard()
937
+
938
+ settings, _ = _measure_facade._read_settings_json()
939
+
940
+ # Check each hook type
941
+ session_end_installed = _measure_facade._is_hook_installed(settings)
942
+ smart_compact_status = _measure_facade._is_smart_compact_installed(settings)
943
+
944
+ # For executable commands: absolute path with shlex.quote (handles spaces/quotes)
945
+ mp_cmd = _measure_facade._shell_script_path()
946
+
947
+ return {
948
+ "session_end": {
949
+ "installed": session_end_installed,
950
+ "label": "Session Tracking",
951
+ "description": "Collects usage data after each session. Powers Trends and Health tabs.",
952
+ "install_cmd": f"{_measure_facade.hint_python()} {mp_cmd} setup-hook",
953
+ "uninstall_cmd": f"{_measure_facade.hint_python()} {mp_cmd} setup-hook --uninstall",
954
+ },
955
+ "smart_compact": {
956
+ "installed": all(smart_compact_status.values()),
957
+ "partial": any(smart_compact_status.values()) and not all(smart_compact_status.values()),
958
+ "detail": smart_compact_status,
959
+ "label": "Smart Compaction",
960
+ "description": "Captures session state before compaction, restores it after. Protects your working memory.",
961
+ "install_cmd": f"{_measure_facade.hint_python()} {mp_cmd} setup-smart-compact",
962
+ "uninstall_cmd": f"{_measure_facade.hint_python()} {mp_cmd} setup-smart-compact --uninstall",
963
+ },
964
+ }
965
+
966
+
967
+ def _collect_codex_hook_status_for_dashboard():
968
+ """Collect Codex project hook status for dashboard toggle panel."""
969
+ _measure_facade = _compat.facade()
970
+ import codex_doctor
971
+
972
+ mp_cmd = _measure_facade._shell_script_path()
973
+ project = _measure_facade.Path.cwd().resolve(strict=False)
974
+ checks = codex_doctor.run_checks(project=project)
975
+ by_name = {check["name"]: check for check in checks}
976
+
977
+ def _ok(name):
978
+ _measure_facade = _compat.facade()
979
+ return by_name.get(name, {}).get("status") == "OK"
980
+
981
+ project_arg = _measure_facade.shlex.quote(str(project))
982
+ base = f"{_measure_facade._runtime_cli('codex')} codex-install --project {project_arg}"
983
+ try:
984
+ hooks_text = (project / ".codex" / "hooks.json").read_text(encoding="utf-8")
985
+ except OSError:
986
+ hooks_text = ""
987
+ return {
988
+ "codex_project": {
989
+ "installed": _ok("Project hooks"),
990
+ "label": "Codex Project Hooks",
991
+ "description": "Installs the aggressive default profile (max savings): SessionStart/UserPromptSubmit for quality tracking, Stop for dashboard refresh and checkpoint capture, plus silent PostToolUse archiving and context-intel. All hooks run silently (no visible Codex Desktop rows). Bash compression stays opt-in (Codex can't rewrite command input yet).",
992
+ "install_cmd": base,
993
+ "uninstall_cmd": base + " --uninstall",
994
+ },
995
+ "codex_compact_prompt": {
996
+ "installed": _ok("Compact prompt"),
997
+ "partial": by_name.get("Compact prompt", {}).get("status") == "WARN",
998
+ "label": "Codex Compact Prompt",
999
+ "description": "Adds Token Optimizer compact guidance to Codex config so manual compaction preserves decisions, files, and continuation state.",
1000
+ "install_cmd": f"{_measure_facade._runtime_cli('codex')} codex-compact-prompt --install",
1001
+ "uninstall_cmd": "Edit ~/.codex/config.toml and remove compact_prompt / experimental_compact_prompt_file",
1002
+ },
1003
+ "codex_bash_compression": {
1004
+ "installed": "PreToolUse" in hooks_text and "bash_hook.py" in hooks_text,
1005
+ "partial": False,
1006
+ "label": "Experimental Bash Compression",
1007
+ "description": "Codex PreToolUse currently cannot rewrite command input, so true invisible Bash compression is not available yet. This hook is experimental and visible.",
1008
+ "install_cmd": base + " --enable-bash-compression",
1009
+ "uninstall_cmd": base + " --disable-bash-compression",
1010
+ },
1011
+ "codex_balanced_profile": {
1012
+ "installed": "UserPromptSubmit" in hooks_text and "codex_hook_bridge.py" in hooks_text,
1013
+ "label": "Balanced Quality Profile",
1014
+ "description": "Default profile. Enables prompt/session hooks for live quality cache and loop nudges with far less noise than per-tool hooks.",
1015
+ "install_cmd": base,
1016
+ "uninstall_cmd": base + " --uninstall",
1017
+ },
1018
+ "codex_telemetry_profile": {
1019
+ "installed": "PostToolUse" in hooks_text and ("archive_result.py" in hooks_text or "context_intel.py" in hooks_text),
1020
+ "label": "PostToolUse Telemetry Profile",
1021
+ "description": "Enables exact tool-output archiving/context-intel. Wired to run silently (archive redirects output, context-intel emits nothing, Bash-only matcher avoids unsupported MCP replacement), so no visible Codex Desktop rows. Included in the aggressive default.",
1022
+ "install_cmd": base + " --profile telemetry",
1023
+ "uninstall_cmd": base + " --uninstall",
1024
+ },
1025
+ "codex_status_line": {
1026
+ "installed": _ok("Codex CLI status line"),
1027
+ "partial": by_name.get("Codex CLI status line", {}).get("status") == "WARN",
1028
+ "label": "Codex CLI Status Line",
1029
+ "description": "Shows model, fast mode, context remaining/used, token count, branch, and cwd in the Codex terminal UI.",
1030
+ "install_cmd": base + " --enable-status-line",
1031
+ "uninstall_cmd": "Edit ~/.codex/config.toml and remove the Token Optimizer [tui] status line block",
1032
+ },
1033
+ "codex_stop_refresh": {
1034
+ "installed": _ok("Feature: Session continuity and dashboard refresh"),
1035
+ "label": "Stop Refresh and Continuity",
1036
+ "description": "On Codex Stop, collects sessions, regenerates the dashboard, and saves a checkpoint for continuity.",
1037
+ "install_cmd": base + " --profile quiet",
1038
+ "uninstall_cmd": base + " --uninstall",
1039
+ },
1040
+ }
1041
+
1042
+
1043
+ def _collect_copilot_hook_status_for_dashboard():
1044
+ """Hook status for the dashboard toggle panel under the Copilot runtime.
1045
+
1046
+ Mirrors the Codex/Hermes collectors. copilot_doctor uses lowercase
1047
+ statuses ("ok"/"warn"/"fail") and check names from copilot_doctor.py.
1048
+ """
1049
+ _measure_facade = _compat.facade()
1050
+ import copilot_doctor # noqa: PLC0415
1051
+
1052
+ mp_cmd = _measure_facade._shell_script_path()
1053
+ checks = copilot_doctor.run_checks()
1054
+ by_name = {check["name"]: check for check in checks}
1055
+
1056
+ def _ok(name):
1057
+ _measure_facade = _compat.facade()
1058
+ return by_name.get(name, {}).get("status") == "ok"
1059
+
1060
+ install_cmd = f"{_measure_facade._runtime_cli('copilot')} copilot-install"
1061
+ doctor_cmd = f"{_measure_facade._runtime_cli('copilot')} copilot-doctor"
1062
+
1063
+ return {
1064
+ "copilot_hooks": {
1065
+ "installed": _ok("TO hook config"),
1066
+ # Installed stays tied to the hook config; a dead legacy `stop` entry
1067
+ # or a bridge that cannot find measure.py (session-end refresh paused), or a
1068
+ # damaged hook payload (missing bridge modules) is installed-but-partial,
1069
+ # not healthy.
1070
+ "partial": any(
1071
+ by_name.get(n, {}).get("status") == "warn"
1072
+ for n in ("TO hook config", "TO session-end hook", "session-end refresh")
1073
+ ) or by_name.get("hook payload", {}).get("status") in ("warn", "fail"),
1074
+ "label": "Copilot CLI Hooks",
1075
+ "description": "Wires Token Optimizer into ~/.copilot/hooks/: sessionStart continuity restore, preToolUse bash compression (capability-gated), postToolUse crash-recovery tally + nudges, session-end rollup.",
1076
+ "install_cmd": install_cmd,
1077
+ "uninstall_cmd": f"{_measure_facade._runtime_cli('copilot')} copilot-uninstall",
1078
+ },
1079
+ "copilot_capabilities": {
1080
+ "installed": _ok("capabilities"),
1081
+ "partial": any(
1082
+ by_name.get(n, {}).get("status") == "warn"
1083
+ for n in ("capabilities", "capabilities freshness", "capability matrix age")
1084
+ ),
1085
+ "label": "Hook Capability Matrix",
1086
+ "description": "Per-CLI-version map of which Copilot hook powers actually work (upstream fields break release to release). Engine features auto-gate on it; reseeds when the CLI version changes.",
1087
+ "install_cmd": install_cmd,
1088
+ "uninstall_cmd": doctor_cmd,
1089
+ },
1090
+ "copilot_cli_data": {
1091
+ "installed": _ok("CLI session data"),
1092
+ "partial": by_name.get("CLI session data", {}).get("status") == "warn",
1093
+ "label": "Copilot CLI Sessions",
1094
+ "description": "Reads ~/.copilot/session-state/ for per-session token totals, compactions, and tool activity. Crash-killed sessions are recovered from partial data.",
1095
+ "install_cmd": doctor_cmd,
1096
+ "uninstall_cmd": doctor_cmd,
1097
+ },
1098
+ "copilot_vscode_data": {
1099
+ "installed": _ok("VS Code debug-logs") or _ok("VS Code OTel DB"),
1100
+ "partial": by_name.get("VS Code data plane", {}).get("status") == "warn",
1101
+ "label": "VS Code Copilot Data",
1102
+ "description": "Per-request AI-credit cost from Copilot Chat debug logs (authoritative), or the OTel trace DB as fallback. One active source at a time — never summed.",
1103
+ "install_cmd": doctor_cmd,
1104
+ "uninstall_cmd": doctor_cmd,
1105
+ },
1106
+ }
1107
+
1108
+
1109
+ def _collect_cursor_hook_status_for_dashboard():
1110
+ """Hook status for the dashboard toggle panel under the Cursor runtime.
1111
+
1112
+ Mirrors _collect_copilot_hook_status_for_dashboard(). cursor_doctor uses
1113
+ lowercase statuses ("ok"/"warn"/"fail") and check names from
1114
+ cursor_doctor.py; the toggles surface install, payload, and data readiness.
1115
+ """
1116
+ _measure_facade = _compat.facade()
1117
+ import cursor_doctor # noqa: PLC0415
1118
+
1119
+ mp_cmd = _measure_facade._shell_script_path()
1120
+ checks = cursor_doctor.run_checks()
1121
+ by_name = {check["name"]: check for check in checks}
1122
+
1123
+ def _ok(name):
1124
+ _measure_facade = _compat.facade()
1125
+ return by_name.get(name, {}).get("status") == "ok"
1126
+
1127
+ install_cmd = f"{_measure_facade._runtime_cli('cursor')} cursor-install"
1128
+ doctor_cmd = f"{_measure_facade._runtime_cli('cursor')} cursor-doctor"
1129
+
1130
+ return {
1131
+ "cursor_hooks": {
1132
+ "installed": _ok("TO hook config"),
1133
+ "partial": by_name.get("TO hook config", {}).get("status") == "warn",
1134
+ "label": "Cursor Hooks",
1135
+ "description": "Merges Token Optimizer into ~/.cursor/hooks.json: sessionStart continuity restore, preToolUse Shell bash compression, postToolUse tally + nudges, preCompact capture, stop-time rollup and session-end dashboard refresh.",
1136
+ "install_cmd": install_cmd,
1137
+ "uninstall_cmd": f"{_measure_facade._runtime_cli('cursor')} cursor-uninstall",
1138
+ },
1139
+ "cursor_payload": {
1140
+ "installed": _ok("hook payload"),
1141
+ "partial": any(
1142
+ by_name.get(n, {}).get("status") == "warn"
1143
+ for n in ("measure-path locator", "persisted python")
1144
+ ),
1145
+ "label": "Cursor Hook Payload",
1146
+ "description": "The installed hook bridge plus its measure-path locator and a trusted absolute Python interpreter (never a bare python3).",
1147
+ "install_cmd": install_cmd,
1148
+ "uninstall_cmd": doctor_cmd,
1149
+ },
1150
+ "cursor_data": {
1151
+ "installed": _ok("IDE token plane") or _ok("CLI transcript plane"),
1152
+ "partial": any(
1153
+ by_name.get(n, {}).get("status") == "warn"
1154
+ for n in ("IDE token plane", "CLI transcript plane")
1155
+ ),
1156
+ "label": "Cursor Session Data",
1157
+ "description": "Best-effort token counts from state.vscdb (IDE) with a chars-over-four transcript estimate as fallback; the hook tally is always authoritative for calls/turns/compactions.",
1158
+ "install_cmd": doctor_cmd,
1159
+ "uninstall_cmd": doctor_cmd,
1160
+ },
1161
+ }
1162
+
1163
+
1164
+ def _collect_grok_hook_status_for_dashboard():
1165
+ """Hook status for the dashboard toggle panel under the Grok Build runtime.
1166
+
1167
+ Mirrors the Codex/Hermes/Antigravity collectors. grok_doctor reports
1168
+ lowercase statuses ("ok"/"warn"/"fail") and check names matching
1169
+ grok_doctor.py's emitted names exactly.
1170
+ """
1171
+ _measure_facade = _compat.facade()
1172
+ import grok_doctor # noqa: PLC0415
1173
+
1174
+ mp_cmd = _measure_facade._shell_script_path()
1175
+ checks = grok_doctor.run_checks()
1176
+ by_name = {check["name"]: check for check in checks}
1177
+
1178
+ def _ok(name):
1179
+ _measure_facade = _compat.facade()
1180
+ return by_name.get(name, {}).get("status") == "ok"
1181
+
1182
+ install_cmd = f"{_measure_facade._runtime_cli('grok')} grok-install"
1183
+ doctor_cmd = f"{_measure_facade._runtime_cli('grok')} grok-doctor"
1184
+
1185
+ return {
1186
+ "grok_hooks": {
1187
+ "installed": _ok("TO hook config"),
1188
+ "partial": by_name.get("TO hook config", {}).get("status") == "warn",
1189
+ "label": "Grok Build Hooks",
1190
+ "description": "Wires Token Optimizer into $GROK_HOME/hooks/token-optimizer.json: sessionStart continuity restore, userPromptSubmit quality tracking, preToolUse bash compression (capability-gated), postToolUse crash-recovery tally + nudges, stop-time rollup.",
1191
+ "install_cmd": install_cmd,
1192
+ "uninstall_cmd": f"{_measure_facade._runtime_cli('grok')} grok-uninstall",
1193
+ },
1194
+ "grok_session_store": {
1195
+ "installed": _ok("session store"),
1196
+ "partial": by_name.get("session store", {}).get("status") == "warn",
1197
+ "label": "Grok Build Sessions",
1198
+ "description": "Reads $GROK_HOME/sessions/ for per-session token totals (updates.jsonl), signals, compactions, and cost (costUsdTicks). Crash-killed sessions recovered from partial data.",
1199
+ "install_cmd": doctor_cmd,
1200
+ "uninstall_cmd": doctor_cmd,
1201
+ },
1202
+ "grok_dashboard_port": {
1203
+ # The doctor's check name is "dashboard daemon" (lowercase, with
1204
+ # the port in the detail text, not the name) — the lookup must
1205
+ # match it exactly or the toggle can never turn green.
1206
+ "installed": _ok("dashboard daemon"),
1207
+ "label": "Dashboard Port 24848",
1208
+ "description": "Confirms that port 24848 is available or already serving the Grok Build Token Optimizer dashboard.",
1209
+ "install_cmd": f"{_measure_facade._runtime_cli('grok')} open-dashboard",
1210
+ "uninstall_cmd": "",
1211
+ },
1212
+ }
1213
+
1214
+
1215
+ def _collect_hermes_hook_status_for_dashboard():
1216
+ """Collect Hermes plugin hook status for dashboard toggle panel.
1217
+
1218
+ Mirrors _collect_codex_hook_status_for_dashboard(). Uses hermes_doctor
1219
+ to determine whether the plugin payload is installed and wired correctly,
1220
+ and exposes the same install/uninstall command surface.
1221
+ """
1222
+ _measure_facade = _compat.facade()
1223
+ import hermes_doctor # noqa: PLC0415
1224
+
1225
+ mp_cmd = _measure_facade._shell_script_path()
1226
+ checks = hermes_doctor.run_checks()
1227
+ by_name = {check["name"]: check for check in checks}
1228
+
1229
+ def _ok(name):
1230
+ _measure_facade = _compat.facade()
1231
+ return by_name.get(name, {}).get("status") == "OK"
1232
+
1233
+ install_cmd = f"{_measure_facade._runtime_cli('hermes')} hermes-install"
1234
+ doctor_cmd = f"{_measure_facade._runtime_cli('hermes')} hermes-doctor"
1235
+
1236
+ return {
1237
+ "hermes_plugin": {
1238
+ "installed": _ok("Plugin directory") and _ok("Plugin files"),
1239
+ "label": "Hermes Plugin",
1240
+ "description": "Installs the Token Optimizer plugin into ~/.hermes/plugins/token-optimizer/. Provides pre_llm_call nudges, post_api_request capture, and session rollup hooks.",
1241
+ "install_cmd": install_cmd,
1242
+ "uninstall_cmd": install_cmd + " --uninstall",
1243
+ },
1244
+ "hermes_hooks": {
1245
+ "installed": _ok("Declared hooks"),
1246
+ "partial": by_name.get("Declared hooks", {}).get("status") == "WARN",
1247
+ "label": "Hermes Hook Declarations",
1248
+ "description": "Verifies that plugin.yaml declares all required hooks: pre_llm_call, post_api_request, on_session_finalize, on_session_end.",
1249
+ "install_cmd": install_cmd,
1250
+ "uninstall_cmd": install_cmd + " --uninstall",
1251
+ },
1252
+ "hermes_state_db": {
1253
+ "installed": _ok("state.db readable"),
1254
+ "partial": by_name.get("state.db", {}).get("status") == "WARN",
1255
+ "label": "Hermes State DB",
1256
+ "description": "Checks that ~/.hermes/state.db is present and readable. Created automatically on first Hermes session.",
1257
+ "install_cmd": doctor_cmd,
1258
+ "uninstall_cmd": "",
1259
+ },
1260
+ "hermes_dashboard_port": {
1261
+ "installed": _ok(f"Dashboard port {hermes_doctor.DASHBOARD_PORT}"),
1262
+ "label": "Dashboard Port 24844",
1263
+ "description": "Confirms that port 24844 is available or already serving the Hermes Token Optimizer dashboard.",
1264
+ "install_cmd": f"{_measure_facade._runtime_cli('hermes')} open-dashboard",
1265
+ "uninstall_cmd": "",
1266
+ },
1267
+ }
1268
+
1269
+
1270
+ def _collect_antigravity_hook_status_for_dashboard():
1271
+ """Antigravity plugin hook status for the dashboard toggle panel.
1272
+
1273
+ Mirrors _collect_hermes_hook_status_for_dashboard(). Uses antigravity_doctor
1274
+ to determine whether the plugin payload is installed and wired, and exposes
1275
+ the same install/uninstall command surface. antigravity_doctor reports
1276
+ lowercase statuses ("ok"/"warn"/"fail").
1277
+ """
1278
+ _measure_facade = _compat.facade()
1279
+ import antigravity_doctor # noqa: PLC0415
1280
+
1281
+ mp_cmd = _measure_facade._shell_script_path()
1282
+ checks = antigravity_doctor.run_checks()
1283
+ by_name = {check["name"]: check for check in checks}
1284
+
1285
+ def _ok(name):
1286
+ _measure_facade = _compat.facade()
1287
+ return by_name.get(name, {}).get("status") == "ok"
1288
+
1289
+ install_cmd = f"{_measure_facade._runtime_cli('antigravity')} antigravity-install"
1290
+ doctor_cmd = f"{_measure_facade._runtime_cli('antigravity')} antigravity-doctor"
1291
+
1292
+ return {
1293
+ "antigravity_plugin": {
1294
+ "installed": _ok("plugin directory") and _ok("plugin payload"),
1295
+ "label": "Antigravity Plugin",
1296
+ "description": "Installs the Token Optimizer plugin into ~/.gemini/config/plugins/token-optimizer/. Provides continuity restore, context nudges, bash compression, and stop rollup.",
1297
+ "install_cmd": install_cmd,
1298
+ "uninstall_cmd": f"{_measure_facade._runtime_cli('antigravity')} antigravity-uninstall",
1299
+ },
1300
+ "antigravity_hooks": {
1301
+ "installed": _ok("plugin hooks"),
1302
+ "partial": by_name.get("plugin hooks", {}).get("status") == "warn",
1303
+ "label": "Antigravity Hook Declarations",
1304
+ "description": "Verifies hooks.json declares PreInvocation, PreToolUse (run_command matcher), and Stop.",
1305
+ "install_cmd": install_cmd,
1306
+ "uninstall_cmd": f"{_measure_facade._runtime_cli('antigravity')} antigravity-uninstall",
1307
+ },
1308
+ "antigravity_consent": {
1309
+ "installed": _ok("consent record"),
1310
+ "partial": by_name.get("consent record", {}).get("status") == "warn",
1311
+ "label": "Data Consent",
1312
+ "description": "Checks that the install-time consent record exists, which gates data collection.",
1313
+ "install_cmd": install_cmd,
1314
+ "uninstall_cmd": doctor_cmd,
1315
+ },
1316
+ "antigravity_dashboard_port": {
1317
+ # The doctor's check name is "dashboard daemon" (lowercase, with
1318
+ # the port in the detail text, not the name) — the lookup must
1319
+ # match it exactly or the toggle can never turn green.
1320
+ "installed": _ok("dashboard daemon"),
1321
+ "label": "Dashboard Port 24847",
1322
+ "description": "Confirms that port 24847 is available or already serving the Antigravity Token Optimizer dashboard.",
1323
+ "install_cmd": f"{_measure_facade._runtime_cli('antigravity')} open-dashboard",
1324
+ "uninstall_cmd": "",
1325
+ },
1326
+ }
1327
+
1328
+
1329
+ def _parse_skill_frontmatter(path: Path) -> dict:
1330
+ _measure_facade = _compat.facade()
1331
+ try:
1332
+ text = path.read_text(encoding="utf-8", errors="replace")
1333
+ except OSError:
1334
+ return {}
1335
+ meta = {}
1336
+ if text.startswith("---"):
1337
+ end = text.find("\n---", 3)
1338
+ if end != -1:
1339
+ for line in text[3:end].splitlines():
1340
+ if ":" not in line:
1341
+ continue
1342
+ key, value = line.split(":", 1)
1343
+ key = key.strip()
1344
+ value = value.strip().strip('"').strip("'")
1345
+ if key in {"name", "description"}:
1346
+ meta[key] = value
1347
+ if "name" not in meta:
1348
+ meta["name"] = path.parent.name
1349
+ # Codex discovers skills from metadata; the SKILL.md body is loaded when
1350
+ # the skill is selected. Count the discovery surface here, not the full
1351
+ # on-demand skill body, otherwise startup/context recommendations are wildly
1352
+ # inflated for large skills.
1353
+ discovery_text = f"name: {meta.get('name', '')}\ndescription: {meta.get('description', '')}\n"
1354
+ meta["tokens"] = _measure_facade._estimate_tokens(discovery_text)
1355
+ meta["body_tokens"] = _measure_facade._estimate_tokens(text)
1356
+ return meta
1357
+
1358
+
1359
+ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, list[dict]]:
1360
+ _measure_facade = _compat.facade()
1361
+ disabled_paths = set()
1362
+ skills_cfg = cfg.get("skills")
1363
+ if isinstance(skills_cfg, dict):
1364
+ entries = skills_cfg.get("config")
1365
+ if isinstance(entries, list):
1366
+ for entry in entries:
1367
+ if not isinstance(entry, dict) or entry.get("enabled", True):
1368
+ continue
1369
+ raw_path = entry.get("path")
1370
+ if isinstance(raw_path, str):
1371
+ resolved = _measure_facade.Path(raw_path).expanduser().resolve(strict=False)
1372
+ disabled_paths.add(str(resolved))
1373
+ if resolved.name != "SKILL.md":
1374
+ disabled_paths.add(str((resolved / "SKILL.md").resolve(strict=False)))
1375
+
1376
+ candidates: list[tuple[_measure_facade.Path, str]] = []
1377
+ for root, source in (
1378
+ (project / ".codex" / "skills", "project"),
1379
+ (_measure_facade.RUNTIME_DIR / "skills", "user"),
1380
+ ):
1381
+ if root.exists():
1382
+ candidates.extend((p, source) for p in root.rglob("SKILL.md"))
1383
+
1384
+ plugin_cache = _measure_facade.RUNTIME_DIR / "plugins" / "cache"
1385
+ if plugin_cache.exists():
1386
+ candidates.extend((p, "plugin") for p in plugin_cache.rglob("skills/*/SKILL.md"))
1387
+
1388
+ # Plugins disabled in config.toml ([plugins."name@marketplace"] enabled=false)
1389
+ # do not expose their cached skills to the model — they belong in "disabled",
1390
+ # not "active", or the inventory reports an advertised surface larger than
1391
+ # what Codex actually loads.
1392
+ disabled_plugin_keys: set[str] = set()
1393
+ plugins_cfg = cfg.get("plugins")
1394
+ if isinstance(plugins_cfg, dict):
1395
+ for _pkey, _pcfg in plugins_cfg.items():
1396
+ if isinstance(_pcfg, dict) and not _pcfg.get("enabled", True):
1397
+ disabled_plugin_keys.add(str(_pkey))
1398
+
1399
+ def _plugin_key_for(path_str: str) -> str | None:
1400
+ # Cache layout: <cache>/<marketplace>/<plugin>/<version>/skills/<name>/SKILL.md
1401
+ _measure_facade = _compat.facade()
1402
+ try:
1403
+ rel = _measure_facade.Path(path_str).relative_to(plugin_cache.resolve(strict=False))
1404
+ except ValueError:
1405
+ return None
1406
+ parts = rel.parts
1407
+ if len(parts) >= 5 and parts[-3] == "skills":
1408
+ return f"{parts[1]}@{parts[0]}"
1409
+ return None
1410
+
1411
+ # The cache keeps old versions after an upgrade, but Codex loads one
1412
+ # version per plugin. Counting every cached copy inflated the plugin
1413
+ # skill total several times over (issue #276).
1414
+ def _version_key(name: str):
1415
+ _measure_facade = _compat.facade()
1416
+ nums = _measure_facade.re.findall(r"\d+", name)
1417
+ return tuple(int(n) for n in nums) if nums else (-1,)
1418
+
1419
+ newest_version: dict[tuple[str, str], str] = {}
1420
+ for path, source in candidates:
1421
+ if source != "plugin":
1422
+ continue
1423
+ try:
1424
+ rel = path.relative_to(plugin_cache)
1425
+ except ValueError:
1426
+ continue
1427
+ if len(rel.parts) >= 6 and rel.parts[-3] == "skills":
1428
+ key = (rel.parts[0], rel.parts[1])
1429
+ current = newest_version.get(key)
1430
+ if current is None or _version_key(rel.parts[2]) > _version_key(current):
1431
+ newest_version[key] = rel.parts[2]
1432
+
1433
+ active = []
1434
+ disabled = []
1435
+ seen: set[str] = set()
1436
+ mp_cmd = _measure_facade._shell_script_path()
1437
+ for path, source in candidates:
1438
+ if source == "plugin":
1439
+ try:
1440
+ rel = path.relative_to(plugin_cache)
1441
+ except ValueError:
1442
+ rel = None
1443
+ if (rel is not None and len(rel.parts) >= 6 and rel.parts[-3] == "skills"
1444
+ and newest_version.get((rel.parts[0], rel.parts[1])) != rel.parts[2]):
1445
+ continue
1446
+ resolved = str(path.expanduser().resolve(strict=False))
1447
+ if resolved in seen:
1448
+ continue
1449
+ seen.add(resolved)
1450
+ meta = _measure_facade._parse_skill_frontmatter(path)
1451
+ item = {
1452
+ "name": meta.get("name") or path.parent.name,
1453
+ "skill_name": meta.get("name") or path.parent.name,
1454
+ "description": meta.get("description", ""),
1455
+ "tokens": meta.get("tokens", 0),
1456
+ "source": source,
1457
+ "path": _measure_facade._display_path(resolved),
1458
+ "disable_cmd": f"{_measure_facade._runtime_cli('codex')} codex-skill disable --path {_measure_facade.shlex.quote(resolved)}",
1459
+ "enable_cmd": f"{_measure_facade._runtime_cli('codex')} codex-skill enable --path {_measure_facade.shlex.quote(resolved)}",
1460
+ }
1461
+ _pkey = _plugin_key_for(resolved)
1462
+ if _pkey is not None:
1463
+ item["plugin"] = _pkey
1464
+ if resolved in disabled_paths or (_pkey is not None and _pkey in disabled_plugin_keys):
1465
+ disabled.append(item)
1466
+ else:
1467
+ active.append(item)
1468
+ active.sort(key=lambda item: ((_measure_facade := _compat.facade()), (item["source"], item["name"]))[1])
1469
+ disabled.sort(key=lambda item: ((_measure_facade := _compat.facade()), (item["source"], item["name"]))[1])
1470
+ return {"active": active, "disabled": disabled}
1471
+
1472
+
1473
+ def _collect_codex_mcp_inventory(cfg: dict) -> list[dict]:
1474
+ _measure_facade = _compat.facade()
1475
+ servers = cfg.get("mcp_servers")
1476
+ if not isinstance(servers, dict):
1477
+ return []
1478
+ items = []
1479
+ mp_cmd = _measure_facade._shell_script_path()
1480
+ for name, server in servers.items():
1481
+ if not isinstance(server, dict):
1482
+ server = {}
1483
+ enabled = bool(server.get("enabled", True))
1484
+ transport = "http" if server.get("url") else "stdio"
1485
+ command = server.get("url") or server.get("command") or ""
1486
+ items.append({
1487
+ "name": name,
1488
+ "command": str(command),
1489
+ "transport": transport,
1490
+ "tokens": _measure_facade.TOKENS_PER_DEFERRED_TOOL,
1491
+ "enabled": enabled,
1492
+ "disable_cmd": f"{_measure_facade._runtime_cli('codex')} codex-mcp disable {_measure_facade.shlex.quote(str(name))}",
1493
+ "enable_cmd": f"{_measure_facade._runtime_cli('codex')} codex-mcp enable {_measure_facade.shlex.quote(str(name))}",
1494
+ })
1495
+ return sorted(items, key=lambda item: ((_measure_facade := _compat.facade()), item["name"])[1])
1496
+
1497
+
1498
+ def _collect_codex_plugin_inventory(cfg: dict) -> list[dict]:
1499
+ _measure_facade = _compat.facade()
1500
+ plugins = cfg.get("plugins")
1501
+ if not isinstance(plugins, dict):
1502
+ return []
1503
+ items = []
1504
+ for name, plugin_cfg in plugins.items():
1505
+ enabled = True
1506
+ if isinstance(plugin_cfg, dict):
1507
+ enabled = bool(plugin_cfg.get("enabled", True))
1508
+ items.append({"name": name, "enabled": enabled})
1509
+ return sorted(items, key=lambda item: ((_measure_facade := _compat.facade()), item["name"])[1])
1510
+
1511
+
1512
+ def _codex_config_path() -> Path:
1513
+ _measure_facade = _compat.facade()
1514
+ return _measure_facade.runtime_home() / "config.toml"
1515
+
1516
+
1517
+ def _safe_codex_config_path() -> Path:
1518
+ _measure_facade = _compat.facade()
1519
+ home = _measure_facade.runtime_home().resolve(strict=False)
1520
+ path = _measure_facade._codex_config_path()
1521
+ if path.exists() and path.is_symlink():
1522
+ raise ValueError(f"{path} must not be a symlink")
1523
+ parent = path.parent
1524
+ if parent.exists():
1525
+ if parent.is_symlink() or not parent.is_dir():
1526
+ raise ValueError(f"{parent} must be a real directory")
1527
+ if not parent.resolve(strict=True).is_relative_to(home):
1528
+ raise ValueError(f"{parent} escapes Codex home")
1529
+ else:
1530
+ parent.mkdir(mode=0o700)
1531
+ return path
1532
+
1533
+
1534
+ def _codex_config_lock():
1535
+ """Bounded portable lease for config.toml writes.
1536
+
1537
+ Serializes concurrent read-modify-write cycles on config.toml (skill
1538
+ enable/disable, MCP toggles). Contenders skip the mutation after 75ms
1539
+ rather than blocking a hook.
1540
+ """
1541
+ _measure_facade = _compat.facade()
1542
+ lease_path = _measure_facade._CODEX_CONFIG_LOCK_PATH.with_suffix(".lease")
1543
+ with _measure_facade.lease_lock(
1544
+ lease_path,
1545
+ deadline=_measure_facade.current_deadline(),
1546
+ acquire_timeout=0.075,
1547
+ ) as acquired:
1548
+ yield acquired
1549
+
1550
+
1551
+ def _skill_mgmt_lock():
1552
+ """Bounded portable lease serializing skill archive/restore mutations.
1553
+
1554
+ The dashboard daemon and a CLI `measure.py skill archive|restore` run in
1555
+ separate processes with no in-process serialization, so this cross-process
1556
+ lease closes the archive/restore TOCTOU windows.
1557
+ Contenders skip the mutation after 75ms rather than blocking a hook.
1558
+ """
1559
+ _measure_facade = _compat.facade()
1560
+ lock_path = _measure_facade.CLAUDE_DIR / "_backups" / ".skill-mgmt.lock"
1561
+ lease_path = lock_path.with_suffix(".lease")
1562
+ with _measure_facade.lease_lock(
1563
+ lease_path,
1564
+ deadline=_measure_facade.current_deadline(),
1565
+ acquire_timeout=0.075,
1566
+ ) as acquired:
1567
+ yield acquired
1568
+
1569
+
1570
+ def _write_codex_config(text: str) -> None:
1571
+ _measure_facade = _compat.facade()
1572
+ path = _measure_facade._safe_codex_config_path()
1573
+ with _measure_facade._codex_config_lock() as acquired:
1574
+ if not acquired:
1575
+ return
1576
+ _measure_facade.codex_io.atomic_write(path, text)
1577
+
1578
+
1579
+ def _toml_string(value: str) -> str:
1580
+ _measure_facade = _compat.facade()
1581
+ return _measure_facade.json.dumps(value)
1582
+
1583
+
1584
+ def _set_toml_key(block: str, key: str, value: str) -> str:
1585
+ _measure_facade = _compat.facade()
1586
+ pattern = _measure_facade.re.compile(rf"(?m)^([ \t]*){_measure_facade.re.escape(key)}([ \t]*=[^\n]*)$")
1587
+ if pattern.search(block):
1588
+ return pattern.sub(lambda match: ((_measure_facade := _compat.facade()), f"{match.group(1)}{key} = {value}")[1], block, count=1)
1589
+ suffix = "" if block.endswith("\n") else "\n"
1590
+ return block + suffix + f"{key} = {value}\n"
1591
+
1592
+
1593
+ def _iter_toml_array_table_spans(text: str, header: str):
1594
+ _measure_facade = _compat.facade()
1595
+ pattern = _measure_facade.re.compile(rf"(?m)^[ \t]*\[\[{_measure_facade.re.escape(header)}\]\][ \t]*(?:#.*)?$")
1596
+ next_header = _measure_facade.re.compile(r"(?m)^[ \t]*\[\[?[^\]\n]+\]?\][ \t]*(?:#.*)?$")
1597
+ for match in pattern.finditer(text):
1598
+ next_match = next_header.search(text, match.end())
1599
+ yield match.start(), next_match.start() if next_match else len(text)
1600
+
1601
+
1602
+ def _decode_toml_string(raw: str) -> str:
1603
+ _measure_facade = _compat.facade()
1604
+ raw = raw.strip()
1605
+ if raw.startswith('"') and raw.endswith('"'):
1606
+ try:
1607
+ return _measure_facade.json.loads(raw)
1608
+ except _measure_facade.json.JSONDecodeError:
1609
+ return raw.strip('"')
1610
+ return raw.strip("'\"")
1611
+
1612
+
1613
+ def _codex_skill_target(raw_path: str | None = None, name: str | None = None) -> Path | None:
1614
+ _measure_facade = _compat.facade()
1615
+ project = _measure_facade.Path.cwd().resolve(strict=False)
1616
+ cfg = _measure_facade._read_codex_config()
1617
+ inventory = _measure_facade._collect_codex_skill_inventory(cfg, project=project)
1618
+ all_items = inventory["active"] + inventory["disabled"]
1619
+ if raw_path:
1620
+ target = _measure_facade.Path(raw_path).expanduser().resolve(strict=False)
1621
+ if target.name != "SKILL.md":
1622
+ target = target / "SKILL.md"
1623
+ for item in all_items:
1624
+ if _measure_facade.Path(item["path"]).expanduser().resolve(strict=False) == target:
1625
+ return target
1626
+ return target if target.exists() else None
1627
+ if name:
1628
+ matches = [item for item in all_items if item["name"] == name or item.get("skill_name") == name]
1629
+ if len(matches) == 1:
1630
+ return _measure_facade.Path(matches[0]["path"]).expanduser().resolve(strict=False)
1631
+ return None
1632
+
1633
+
1634
+ def _manage_codex_skill(action: str, *, raw_path: str | None = None, name: str | None = None) -> bool:
1635
+ _measure_facade = _compat.facade()
1636
+ target = _measure_facade._codex_skill_target(raw_path=raw_path, name=name)
1637
+ if not target:
1638
+ return False
1639
+ try:
1640
+ text = _measure_facade._safe_codex_config_path().read_text(encoding="utf-8")
1641
+ except OSError:
1642
+ text = ""
1643
+
1644
+ enabled = action == "enable"
1645
+ target_str = str(target)
1646
+ replacement = None
1647
+ for start, end in _measure_facade._iter_toml_array_table_spans(text, "skills.config"):
1648
+ block = text[start:end]
1649
+ path_match = _measure_facade.re.search(r"(?m)^[ \t]*path[ \t]*=[ \t]*(.+?)[ \t]*(?:#.*)?$", block)
1650
+ if not path_match:
1651
+ continue
1652
+ configured = _measure_facade.Path(_measure_facade._decode_toml_string(path_match.group(1))).expanduser().resolve(strict=False)
1653
+ if configured.name != "SKILL.md":
1654
+ configured = configured / "SKILL.md"
1655
+ if configured == target:
1656
+ replacement = text[:start] + _measure_facade._set_toml_key(block, "enabled", "true" if enabled else "false") + text[end:]
1657
+ break
1658
+
1659
+ if replacement is None:
1660
+ suffix = "" if not text or text.endswith("\n") else "\n"
1661
+ replacement = (
1662
+ text
1663
+ + suffix
1664
+ + "\n[[skills.config]]\n"
1665
+ + f"path = {_measure_facade._toml_string(target_str)}\n"
1666
+ + f"enabled = {'true' if enabled else 'false'}\n"
1667
+ )
1668
+ _measure_facade._write_codex_config(replacement)
1669
+ return True
1670
+
1671
+
1672
+ def _toml_table_header_variants(prefix: str, name: str) -> list[str]:
1673
+ _measure_facade = _compat.facade()
1674
+ if _measure_facade.re.fullmatch(r"[A-Za-z0-9_-]+", name):
1675
+ return [f"[{prefix}.{name}]"]
1676
+ return [f"[{prefix}.{_measure_facade._toml_string(name)}]"]
1677
+
1678
+
1679
+ def _set_codex_named_table_enabled(prefix: str, name: str, enabled: bool) -> bool:
1680
+ _measure_facade = _compat.facade()
1681
+ path = _measure_facade._safe_codex_config_path()
1682
+ try:
1683
+ text = path.read_text(encoding="utf-8")
1684
+ except OSError:
1685
+ return False
1686
+ next_header = _measure_facade.re.compile(r"(?m)^[ \t]*\[[^\]\n]+\][ \t]*(?:#.*)?$")
1687
+ for header in _measure_facade._toml_table_header_variants(prefix, name):
1688
+ pattern = _measure_facade.re.compile(rf"(?m)^[ \t]*{_measure_facade.re.escape(header)}[ \t]*(?:#.*)?$")
1689
+ match = pattern.search(text)
1690
+ if not match:
1691
+ continue
1692
+ next_match = next_header.search(text, match.end())
1693
+ end = next_match.start() if next_match else len(text)
1694
+ block = text[match.start():end]
1695
+ updated = _measure_facade._set_toml_key(block, "enabled", "true" if enabled else "false")
1696
+ _measure_facade._write_codex_config(text[:match.start()] + updated + text[end:])
1697
+ return True
1698
+ return False
1699
+
1700
+
1701
+ def _manage_codex_mcp(action: str, name: str) -> bool:
1702
+ _measure_facade = _compat.facade()
1703
+ return _measure_facade._set_codex_named_table_enabled("mcp_servers", name, action == "enable")
1704
+
1705
+
1706
+ def _collect_management_data(components=None, trends=None):
1707
+ """Collect data for the Manage tab: active/archived skills, MCP servers."""
1708
+ _measure_facade = _compat.facade()
1709
+ if components is None:
1710
+ components = _measure_facade.measure_components()
1711
+
1712
+ mp_cmd = _measure_facade._shell_script_path()
1713
+ if _measure_facade.detect_runtime() == "codex":
1714
+ project = _measure_facade.Path.cwd().resolve(strict=False)
1715
+ project_arg = _measure_facade.shlex.quote(str(project))
1716
+ base = f"{_measure_facade._runtime_cli('codex')} codex-install --project {project_arg}"
1717
+ cfg = _measure_facade._read_codex_config()
1718
+ codex_skills = _measure_facade._collect_codex_skill_inventory(cfg, project=project)
1719
+ codex_mcp = _measure_facade._collect_codex_mcp_inventory(cfg)
1720
+ codex_mcp_active = [item for item in codex_mcp if item.get("enabled", True)]
1721
+ codex_mcp_disabled = [item for item in codex_mcp if not item.get("enabled", True)]
1722
+ codex_plugins = _measure_facade._collect_codex_plugin_inventory(cfg)
1723
+ return {
1724
+ "mode": "codex",
1725
+ "codex": {
1726
+ "project": _measure_facade._display_path(project),
1727
+ "install_cmd": base,
1728
+ "install_quiet_profile_cmd": base + " --profile quiet",
1729
+ "install_balanced_profile_cmd": base + " --profile balanced",
1730
+ "install_telemetry_profile_cmd": base + " --profile telemetry",
1731
+ "install_aggressive_profile_cmd": base + " --profile aggressive",
1732
+ "install_with_bash_compression_cmd": base + " --enable-bash-compression",
1733
+ "install_with_hot_path_hooks_cmd": base + " --enable-hot-path-hooks --enable-prompt-hooks",
1734
+ "install_with_status_line_cmd": base + " --enable-status-line",
1735
+ "refresh_cmd": f"{_measure_facade._runtime_cli('codex')} session-end-flush --trigger manual --no-defer",
1736
+ "doctor_cmd": f"{_measure_facade._runtime_cli('codex')} codex-doctor --project {project_arg}",
1737
+ "dashboard_cmd": f"{_measure_facade._runtime_cli('codex')} dashboard",
1738
+ },
1739
+ "skills": {"active": codex_skills["active"], "archived": [], "disabled": codex_skills["disabled"]},
1740
+ "mcp_servers": {"active": codex_mcp_active, "disabled": codex_mcp_disabled, "cloud": []},
1741
+ "plugins": codex_plugins,
1742
+ "v5_features": _measure_facade._get_v5_feature_status(),
1743
+ }
1744
+
1745
+ # Hermes: list its own skills (~/.hermes/skills) and MCP servers
1746
+ # (config.yaml mcp_servers) read-only, without scanning CLAUDE_DIR,
1747
+ # settings.json or claude_desktop_config.json.
1748
+ if _measure_facade.detect_runtime() == "hermes":
1749
+ hermes_cfg = _measure_facade._hermes_config(_measure_facade.runtime_home())
1750
+ hermes_skills = _measure_facade._hermes_skill_inventory(_measure_facade.runtime_home(), hermes_cfg)
1751
+ hermes_mcp = _measure_facade._hermes_mcp_inventory(hermes_cfg)
1752
+ return {
1753
+ "mode": "hermes",
1754
+ "read_only": True,
1755
+ "skills": hermes_skills,
1756
+ "mcp_servers": {"active": [i for i in hermes_mcp if i["enabled"]],
1757
+ "disabled": [i for i in hermes_mcp if not i["enabled"]], "cloud": []},
1758
+ "plugins": [],
1759
+ "v5_features": _measure_facade._get_v5_feature_status(),
1760
+ }
1761
+
1762
+ # Cursor: same shape as Hermes — Cursor has no Claude-style skills/MCP/
1763
+ # settings.json management surface, and falling through would silently
1764
+ # collect CLAUDE_DIR/_backups and Claude skills/MCP under a Cursor pin.
1765
+ if _measure_facade.detect_runtime() == "cursor":
1766
+ return {
1767
+ "mode": "cursor",
1768
+ "skills": {"active": [], "archived": []},
1769
+ "mcp_servers": {"active": [], "disabled": [], "cloud": []},
1770
+ "plugins": [],
1771
+ "v5_features": _measure_facade._get_v5_feature_status(),
1772
+ }
1773
+
1774
+ backups_dir = _measure_facade.CLAUDE_DIR / "_backups"
1775
+
1776
+ # Active skills
1777
+ active_skills = []
1778
+ skills_detail = components.get("skills_detail", {})
1779
+ for name in sorted(components.get("skills", {}).get("names", [])):
1780
+ sd = skills_detail.get(name, {})
1781
+ active_skills.append({
1782
+ "name": name,
1783
+ "skill_name": sd.get("skill_name", name),
1784
+ "tokens": sd.get("frontmatter_tokens", 100),
1785
+ "description": sd.get("description", ""),
1786
+ "archive_cmd": f"{_measure_facade.hint_python()} {mp_cmd} skill archive {_measure_facade.shlex.quote(name)}",
1787
+ })
1788
+
1789
+ # Archived skills (scan backup dirs)
1790
+ archived_skills = []
1791
+ if backups_dir.exists():
1792
+ for archive_dir in sorted(backups_dir.iterdir(), reverse=True):
1793
+ if not archive_dir.is_dir() or not archive_dir.name.startswith(_measure_facade.SKILL_ARCHIVE_DIR_PREFIXES):
1794
+ continue
1795
+ # "skills-archived-DATE" / "skills-deduped-DATE" -> "DATE"
1796
+ date_part = archive_dir.name.split("-", 2)[2] if archive_dir.name.count("-") >= 2 else ""
1797
+ try:
1798
+ entries = sorted(archive_dir.iterdir())
1799
+ except OSError:
1800
+ continue
1801
+ for item in entries:
1802
+ # One unreadable entry must not blank the whole Manage tab.
1803
+ try:
1804
+ if not item.is_dir():
1805
+ continue
1806
+ # A real archived skill carries SKILL.md; a symlinked skill is
1807
+ # archived as a dir holding only the marker. SKILL.md
1808
+ # takes precedence so a real skill is never mislabeled as a link.
1809
+ # Surface both so symlinked skills stay restorable from the UI.
1810
+ has_skill_md = (item / "SKILL.md").exists()
1811
+ is_symlink_record = not has_skill_md and (item / _measure_facade.SYMLINK_TARGET_MARKER).exists()
1812
+ if not has_skill_md and not is_symlink_record:
1813
+ continue
1814
+ desc = "Symlinked skill" if is_symlink_record else ""
1815
+ if not is_symlink_record:
1816
+ content = (item / "SKILL.md").read_text(encoding="utf-8")[:2000]
1817
+ if content.startswith("---"):
1818
+ end = content.find("---", 3)
1819
+ if end > 0:
1820
+ for line in content[3:end].split("\n"):
1821
+ if line.strip().startswith("description:"):
1822
+ desc = line.strip()[12:].strip()[:100]
1823
+ break
1824
+ except OSError:
1825
+ continue
1826
+ archived_skills.append({
1827
+ "name": item.name,
1828
+ "archived_date": date_part,
1829
+ "archive_dir": archive_dir.name,
1830
+ "description": desc,
1831
+ "symlink": is_symlink_record,
1832
+ "restore_cmd": f"{_measure_facade.hint_python()} {mp_cmd} skill restore {_measure_facade.shlex.quote(item.name)}",
1833
+ })
1834
+
1835
+ # MCP servers (local settings.json)
1836
+ settings, _ = _measure_facade._read_settings_json()
1837
+ mcp_servers_config = settings.get("mcpServers", {})
1838
+ disabled_config = settings.get("_disabledMcpServers", {})
1839
+
1840
+ active_mcps = []
1841
+ for name in sorted(mcp_servers_config.keys()):
1842
+ cfg = mcp_servers_config[name]
1843
+ tool_count = len(cfg.get("tools", []))
1844
+ active_mcps.append({
1845
+ "name": name,
1846
+ "source": "local",
1847
+ "tool_count": tool_count,
1848
+ "command": cfg.get("command", ""),
1849
+ "disable_cmd": f"{_measure_facade.hint_python()} {mp_cmd} mcp disable {_measure_facade.shlex.quote(name)}",
1850
+ })
1851
+
1852
+ disabled_mcps = []
1853
+ for name in sorted(disabled_config.keys()):
1854
+ disabled_mcps.append({
1855
+ "name": name,
1856
+ "source": "local",
1857
+ "enable_cmd": f"{_measure_facade.hint_python()} {mp_cmd} mcp enable {_measure_facade.shlex.quote(name)}",
1858
+ })
1859
+
1860
+ # Cloud-synced MCP servers (Claude Desktop config)
1861
+ cloud_mcps = []
1862
+ desktop_config = _measure_facade.HOME / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
1863
+ if desktop_config.exists():
1864
+ try:
1865
+ dc = _measure_facade.json.loads(desktop_config.read_text(encoding="utf-8"))
1866
+ for name in sorted(dc.get("mcpServers", {}).keys()):
1867
+ if name not in mcp_servers_config and name not in disabled_config:
1868
+ cfg = dc["mcpServers"][name]
1869
+ cloud_mcps.append({
1870
+ "name": name,
1871
+ "source": "cloud",
1872
+ "command": cfg.get("command", ""),
1873
+ })
1874
+ except (_measure_facade.json.JSONDecodeError, OSError):
1875
+ pass
1876
+
1877
+ return {
1878
+ "skills": {
1879
+ "active": active_skills,
1880
+ "archived": archived_skills,
1881
+ },
1882
+ "mcp_servers": {
1883
+ "active": active_mcps,
1884
+ "disabled": disabled_mcps,
1885
+ "cloud": cloud_mcps,
1886
+ },
1887
+ "v5_features": _measure_facade._get_v5_feature_status(),
1888
+ }
1889
+
1890
+
1891
+ def plugin_cleanup(dry_run=None, quiet=None):
1892
+ """Report stale plugin cache dirs and archive local/plugin skill overlaps.
1893
+
1894
+ Two actions:
1895
+ 1. Stale cache REPORTING: lists old plugin version dirs in ~/.claude/plugins/cache/
1896
+ not referenced by installPath. Does NOT delete them because installPath is not
1897
+ always the authoritative source (Claude Code's loader may resolve via marketplace
1898
+ source, especially for directory-sourced plugins). Users should review manually.
1899
+ 2. Local/plugin overlap: archives local skills in ~/.claude/skills/ that duplicate
1900
+ plugin-installed skills (only bare SKILL.md; keeps skills with custom reference files).
1901
+ """
1902
+ _measure_facade = _compat.facade()
1903
+ import shutil
1904
+
1905
+ actions_taken = []
1906
+
1907
+ # Defense-in-depth: under a foreign runtime (OpenCode, Copilot),
1908
+ # do not touch ~/.claude.
1909
+ if _measure_facade._is_foreign_runtime():
1910
+ if not quiet:
1911
+ print(f" Skipped: {_measure_facade.runtime_name_for_humans()} runtime detected; not modifying ~/.claude.")
1912
+ return actions_taken
1913
+
1914
+ # --- Report 1: Stale cache version dirs (report only, never delete) ---
1915
+ registry = _measure_facade.CLAUDE_DIR / "plugins" / "installed_plugins.json"
1916
+ cache_dir = _measure_facade.CLAUDE_DIR / "plugins" / "cache"
1917
+
1918
+ active_paths = set()
1919
+ if registry.exists():
1920
+ try:
1921
+ with open(registry, "r", encoding="utf-8") as f:
1922
+ data = _measure_facade.json.load(f)
1923
+ for plugin_key, installs in data.get("plugins", {}).items():
1924
+ if not isinstance(installs, list):
1925
+ continue
1926
+ for inst in installs:
1927
+ raw = inst.get("installPath", "")
1928
+ if raw:
1929
+ active_paths.add(str(_measure_facade.Path(raw).resolve()))
1930
+ except (_measure_facade.json.JSONDecodeError, OSError):
1931
+ pass
1932
+
1933
+ stale_dirs = []
1934
+ if cache_dir.exists():
1935
+ for marketplace in sorted(cache_dir.iterdir()):
1936
+ if not marketplace.is_dir():
1937
+ continue
1938
+ for plugin in sorted(marketplace.iterdir()):
1939
+ if not plugin.is_dir():
1940
+ continue
1941
+ for version_dir in sorted(plugin.iterdir()):
1942
+ if not version_dir.is_dir():
1943
+ continue
1944
+ resolved = str(version_dir.resolve())
1945
+ if resolved not in active_paths:
1946
+ has_skills = (version_dir / "skills").is_dir()
1947
+ stale_dirs.append({
1948
+ "path": version_dir,
1949
+ "display": f"{marketplace.name}/{plugin.name}/{version_dir.name}",
1950
+ "has_skills": has_skills,
1951
+ })
1952
+
1953
+ if stale_dirs:
1954
+ skills_stale = [d for d in stale_dirs if d["has_skills"]]
1955
+ if not quiet:
1956
+ print(f"\n Stale plugin cache: {len(stale_dirs)} unreferenced dirs ({len(skills_stale)} with skills)")
1957
+ print(" These are NOT auto-deleted (Claude Code's loader may still use them).")
1958
+ print(" Review manually: ls ~/.claude/plugins/cache/")
1959
+ elif not quiet:
1960
+ print("\n Stale plugin cache: clean")
1961
+
1962
+ # --- Local skills that duplicate plugin skills ---
1963
+ # Scan plugin skills to get the set of skill directory names
1964
+ plugin_skill_names = set()
1965
+ if registry.exists():
1966
+ try:
1967
+ with open(registry, "r", encoding="utf-8") as f:
1968
+ data = _measure_facade.json.load(f)
1969
+
1970
+ # Load enabledPlugins to only check active plugins
1971
+ enabled = None
1972
+ if _measure_facade._is_regular_file(_measure_facade.SETTINGS_PATH):
1973
+ try:
1974
+ settings = _measure_facade.json.loads(_measure_facade.SETTINGS_PATH.read_text(encoding="utf-8"))
1975
+ enabled = settings.get("enabledPlugins")
1976
+ except (_measure_facade.json.JSONDecodeError, OSError):
1977
+ pass
1978
+
1979
+ for plugin_key, installs in data.get("plugins", {}).items():
1980
+ if not isinstance(installs, list):
1981
+ continue
1982
+ if enabled is not None and not enabled.get(plugin_key, False):
1983
+ continue
1984
+ for inst in installs:
1985
+ raw = inst.get("installPath", "")
1986
+ if not raw:
1987
+ continue
1988
+ install_path = _measure_facade.Path(raw)
1989
+ if not install_path.exists():
1990
+ continue
1991
+ skills_path = install_path / "skills"
1992
+ if skills_path.is_dir():
1993
+ for item in skills_path.iterdir():
1994
+ if item.is_dir() and (item / "SKILL.md").exists():
1995
+ plugin_skill_names.add(item.name)
1996
+ except (_measure_facade.json.JSONDecodeError, OSError):
1997
+ pass
1998
+
1999
+ # Check ~/.claude/skills/ for overlaps
2000
+ # Only archive if local skill is a plain symlink OR has no extra files beyond SKILL.md.
2001
+ # Local skills with custom reference files (loaded on-demand) have content the plugin
2002
+ # version lacks, so archiving them would lose functionality.
2003
+ skills_dir = _measure_facade.CLAUDE_DIR / "skills"
2004
+ overlaps = []
2005
+ if skills_dir.exists() and plugin_skill_names:
2006
+ for item in sorted(skills_dir.iterdir()):
2007
+ if not item.is_dir() or not (item / "SKILL.md").exists():
2008
+ continue
2009
+ if item.name in plugin_skill_names:
2010
+ # Safe to archive: symlinks (just a pointer) or bare skills (only SKILL.md)
2011
+ if item.is_symlink():
2012
+ overlaps.append(item)
2013
+ else:
2014
+ extra_files = [f.name for f in item.iterdir()
2015
+ if f.name != "SKILL.md" and not f.name.startswith(".")]
2016
+ if not extra_files:
2017
+ overlaps.append(item)
2018
+ elif not quiet:
2019
+ print(f" [skip] {item.name}: local copy has extra files ({', '.join(extra_files[:3])}), keeping it")
2020
+
2021
+ backups_dir = _measure_facade.CLAUDE_DIR / "_backups"
2022
+ if overlaps:
2023
+ if not quiet:
2024
+ print(f" Local/plugin overlaps: {len(overlaps)} skills loaded twice")
2025
+ today = _measure_facade.time.strftime("%Y%m%d")
2026
+ archive_dir = backups_dir / f"skills-deduped-{today}"
2027
+ for item in overlaps:
2028
+ if dry_run:
2029
+ if not quiet:
2030
+ print(f" [dry-run] would archive: {item.name} (exists as plugin + local)")
2031
+ else:
2032
+ try:
2033
+ archive_dir.mkdir(parents=True, exist_ok=True)
2034
+ dest = archive_dir / item.name
2035
+ if dest.exists():
2036
+ if not quiet:
2037
+ print(f" [skip] {item.name}: already archived today")
2038
+ continue
2039
+ # Move (handles both dirs and symlinks)
2040
+ if item.is_symlink():
2041
+ # For symlinks: record target, then remove the symlink
2042
+ target = _measure_facade.os.readlink(item)
2043
+ dest.mkdir(parents=True, exist_ok=True)
2044
+ (dest / _measure_facade.SYMLINK_TARGET_MARKER).write_text(target, encoding="utf-8")
2045
+ item.unlink()
2046
+ else:
2047
+ shutil.move(str(item), str(dest))
2048
+ if not quiet:
2049
+ print(f" archived: {item.name} -> {archive_dir.name}/")
2050
+ actions_taken.append(f"archived duplicate local skill: {item.name}")
2051
+ except OSError as e:
2052
+ if not quiet:
2053
+ print(f" [error] {item.name}: {e}")
2054
+ elif not quiet:
2055
+ print(" Local/plugin overlaps: none")
2056
+
2057
+ if not quiet:
2058
+ if actions_taken:
2059
+ print(f"\n {len(actions_taken)} fixes applied. Restart Claude Code to take effect.")
2060
+ print(f" Restore archived skills from: {backups_dir}/skills-deduped-*/")
2061
+ elif not dry_run:
2062
+ print("\n Everything clean. No duplicates found.")
2063
+ print()
2064
+
2065
+ return actions_taken
2066
+
2067
+
2068
+ def _manage_skill(action, name):
2069
+ """Archive or restore a skill.
2070
+
2071
+ Skills in ~/.claude/skills are often symlinks pointing into a shared skills
2072
+ repo. Archiving a symlinked skill records the link target and removes only
2073
+ the link, never the real source.
2074
+
2075
+ Held under a cross-process lock so a dashboard-daemon call and a CLI call
2076
+ can't interleave their archive/restore mutations.
2077
+ """
2078
+ _measure_facade = _compat.facade()
2079
+ with _measure_facade._skill_mgmt_lock() as acquired:
2080
+ if not acquired:
2081
+ return False
2082
+ return _measure_facade._manage_skill_locked(action, name)
2083
+
2084
+
2085
+ def _manage_skill_locked(action, name):
2086
+ _measure_facade = _compat.facade()
2087
+ import shutil
2088
+
2089
+ # Defense-in-depth: never mutate ~/.claude/skills when running
2090
+ # under a foreign runtime (OpenCode, Copilot), even if reached outside the
2091
+ # CLI dispatch guard (e.g. the dashboard /api/v5/toggle path).
2092
+ if _measure_facade._is_foreign_runtime():
2093
+ print(f" [!] Refusing to modify ~/.claude skills under the {_measure_facade.runtime_name_for_humans()} runtime.")
2094
+ return False
2095
+
2096
+ # Validate name: prevent path traversal
2097
+ if not isinstance(name, str) or not name or "/" in name or "\\" in name or name in (".", "..") or "\0" in name:
2098
+ print(f" [!] Invalid skill name: {name}")
2099
+ return False
2100
+ skills_dir = _measure_facade.CLAUDE_DIR / "skills"
2101
+ # Containment check on the UN-resolved path. The name is already validated as
2102
+ # a single path component, so the join cannot escape skills_dir. Do NOT use
2103
+ # .resolve() here: legitimate skills are often symlinks pointing outside
2104
+ # ~/.claude/skills, and resolving the target would misflag them.
2105
+ candidate = skills_dir / name
2106
+ if candidate.parent != skills_dir:
2107
+ print(f" [!] Path traversal detected: {name}")
2108
+ return False
2109
+ backups_dir = _measure_facade.CLAUDE_DIR / "_backups"
2110
+ today = _measure_facade.datetime.now().strftime("%Y%m%d")
2111
+ archive_dir = backups_dir / f"skills-archived-{today}"
2112
+
2113
+ if action == "archive":
2114
+ src = skills_dir / name
2115
+ if not src.exists() and not src.is_symlink():
2116
+ print(f" Skill '{name}' not found in {skills_dir}")
2117
+ return False
2118
+ dst = archive_dir / name
2119
+ if dst.exists() or dst.is_symlink():
2120
+ print(f" Skill '{name}' already archived. Remove it first.")
2121
+ return False
2122
+ try:
2123
+ archive_dir.mkdir(parents=True, exist_ok=True)
2124
+ if src.is_symlink():
2125
+ # Record the link target, remove only the link (not the real source)
2126
+ target = _measure_facade.os.readlink(src)
2127
+ dst.mkdir(parents=True, exist_ok=True)
2128
+ (dst / _measure_facade.SYMLINK_TARGET_MARKER).write_text(target, encoding="utf-8")
2129
+ src.unlink()
2130
+ else:
2131
+ shutil.move(str(src), str(dst))
2132
+ except OSError as e:
2133
+ print(f" [!] Failed to archive '{name}': {e}")
2134
+ return False
2135
+ print(f" Archived: {name} -> {archive_dir.name}/")
2136
+ return True
2137
+
2138
+ elif action == "restore":
2139
+ # Search all archive dirs for this skill
2140
+ if backups_dir.exists():
2141
+ for ad in sorted(backups_dir.iterdir(), reverse=True):
2142
+ if not ad.is_dir() or not ad.name.startswith(_measure_facade.SKILL_ARCHIVE_DIR_PREFIXES):
2143
+ continue
2144
+ src = ad / name
2145
+ if not src.exists() and not src.is_symlink():
2146
+ continue
2147
+ dst = skills_dir / name
2148
+ if dst.exists() or dst.is_symlink():
2149
+ print(f" Skill '{name}' already exists in skills/. Remove it first.")
2150
+ return False
2151
+ # A symlink record is a dir holding the marker and NO SKILL.md.
2152
+ # Requiring SKILL.md to be absent stops a real skill that happens
2153
+ # to ship the marker file from being turned into a link + deleted.
2154
+ marker = src / _measure_facade.SYMLINK_TARGET_MARKER
2155
+ is_symlink_record = (
2156
+ src.is_dir() and marker.exists() and not (src / "SKILL.md").exists()
2157
+ )
2158
+ try:
2159
+ if is_symlink_record:
2160
+ target = marker.read_text(encoding="utf-8").strip()
2161
+ if not target:
2162
+ print(f" [!] Archived link target for '{name}' is empty; cannot restore.")
2163
+ return False
2164
+ dst.symlink_to(target)
2165
+ # Link recreated; drop the archive record. If that fails,
2166
+ # remove the just-created link so a retry isn't blocked.
2167
+ try:
2168
+ shutil.rmtree(src)
2169
+ except OSError as e:
2170
+ dst.unlink(missing_ok=True)
2171
+ print(f" [!] Failed to clear archive for '{name}': {e}")
2172
+ return False
2173
+ else:
2174
+ shutil.move(str(src), str(dst))
2175
+ except OSError as e:
2176
+ print(f" [!] Failed to restore '{name}': {e}")
2177
+ return False
2178
+ print(f" Restored: {name} from {ad.name}/")
2179
+ # Clean up empty archive dir
2180
+ try:
2181
+ if not list(ad.iterdir()):
2182
+ ad.rmdir()
2183
+ except OSError:
2184
+ pass
2185
+ return True
2186
+ print(f" Skill '{name}' not found in any archive directory.")
2187
+ return False
2188
+ else:
2189
+ print(f" Unknown action: {action}")
2190
+ return False
2191
+
2192
+
2193
+ def _manage_mcp(action, name):
2194
+ """Disable or enable an MCP server by moving between mcpServers and _disabledMcpServers."""
2195
+ # Defense-in-depth: never mutate ~/.claude/settings.json under
2196
+ # a foreign runtime (OpenCode, Copilot), even when reached outside the CLI
2197
+ # dispatch guard (e.g. the dashboard /api/mcp/{enable,disable} HTTP path),
2198
+ # mirroring _manage_skill_locked.
2199
+ _measure_facade = _compat.facade()
2200
+ if _measure_facade._is_foreign_runtime():
2201
+ print(f" [!] Refusing to modify ~/.claude settings under the {_measure_facade.runtime_name_for_humans()} runtime.")
2202
+ return False
2203
+
2204
+ # Writes `settings` back.
2205
+ settings, _ok = _measure_facade._read_settings_for_write()
2206
+ if not _ok or not settings:
2207
+ print(" settings.json not found, empty, or unreadable")
2208
+ return False
2209
+
2210
+ active = settings.get("mcpServers", {})
2211
+ disabled = settings.get("_disabledMcpServers", {})
2212
+
2213
+ if action == "disable":
2214
+ if name not in active:
2215
+ print(f" MCP server '{name}' not found in active servers.")
2216
+ return False
2217
+ config = active.pop(name)
2218
+ disabled[name] = config
2219
+ settings["_disabledMcpServers"] = disabled
2220
+ settings["mcpServers"] = active
2221
+ if _measure_facade._write_settings_atomic(settings):
2222
+ print(f" Disabled MCP server: {name}")
2223
+ return True
2224
+ print(f" Could not disable MCP server '{name}'; settings.json was not changed.", file=_measure_facade.sys.stderr)
2225
+ return False
2226
+
2227
+ elif action == "enable":
2228
+ if name not in disabled:
2229
+ print(f" MCP server '{name}' not found in disabled servers.")
2230
+ return False
2231
+ config = disabled.pop(name)
2232
+ active[name] = config
2233
+ settings["mcpServers"] = active
2234
+ if disabled:
2235
+ settings["_disabledMcpServers"] = disabled
2236
+ else:
2237
+ settings.pop("_disabledMcpServers", None)
2238
+ # Deliberate top-level removal (the last disabled server was re-enabled),
2239
+ # declared so the choke-point guard permits exactly this key.
2240
+ if _measure_facade._write_settings_atomic(settings, allow_removing_keys={"_disabledMcpServers"}):
2241
+ print(f" Enabled MCP server: {name}")
2242
+ return True
2243
+ print(f" Could not enable MCP server '{name}'; settings.json was not changed.", file=_measure_facade.sys.stderr)
2244
+ return False
2245
+ else:
2246
+ print(f" Unknown action: {action}")
2247
+ return False
2248
+
2249
+
2250
+ def _codex_memory_review_data(mem):
2251
+ """Dashboard memory card data for the Codex machine-wide memory component.
2252
+
2253
+ Codex memory lives in state_*.sqlite rows, not a MEMORY.md file, so there is
2254
+ no line count, entry index, topic-file listing or link audit. Only report
2255
+ what was measured: thread count, tokens, largest thread, and scan status.
2256
+ """
2257
+ _measure_facade = _compat.facade()
2258
+ files = mem.get("files") or []
2259
+ return {
2260
+ "codex": True,
2261
+ "target": mem.get("path", ""),
2262
+ "thread_count": int(mem.get("thread_count", 0) or 0),
2263
+ "total_tokens": int(mem.get("tokens", 0) or 0),
2264
+ "largest_thread_tokens": max((int(f.get("memory_tokens", 0) or 0) for f in files), default=0),
2265
+ "scan_partial": bool(mem.get("truncated")),
2266
+ }
2267
+
2268
+
2269
+ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2270
+ """Generate a persistent Trends + Health dashboard (no audit data needed).
2271
+
2272
+ Outputs to DASHBOARD_PATH (~/.claude/_backups/token-optimizer/dashboard.html).
2273
+ Used by the SessionEnd hook for auto-refresh and for standalone viewing.
2274
+ """
2275
+ # Skip regeneration if dashboard was updated within the last 60 seconds
2276
+ # (prevents rapid /clear cycles from blocking on repeated full pipelines).
2277
+ # force=True bypasses the throttle -- used by ensure-health's
2278
+ # version-mismatch regen path so a freshly-updated plugin always
2279
+ # wins over a recently-written stale file.
2280
+ _measure_facade = _compat.facade()
2281
+ if quiet and not force and _measure_facade.DASHBOARD_PATH.exists():
2282
+ try:
2283
+ age = _measure_facade.time.time() - _measure_facade.DASHBOARD_PATH.stat().st_mtime
2284
+ if age < 60:
2285
+ return str(_measure_facade.DASHBOARD_PATH)
2286
+ except OSError:
2287
+ pass
2288
+ if _measure_facade._running_under_hook():
2289
+ _measure_facade._arm_dashboard_selfheal_on_timeout(days=days)
2290
+
2291
+ # Version-downgrade guard: never let an OLDER build overwrite a dashboard a
2292
+ # NEWER build already wrote (the "fixed but still broken" regression -- a
2293
+ # stale daemon or pre-upgrade session clobbering a just-shipped fix). Checked
2294
+ # BEFORE the expensive data build so an older writer skips cheaply. force does
2295
+ # NOT bypass this: force governs the 60s throttle, not version precedence.
2296
+ # Newer/equal writers proceed (equal is not strictly newer). Fail-open.
2297
+ if _measure_facade._dashboard_on_disk_is_newer(_measure_facade.DASHBOARD_PATH):
2298
+ if not quiet:
2299
+ print(f" [Token Optimizer] Skipping dashboard write: the on-disk dashboard "
2300
+ f"was written by a newer version than this build (v{_measure_facade.TOKEN_OPTIMIZER_VERSION}).")
2301
+ return str(_measure_facade.DASHBOARD_PATH)
2302
+
2303
+ script_dir = _measure_facade.Path(_measure_facade.__file__).resolve().parent
2304
+ template_path = script_dir.parent / "assets" / "dashboard.html"
2305
+ if not template_path.exists():
2306
+ if not quiet:
2307
+ print(f"Error: dashboard template not found at: {template_path}")
2308
+ return None
2309
+
2310
+ if not quiet:
2311
+ print(" Measuring current token overhead...")
2312
+ components = _measure_facade.measure_components()
2313
+ totals = _measure_facade.calculate_totals(components)
2314
+ baselines = _measure_facade.get_session_baselines(5)
2315
+
2316
+ calibration = _measure_facade.detect_calibration_gap(components, totals, baselines)
2317
+
2318
+ ctx_window, ctx_source = _measure_facade.detect_context_window()
2319
+ snapshot = {
2320
+ "components": components,
2321
+ "totals": totals,
2322
+ "session_baselines": baselines,
2323
+ "calibration": calibration,
2324
+ "context_window": ctx_window,
2325
+ "context_source": ctx_source,
2326
+ }
2327
+
2328
+ if not quiet:
2329
+ print(" Collecting usage trends...")
2330
+ try:
2331
+ trends = _measure_facade._collect_trends_data(days=days)
2332
+ except Exception:
2333
+ trends = None
2334
+
2335
+ if not quiet:
2336
+ print(" Checking session health...")
2337
+ try:
2338
+ health = _measure_facade._collect_health_data()
2339
+ except Exception:
2340
+ health = None
2341
+
2342
+ # Generate auto-recommendations from rules engine
2343
+ if not quiet:
2344
+ print(" Generating auto-recommendations...")
2345
+ auto_plan, rec_count = _measure_facade.generate_auto_recommendations(components, trends=trends, days=days)
2346
+ if not quiet and rec_count > 0:
2347
+ print(f" Found {rec_count} auto-recommendations")
2348
+
2349
+ # Generate coach data for the Coach tab (reuse already-collected components/trends)
2350
+ if not quiet:
2351
+ print(" Generating coach data...")
2352
+ try:
2353
+ coach = _measure_facade.generate_coach_data(components=components, trends=trends)
2354
+ except Exception:
2355
+ coach = None
2356
+
2357
+ # Collect context quality data (v2.0)
2358
+ if not quiet:
2359
+ print(" Analyzing context quality...")
2360
+ quality = _measure_facade._collect_quality_for_dashboard()
2361
+
2362
+ # Collect hook installation status for dashboard toggles
2363
+ hook_status = _measure_facade._collect_hook_status_for_dashboard()
2364
+
2365
+ # Collect management data for Manage tab
2366
+ if not quiet:
2367
+ print(" Collecting management data...")
2368
+ management = _measure_facade._collect_management_data(components=components, trends=trends)
2369
+
2370
+ # Collect per-turn data for the default visible 7-day table in local-file mode.
2371
+ # Served mode can fetch older rows on demand, but the static dashboard needs a
2372
+ # bounded preload so it stays responsive and doesn't balloon in size.
2373
+ if not quiet:
2374
+ print(" Collecting per-turn data for recent sessions...")
2375
+ session_turns = {}
2376
+ # Bound the preload: the visible table only shows the most recent sessions, but a
2377
+ # busy 7-day window can hold hundreds, and each parse_session_turns re-reads a full
2378
+ # transcript. Cap total preloaded sessions so a fresh (cold-cache) dashboard gen in
2379
+ # the deferred flush worker never turns this into a multi-second parse storm. Older
2380
+ # rows are fetched on demand in served mode.
2381
+ _turn_preload_budget = _measure_facade._int_env("TOKEN_OPTIMIZER_TURN_PRELOAD_MAX", 40)
2382
+ # Also bound per-file size: parse_session_turns reads a whole transcript, and a
2383
+ # single long session JSONL can reach 100MB+. Preloading 40 of those under the
2384
+ # 45s regen-step / 20s flush budget trips REGEN_STEP_TIMEOUT and can kill a
2385
+ # flush worker mid-dashboard-write. Skip oversized transcripts here; served mode
2386
+ # still fetches their rows on demand, exactly like older rows past the count cap.
2387
+ _turn_preload_maxbytes = _measure_facade._int_env("TOKEN_OPTIMIZER_TURN_PRELOAD_MAX_BYTES", 8_000_000)
2388
+ try:
2389
+ for day in (trends or {}).get("daily", [])[:7]:
2390
+ if len(session_turns) >= _turn_preload_budget:
2391
+ break
2392
+ for session in day.get("session_details", []):
2393
+ if len(session_turns) >= _turn_preload_budget:
2394
+ break
2395
+ session_key = session.get("session_key")
2396
+ jsonl_path = session.get("jsonl_path")
2397
+ if not session_key or session_key in session_turns or not jsonl_path:
2398
+ continue
2399
+ jsonl_resolved = str(_measure_facade.Path(jsonl_path).expanduser()) if jsonl_path.startswith("~") else jsonl_path
2400
+ if not _measure_facade.os.path.exists(jsonl_resolved):
2401
+ continue
2402
+ try:
2403
+ if _measure_facade.os.path.getsize(jsonl_resolved) > _turn_preload_maxbytes:
2404
+ continue
2405
+ except OSError:
2406
+ continue
2407
+ turns = _measure_facade.parse_session_turns(jsonl_resolved)
2408
+ if turns:
2409
+ session_turns[session_key] = turns
2410
+ except Exception:
2411
+ pass
2412
+
2413
+ pricing_tier = _measure_facade._load_pricing_tier()
2414
+ ttl_period_summary = []
2415
+ for period in (7, 30):
2416
+ try:
2417
+ ttl_period_summary.append(_measure_facade._build_ttl_period_summary(period))
2418
+ except Exception:
2419
+ ttl_period_summary.append({
2420
+ "label": f"{period}d: unavailable",
2421
+ "period_days": period,
2422
+ "mixed_sessions": 0,
2423
+ "five_only_sessions": 0,
2424
+ "one_hour_only_sessions": 0,
2425
+ })
2426
+ # Lightweight memory health for dashboard cards (reuses already-computed components,
2427
+ # no second measure_components() call, no full detector suite)
2428
+ mr_data = None
2429
+ try:
2430
+ mem = components.get("memory_md", {})
2431
+ if _measure_facade.detect_runtime() == "codex" and mem.get("exists"):
2432
+ mr_data = _measure_facade._codex_memory_review_data(mem)
2433
+ elif mem.get("exists") and mem.get("path"):
2434
+ mem_path = _measure_facade.Path(mem["path"])
2435
+ memory_dir = mem_path.parent
2436
+ parsed = _measure_facade._mr_parse_memory_index(str(mem_path))
2437
+ files_on_disk = _measure_facade._mr_scan_topic_files(str(memory_dir))
2438
+ linked_basenames = {_measure_facade.Path(link["target"]).name for link in parsed["links_all"]}
2439
+ files_set = set(files_on_disk)
2440
+ orphan_count = len(files_set - linked_basenames)
2441
+ broken_count = len([link for link in parsed["links_all"] if _measure_facade.Path(link["target"]).name not in files_set])
2442
+ total_lines = parsed["total_lines"]
2443
+ sev_medium = (1 if total_lines > _measure_facade._MR_MEMORY_LINE_LIMIT else 0) + (1 if broken_count > 0 else 0)
2444
+ mr_data = {
2445
+ "target": str(mem_path),
2446
+ "total_lines": total_lines,
2447
+ "entry_count": len(parsed["entries"]),
2448
+ "topic_files_count": len(files_on_disk),
2449
+ "linked_files_count": len(linked_basenames & files_set),
2450
+ "findings": [], # lightweight mode skips full findings
2451
+ "severity_counts": {"high": 0, "medium": sev_medium, "low": orphan_count},
2452
+ "savings": {"total_tokens": max(0, total_lines - _measure_facade._MR_MEMORY_LINE_LIMIT) * 15, "by_category": {}},
2453
+ "truncated": total_lines > _measure_facade._MR_MEMORY_LINE_LIMIT,
2454
+ "truncated_lines": max(0, total_lines - _measure_facade._MR_MEMORY_LINE_LIMIT),
2455
+ }
2456
+ except Exception:
2457
+ pass
2458
+
2459
+ # CLAUDE.md health summary for dashboard card (from already-computed components)
2460
+ claude_md_health = None
2461
+ try:
2462
+ if _measure_facade.detect_runtime() not in ("claude", "codex"):
2463
+ # Only Claude Code and Codex have an instruction-file chain this
2464
+ # card describes; other runtimes would show a "CLAUDE.md" card.
2465
+ raise LookupError
2466
+ instruction_tokens = 0
2467
+ context_window = components.get("context_window") or _measure_facade.detect_context_window()[0]
2468
+ for key in components:
2469
+ if (
2470
+ (_measure_facade.detect_runtime() == "codex" and key.startswith("agents_md"))
2471
+ or (_measure_facade.detect_runtime() != "codex" and key.startswith("claude_md"))
2472
+ ) and components[key].get("exists"):
2473
+ instruction_tokens += components[key].get("tokens", 0)
2474
+ instruction_pct = instruction_tokens / context_window * 100 if context_window else 0
2475
+ instruction_status = "good"
2476
+ if coach:
2477
+ for p in coach.get("patterns_bad", []):
2478
+ if "CLAUDE.md" in p.get("name", "") or "AGENTS.md" in p.get("name", ""):
2479
+ instruction_status = "warning" if p.get("severity") == "medium" else "notice"
2480
+ break
2481
+ claude_md_health = {
2482
+ "tokens": instruction_tokens,
2483
+ "pct": round(instruction_pct, 1),
2484
+ "status": instruction_status,
2485
+ }
2486
+ except Exception:
2487
+ pass
2488
+
2489
+ # Merged savings (measured + realized + opportunity + estimated, tier-labelled).
2490
+ # Wrapped so a slow/failed eval never breaks the SessionEnd dashboard regen.
2491
+ savings_data = _measure_facade._dashboard_savings_data(days=30, include_billing_mode=True)
2492
+ if savings_data != {"total_tokens": 0, "total_cost_usd": 0.0, "by_category": {}}:
2493
+ try:
2494
+ savings_data["billing_mode"] = _measure_facade.keepwarm_billing_mode()
2495
+ except Exception:
2496
+ pass
2497
+
2498
+ # Cache-TTL watchdog (opportunity tier — observed waste, potential recovery).
2499
+ # Standalone analysis; never reaches the realized savings headline. Fail-open.
2500
+ # Mirrors generate_dashboard's cache_health wiring so the standalone/daemon
2501
+ # dashboard renders the same cache-health panel as the full audit dashboard.
2502
+ try:
2503
+ cache_health = _measure_facade._cache_ttl_waste_cached(days=30)
2504
+ except Exception:
2505
+ cache_health = {"available": False, "tier": "opportunity"}
2506
+
2507
+ # U7: keep-warm cache-automation sub-block carried inside the cache-health
2508
+ # payload (realized vs spend vs NET, tripwire ratio, the 5 tile states,
2509
+ # predictor transparency). Fail-open so it never blocks dashboard regen.
2510
+ try:
2511
+ if isinstance(cache_health, dict):
2512
+ cache_health["keepwarm"] = _measure_facade.keepwarm_cache_health_block(days=30)
2513
+ except Exception:
2514
+ pass
2515
+
2516
+ # Subscription runway. This generator produces the dashboard the CLI writes,
2517
+ # so the key must be assembled here too: the template gates the card on
2518
+ # `data.runway` and silently renders nothing when it is absent, which is
2519
+ # indistinguishable from the card being switched off. None on API-billed
2520
+ # setups or when the meter has never been read (a stale-but-present reading is
2521
+ # kept and dated on the card), and the template omits the card.
2522
+ try:
2523
+ runway = _measure_facade.runway_snapshot(days=30)
2524
+ except Exception:
2525
+ runway = None
2526
+
2527
+ data = {
2528
+ "runway": runway,
2529
+ "snapshot": snapshot,
2530
+ "audit": {},
2531
+ "plan": auto_plan if auto_plan else None,
2532
+ "trends": trends,
2533
+ "health": health,
2534
+ "coach": coach,
2535
+ "quality": quality,
2536
+ "manage": management,
2537
+ "hooks": hook_status,
2538
+ "savings": savings_data,
2539
+ "cache_health": cache_health,
2540
+ "standalone": True,
2541
+ "auto_plan": True,
2542
+ "generated_at": _measure_facade.datetime.now().isoformat(),
2543
+ "pricing_tier": pricing_tier,
2544
+ "pricing_tier_label": _measure_facade._pricing_tier_label(pricing_tier),
2545
+ "pricing_tiers": {} if _measure_facade.detect_runtime() == "codex" else {k: v["label"] for k, v in _measure_facade.PRICING_TIERS.items()},
2546
+ "ttl_period_summary": ttl_period_summary,
2547
+ "session_turns": session_turns,
2548
+ "memory_review": mr_data,
2549
+ "claude_md_health": claude_md_health,
2550
+ "v5_recommendation": _measure_facade._get_v5_savings_recommendation(),
2551
+ "version": _measure_facade.TOKEN_OPTIMIZER_VERSION,
2552
+ "runtime": _measure_facade.detect_runtime(),
2553
+ "runtime_label": _measure_facade.runtime_name_for_humans(),
2554
+ }
2555
+ data = _measure_facade._sanitize_dashboard_paths(data)
2556
+
2557
+ template = template_path.read_text(encoding="utf-8")
2558
+ data_json = _measure_facade.json.dumps(data, ensure_ascii=True, default=str)
2559
+ data_json = data_json.replace("</", "<\\/") # Prevent </script> injection
2560
+ placeholder = "window.__TOKEN_DATA__ = null;"
2561
+ injected = template.replace(placeholder, f"window.__TOKEN_DATA__ = {data_json};", 1)
2562
+ if injected == template:
2563
+ if not quiet:
2564
+ print(" [Warning] Data injection failed: placeholder not found in template.")
2565
+ return None
2566
+
2567
+ # v5.4.10: dual-path write (same pattern as daemon script in v5.4.7).
2568
+ # DASHBOARD_PATH depends on SNAPSHOT_DIR which resolves differently in
2569
+ # plugin-hook context (runtime plugin data set) vs standalone CLI.
2570
+ # The daemon script's DASHBOARD constant points to whichever path was
2571
+ # active when setup-daemon ran. Write to BOTH so the daemon always
2572
+ # serves current content regardless of which path it expects.
2573
+ legacy_dashboard = _measure_facade.RUNTIME_DIR / "_backups" / "token-optimizer" / "dashboard.html"
2574
+ write_paths = {_measure_facade.DASHBOARD_PATH, legacy_dashboard}
2575
+ wrote_any = False
2576
+ for wp in write_paths:
2577
+ try:
2578
+ wp.parent.mkdir(parents=True, exist_ok=True)
2579
+ # Atomic write: three uncoordinated callers can target this same path
2580
+ # (background freshness regen, manual POST /api/regenerate, and the
2581
+ # SessionEnd flush worker's inline gen). A plain O_TRUNC write lets two
2582
+ # of them interleave into a torn/mixed file, and a GET between the
2583
+ # truncate and the final byte serves partial HTML. Write to a temp
2584
+ # sibling then os.replace so every reader sees one complete generation.
2585
+ tmp_fd, tmp_name = _measure_facade.tempfile.mkstemp(dir=str(wp.parent), prefix=".dash-", suffix=".tmp")
2586
+ try:
2587
+ if hasattr(_measure_facade.os, "fchmod"): # POSIX only (os.fchmod is absent on Windows)
2588
+ _measure_facade.os.fchmod(tmp_fd, 0o600)
2589
+ with _measure_facade.os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
2590
+ f.write(injected)
2591
+ _measure_facade.os.replace(tmp_name, str(wp))
2592
+ except BaseException:
2593
+ # BaseException, not OSError: the SessionEnd flush worker runs this
2594
+ # under a 20s hook budget that raises _HookTimeout (a BaseException).
2595
+ # A bare `except OSError` would let a mid-write timeout skip the
2596
+ # unlink and leak a ~5MB .dash-*.tmp. Clean up on any interruption,
2597
+ # then re-raise so the timeout still propagates to the worker.
2598
+ try:
2599
+ _measure_facade.os.unlink(tmp_name)
2600
+ except OSError:
2601
+ pass
2602
+ raise
2603
+ wrote_any = True
2604
+ except OSError:
2605
+ continue
2606
+ if not wrote_any:
2607
+ if not quiet:
2608
+ print(" [Error] Failed to write dashboard to any path")
2609
+ return None
2610
+
2611
+ # Sidecar meta (version + shape) next to each written HTML, so ensure-health's
2612
+ # staleness check reads a few bytes instead of the whole 4-5MB file. Written
2613
+ # AFTER the HTML os.replace above and itself atomic: a torn or
2614
+ # (html_new, meta_old) sidecar can let an OLDER concurrent build's downgrade
2615
+ # guard clobber a NEWER dashboard, so both writes must be all-or-nothing.
2616
+ for wp in write_paths:
2617
+ try:
2618
+ if wp.exists():
2619
+ _measure_facade._write_dashboard_meta_atomic(_measure_facade._dashboard_meta_path(wp))
2620
+ except OSError:
2621
+ pass
2622
+
2623
+ if not quiet:
2624
+ print(f" Dashboard: {_measure_facade.DASHBOARD_PATH}")
2625
+ print(f" Local: {_measure_facade.DASHBOARD_PATH.as_uri()}")
2626
+ print(f" Remote: {_measure_facade.hint_python()} {_measure_facade._display_path(_measure_facade.Path(_measure_facade.__file__).resolve())} dashboard --serve")
2627
+
2628
+ return str(_measure_facade.DASHBOARD_PATH)
2629
+
2630
+
2631
+ def _dispatch_dashboard(args):
2632
+ """CLI ``dashboard`` entry. Bounded ONLY on the hook path.
2633
+
2634
+ Interactive ``--serve`` is unbounded on purpose: a user watching the
2635
+ dashboard must not have the process killed after 20s. A plain interactive
2636
+ ``dashboard`` run (no ``--serve``) from a terminal is also left unbounded
2637
+ The 20s budget exists to cap the escaped fossil on the hook
2638
+ pipe, not to kill a user-driven generation. ``--serve`` and "stdin is a
2639
+ tty" both mark an interactive context; the budget arms only when
2640
+ ``_running_under_hook()`` is true and ``--serve`` is absent.
2641
+ """
2642
+ _measure_facade = _compat.facade()
2643
+ cp = None
2644
+ serve = False
2645
+ serve_port = 8080
2646
+ serve_host = "127.0.0.1"
2647
+ for i, a in enumerate(args):
2648
+ if a == "--coord-path" and i + 1 < len(args):
2649
+ cp = args[i + 1]
2650
+ elif a == "--serve":
2651
+ serve = True
2652
+ elif a == "--host" and i + 1 < len(args):
2653
+ serve_host = args[i + 1]
2654
+ serve = True
2655
+ elif a == "--port" and i + 1 < len(args):
2656
+ try:
2657
+ serve_port = int(args[i + 1])
2658
+ except ValueError:
2659
+ print(f"[Error] Invalid --port value: {args[i + 1]}")
2660
+ _measure_facade.sys.exit(1)
2661
+ serve = True
2662
+ if not cp:
2663
+ days = 30
2664
+ quiet = "--quiet" in args or "-q" in args
2665
+ # --force bypasses the 60s write throttle. The detached version-bump
2666
+ # self-heal passes it so a stale file just written by a killed regen
2667
+ # cannot throttle-skip the heal (the PR #154 version guard still applies).
2668
+ force = "--force" in args
2669
+ for i, a in enumerate(args):
2670
+ if a == "--days" and i + 1 < len(args):
2671
+ try:
2672
+ days = int(args[i + 1])
2673
+ except ValueError:
2674
+ pass
2675
+ deadline = (
2676
+ None if (serve or not _measure_facade._running_under_hook()) else _measure_facade._install_hook_budget(_measure_facade._dashboard_hook_budget_seconds())
2677
+ )
2678
+ timed_out = False
2679
+ try:
2680
+ lock = (_measure_facade._dashboard_selfheal_build_lock()
2681
+ if _measure_facade.os.environ.get("TOKEN_OPTIMIZER_DASHBOARD_SELFHEAL") == "1"
2682
+ else _measure_facade.nullcontext(True))
2683
+ with lock as acquired:
2684
+ if not acquired:
2685
+ _measure_facade.sys.exit(0)
2686
+ out = _measure_facade.generate_standalone_dashboard(days=days, quiet=quiet, force=force)
2687
+ except _measure_facade._HookTimeout:
2688
+ out = None
2689
+ timed_out = True
2690
+ finally:
2691
+ _measure_facade._clear_hook_budget(deadline)
2692
+ # Bug B self-heal: a bounded hook regen that the 20s budget killed leaves
2693
+ # the on-disk dashboard stale. Finish it in a detached, unbounded child so
2694
+ # the file catches up without ever blocking the session. forward
2695
+ # `force` -- a killed --force regen just wrote a stale file seconds ago, so
2696
+ # the detached retry must ALSO bypass the 60s write throttle or it
2697
+ # throttle-skips and the file stays stale (the PR #154 version guard still
2698
+ # applies, so a forced heal never clobbers a newer dashboard).
2699
+ if timed_out:
2700
+ _measure_facade._spawn_detached_dashboard_selfheal(days=days, force=force)
2701
+ if out and serve:
2702
+ _measure_facade._serve_dashboard(out, port=serve_port, host=serve_host)
2703
+ elif out and not quiet:
2704
+ _measure_facade._open_dashboard(fallback_filepath=out)
2705
+ _measure_facade.sys.exit(0 if out else 1)
2706
+ deadline = (
2707
+ None if (serve or not _measure_facade._running_under_hook()) else _measure_facade._install_hook_budget(_measure_facade._dashboard_hook_budget_seconds())
2708
+ )
2709
+ timed_out = False
2710
+ try:
2711
+ out = _measure_facade.generate_dashboard(cp)
2712
+ except _measure_facade._HookTimeout:
2713
+ out = None
2714
+ timed_out = True
2715
+ finally:
2716
+ _measure_facade._clear_hook_budget(deadline)
2717
+ # Bug B self-heal (coord-path regen): same as the standalone branch above.
2718
+ if timed_out:
2719
+ _measure_facade._spawn_detached_dashboard_selfheal()
2720
+ if serve and out:
2721
+ _measure_facade._serve_dashboard(out, port=serve_port, host=serve_host)
2722
+
2723
+
2724
+ def _collect_trends_from_db(days=None):
2725
+ """Query SQLite trends DB for aggregated usage data.
2726
+
2727
+ Returns same dict shape as _collect_trends_from_jsonl, or None if DB
2728
+ doesn't exist or has no data for the requested period.
2729
+ """
2730
+ _measure_facade = _compat.facade()
2731
+ if not _measure_facade.TRENDS_DB.exists():
2732
+ return None
2733
+
2734
+ try:
2735
+ conn = _measure_facade._init_trends_db()
2736
+ conn.row_factory = _measure_facade.sqlite3.Row
2737
+ # Verify it's a valid DB before proceeding
2738
+ conn.execute("SELECT 1 FROM session_log LIMIT 1")
2739
+ except (_measure_facade.sqlite3.Error, _measure_facade.sqlite3.DatabaseError):
2740
+ try:
2741
+ conn.close()
2742
+ except Exception:
2743
+ pass
2744
+ return None
2745
+
2746
+ try:
2747
+ _measure_facade._read_path_upkeep(conn, days)
2748
+ return _measure_facade._query_trends_db(conn, days)
2749
+ except (_measure_facade.sqlite3.Error, _measure_facade.sqlite3.DatabaseError):
2750
+ return None
2751
+ finally:
2752
+ conn.close()
2753
+
2754
+
2755
+ def _activity_window_predicate(conn, cutoff):
2756
+ """SQL fragment + params limiting session_log scans to rows that can hold
2757
+ activity inside the window, or ("", ()) when the activity bounds columns
2758
+ are unavailable (pre-migration shapes), keeping the unfiltered scan.
2759
+
2760
+ last_activity_day is maintained by every daily_usage_json writer (collect,
2761
+ _backfill_daily_usage, _store_adapter_activity, repair_activity_dates and
2762
+ _collect_trends_from_jsonl). Bounds cover the union of combined usage,
2763
+ parent usage and metadata days. NULL bounds keep rows with no dated evidence.
2764
+ The fragment is a superset of "has an in-window slice", never a subset:
2765
+ metrics-only days can only widen last_activity_day, so filtering on it can
2766
+ keep extra rows but can never drop a row that contributes window slices."""
2767
+ _measure_facade = _compat.facade()
2768
+ columns = {r[1] for r in conn.execute("PRAGMA table_info(session_log)")}
2769
+ if "last_activity_day" not in columns:
2770
+ return "", ()
2771
+ return " AND (last_activity_day IS NULL OR last_activity_day >= ?)", (cutoff,)
2772
+
2773
+
2774
+ def _query_trends_db(conn, days):
2775
+ """Internal: run all queries against the trends DB. Caller handles errors."""
2776
+ _measure_facade = _compat.facade()
2777
+ cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
2778
+
2779
+ _measure_facade.ensure_activity_view(conn)
2780
+ window_pred, window_params = _measure_facade._activity_window_predicate(conn, cutoff)
2781
+ population_metrics = _measure_facade._query_dashboard_population_metrics(conn, days)
2782
+ spent_basis = _measure_facade._dashboard_spent_token_basis(conn, days=days)
2783
+ coverage = _measure_facade.activity_coverage(conn)
2784
+
2785
+ # Basic stats
2786
+ # v5.4.9: "Total tokens" matches Claude Code Desktop methodology exactly:
2787
+ # fresh_input + output. Both cache_read and cache_create are excluded from
2788
+ # the headline since Desktop's "X in · Y out" per-model view uses only
2789
+ # those two fields. session_log.input_tokens stores total_full_input
2790
+ # (fresh + cache_read + cache_create). We derive fresh by subtracting both
2791
+ # cache categories using stored fields:
2792
+ # fresh = input_tokens * (1 - cache_hit_rate) - cache_create_*
2793
+ # where input_tokens * (1 - cache_hit_rate) = fresh + cache_create
2794
+ # cache_create_1h/5m are stored separately in session_log since v5.3.5.
2795
+ # v5.4.9: per-session clamping for fresh_input. Aggregate-level subtraction
2796
+ # lets sessions where cache_create_stored > (input_tokens * (1 - chr)) eat
2797
+ # positive contributions from other sessions due to rounding drift between
2798
+ # cache_hit_rate (float) and cache_create_* (int). Clamp at per-row level.
2799
+ row = conn.execute(
2800
+ """SELECT COUNT(DISTINCT id) as cnt,
2801
+ COALESCE(SUM(duration_minutes), 0) as total_dur,
2802
+ COALESCE(SUM(input_tokens), 0) as total_in,
2803
+ COALESCE(SUM(output_tokens), 0) as total_out,
2804
+ COALESCE(SUM(message_count), 0) as total_msgs,
2805
+ COALESCE(SUM(
2806
+ COALESCE(cache_create_1h_tokens, 0)
2807
+ + COALESCE(cache_create_5m_tokens, 0)
2808
+ ), 0) as total_cache_create
2809
+ FROM session_activity WHERE date >= ?""", (cutoff,)
2810
+ ).fetchone()
2811
+
2812
+ # Per-session fresh_input with non-negative clamp (see comment above).
2813
+ fresh_rows = conn.execute(
2814
+ """SELECT input_tokens * (1.0 - COALESCE(cache_hit_rate, 0)) as bp_c,
2815
+ COALESCE(cache_create_1h_tokens, 0) + COALESCE(cache_create_5m_tokens, 0) as cc
2816
+ FROM session_activity WHERE date >= ?""", (cutoff,)
2817
+ ).fetchall()
2818
+ _total_fresh_clamped = sum(max(0, (r["bp_c"] or 0) - (r["cc"] or 0)) for r in fresh_rows)
2819
+
2820
+ session_count = row["cnt"]
2821
+ if session_count == 0 and coverage["complete"]:
2822
+ return None
2823
+
2824
+ total_duration = row["total_dur"]
2825
+ total_input = row["total_in"]
2826
+ total_output = row["total_out"]
2827
+ total_messages = row["total_msgs"]
2828
+ total_fresh_input = int(_total_fresh_clamped)
2829
+ total_cache_create = int(row["total_cache_create"])
2830
+ total_cache_read = max(0, int(total_input) - total_fresh_input - total_cache_create)
2831
+ # Billable tokens are retained as a separate diagnostic, not used for the
2832
+ # official-compatible spent-token headline. Cache writes are real billing
2833
+ # cost, but including them in the headline makes the spent basis diverge
2834
+ # from the provider's fresh-input plus streamed-output stats.
2835
+ total_billable_tokens = total_fresh_input + total_cache_create + total_output
2836
+
2837
+ # Skill usage
2838
+ skill_rows = conn.execute(
2839
+ """SELECT skill, SUM(session_count) as sess, SUM(invocations) as inv
2840
+ FROM skill_daily WHERE date >= ? GROUP BY skill ORDER BY sess DESC""",
2841
+ (cutoff,),
2842
+ ).fetchall()
2843
+ skill_sessions = {r["skill"]: r["sess"] for r in skill_rows}
2844
+
2845
+ # Model mix
2846
+ model_rows = conn.execute(
2847
+ """SELECT model, SUM(total_tokens) as tot
2848
+ FROM model_daily WHERE date >= ? GROUP BY model ORDER BY tot DESC""",
2849
+ (cutoff,),
2850
+ ).fetchall()
2851
+ billable_model_mix = {r["model"]: r["tot"] for r in model_rows}
2852
+ reported_model_mix = {}
2853
+ reported_combined_rows = 0
2854
+ for parent_raw, combined_raw in conn.execute(
2855
+ "SELECT parent_daily_usage_json,daily_usage_json FROM session_log "
2856
+ "WHERE COALESCE(is_sidechain,0)=0" + window_pred, window_params):
2857
+ raw, provenance = _measure_facade._spent_daily_usage(parent_raw, combined_raw)
2858
+ usage = _measure_facade._safe_json_dict(raw)
2859
+ in_window = False
2860
+ for day in _measure_facade._activity_days(usage):
2861
+ if day < cutoff:
2862
+ continue
2863
+ in_window = True
2864
+ for model, bucket in usage[day].items():
2865
+ normalized = _measure_facade._normalize_model_name(model)
2866
+ if normalized and isinstance(bucket, dict):
2867
+ reported_model_mix[normalized] = reported_model_mix.get(normalized, 0) + _measure_facade._bucket_int(bucket.get("fresh_input")) + _measure_facade._bucket_int(bucket.get("output"))
2868
+ if provenance == "combined" and in_window:
2869
+ reported_combined_rows += 1
2870
+ model_mix = reported_model_mix or billable_model_mix
2871
+
2872
+ # Subagents
2873
+ sub_rows = conn.execute(
2874
+ """SELECT agent_type, SUM(spawn_count) as tot
2875
+ FROM subagent_daily WHERE date >= ? GROUP BY agent_type ORDER BY tot DESC""",
2876
+ (cutoff,),
2877
+ ).fetchall()
2878
+ subagents = {r["agent_type"]: r["tot"] for r in sub_rows}
2879
+
2880
+ # Tool calls (aggregate from session_log JSON)
2881
+ total_tools = {}
2882
+ tool_rows = conn.execute(
2883
+ "SELECT tool_calls_json FROM session_activity WHERE date >= ? AND tool_calls_json IS NOT NULL",
2884
+ (cutoff,),
2885
+ ).fetchall()
2886
+ for tr in tool_rows:
2887
+ try:
2888
+ calls = _measure_facade.json.loads(tr["tool_calls_json"])
2889
+ for tool, count in calls.items():
2890
+ total_tools[tool] = total_tools.get(tool, 0) + count
2891
+ except (_measure_facade.json.JSONDecodeError, TypeError):
2892
+ pass
2893
+ total_tools = dict(sorted(total_tools.items(), key=lambda x: ((_measure_facade := _compat.facade()), -x[1])[1]))
2894
+
2895
+ # Installed skills vs used (normalize names: usage logs use SKILL.md name, install list uses dir name)
2896
+ components = _measure_facade.measure_components()
2897
+ installed_skills = set(components.get("skills", {}).get("names", []))
2898
+ name_to_dir = components.get("skills", {}).get("name_to_dir", {})
2899
+ used_skills_raw = set(skill_sessions.keys())
2900
+ # Map used skill names to directory names where possible.
2901
+ # Handles: exact match, SKILL.md name mapping, and namespaced sub-skills
2902
+ # (e.g., "compound-engineering:ce-brainstorm" counts "compound-engineering" as used).
2903
+ used_skills = set()
2904
+ for s in used_skills_raw:
2905
+ if s in installed_skills:
2906
+ used_skills.add(s)
2907
+ elif s in name_to_dir:
2908
+ used_skills.add(name_to_dir[s])
2909
+ elif ":" in s:
2910
+ parent = s.split(":")[0]
2911
+ if parent in installed_skills:
2912
+ used_skills.add(parent)
2913
+ elif parent in name_to_dir:
2914
+ used_skills.add(name_to_dir[parent])
2915
+ else:
2916
+ used_skills.add(s)
2917
+ else:
2918
+ used_skills.add(s)
2919
+ never_used = installed_skills - used_skills
2920
+ never_used_overhead = len(never_used) * _measure_facade.TOKENS_PER_SKILL_APPROX
2921
+
2922
+ # Trajectory
2923
+ snapshots = _measure_facade._load_overhead_snapshots()
2924
+ current_total = _measure_facade.calculate_totals(components).get("estimated_total", 0)
2925
+
2926
+ # Daily breakdown from session_log
2927
+ pricing_tier = _measure_facade._load_pricing_tier()
2928
+ daily = {}
2929
+ total_cost_usd = 0.0
2930
+ total_cost_priced_tokens = 0
2931
+ total_cost_unpriced_tokens = 0
2932
+ total_unpriced_sessions = 0
2933
+ session_rows = conn.execute(
2934
+ """SELECT date, jsonl_path, duration_minutes, input_tokens, output_tokens,
2935
+ message_count, api_calls, cache_hit_rate,
2936
+ cache_create_1h_tokens, cache_create_5m_tokens,
2937
+ avg_call_gap_seconds, max_call_gap_seconds, p95_call_gap_seconds, skills_json,
2938
+ subagents_json, model_usage_json, slug, topic, project,
2939
+ model_usage_breakdown_json, daily_usage_json, parent_daily_usage_json,
2940
+ quality_score, quality_grade
2941
+ FROM session_log WHERE 1=1""" + window_pred + """ ORDER BY date DESC""",
2942
+ window_params,
2943
+ ).fetchall()
2944
+
2945
+ def _day_entry(date):
2946
+ _measure_facade = _compat.facade()
2947
+ if date not in daily:
2948
+ daily[date] = {
2949
+ "date": date,
2950
+ "sessions": 0,
2951
+ "total_input": 0,
2952
+ "total_output": 0,
2953
+ "skills_used": {},
2954
+ "session_details": [],
2955
+ }
2956
+ return daily[date]
2957
+
2958
+ for sr in session_rows:
2959
+ try:
2960
+ skills = _measure_facade.json.loads(sr["skills_json"]) if sr["skills_json"] else {}
2961
+ except (_measure_facade.json.JSONDecodeError, TypeError):
2962
+ skills = {}
2963
+ try:
2964
+ subagents_meta = _measure_facade.json.loads(sr["subagents_json"]) if sr["subagents_json"] else {}
2965
+ except (_measure_facade.json.JSONDecodeError, TypeError):
2966
+ subagents_meta = {}
2967
+
2968
+ # One pricing path for every per-session dollar figure (the dashboard
2969
+ # here, `session-cost` for plain-language questions): _price_session_row.
2970
+ inp_total = sr["input_tokens"] or 0
2971
+ out_total = sr["output_tokens"] or 0
2972
+ chr_val = sr["cache_hit_rate"] or 0
2973
+ cache_create_1h = sr["cache_create_1h_tokens"] or 0
2974
+ cache_create_5m = sr["cache_create_5m_tokens"] or 0
2975
+ priced_row = _measure_facade._price_session_row(sr, pricing_tier)
2976
+ mu = priced_row["model_usage"]
2977
+ dom_model = priced_row["dom_model"]
2978
+ du = priced_row["daily_usage"]
2979
+ session_total_cost = priced_row["total_cost"]
2980
+ # A day before the window is dropped.
2981
+ slices = [sl for sl in priced_row["slices"] if sl[0] >= cutoff]
2982
+
2983
+ window_unpriced = 0
2984
+ jsonl_path = sr["jsonl_path"]
2985
+ # A session active on several days is listed on each; its latest day is
2986
+ # the primary entry. Per-session stats (skills, cache/TTL mix, coaching)
2987
+ # must read only primary entries or a multi-day session counts twice.
2988
+ primary_date = max((sl[0] for sl in slices), default=None)
2989
+ for date, day_cost, day_priced, day_unpriced, day_in, day_out in slices:
2990
+ d = _day_entry(date)
2991
+ d["sessions"] += 1
2992
+ d["total_input"] += day_in
2993
+ d["total_output"] += day_out
2994
+ if date == primary_date:
2995
+ for skill, cnt in skills.items():
2996
+ d["skills_used"][skill] = d["skills_used"].get(skill, 0) + cnt
2997
+ total_cost_usd += day_cost
2998
+ total_cost_priced_tokens += day_priced
2999
+ total_cost_unpriced_tokens += day_unpriced
3000
+ window_unpriced += day_unpriced
3001
+
3002
+ sd = {
3003
+ "metadata_basis": "lifetime session metadata; day_input/output and cost describe activity",
3004
+ "duration_minutes": round(sr["duration_minutes"] or 0, 1),
3005
+ "input_tokens": inp_total,
3006
+ "output_tokens": out_total,
3007
+ "message_count": sr["message_count"] or 0,
3008
+ "api_calls": sr["api_calls"] or 0,
3009
+ "skills": list(skills.keys()),
3010
+ "subagents": list(subagents_meta.keys()),
3011
+ "cache_hit_rate": round(chr_val, 3),
3012
+ "cache_create_1h_tokens": cache_create_1h,
3013
+ "cache_create_5m_tokens": cache_create_5m,
3014
+ "avg_call_gap_seconds": sr["avg_call_gap_seconds"],
3015
+ "max_call_gap_seconds": sr["max_call_gap_seconds"],
3016
+ "p95_call_gap_seconds": sr["p95_call_gap_seconds"],
3017
+ "slug": sr["slug"],
3018
+ "session_key": _measure_facade._make_session_key(jsonl_path),
3019
+ "jsonl_path": jsonl_path,
3020
+ "topic": sr["topic"],
3021
+ "project": _measure_facade._clean_project_name(sr["project"]),
3022
+ # cost_usd is THIS day's share; session_cost_usd is the whole session.
3023
+ "cost_usd": round(day_cost, 4),
3024
+ "session_cost_usd": round(session_total_cost, 4),
3025
+ # input/output_tokens above are whole-session totals (the row
3026
+ # describes the session); these are this day's share, the same
3027
+ # numbers the day's total_input/total_output add up.
3028
+ "day_input_tokens": day_in,
3029
+ "day_output_tokens": day_out,
3030
+ "spans_days": len(du) > 1,
3031
+ "continuation": date != primary_date,
3032
+ "cost_priced_tokens": day_priced,
3033
+ "cost_unpriced_tokens": day_unpriced,
3034
+ "model": _measure_facade._normalize_model_name(dom_model) or dom_model,
3035
+ "model_count": len(mu) if mu else 1,
3036
+ }
3037
+ # Prefer stored quality score (persisted during collect), fall back to recomputation
3038
+ if sr["quality_score"] is not None:
3039
+ sd["quality_score"] = sr["quality_score"]
3040
+ sd["quality_grade"] = sr["quality_grade"] or _measure_facade.score_to_grade(round(sr["quality_score"]))
3041
+ sd["quality_band"] = _measure_facade.score_to_band(sr["quality_score"])
3042
+ else:
3043
+ sq = _measure_facade.score_session_quality(sd)
3044
+ sd["quality_score"] = sq["score"]
3045
+ sd["quality_grade"] = sq["grade"]
3046
+ sd["quality_band"] = sq["band"]
3047
+ d["session_details"].append(sd)
3048
+ if window_unpriced > 0:
3049
+ total_unpriced_sessions += 1
3050
+
3051
+ daily_sorted = sorted(daily.values(), key=lambda x: ((_measure_facade := _compat.facade()), x["date"])[1], reverse=True)
3052
+ grade_rank = {grade: idx for idx, grade in enumerate(["F", "D", "C", "B", "A", "S"])}
3053
+ for d in daily_sorted:
3054
+ details = d.get("session_details", [])
3055
+ d["total_cost_usd"] = round(sum(float(sd.get("cost_usd") or 0.0) for sd in details), 4)
3056
+ d["cost_priced_tokens"] = sum(int(sd.get("cost_priced_tokens") or 0) for sd in details)
3057
+ d["cost_unpriced_tokens"] = sum(int(sd.get("cost_unpriced_tokens") or 0) for sd in details)
3058
+ scores = [float(sd["quality_score"]) for sd in details if sd.get("quality_score") is not None]
3059
+ if scores:
3060
+ d["avg_quality_score"] = round(sum(scores) / len(scores), 1)
3061
+ grades = [sd.get("quality_grade") for sd in details if sd.get("quality_grade")]
3062
+ if grades:
3063
+ d["worst_grade"] = min(grades, key=lambda grade: ((_measure_facade := _compat.facade()), grade_rank.get(grade, 999))[1])
3064
+
3065
+ # Rolling quality trend from session_log
3066
+ quality_trend_rows = conn.execute(
3067
+ """SELECT date,
3068
+ AVG(quality_score) as avg_q,
3069
+ MIN(quality_score) as min_q,
3070
+ MAX(quality_score) as max_q,
3071
+ COUNT(*) as n
3072
+ FROM session_log
3073
+ WHERE date >= ? AND quality_score IS NOT NULL
3074
+ GROUP BY date ORDER BY date""",
3075
+ (cutoff,),
3076
+ ).fetchall()
3077
+ quality_trend = [
3078
+ {
3079
+ "date": r["date"],
3080
+ "avg_quality": round(r["avg_q"], 1),
3081
+ "min_quality": round(r["min_q"], 1),
3082
+ "max_quality": round(r["max_q"], 1),
3083
+ "sessions": r["n"],
3084
+ }
3085
+ for r in quality_trend_rows
3086
+ ]
3087
+
3088
+ # conn.close() removed — caller (_collect_trends_from_db) owns the connection
3089
+ # and closes it in its finally block (double-close fix).
3090
+
3091
+ # Pricing tier info for dashboard
3092
+ pricing_tier = _measure_facade._load_pricing_tier()
3093
+ tier_label = _measure_facade._pricing_tier_label(pricing_tier)
3094
+
3095
+ return {
3096
+ "period_days": days,
3097
+ "session_count": session_count,
3098
+ "total_input_tokens": total_input, # raw (includes cache reads + cache creates)
3099
+ "total_output_tokens": total_output,
3100
+ "total_fresh_input": total_fresh_input, # v5.4.9: billable fresh input (Desktop-parity)
3101
+ "total_cache_read": total_cache_read,
3102
+ "total_cache_create": total_cache_create, # separate (bills at 1.25x fresh)
3103
+ "total_tokens": spent_basis["tokens"],
3104
+ "total_billable_tokens": total_billable_tokens,
3105
+ "spent_token_basis": spent_basis,
3106
+ "activity_coverage": coverage,
3107
+ "total_tokens_raw": total_input + total_output, # includes cache, for debugging
3108
+ "total_messages": total_messages, # Desktop-parity headline
3109
+ "avg_duration_minutes": round(total_duration / session_count, 1) if session_count else 0,
3110
+ "avg_input_tokens": round(total_input / session_count) if session_count else 0,
3111
+ "avg_output_tokens": round(total_output / session_count) if session_count else 0,
3112
+ "skills": {
3113
+ "used": dict(sorted(skill_sessions.items(), key=lambda x: ((_measure_facade := _compat.facade()), -x[1])[1])),
3114
+ "installed_count": len(installed_skills),
3115
+ "never_used": sorted(never_used),
3116
+ "never_used_overhead": never_used_overhead,
3117
+ },
3118
+ "subagents": subagents,
3119
+ "model_mix": model_mix,
3120
+ "billable_model_mix": billable_model_mix,
3121
+ "model_mix_combined_fallback_rows": reported_combined_rows,
3122
+ "tool_calls": total_tools,
3123
+ "trajectory": {
3124
+ "snapshots": snapshots,
3125
+ "current_total": current_total,
3126
+ },
3127
+ "daily": daily_sorted,
3128
+ "total_cost_usd": round(total_cost_usd, 4),
3129
+ "cost_priced_tokens": total_cost_priced_tokens,
3130
+ "cost_unpriced_tokens": total_cost_unpriced_tokens,
3131
+ "cost_unpriced_sessions": total_unpriced_sessions,
3132
+ "cost_coverage_pct": round(100 * total_cost_priced_tokens / max(total_cost_priced_tokens + total_cost_unpriced_tokens, 1), 1),
3133
+ "cost_note": "Costs exclude sessions whose logs do not expose a recognized model id." if total_cost_unpriced_tokens else None,
3134
+ "quality_trend": quality_trend,
3135
+ "pricing_tier": pricing_tier,
3136
+ "pricing_tier_label": tier_label,
3137
+ "source": "sqlite",
3138
+ "population_metrics": population_metrics,
3139
+ }
3140
+
3141
+
3142
+ def _query_dashboard_population_metrics(conn, days):
3143
+ """Return explicitly labelled dashboard populations from session_log."""
3144
+ _measure_facade = _compat.facade()
3145
+ _measure_facade.ensure_activity_view(conn)
3146
+ cutoff = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
3147
+ row = conn.execute(
3148
+ """SELECT COUNT(*) AS all_n,
3149
+ SUM(CASE WHEN COALESCE(is_sidechain,0)=0 THEN 1 ELSE 0 END) AS main_n,
3150
+ SUM(CASE WHEN COALESCE(is_sidechain,0)=1 THEN 1 ELSE 0 END) AS delegated_n,
3151
+ SUM(CASE WHEN COALESCE(is_sidechain,0)=0 AND COALESCE(message_count,0)>=20 THEN 1 ELSE 0 END) AS eligible_n,
3152
+ SUM(CASE WHEN COALESCE(is_sidechain,0)=1 OR COALESCE(message_count,0)<20 THEN 1 ELSE 0 END) AS ineligible_n,
3153
+ AVG(CASE WHEN COALESCE(is_sidechain,0)=0 AND COALESCE(message_count,0)>=20 THEN cache_hit_rate END) AS eligible_hit,
3154
+ AVG(CASE WHEN COALESCE(is_sidechain,0)=1 OR COALESCE(message_count,0)<20 THEN cache_hit_rate END) AS ineligible_hit
3155
+ FROM session_log WHERE rowid IN (SELECT id FROM session_activity WHERE date >= ?)""", (cutoff,)
3156
+ ).fetchone()
3157
+ return {
3158
+ "all_sessions": int(row["all_n"] or 0),
3159
+ "main_work_sessions": int(row["main_n"] or 0),
3160
+ "delegated_sessions": int(row["delegated_n"] or 0),
3161
+ "cache_eligible_main_sessions": int(row["eligible_n"] or 0),
3162
+ "cache_ineligible_sessions": int(row["ineligible_n"] or 0),
3163
+ "cache_eligible_main_hit_rate": round(float(row["eligible_hit"] or 0), 4),
3164
+ "cache_ineligible_hit_rate": round(float(row["ineligible_hit"] or 0), 4),
3165
+ }
3166
+
3167
+
3168
+ def _collect_trends_from_jsonl(days=None):
3169
+ """Use the same dated queries without a persistent DB (read-only fallback).
3170
+
3171
+ Discover all transcripts: mtime is only an ingestion hint. Deduplicate the
3172
+ complete history before slicing, including history replayed into a new file.
3173
+ """
3174
+ _measure_facade = _compat.facade()
3175
+ conn = _measure_facade.sqlite3.connect(":memory:")
3176
+ conn.row_factory = _measure_facade.sqlite3.Row
3177
+ try:
3178
+ conn.executescript(_measure_facade._SCHEMA)
3179
+ _measure_facade.ensure_activity_schema(conn)
3180
+ ledger = {}
3181
+ best = {}
3182
+ for filepath, mtime, project in _measure_facade._find_all_jsonl_files(None):
3183
+ parsed = _measure_facade._parse_session_jsonl(filepath)
3184
+ if not parsed:
3185
+ continue
3186
+ key = _measure_facade._canonical_session_uuid(filepath) or str(filepath)
3187
+ rank = _measure_facade._session_rank(parsed.get("message_count"), parsed.get("total_input_tokens"), parsed.get("total_output_tokens"))
3188
+ if key not in best or rank > best[key][0]:
3189
+ best[key] = (rank, filepath, mtime, project, parsed)
3190
+ for _, filepath, mtime, project, original in best.values():
3191
+ subagent_files = _measure_facade._session_subagent_files(filepath)
3192
+ merged = _measure_facade._session_merged_requests(filepath, original, subagent_files)
3193
+ if merged is not None:
3194
+ net, counted = _measure_facade._net_and_record(merged, ledger)
3195
+ parsed = _measure_facade._parsed_net_of_counted(original, counted)
3196
+ daily = _measure_facade._daily_usage_from_merged(net)
3197
+ calls = dict(parsed.get("daily_calls") or {})
3198
+ for u in net.values():
3199
+ if not u.get("advisor") and u.get("n", 1) and u.get("day"):
3200
+ day = u["day"]
3201
+ calls[day] = calls.get(day, 0) + 1
3202
+ else:
3203
+ parsed = original
3204
+ daily = _measure_facade._session_daily_usage(filepath, parsed=original,
3205
+ subagent_files=subagent_files)
3206
+ calls = dict(original.get("daily_calls") or {})
3207
+ daily_metrics = _measure_facade._session_daily_metrics(parsed, subagent_files)
3208
+ # Same bounds rule as collect_sessions: combined/parent usage and
3209
+ # metadata days, never the file's ingestion timestamp.
3210
+ bounds = _measure_facade._activity_bounds(daily, parsed.get("daily_usage"), daily_metrics)
3211
+ quality = _measure_facade.score_session_quality(parsed)
3212
+ values = {
3213
+ "jsonl_path": str(filepath), "date": bounds[-1] if bounds else "",
3214
+ "first_activity_day": bounds[0] if bounds else None,
3215
+ "last_activity_day": bounds[-1] if bounds else None,
3216
+ "project": project,
3217
+ "duration_minutes": parsed.get("duration_minutes"), "input_tokens": parsed.get("total_input_tokens"),
3218
+ "output_tokens": parsed.get("total_output_tokens"), "message_count": parsed.get("message_count"),
3219
+ "api_calls": parsed.get("api_calls"), "cache_hit_rate": parsed.get("cache_hit_rate"),
3220
+ "cache_create_1h_tokens": parsed.get("total_cache_create_1h", 0),
3221
+ "cache_create_5m_tokens": parsed.get("total_cache_create_5m", 0),
3222
+ "avg_call_gap_seconds": parsed.get("avg_call_gap_seconds"),
3223
+ "max_call_gap_seconds": parsed.get("max_call_gap_seconds"),
3224
+ "p95_call_gap_seconds": parsed.get("p95_call_gap_seconds"),
3225
+ "model_usage_json": _measure_facade.json.dumps(parsed.get("model_usage") or {}),
3226
+ "model_usage_breakdown_json": _measure_facade.json.dumps(parsed.get("model_usage_breakdown") or {}),
3227
+ "daily_usage_json": _measure_facade.json.dumps(daily), "parent_daily_usage_json": _measure_facade.json.dumps(parsed.get("daily_usage") or {}),
3228
+ "daily_calls_json": _measure_facade.json.dumps(calls), "daily_metrics_json": _measure_facade.json.dumps(daily_metrics),
3229
+ "skills_json": _measure_facade.json.dumps(parsed.get("skills_used") or {}),
3230
+ "subagents_json": _measure_facade.json.dumps(parsed.get("subagents_used") or {}),
3231
+ "tool_calls_json": _measure_facade.json.dumps(parsed.get("tool_calls") or {}),
3232
+ "slug": parsed.get("slug"), "topic": parsed.get("topic"),
3233
+ "quality_score": quality["score"], "quality_grade": quality["grade"],
3234
+ "is_sidechain": int(bool(parsed.get("is_sidechain"))), "transcript_mtime": mtime,
3235
+ }
3236
+ conn.execute("INSERT INTO session_log (" + ",".join(values) + ") VALUES ("
3237
+ + ",".join("?" for _ in values) + ")", tuple(values.values()))
3238
+ _measure_facade._rebuild_aggregate_tables(conn)
3239
+ return _measure_facade._query_trends_db(conn, days)
3240
+ finally:
3241
+ conn.close()
3242
+
3243
+
3244
+ def _collect_git_commits(days=None):
3245
+ """Scan known git repos for commits within the time window.
3246
+
3247
+ Checks project directories under ~/.claude/projects/ (reversing the
3248
+ dashed name to a real path) and skill repos under ~/.claude/skills/.
3249
+
3250
+ Returns: { "2026-03-01": [{"repo": "name", "commits": ["msg1", ...]}], ... }
3251
+ """
3252
+ _measure_facade = _compat.facade()
3253
+ cutoff_date = (_measure_facade.datetime.now() - _measure_facade.timedelta(days=days)).strftime("%Y-%m-%d")
3254
+
3255
+ # Collect candidate repo paths
3256
+ repo_paths = {} # path -> display name
3257
+
3258
+ # 1. From project directories
3259
+ projects_base = _measure_facade.CLAUDE_DIR / "projects"
3260
+ if projects_base.exists():
3261
+ for project_dir in projects_base.iterdir():
3262
+ if not project_dir.is_dir():
3263
+ continue
3264
+ # Reverse dashed name to real path: -Users-alex-myproject -> /Users/alex/myproject
3265
+ real_path = "/" + project_dir.name.lstrip("-").replace("-", "/")
3266
+ rp = _measure_facade.Path(real_path)
3267
+ if rp.is_dir() and (rp / ".git").exists():
3268
+ repo_paths[str(rp)] = _measure_facade._clean_project_name(project_dir.name)
3269
+
3270
+ # 2. From skill repos
3271
+ skills_dir = _measure_facade.CLAUDE_DIR / "skills"
3272
+ if skills_dir.exists():
3273
+ for skill_dir in skills_dir.iterdir():
3274
+ if skill_dir.is_dir() and (skill_dir / ".git").exists():
3275
+ repo_paths[str(skill_dir)] = skill_dir.name
3276
+
3277
+ if not repo_paths:
3278
+ return {}
3279
+
3280
+ result = {} # date -> [{"repo": name, "commits": [msg, ...]}]
3281
+
3282
+ for repo_path, display_name in repo_paths.items():
3283
+ try:
3284
+ proc = _measure_facade.subprocess.run(
3285
+ ["git", "-C", repo_path, "log", "--oneline",
3286
+ f"--since={cutoff_date}", "--format=%ai|%s"],
3287
+ capture_output=True, text=True, timeout=10, creationflags=_measure_facade._NO_WINDOW,
3288
+ )
3289
+ if proc.returncode != 0 or not proc.stdout.strip():
3290
+ continue
3291
+ for line in proc.stdout.strip().split("\n"):
3292
+ if "|" not in line:
3293
+ continue
3294
+ date_part, msg = line.split("|", 1)
3295
+ date = date_part.strip()[:10] # YYYY-MM-DD
3296
+ if date not in result:
3297
+ result[date] = []
3298
+ # Find or create repo entry for this date
3299
+ repo_entry = None
3300
+ for entry in result[date]:
3301
+ if entry["repo"] == display_name:
3302
+ repo_entry = entry
3303
+ break
3304
+ if repo_entry is None:
3305
+ repo_entry = {"repo": display_name, "commits": []}
3306
+ result[date].append(repo_entry)
3307
+ repo_entry["commits"].append(msg.strip())
3308
+ except (_measure_facade.subprocess.TimeoutExpired, OSError):
3309
+ continue
3310
+
3311
+ return result
3312
+
3313
+
3314
+ def _collect_trends_data(days=None):
3315
+ """Collect trends data, preferring SQLite DB when available.
3316
+
3317
+ Falls back to live JSONL parsing if DB doesn't exist or is empty.
3318
+ """
3319
+ # Try SQLite first (faster, accumulated data)
3320
+ _measure_facade = _compat.facade()
3321
+ result = _measure_facade._collect_trends_from_db(days)
3322
+ if result is not None:
3323
+ result["git_commits"] = _measure_facade._collect_git_commits(days)
3324
+ return result
3325
+ # Fall back to live JSONL parsing
3326
+ result = _measure_facade._collect_trends_from_jsonl(days)
3327
+ if result is not None:
3328
+ result["git_commits"] = _measure_facade._collect_git_commits(days)
3329
+ return result
3330
+
3331
+
3332
+ def _build_ttl_period_summary(period_days):
3333
+ """Build a compact TTL mix summary for a given period."""
3334
+ _measure_facade = _compat.facade()
3335
+ trends = _measure_facade._collect_trends_data(days=period_days)
3336
+ if not trends:
3337
+ return {
3338
+ "label": f"{period_days}d: no cache-write data",
3339
+ "period_days": period_days,
3340
+ "mixed_sessions": 0,
3341
+ "five_only_sessions": 0,
3342
+ "one_hour_only_sessions": 0,
3343
+ }
3344
+
3345
+ mixed_sessions = 0
3346
+ five_only_sessions = 0
3347
+ one_hour_only_sessions = 0
3348
+ for day in trends.get("daily", []):
3349
+ for session in day.get("session_details", []):
3350
+ if session.get("continuation"):
3351
+ continue
3352
+ ttl_1h = session.get("cache_create_1h_tokens", 0) or 0
3353
+ ttl_5m = session.get("cache_create_5m_tokens", 0) or 0
3354
+ if ttl_1h and ttl_5m:
3355
+ mixed_sessions += 1
3356
+ elif ttl_5m and not ttl_1h:
3357
+ five_only_sessions += 1
3358
+ elif ttl_1h and not ttl_5m:
3359
+ one_hour_only_sessions += 1
3360
+
3361
+ if mixed_sessions == 0 and five_only_sessions == 0:
3362
+ label = f"{period_days}d: all 1h-only"
3363
+ else:
3364
+ parts = []
3365
+ if mixed_sessions:
3366
+ parts.append(f"{mixed_sessions} mixed")
3367
+ if five_only_sessions:
3368
+ parts.append(f"{five_only_sessions} 5m-only")
3369
+ label = f"{period_days}d: " + ", ".join(parts)
3370
+
3371
+ return {
3372
+ "label": label,
3373
+ "period_days": period_days,
3374
+ "mixed_sessions": mixed_sessions,
3375
+ "five_only_sessions": five_only_sessions,
3376
+ "one_hour_only_sessions": one_hour_only_sessions,
3377
+ }
3378
+
3379
+
3380
+ def usage_trends(days=None, as_json=None):
3381
+ """Analyze usage trends across all Claude Code sessions."""
3382
+ _measure_facade = _compat.facade()
3383
+ trends = _measure_facade._collect_trends_data(days)
3384
+ if trends is None:
3385
+ print(f"\nNo session logs found in the last {days} days.")
3386
+ print(f"Looked in: {_measure_facade.CLAUDE_DIR / 'projects' / '*' / '*.jsonl'}")
3387
+ return
3388
+
3389
+ if as_json:
3390
+ result = dict(trends)
3391
+ result.pop("trajectory", None)
3392
+ print(_measure_facade.json.dumps(result, indent=2, default=str))
3393
+ return
3394
+
3395
+ session_count = trends["session_count"]
3396
+ avg_dur = trends["avg_duration_minutes"]
3397
+ avg_in = trends["avg_input_tokens"]
3398
+ avg_out = trends["avg_output_tokens"]
3399
+
3400
+ def _fmt_tokens(n):
3401
+ _measure_facade = _compat.facade()
3402
+ if n >= 1_000_000:
3403
+ return f"{n / 1_000_000:.1f}M"
3404
+ if n >= 1_000:
3405
+ return f"{n / 1_000:.0f}K"
3406
+ return str(int(n))
3407
+
3408
+ print(f"\nUSAGE TRENDS (last {days} days)")
3409
+ print("=" * 55)
3410
+ print(f"\n Sessions: {session_count} | Avg duration: {avg_dur:.0f} min | Avg tokens/session: {_fmt_tokens(avg_in)} in (incl. cache reads) / {_fmt_tokens(avg_out)} out")
3411
+
3412
+ skill_sessions = trends["skills"]["used"]
3413
+ installed_count = trends["skills"]["installed_count"]
3414
+ never_used = trends["skills"]["never_used"]
3415
+
3416
+ print("\nSKILLS")
3417
+ if skill_sessions:
3418
+ print(f" Used ({len(skill_sessions)} of {installed_count} installed):")
3419
+ for skill, count in sorted(skill_sessions.items(), key=lambda x: ((_measure_facade := _compat.facade()), -x[1])[1])[:15]:
3420
+ dots = "." * max(2, 30 - len(skill))
3421
+ print(f" {_measure_facade._strip_ansi(str(skill))} {dots} {count} session{'s' if count != 1 else ''}")
3422
+ if len(skill_sessions) > 15:
3423
+ print(f" ... and {len(skill_sessions) - 15} more")
3424
+ else:
3425
+ print(f" No skill invocations found in {session_count} sessions.")
3426
+
3427
+ if never_used:
3428
+ approx_overhead = len(never_used) * _measure_facade.TOKENS_PER_SKILL_APPROX
3429
+ print(f"\n Never used (last {days} days):")
3430
+ names = sorted(never_used)
3431
+ line = " "
3432
+ for i, name in enumerate(names):
3433
+ addition = name + (", " if i < len(names) - 1 else "")
3434
+ if len(line) + len(addition) > 72:
3435
+ print(line.rstrip(", "))
3436
+ line = " " + addition
3437
+ else:
3438
+ line += addition
3439
+ if line.strip():
3440
+ print(line.rstrip(", "))
3441
+ print(f" ({len(never_used)} skills, ~{approx_overhead:,} tokens overhead)")
3442
+
3443
+ total_subagents = trends["subagents"]
3444
+ if total_subagents:
3445
+ print("\nSUBAGENTS")
3446
+ for agent, count in sorted(total_subagents.items(), key=lambda x: ((_measure_facade := _compat.facade()), -x[1])[1]):
3447
+ dots = "." * max(2, 30 - len(agent))
3448
+ print(f" {_measure_facade._strip_ansi(str(agent))} {dots} {count} spawned")
3449
+
3450
+ total_model_tokens = trends["model_mix"]
3451
+ if total_model_tokens:
3452
+ # Model shares count fresh input + output (cache reads excluded), unlike
3453
+ # the per-session average above; say so, or the two read as contradictory.
3454
+ print("\nMODEL MIX (share of tokens, excl. cache reads)")
3455
+ grand_total = sum(total_model_tokens.values())
3456
+ for model, tokens in sorted(total_model_tokens.items(), key=lambda x: ((_measure_facade := _compat.facade()), -x[1])[1]):
3457
+ pct = tokens / grand_total * 100 if grand_total else 0
3458
+ dots = "." * max(2, 26 - len(model))
3459
+ print(f" {_measure_facade._strip_ansi(str(model))} {dots} {pct:.0f}% of tokens ({_fmt_tokens(tokens)})")
3460
+
3461
+ trajectory = trends.get("trajectory", {})
3462
+ snapshots = trajectory.get("snapshots", [])
3463
+ if snapshots:
3464
+ print("\nOVERHEAD TRAJECTORY (from saved snapshots)")
3465
+ for snap in snapshots:
3466
+ ts = snap["timestamp"][:10] if snap["timestamp"] else "unknown"
3467
+ label = snap["label"]
3468
+ total = snap["total"]
3469
+ print(f" {ts}: {total:,} tokens ({label})")
3470
+
3471
+ current_total = trajectory.get("current_total", 0)
3472
+ if snapshots and current_total:
3473
+ latest = snapshots[-1]["total"]
3474
+ drift = current_total - latest
3475
+ if abs(drift) > 500:
3476
+ direction = "+" if drift > 0 else ""
3477
+ print(f" Today: {current_total:,} tokens (current)")
3478
+ print(f" Drift since last snapshot: {direction}{drift:,} tokens")
3479
+
3480
+ print()
3481
+
3482
+
3483
+ def _status_bar_dir():
3484
+ _measure_facade = _compat.facade()
3485
+ return _measure_facade.SNAPSHOT_DIR / "status-bar"
3486
+
3487
+
3488
+ def _status_bar_key(session_id):
3489
+ """A file-name-safe key for a session: long ids are shortened with a hash so a
3490
+ file name never exceeds what the filesystem allows."""
3491
+ _measure_facade = _compat.facade()
3492
+ sid = str(session_id)
3493
+ if len(sid) <= 100:
3494
+ return sid
3495
+ return sid[:64] + "-" + _measure_facade.hashlib.sha256(sid.encode("utf-8")).hexdigest()[:16]
3496
+
3497
+
3498
+ def _status_bar_cache_path(session_id):
3499
+ _measure_facade = _compat.facade()
3500
+ return _measure_facade._status_bar_dir() / f"{_measure_facade._status_bar_key(session_id)}.json"
3501
+
3502
+
3503
+ def _status_bar_lock_path(session_id):
3504
+ _measure_facade = _compat.facade()
3505
+ return _measure_facade._status_bar_dir() / f"{_measure_facade._status_bar_key(session_id)}.refresh.lock"
3506
+
3507
+
3508
+ def _realized_savings_buckets(conn, cutoff, session_uuid=None, by_day=None):
3509
+ """Realized savings per bucket, netted exactly like the window headline.
3510
+
3511
+ Buckets are local days (savings_events / compression_events timestamps are
3512
+ naive local ISO) when *by_day*, else one bucket keyed "". With
3513
+ *session_uuid* only that session's rows count. Each bucket is
3514
+ {"tokens": int, "usd": float, "events": int}. Raises sqlite3.Error so the
3515
+ caller can tell a busy or broken DB from an empty one.
3516
+ """
3517
+ _measure_facade = _compat.facade()
3518
+ params = [cutoff]
3519
+ if session_uuid is not None:
3520
+ # Other runtimes' ids are not UUIDs: their rows keep the id in session_id.
3521
+ params.extend([session_uuid, session_uuid])
3522
+ se_sql = _measure_facade._BUCKET_SAVINGS_SQL[
3523
+ _measure_facade._counted_table(conn, "savings_events"), bool(by_day), session_uuid is not None]
3524
+ ce_sql = _measure_facade._BUCKET_COMPRESSION_SQL[
3525
+ _measure_facade._counted_table(conn, "compression_events"), bool(by_day), session_uuid is not None]
3526
+ se_rows = conn.execute(se_sql, tuple(params)).fetchall()
3527
+ ce_rows = conn.execute(ce_sql, tuple(params)).fetchall()
3528
+ ce_session_rates = _measure_facade._compression_session_rates(
3529
+ conn, [r[6] for r in ce_rows
3530
+ if not _measure_facade._compression_known_model(r[5])],
3531
+ [r[7] for r in ce_rows if not _measure_facade._compression_known_model(r[5])])
3532
+ deltas, _rt, _ut = _measure_facade._session_model_reprice(
3533
+ conn, cutoff, session_uuid=session_uuid, by_day=True)
3534
+
3535
+ se_by_bucket = {}
3536
+ for bucket, event_type, cnt, tok, cost in se_rows:
3537
+ se_by_bucket.setdefault(bucket or "", []).append((event_type, cnt, tok, cost))
3538
+ deltas_by_bucket = {}
3539
+ for (day, event_type), delta in deltas.items():
3540
+ key = (day or "") if by_day else ""
3541
+ per = deltas_by_bucket.setdefault(key, {})
3542
+ per[event_type] = per.get(event_type, 0.0) + delta
3543
+
3544
+ fallback_rate = _measure_facade._estimate_compression_cost_per_mtok()
3545
+ tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
3546
+ ce_by_bucket = {}
3547
+ for bucket, feature, cnt, orig, comp, model, s_uuid, sid in ce_rows:
3548
+ tokens_saved = (orig or 0) - (comp or 0)
3549
+ key = s_uuid if s_uuid in ce_session_rates else ("session_id", sid)
3550
+ rate = _measure_facade._compression_priced_rate(model, key, ce_session_rates, fallback_rate, tier_data)
3551
+ feats = ce_by_bucket.setdefault(bucket or "", {})
3552
+ entry = feats.setdefault(feature, {"events": 0, "tokens_saved": 0, "cost_saved_usd": 0.0})
3553
+ entry["events"] += cnt or 0
3554
+ entry["tokens_saved"] += tokens_saved
3555
+ entry["cost_saved_usd"] = round(
3556
+ entry["cost_saved_usd"] + round(tokens_saved * rate / 1_000_000, 6), 6)
3557
+
3558
+ out = {}
3559
+ for bucket in set(se_by_bucket) | set(ce_by_bucket):
3560
+ by_category, tok, cost, events, _popped, _rp = _measure_facade._net_realized_savings(
3561
+ se_by_bucket.get(bucket, []), deltas_by_bucket.get(bucket, {}))
3562
+ a_tok, a_cost, a_events = _measure_facade._merge_v5_compression(
3563
+ by_category, ce_by_bucket.get(bucket, {}), fallback_rate)
3564
+ out[bucket] = {
3565
+ "tokens": int(tok + a_tok),
3566
+ "usd": round(cost + a_cost, 4),
3567
+ "events": int(events + a_events),
3568
+ }
3569
+ return out
3570
+
3571
+
3572
+ def _open_trends_db_readonly(timeout=None):
3573
+ """Read-only connection to trends.db; never creates or migrates it."""
3574
+ _measure_facade = _compat.facade()
3575
+ uri = _measure_facade.Path(_measure_facade.TRENDS_DB).resolve().as_uri() + "?mode=ro"
3576
+ conn = _measure_facade.sqlite3.connect(uri, uri=True, timeout=timeout)
3577
+ conn.execute(f"PRAGMA busy_timeout={int(timeout * 1000)}")
3578
+ return conn
3579
+
3580
+
3581
+ def _dashboard_saved_tokens(summary):
3582
+ """The dashboard's Tokens Saved headline: measured plus the estimated tier.
3583
+
3584
+ Mirrors tokensSavedCardHtml in assets/dashboard.html exactly (same fields,
3585
+ same `a || b` fallbacks), so the status bar and the dashboard never disagree.
3586
+ """
3587
+ _measure_facade = _compat.facade()
3588
+ s = summary or {}
3589
+
3590
+ def num(v):
3591
+ _measure_facade = _compat.facade()
3592
+ try:
3593
+ return max(0, int(float(v or 0)))
3594
+ except (TypeError, ValueError, OverflowError):
3595
+ return 0
3596
+
3597
+ def tok(obj):
3598
+ _measure_facade = _compat.facade()
3599
+ try:
3600
+ return num((obj or {}).get("tokens_saved", 0))
3601
+ except AttributeError:
3602
+ return 0
3603
+
3604
+ estimated = (tok(s.get("mcp_cap_estimated"))
3605
+ + tok(s.get("hint_followed") or s.get("hint_followed_estimated"))
3606
+ + tok(s.get("verbosity_steer") or s.get("verbosity_steer_estimated"))
3607
+ + tok(s.get("resume_lean_estimated"))
3608
+ + tok(s.get("checkpoint_restore_estimated")))
3609
+ measured = num(s.get("total_tokens", 0))
3610
+ # The dashboard draws no Tokens Saved card only when nothing was measured
3611
+ # AND nothing estimated exists -- estimates still surface on their own.
3612
+ return measured + estimated, measured
3613
+
3614
+
3615
+ def _status_bar_savings_or_reason(session_id, _retried=None):
3616
+ """Compute the savings object. Returns (savings_dict, None) or (None, reason)."""
3617
+ _measure_facade = _compat.facade()
3618
+ if not _measure_facade.Path(_measure_facade.TRENDS_DB).exists():
3619
+ return None, "no savings recorded yet"
3620
+ today = _measure_facade.datetime.now().date()
3621
+ first_day = today - _measure_facade.timedelta(days=_measure_facade._STATUS_BAR_DAYS - 1)
3622
+ cutoff = _measure_facade.datetime(first_day.year, first_day.month, first_day.day).isoformat()
3623
+ try:
3624
+ conn = _measure_facade._open_trends_db_readonly()
3625
+ try:
3626
+ # One read transaction: both bucket reads see the same committed rows (the
3627
+ # 30-day headline below runs on its own connection, as the dashboard's does).
3628
+ conn.execute("BEGIN")
3629
+ days = _measure_facade._realized_savings_buckets(conn, cutoff, by_day=True)
3630
+ window = _measure_facade._realized_savings_buckets(conn, cutoff).get("", {"tokens": 0})
3631
+ sess = _measure_facade._realized_savings_buckets(conn, "", session_uuid=session_id).get(
3632
+ "", {"tokens": 0, "usd": 0.0})
3633
+ conn.execute("COMMIT")
3634
+ finally:
3635
+ conn.close()
3636
+ except _measure_facade.sqlite3.OperationalError as e:
3637
+ msg = str(e).lower()
3638
+ if "locked" in msg or "busy" in msg:
3639
+ return None, "savings database busy"
3640
+ if "no such column" in msg or "no such table" in msg:
3641
+ # A database from before these columns: the normal writer migrates it once.
3642
+ try:
3643
+ migrated = _measure_facade._init_trends_db()
3644
+ if migrated is not None:
3645
+ migrated.close()
3646
+ except Exception:
3647
+ return None, "savings database unreadable"
3648
+ if _retried:
3649
+ return None, "savings database unreadable"
3650
+ return _measure_facade._status_bar_savings_or_reason(session_id, _retried=True)
3651
+ return None, "savings database unreadable"
3652
+ except (_measure_facade.sqlite3.Error, OSError, ValueError):
3653
+ return None, "savings database unreadable"
3654
+ daily = []
3655
+ for i in range(_measure_facade._STATUS_BAR_DAYS):
3656
+ d = (first_day + _measure_facade.timedelta(days=i)).isoformat()
3657
+ b = days.get(d, {})
3658
+ daily.append({"date": d, "tokens": int(b.get("tokens", 0)),
3659
+ "usd": float(b.get("usd", 0.0))})
3660
+ headline = _measure_facade._get_merged_savings(days=_measure_facade._STATUS_BAR_DAYS)
3661
+ shown, measured = _measure_facade._dashboard_saved_tokens(headline)
3662
+ # The headline pass fails open to zeros; when the window, netted the way the
3663
+ # headline nets it, shows savings but the headline is zero, it failed: say so
3664
+ # rather than cache a false 0. Single days are not compared, since a debit on
3665
+ # one day can honestly cancel savings on another.
3666
+ if measured == 0 and int(window.get("tokens", 0)) > 0:
3667
+ return None, "savings database busy"
3668
+ return {
3669
+ "unit": "tokens",
3670
+ "session_tokens": int(sess.get("tokens", 0)),
3671
+ "session_usd": float(sess.get("usd", 0.0)),
3672
+ "daily": daily,
3673
+ "total_30d_usd": headline["total_cost_usd"],
3674
+ # The dashboard's headline (measured + estimated); the measured floor beside it.
3675
+ "total_30d_tokens": shown,
3676
+ "total_30d_measured_tokens": measured,
3677
+ "computed_at": _measure_facade.time.time(),
3678
+ }, None
3679
+
3680
+
3681
+ def _status_bar_write_cache(session_id, savings, reason):
3682
+ _measure_facade = _compat.facade()
3683
+ d = _measure_facade._status_bar_dir()
3684
+ d.mkdir(parents=True, exist_ok=True)
3685
+ path = _measure_facade._status_bar_cache_path(session_id)
3686
+ if savings is None:
3687
+ # A failed refresh keeps the last good figures (they read as stale), never null them.
3688
+ prior = _measure_facade._status_bar_read_cache(session_id)
3689
+ if prior is not None and prior.get("savings") is not None:
3690
+ return
3691
+ tmp = path.with_name(f".{path.name}.{_measure_facade.os.getpid()}.tmp")
3692
+ tmp.write_text(_measure_facade.json.dumps({
3693
+ "schema": _measure_facade._STATUS_BAR_SCHEMA,
3694
+ "computed_at": _measure_facade.time.time(),
3695
+ "savings": savings,
3696
+ "reason": reason,
3697
+ }), encoding="utf-8")
3698
+ _measure_facade.os.replace(tmp, path)
3699
+ # Bound the directory: drop caches for sessions untouched for 30 days.
3700
+ cutoff = _measure_facade.time.time() - _measure_facade._STATUS_BAR_CACHE_RETENTION_S
3701
+ orphan_cutoff = _measure_facade.time.time() - 86400
3702
+ try:
3703
+ for f in d.iterdir():
3704
+ try:
3705
+ name = f.name
3706
+ # Temp files and set-aside locks left by a crash go after a day.
3707
+ orphan = name.endswith((".tmp", ".stale", ".release"))
3708
+ if (orphan and f.stat().st_mtime < orphan_cutoff) or (
3709
+ name.endswith(".json") and f.stat().st_mtime < cutoff):
3710
+ f.unlink()
3711
+ except OSError:
3712
+ pass
3713
+ except OSError:
3714
+ pass
3715
+
3716
+
3717
+ def _status_bar_read_cache(session_id):
3718
+ _measure_facade = _compat.facade()
3719
+ try:
3720
+ data = _measure_facade.json.loads(_measure_facade._status_bar_cache_path(session_id).read_text(encoding="utf-8"))
3721
+ except (OSError, ValueError):
3722
+ return None
3723
+ if not isinstance(data, dict) or not isinstance(data.get("computed_at"), (int, float)):
3724
+ return None
3725
+ return data
3726
+
3727
+
3728
+ def _status_bar_start_refresh(session_id):
3729
+ """Start ONE detached `status-bar --sync` child. Returns True if started.
3730
+
3731
+ A lock file (O_EXCL) makes concurrent callers start at most one child; the
3732
+ child removes it when done, and a lock older than 120 s counts as abandoned.
3733
+ The lock holds a random owner token, passed to the child in the
3734
+ TO_STATUS_BAR_LOCK_TOKEN environment variable; the child deletes the lock
3735
+ only while it still holds that token.
3736
+ """
3737
+ _measure_facade = _compat.facade()
3738
+ token = _measure_facade._status_bar_acquire_lock(session_id)
3739
+ if token is None:
3740
+ return False
3741
+ # The child releases the lock only if it still holds this token, so a child
3742
+ # that outlives its lock never deletes a newer caller's lock.
3743
+ proc = _measure_facade.spawn_detached(
3744
+ [_measure_facade._detached_python_exe(), str(_measure_facade.MEASURE_PY_PATH), "status-bar",
3745
+ "--session", session_id, "--sync", "--release-lock"],
3746
+ stdin=_measure_facade.subprocess.DEVNULL, stdout=_measure_facade.subprocess.DEVNULL, stderr=_measure_facade.subprocess.DEVNULL,
3747
+ env={**_measure_facade.os.environ, _measure_facade._STATUS_BAR_LOCK_TOKEN_ENV: token})
3748
+ if proc is None:
3749
+ _measure_facade._log_spawn_failure("status-bar refresh spawn failed")
3750
+ _measure_facade._status_bar_release_lock(session_id, token)
3751
+ return False
3752
+ return True
3753
+
3754
+
3755
+ def _status_bar_acquire_lock(session_id):
3756
+ """Take the session's refresh lock; its owner token, or None when it is held."""
3757
+ _measure_facade = _compat.facade()
3758
+ lock = _measure_facade._status_bar_lock_path(session_id)
3759
+ token = _measure_facade.os.urandom(16).hex()
3760
+ fd = None
3761
+ try:
3762
+ lock.parent.mkdir(parents=True, exist_ok=True)
3763
+ try:
3764
+ fd = _measure_facade.os.open(str(lock), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY)
3765
+ except FileExistsError:
3766
+ if _measure_facade.time.time() - lock.stat().st_mtime < _measure_facade._STATUS_BAR_LOCK_STALE_S:
3767
+ return None
3768
+ # Take an abandoned lock over by renaming it aside. Rename is atomic,
3769
+ # so when two callers race only one moves the file; the other gets
3770
+ # FileNotFoundError and backs off instead of deleting the winner's lock.
3771
+ quarantine = lock.with_name(
3772
+ f"{lock.name}.{_measure_facade.os.getpid()}.{_measure_facade.time.time_ns()}.stale")
3773
+ try:
3774
+ _measure_facade.os.rename(str(lock), str(quarantine))
3775
+ except OSError:
3776
+ return None
3777
+ try:
3778
+ moved_fresh = (_measure_facade.time.time() - _measure_facade.os.stat(str(quarantine)).st_mtime
3779
+ < _measure_facade._STATUS_BAR_LOCK_STALE_S)
3780
+ except OSError:
3781
+ moved_fresh = False
3782
+ if moved_fresh:
3783
+ # Another caller replaced the stale lock between our check and the
3784
+ # rename, so we moved its live lock. Put it back without
3785
+ # overwriting anything (link fails if the name is taken) and back off.
3786
+ _measure_facade._status_bar_put_back(quarantine, lock)
3787
+ try:
3788
+ quarantine.unlink()
3789
+ except OSError:
3790
+ pass
3791
+ return None
3792
+ try:
3793
+ quarantine.unlink()
3794
+ except OSError:
3795
+ pass
3796
+ try:
3797
+ fd = _measure_facade.os.open(str(lock), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY)
3798
+ except FileExistsError:
3799
+ return None
3800
+ written = _measure_facade.os.write(fd, token.encode("ascii"))
3801
+ _measure_facade.os.close(fd)
3802
+ fd = None
3803
+ if written != len(token):
3804
+ # A short write leaves a lock nobody can prove they own: remove ours now.
3805
+ try:
3806
+ lock.unlink()
3807
+ except OSError:
3808
+ pass
3809
+ return None
3810
+ return token
3811
+ except OSError:
3812
+ if fd is not None:
3813
+ try:
3814
+ _measure_facade.os.close(fd)
3815
+ except OSError:
3816
+ pass
3817
+ try:
3818
+ lock.unlink()
3819
+ except OSError:
3820
+ pass
3821
+ return None
3822
+
3823
+
3824
+ def _status_bar_release_lock(session_id, token):
3825
+ """Delete the refresh lock only when it still holds `token`. Never raises.
3826
+
3827
+ The lock is moved aside first (one atomic rename) and only then checked, so a
3828
+ lock another process created after ours is never deleted by mistake: when the
3829
+ moved file is not ours it goes back, unless a newer lock already took its name.
3830
+ """
3831
+ _measure_facade = _compat.facade()
3832
+ if not token:
3833
+ return False
3834
+ lock = _measure_facade._status_bar_lock_path(session_id)
3835
+ aside = lock.with_name(f"{lock.name}.{_measure_facade.os.getpid()}.{_measure_facade.time.time_ns()}.release")
3836
+ try:
3837
+ _measure_facade.os.rename(str(lock), str(aside))
3838
+ except OSError:
3839
+ return False
3840
+ try:
3841
+ mine = aside.read_text(encoding="ascii", errors="replace").strip() == token
3842
+ except OSError:
3843
+ mine = False
3844
+ if not mine:
3845
+ _measure_facade._status_bar_put_back(aside, lock)
3846
+ try:
3847
+ aside.unlink()
3848
+ except OSError:
3849
+ pass
3850
+ return mine
3851
+
3852
+
3853
+ def _status_bar_put_back(aside, lock):
3854
+ """Return a lock moved aside to its name, never over a newer one.
3855
+
3856
+ The caller still removes `aside` afterwards. A hard link puts it back only
3857
+ while the name is free. Without hard links it is dropped: a check-then-rename
3858
+ could replace a newer lock, and losing an old one only allows a duplicate
3859
+ refresh.
3860
+ """
3861
+ _measure_facade = _compat.facade()
3862
+ try:
3863
+ _measure_facade.os.link(str(aside), str(lock))
3864
+ except (OSError, AttributeError):
3865
+ pass
3866
+
3867
+
3868
+ def _status_bar_compactions(path, session_id=None):
3869
+ """How many times this transcript was compacted (compact_boundary rows), or None.
3870
+
3871
+ Counts rows whose parsed JSON is a system compact_boundary (the same key can
3872
+ sit inside a structured tool result). The quality cache's own count can lag
3873
+ a compaction, and the band shows this number right after one. The transcript
3874
+ only grows, so with a session id the count resumes after the last whole line
3875
+ the previous call read (kept beside the status cache).
3876
+ """
3877
+ _measure_facade = _compat.facade()
3878
+ memo = None
3879
+ if session_id:
3880
+ try:
3881
+ memo = _measure_facade._status_bar_dir() / f"compactions-{_measure_facade._status_bar_key(_measure_facade.sanitize_session_id(session_id))}.json"
3882
+ except Exception:
3883
+ memo = None
3884
+ start, count = 0, 0
3885
+ try:
3886
+ size = _measure_facade.os.path.getsize(path)
3887
+ except OSError:
3888
+ return None
3889
+ if memo is not None:
3890
+ try:
3891
+ m = _measure_facade.json.loads(memo.read_text(encoding="utf-8"))
3892
+ if m.get("path") == str(path) and 0 <= int(m.get("size", -1)) <= size:
3893
+ start, count = int(m["size"]), int(m["count"])
3894
+ except (OSError, ValueError, TypeError, KeyError):
3895
+ start, count = 0, 0
3896
+ try:
3897
+ end = start
3898
+ with open(path, "rb") as fh:
3899
+ if start > 0:
3900
+ # Resume only on a line boundary; anything else recounts from the top.
3901
+ fh.seek(start - 1)
3902
+ if fh.read(1) != b"\n":
3903
+ start, count, end = 0, 0, 0
3904
+ fh.seek(start)
3905
+ for line in fh:
3906
+ if not line.endswith(b"\n"):
3907
+ break # a row still being written: the next call reads it whole
3908
+ end += len(line)
3909
+ if _measure_facade._COMPACT_MARK not in line:
3910
+ continue
3911
+ try:
3912
+ row = _measure_facade.json.loads(line)
3913
+ except (ValueError, UnicodeDecodeError):
3914
+ continue
3915
+ if isinstance(row, dict) and row.get("type") == "system" and row.get("subtype") == "compact_boundary":
3916
+ count += 1
3917
+ if memo is not None:
3918
+ try:
3919
+ # Never written backwards: a slower reader that ended earlier leaves a newer memo alone.
3920
+ try:
3921
+ cur = _measure_facade.json.loads(memo.read_text(encoding="utf-8"))
3922
+ newer = cur.get("path") == str(path) and int(cur.get("size", -1)) > end
3923
+ except (OSError, ValueError, TypeError):
3924
+ newer = False
3925
+ if not newer:
3926
+ memo.parent.mkdir(parents=True, exist_ok=True)
3927
+ tmp = memo.with_name(f".{memo.name}.{_measure_facade.os.getpid()}.tmp")
3928
+ tmp.write_text(_measure_facade.json.dumps({"path": str(path), "size": end, "count": count}), encoding="utf-8")
3929
+ _measure_facade.os.replace(tmp, memo)
3930
+ except OSError:
3931
+ pass
3932
+ return count
3933
+ except OSError:
3934
+ return None
3935
+
3936
+
3937
+ def _status_bar_transcript_state(path):
3938
+ """(last_request_epoch, cache_lifetime, model) from a transcript, read from the end.
3939
+
3940
+ last_request_epoch: timestamp of the newest MAIN-thread assistant row that
3941
+ carries usage (isSidechain / agentId rows and <synthetic> rows skipped).
3942
+ cache_lifetime: the newest non-unknown _keepwarm_ttl_kind on main-thread rows,
3943
+ so read-only turns after a 1h write still report "1h". model: the newest
3944
+ main-thread assistant row's message.model (raw id, for the compact-window
3945
+ resolver). Scans at most 16 MB backwards. Returns (None, None, None) when
3946
+ the file is missing or unreadable.
3947
+ """
3948
+ _measure_facade = _compat.facade()
3949
+ last_ts = None
3950
+ lifetime = None
3951
+ model = None
3952
+
3953
+ def _take(raw):
3954
+ _measure_facade = _compat.facade()
3955
+ nonlocal last_ts, lifetime, model
3956
+ raw = raw.strip()
3957
+ if not raw or b'"assistant"' not in raw:
3958
+ return
3959
+ try:
3960
+ rec = _measure_facade.json.loads(raw)
3961
+ except (ValueError, UnicodeDecodeError):
3962
+ return
3963
+ if not isinstance(rec, dict) or rec.get("type") != "assistant":
3964
+ return
3965
+ if rec.get("isSidechain") is True or rec.get("agentId"):
3966
+ return
3967
+ msg = rec.get("message")
3968
+ if not isinstance(msg, dict) or msg.get("model") == "<synthetic>":
3969
+ return
3970
+ if model is None:
3971
+ m = msg.get("model")
3972
+ if isinstance(m, str) and m:
3973
+ model = m
3974
+ usage = msg.get("usage")
3975
+ if not isinstance(usage, dict) or not usage:
3976
+ return
3977
+ if last_ts is None:
3978
+ last_ts = _measure_facade._keepwarm_iso_to_epoch(rec.get("timestamp"))
3979
+ if lifetime is None:
3980
+ try:
3981
+ kind = _measure_facade._keepwarm_ttl_kind(usage)
3982
+ except (TypeError, ValueError, OverflowError):
3983
+ kind = "unknown" # one malformed row; the older rows still count
3984
+ if kind != "unknown":
3985
+ lifetime = kind
3986
+
3987
+ try:
3988
+ with open(path, "rb") as fh:
3989
+ pos = fh.seek(0, _measure_facade.os.SEEK_END)
3990
+ carry = b""
3991
+ scanned = 0
3992
+ while pos > 0 and scanned < _measure_facade._STATUS_BAR_TAIL_MAX_BYTES:
3993
+ step = min(_measure_facade._STATUS_BAR_TAIL_CHUNK, pos)
3994
+ pos -= step
3995
+ fh.seek(pos)
3996
+ buf = fh.read(step) + carry
3997
+ scanned += step
3998
+ parts = buf.split(b"\n")
3999
+ carry = parts[0]
4000
+ for raw in reversed(parts[1:]):
4001
+ _take(raw)
4002
+ if last_ts is not None and lifetime is not None and model is not None:
4003
+ return last_ts, lifetime, model
4004
+ if pos == 0 and carry:
4005
+ _take(carry)
4006
+ except (OSError, TypeError, ValueError):
4007
+ return None, None, None
4008
+ return last_ts, lifetime, model
4009
+
4010
+
4011
+ def _status_bar_quality_cache_dirs():
4012
+ _measure_facade = _compat.facade()
4013
+ dirs = [_measure_facade.QUALITY_CACHE_DIR, _measure_facade.RUNTIME_DIR / "token-optimizer"]
4014
+ env_pd = _measure_facade.os.environ.get("CLAUDE_PLUGIN_DATA", "").strip()
4015
+ if env_pd:
4016
+ dirs.append(_measure_facade.Path(env_pd) / "token-optimizer")
4017
+ try:
4018
+ for d in (_measure_facade.RUNTIME_DIR / "plugins" / "data").iterdir():
4019
+ if "token-optimizer" in d.name:
4020
+ dirs.append(d / "token-optimizer")
4021
+ except OSError:
4022
+ pass
4023
+ seen, out = set(), []
4024
+ for d in dirs:
4025
+ key = str(d)
4026
+ if key not in seen:
4027
+ seen.add(key)
4028
+ out.append(d)
4029
+ return out
4030
+
4031
+
4032
+ def _status_bar_freshest(name):
4033
+ """The newest file called `name` across Token Optimizer's storage dirs, or None."""
4034
+ _measure_facade = _compat.facade()
4035
+ best, best_mtime = None, -1.0
4036
+ for d in _measure_facade._status_bar_quality_cache_dirs():
4037
+ f = d / name
4038
+ try:
4039
+ mt = f.stat().st_mtime
4040
+ except OSError:
4041
+ continue
4042
+ if mt > best_mtime:
4043
+ best, best_mtime = f, mt
4044
+ return best
4045
+
4046
+
4047
+ def _status_bar_checkpoint_epoch(session_id):
4048
+ """When this session last saved a checkpoint, epoch seconds, or None.
4049
+
4050
+ The newer of the quality cache's last_checkpoint_epoch (quality-triggered
4051
+ saves only) and this session's newest checkpoint file, so stop and
4052
+ compaction checkpoints count too.
4053
+ """
4054
+ _measure_facade = _compat.facade()
4055
+ newest_file = None
4056
+ for d in _measure_facade._status_bar_quality_cache_dirs():
4057
+ try:
4058
+ for f in (d / "checkpoints").glob(f"{session_id}-*.md"):
4059
+ mt = int(f.stat().st_mtime)
4060
+ if newest_file is None or mt > newest_file:
4061
+ newest_file = mt
4062
+ except OSError:
4063
+ continue
4064
+ cached = _measure_facade._status_bar_cached_checkpoint_epoch(session_id)
4065
+ found = [v for v in (cached, newest_file) if v is not None]
4066
+ return max(found) if found else None
4067
+
4068
+
4069
+ def _status_bar_cached_checkpoint_epoch(session_id):
4070
+ """last_checkpoint_epoch from the freshest quality-cache-<sid>.json, or None.
4071
+
4072
+ None when the checkpoint it names is no longer on disk (retention removed
4073
+ it), so the band never reports a save that cannot be restored.
4074
+ """
4075
+ _measure_facade = _compat.facade()
4076
+ best = _measure_facade._status_bar_freshest(f"quality-cache-{session_id}.json")
4077
+ if best is None:
4078
+ return None
4079
+ try:
4080
+ cache = _measure_facade.json.loads(best.read_text(encoding="utf-8"))
4081
+ val = cache.get("last_checkpoint_epoch")
4082
+ saved = cache.get("last_checkpoint_path")
4083
+ except (OSError, ValueError, AttributeError):
4084
+ return None
4085
+ if isinstance(val, bool) or not isinstance(val, (int, float)):
4086
+ return None
4087
+ if not isinstance(saved, str) or not saved:
4088
+ return None
4089
+ try:
4090
+ if not _measure_facade.Path(saved).is_file():
4091
+ return None
4092
+ except (OSError, ValueError):
4093
+ return None
4094
+ return val
4095
+
4096
+
4097
+ def _status_bar_earlier_checkpoint(session_id):
4098
+ """The earlier session's checkpoint flagged for this one at start, or None.
4099
+
4100
+ Reads the resumable flag the SessionStart pointer writes (freshest across
4101
+ the quality-cache dirs), so the band names the same checkpoint the
4102
+ terminal status line marks as resumable.
4103
+ """
4104
+ _measure_facade = _compat.facade()
4105
+ best = _measure_facade._status_bar_freshest(f"resumable-{session_id}.json")
4106
+ if best is None:
4107
+ return None
4108
+ try:
4109
+ flag = _measure_facade.json.loads(best.read_text(encoding="utf-8"))
4110
+ # Only a checkpoint on this work: an unrelated recent one is noise here.
4111
+ if flag.get("relevant") is not True:
4112
+ return None
4113
+ cp = _measure_facade.Path(str(flag.get("checkpoint") or ""))
4114
+ # Only a file in one of Token Optimizer's own checkpoint folders is read.
4115
+ homes = {str((d / "checkpoints").resolve()) for d in _measure_facade._status_bar_quality_cache_dirs()}
4116
+ if cp.suffix != ".md" or str(cp.resolve().parent) not in homes:
4117
+ return None
4118
+ epoch = int(cp.stat().st_mtime)
4119
+ except (OSError, ValueError, AttributeError, TypeError, RuntimeError):
4120
+ return None
4121
+ if not cp.name or cp.name.startswith(session_id):
4122
+ return None
4123
+ try:
4124
+ about = _measure_facade._checkpoint_descriptor(cp) or None
4125
+ except Exception:
4126
+ about = None
4127
+ return {"epoch": epoch, "about": about}
4128
+
4129
+
4130
+ def _status_bar_prompt_cache(session_id):
4131
+ """The session's native prompt_cache object, bridged by statusline.js, or None.
4132
+
4133
+ Claude Code v2.1.251+ hands the status line a `prompt_cache` object
4134
+ (ttl, expires_at, warm, hit_ratio, ...; main conversations only).
4135
+ statusline.js mirrors it to prompt-cache-<sid>.json so this payload can
4136
+ source the cache countdown/cold state from it instead of guessing from
4137
+ the transcript. Stale or malformed files fall back to the transcript.
4138
+ """
4139
+ _measure_facade = _compat.facade()
4140
+ best = _measure_facade._status_bar_freshest(f"prompt-cache-{session_id}.json")
4141
+ if best is None:
4142
+ return None
4143
+ try:
4144
+ data = _measure_facade.json.loads(best.read_text(encoding="utf-8"))
4145
+ except (OSError, ValueError):
4146
+ return None
4147
+ if not isinstance(data, dict):
4148
+ return None
4149
+ try:
4150
+ if _measure_facade.time.time() - float(data.get("timestamp", 0)) / 1000 > _measure_facade._PROMPT_CACHE_SIDECAR_MAX_AGE_S:
4151
+ return None
4152
+ except (TypeError, ValueError):
4153
+ return None
4154
+ ttl = data.get("ttl")
4155
+ if ttl not in ("5m", "1h"):
4156
+ ttl = None
4157
+ try:
4158
+ expires_at = int(data["expires_at"]) if data.get("expires_at") is not None else None
4159
+ except (TypeError, ValueError):
4160
+ expires_at = None
4161
+ warm = data.get("warm") if isinstance(data.get("warm"), bool) else None
4162
+ return {"ttl": ttl, "expires_at": expires_at, "warm": warm}
4163
+
4164
+
4165
+ def status_bar_payload(session_id, transcript=None, sync=None):
4166
+ """Build the status-bar JSON object (see STATUS_BAR_HELP). Never raises."""
4167
+ _measure_facade = _compat.facade()
4168
+ sid = _measure_facade.sanitize_session_id(session_id)
4169
+ session_note = None
4170
+ # --session may carry a pasted truncated id. A <6-char id
4171
+ # sanitizes to "unknown"; a longer prefix finds no exact transcript.
4172
+ # Resolve a UNIQUE prefix to the real session; when it matches zero or
4173
+ # many, say so in savings_reason instead of degrading silently.
4174
+ prefix = _measure_facade.re.sub(r"[^a-zA-Z0-9_-]", "", str(session_id or ""))
4175
+ try:
4176
+ path = _measure_facade.Path(transcript) if transcript else (
4177
+ _measure_facade._find_session_jsonl_by_id(sid) if sid != "unknown" else None)
4178
+ except Exception:
4179
+ path = None
4180
+ if path is None and prefix:
4181
+ matches = _measure_facade._session_id_prefix_matches(prefix)
4182
+ if len(matches) == 1:
4183
+ path = matches[0]
4184
+ sid = matches[0].stem
4185
+ elif len(matches) > 1:
4186
+ session_note = ("session id prefix '%s' is ambiguous "
4187
+ "(%d sessions match)" % (prefix, len(matches)))
4188
+ elif sid == "unknown":
4189
+ session_note = "no session id matches '%s'" % prefix
4190
+ out = {
4191
+ "schema": _measure_facade._STATUS_BAR_SCHEMA,
4192
+ "session_id": sid,
4193
+ "savings": None,
4194
+ "savings_state": "unavailable",
4195
+ "savings_age_s": None,
4196
+ "savings_reason": None,
4197
+ "refresh_started": False,
4198
+ "last_request_epoch": None,
4199
+ "cache_lifetime": None,
4200
+ "cache_expires_at": None,
4201
+ "cache_warm": None,
4202
+ "cache_source": None,
4203
+ "compactWindow": {"tokens": None, "source": "unresolved"},
4204
+ "last_checkpoint_epoch": None,
4205
+ "earlier_checkpoint": None,
4206
+ "compactions": None,
4207
+ }
4208
+ if sid == "unknown" or session_note:
4209
+ out["savings_reason"] = session_note or "no session id"
4210
+ return out
4211
+
4212
+ try:
4213
+ session_model = None
4214
+ if path is not None:
4215
+ out["last_request_epoch"], out["cache_lifetime"], session_model = (
4216
+ _measure_facade._status_bar_transcript_state(path))
4217
+ out["compactions"] = _measure_facade._status_bar_compactions(path, sid)
4218
+ # The native prompt_cache object (v2.1.251+) is authoritative for the
4219
+ # cache countdown/cold state when statusline.js bridged it recently;
4220
+ # the transcript-derived lifetime stays as the fallback.
4221
+ pc = _measure_facade._status_bar_prompt_cache(sid)
4222
+ if pc is not None:
4223
+ if pc["ttl"]:
4224
+ out["cache_lifetime"] = pc["ttl"]
4225
+ out["cache_expires_at"] = pc["expires_at"]
4226
+ out["cache_warm"] = pc["warm"]
4227
+ out["cache_source"] = "prompt_cache"
4228
+ elif out["cache_lifetime"] is not None:
4229
+ out["cache_source"] = "transcript"
4230
+ # The resolver's compact window for THIS session's model, so the band
4231
+ # can honor /autocompact and autoCompactWindow, not just the env var.
4232
+ # tokens is null when no override is known: the band then uses the
4233
+ # host's own reported number.
4234
+ model = session_model or _measure_facade.os.environ.get("CLAUDE_MODEL") or _measure_facade.os.environ.get("ANTHROPIC_MODEL")
4235
+ resolved = _measure_facade._resolve_compact_window(model)
4236
+ out["compactWindow"] = {
4237
+ "tokens": resolved["tokens"] if resolved["user_override"] else None,
4238
+ "source": resolved["source"],
4239
+ }
4240
+ except Exception:
4241
+ pass
4242
+ try:
4243
+ out["last_checkpoint_epoch"] = _measure_facade._status_bar_checkpoint_epoch(sid)
4244
+ except Exception:
4245
+ pass
4246
+ try:
4247
+ out["earlier_checkpoint"] = _measure_facade._status_bar_earlier_checkpoint(sid)
4248
+ except Exception:
4249
+ pass
4250
+
4251
+ try:
4252
+ if sync:
4253
+ savings, reason = _measure_facade._status_bar_savings_or_reason(sid)
4254
+ try:
4255
+ _measure_facade._status_bar_write_cache(sid, savings, reason)
4256
+ except OSError:
4257
+ pass
4258
+ out["savings"], out["savings_reason"] = savings, reason
4259
+ out["savings_age_s"] = 0.0
4260
+ out["savings_state"] = "fresh" if savings is not None else "unavailable"
4261
+ return out
4262
+ if not _measure_facade.Path(_measure_facade.TRENDS_DB).exists():
4263
+ out["savings_reason"] = "no savings recorded yet"
4264
+ return out
4265
+ cached = _measure_facade._status_bar_read_cache(sid)
4266
+ if cached is None:
4267
+ out["savings_state"] = "loading"
4268
+ out["savings_reason"] = "computing savings"
4269
+ out["refresh_started"] = _measure_facade._status_bar_start_refresh(sid)
4270
+ return out
4271
+ age = max(0.0, _measure_facade.time.time() - float(cached["computed_at"]))
4272
+ out["savings"] = cached.get("savings")
4273
+ out["savings_reason"] = cached.get("reason") if out["savings"] is None else None
4274
+ out["savings_age_s"] = round(age, 1)
4275
+ stale = age > _measure_facade._STATUS_BAR_CACHE_MAX_AGE_S
4276
+ if out["savings"] is None:
4277
+ out["savings_state"] = "unavailable"
4278
+ else:
4279
+ out["savings_state"] = "stale" if stale else "fresh"
4280
+ if stale:
4281
+ out["refresh_started"] = _measure_facade._status_bar_start_refresh(sid)
4282
+ except Exception:
4283
+ out["savings"] = None
4284
+ out["savings_state"] = "unavailable"
4285
+ out["savings_reason"] = "savings unavailable"
4286
+ return out
4287
+
4288
+
4289
+ def _status_bar_cli(args):
4290
+ """`status-bar` subcommand. Prints one JSON object; exit 0 (2 on bad usage)."""
4291
+ _measure_facade = _compat.facade()
4292
+ if "--help" in args or "-h" in args:
4293
+ print(_measure_facade.STATUS_BAR_HELP)
4294
+ _measure_facade.sys.exit(0)
4295
+
4296
+ def _opt(name):
4297
+ _measure_facade = _compat.facade()
4298
+ if name in args:
4299
+ i = args.index(name)
4300
+ # A following flag is not a value: `--session --json` has no session.
4301
+ if i + 1 < len(args) and not args[i + 1].startswith("--"):
4302
+ return args[i + 1]
4303
+ return None
4304
+
4305
+ session = _opt("--session")
4306
+ if not session:
4307
+ print(_measure_facade.STATUS_BAR_HELP, file=_measure_facade.sys.stderr)
4308
+ _measure_facade.sys.exit(2)
4309
+ sync = "--sync" in args
4310
+ child = sync and "--release-lock" in args
4311
+ sid = _measure_facade.sanitize_session_id(session)
4312
+ token = _measure_facade.os.environ.get(_measure_facade._STATUS_BAR_LOCK_TOKEN_ENV, "") if child else None
4313
+ if sync and not child:
4314
+ # A direct --sync takes the same lock as the background refresh; when one is
4315
+ # already running, this answers from the cache instead of computing twice.
4316
+ token = _measure_facade._status_bar_acquire_lock(sid) if sid != "unknown" else None
4317
+ if token is None:
4318
+ sync = False
4319
+ # The background child gets a hard wall-clock budget: a hung read never lingers.
4320
+ def _out_of_time():
4321
+ # Killed by its budget: leave a reason for the band and free the lock.
4322
+ _measure_facade = _compat.facade()
4323
+ try:
4324
+ _measure_facade._status_bar_write_cache(sid, None, "savings took too long to compute")
4325
+ except OSError:
4326
+ pass
4327
+ _measure_facade._status_bar_release_lock(sid, token)
4328
+ _measure_facade._log_spawn_failure("status-bar refresh child ran out of time")
4329
+
4330
+ budget = _measure_facade._install_hook_budget(_measure_facade._STATUS_BAR_CHILD_BUDGET_S, on_timeout=_out_of_time) if child else None
4331
+ try:
4332
+ payload = _measure_facade.status_bar_payload(session, transcript=_opt("--transcript"), sync=sync)
4333
+ except Exception:
4334
+ payload = {"schema": _measure_facade._STATUS_BAR_SCHEMA, "session_id": sid, "savings": None,
4335
+ "savings_state": "unavailable", "savings_reason": "savings unavailable"}
4336
+ finally:
4337
+ if token:
4338
+ _measure_facade._status_bar_release_lock(sid, token)
4339
+ if budget is not None:
4340
+ try:
4341
+ budget.cancel()
4342
+ except Exception:
4343
+ pass
4344
+ # Always one JSON object, exit 0: JSON has no Infinity or NaN, so those read as null.
4345
+ print(_measure_facade.json.dumps(_measure_facade._status_bar_finite(payload), allow_nan=False))
4346
+ _measure_facade.sys.exit(0)
4347
+
4348
+
4349
+ def _status_bar_finite(v):
4350
+ """The payload with every non-finite float (inf, nan) replaced by None."""
4351
+ _measure_facade = _compat.facade()
4352
+ if isinstance(v, float):
4353
+ return v if _measure_facade.math.isfinite(v) else None
4354
+ if isinstance(v, dict):
4355
+ return {k: _measure_facade._status_bar_finite(x) for k, x in v.items()}
4356
+ if isinstance(v, (list, tuple)):
4357
+ return [_measure_facade._status_bar_finite(x) for x in v]
4358
+ return v