@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,1231 @@
1
+ """Definition-only implementations; mutable state belongs to measure."""
2
+ from __future__ import annotations
3
+ from . import _compat
4
+
5
+
6
+ def _safe_int(value):
7
+ """Coerce to int, mapping non-finite/garbage input to 0.
8
+
9
+ Claude-path equivalent of codex_session._safe_int: json.loads accepts the
10
+ non-standard Infinity/NaN literals, so a corrupt or hostile transcript can
11
+ put float("inf")/nan into usage fields where int() then raises
12
+ OverflowError/ValueError — neither caught by the readers' OSError guards.
13
+ """
14
+ _measure_facade = _compat.facade()
15
+ try:
16
+ return int(float(value or 0))
17
+ except (TypeError, ValueError, OverflowError):
18
+ return 0
19
+
20
+
21
+ def _windows_stdio_kwargs():
22
+ """Usable std streams to hand a console-less child on Windows, else {}.
23
+
24
+ With creationflags=CREATE_NO_WINDOW and no std streams, a Windows child gets
25
+ a hidden console (python.exe) or NULL handles (pythonw.exe), so everything
26
+ it prints is lost. Passing the parent's streams makes CPython hand the child
27
+ the parent's own handles. Same guard as hooks/run.py (kept as a copy: this
28
+ script must not import from hooks/). Off Windows the child inherits the
29
+ streams anyway, so nothing is added.
30
+ """
31
+ _measure_facade = _compat.facade()
32
+ if _measure_facade.sys.platform != "win32":
33
+ return {}
34
+ kwargs = {}
35
+ missing = []
36
+ for name in ("stdin", "stdout", "stderr"):
37
+ stream = getattr(_measure_facade.sys, name, None)
38
+ if stream is None:
39
+ missing.append(name)
40
+ continue
41
+ try:
42
+ stream.fileno()
43
+ except (AttributeError, OSError, ValueError):
44
+ missing.append(name)
45
+ continue
46
+ kwargs[name] = stream
47
+ # Same rule as hooks/run.py: a stream left out falls back to a possibly
48
+ # stale handle and the spawn fails, so an unusable one gets DEVNULL.
49
+ if kwargs:
50
+ for name in missing:
51
+ kwargs[name] = _measure_facade.subprocess.DEVNULL
52
+ return kwargs
53
+
54
+
55
+ def _run_script_child(script, extra_args=None, **run_kwargs):
56
+ """Run a sibling script under this interpreter with its output visible."""
57
+ _measure_facade = _compat.facade()
58
+ return _measure_facade.subprocess.run(
59
+ [_measure_facade.sys.executable, str(script), *extra_args],
60
+ creationflags=_measure_facade._NO_WINDOW,
61
+ **_measure_facade._windows_stdio_kwargs(),
62
+ **run_kwargs,
63
+ )
64
+
65
+
66
+ def _detached_python_exe():
67
+ """Interpreter to use for FIRE-AND-FORGET python children.
68
+
69
+ Belt-and-suspenders on top of the detach flags: on Windows,
70
+ prefer the GUI-subsystem ``pythonw.exe`` twin next to ``sys.executable`` so
71
+ the child cannot allocate a console even if a future edit drops
72
+ ``DETACHED_PROCESS``/``CREATE_NO_WINDOW``, or a host launches us in a way we
73
+ do not control. Falls back to ``sys.executable`` when no usable twin exists
74
+ (MS Store alias, no twin) and is a pure no-op off Windows -- POSIX behaviour
75
+ is byte-identical.
76
+
77
+ ONLY for children whose stdio is DEVNULL. Do NOT use it for
78
+ ``capture_output=True`` runs: those already suppress the window via
79
+ ``creationflags=_NO_WINDOW``, and swapping the interpreter there would trade
80
+ a solved problem for pythonw's None-stdio semantics.
81
+ """
82
+ _measure_facade = _compat.facade()
83
+ return _measure_facade._windows_gui_python() or _measure_facade.sys.executable or "python3"
84
+
85
+
86
+ def _is_foreign_runtime() -> bool:
87
+ """True when running under a runtime whose audit target is NOT ~/.claude."""
88
+ _measure_facade = _compat.facade()
89
+ return _measure_facade.detect_runtime() in _measure_facade._FOREIGN_RUNTIMES
90
+
91
+
92
+ def _copilot_audit_notice() -> None:
93
+ """Explain why the Claude audit does not run under Copilot, and where to go."""
94
+ _measure_facade = _compat.facade()
95
+ print("Token Optimizer — GitHub Copilot runtime detected.")
96
+ print()
97
+ print("This audit targets a Claude Code / Codex setup (it scans ~/.claude), so it")
98
+ print("will not run here and will not modify ~/.claude or your Copilot config.")
99
+ print()
100
+ print("On GitHub Copilot, use the Copilot-native commands instead:")
101
+ print(" measure.py copilot-summary — session cost/quality summary")
102
+ print(" measure.py copilot-rollup — collect sessions into trends")
103
+ print(" measure.py copilot-doctor — readiness + hook capability probe")
104
+ print(" measure.py copilot-install — wire Token Optimizer into ~/.copilot")
105
+ print(" measure.py copilot-home — print resolved Copilot home (auto-detects WSL; override via TOKEN_OPTIMIZER_COPILOT_HOME)")
106
+ print()
107
+ print("To force this skill onto a specific runtime, set TOKEN_OPTIMIZER_RUNTIME.")
108
+
109
+
110
+ def _cursor_audit_notice() -> None:
111
+ """Explain why the Claude audit does not run under Cursor, and where to go."""
112
+ _measure_facade = _compat.facade()
113
+ print("Token Optimizer — Cursor runtime detected.")
114
+ print()
115
+ print("This audit targets a Claude Code / Codex setup (it scans ~/.claude), so it")
116
+ print("will not run here and will not modify ~/.claude or your Cursor config.")
117
+ print()
118
+ print("On Cursor, use the Cursor-native commands instead:")
119
+ print(" measure.py cursor-summary — session token/quality summary")
120
+ print(" measure.py cursor-rollup — collect sessions into trends")
121
+ print(" measure.py cursor-doctor — readiness + hook firing probe")
122
+ print(" measure.py cursor-install — wire Token Optimizer into ~/.cursor/hooks.json")
123
+ print(" measure.py cursor-uninstall — remove Token Optimizer's Cursor entries")
124
+
125
+
126
+ def _grok_audit_notice() -> None:
127
+ """Explain why the Claude audit does not run under Grok Build, and where to go."""
128
+ _measure_facade = _compat.facade()
129
+ print("Token Optimizer — Grok Build runtime detected.")
130
+ print()
131
+ print("This audit targets a Claude Code / Codex setup (it scans ~/.claude), so it")
132
+ print("will not run here and will not modify ~/.claude or your Grok config.")
133
+ print()
134
+ print("On Grok Build, use the Grok-native commands instead:")
135
+ print(" measure.py grok-summary — session token/cost summary")
136
+ print(" measure.py grok-rollup — collect sessions into trends")
137
+ print(" measure.py grok-doctor — readiness + hook probe")
138
+ print(" measure.py grok-install — wire Token Optimizer into $GROK_HOME/hooks/")
139
+ print(" measure.py grok-home — print resolved Grok home (override via TOKEN_OPTIMIZER_GROK_HOME)")
140
+ print()
141
+ print("To force this skill onto a specific runtime, set TOKEN_OPTIMIZER_RUNTIME.")
142
+
143
+
144
+ def _foreign_audit_notice() -> None:
145
+ """Route to the right per-runtime notice for blocked Claude-target commands.
146
+
147
+ Dispatch is table-driven so adding a foreign runtime means one entry here
148
+ plus _FOREIGN_RUNTIMES — never a fall-through to another runtime's notice.
149
+ """
150
+ _measure_facade = _compat.facade()
151
+ notices = {
152
+ "opencode": _measure_facade._opencode_audit_notice,
153
+ "copilot": _measure_facade._copilot_audit_notice,
154
+ "hermes": _measure_facade._hermes_audit_notice,
155
+ "cursor": _measure_facade._cursor_audit_notice,
156
+ "antigravity": _measure_facade._antigravity_audit_notice,
157
+ "grok": _measure_facade._grok_audit_notice,
158
+ "devin": _measure_facade._devin_audit_notice,
159
+ }
160
+ handler = notices.get(_measure_facade.detect_runtime())
161
+ if handler is not None:
162
+ handler()
163
+ else: # future foreign runtime without a notice yet: generic, never wrong
164
+ print(f"Token Optimizer — {_measure_facade.runtime_name_for_humans()} runtime detected.")
165
+ print("Claude-targeting commands are disabled here; they scan/modify ~/.claude.")
166
+ print("Set TOKEN_OPTIMIZER_RUNTIME to force a specific runtime.")
167
+
168
+
169
+ def _devin_audit_notice() -> None:
170
+ _measure_facade = _compat.facade()
171
+ print("Token Optimizer - Devin CLI runtime detected.")
172
+ print("Claude-targeting commands will not run here or modify ~/.claude.")
173
+ print("Use devin-install, devin-doctor, devin-summary or devin-filter.")
174
+ print("No native dashboard, quality, savings or provider collector is available.")
175
+
176
+
177
+ def _opencode_audit_notice() -> None:
178
+ """Explain why the Claude audit does not run under OpenCode, and where to go.
179
+
180
+ Printed instead of scanning/mutating ~/.claude when OpenCode is detected.
181
+ """
182
+ _measure_facade = _compat.facade()
183
+ print("Token Optimizer — OpenCode runtime detected.")
184
+ print()
185
+ print("This audit targets a Claude Code / Codex setup (it scans ~/.claude), so it")
186
+ print("will not run here and will not modify ~/.claude or your OpenCode config.")
187
+ print()
188
+ print("On OpenCode, Token Optimizer runs automatically as a plugin:")
189
+ print(" - Live context-quality, savings, and continuity tracking via session hooks")
190
+ print(" - Dashboard / status: run the `token_dashboard` or `token_status` tool")
191
+ print()
192
+ print("Install or refresh the OpenCode plugin (builds the native TS plugin")
193
+ print("into ~/.config/opencode/plugins/, NOT the ~/.claude skill tree):")
194
+ print(" install.sh --opencode")
195
+ print(" or via npm: opencode plugin token-optimizer-opencode")
196
+ print()
197
+ print("To force this skill onto a specific runtime, set TOKEN_OPTIMIZER_RUNTIME.")
198
+
199
+
200
+ def _hermes_audit_notice() -> None:
201
+ """Explain why the Claude audit does not run under Hermes, and where to go.
202
+
203
+ Printed instead of scanning/mutating ~/.claude when Hermes is detected.
204
+ Hermes sessions live in ~/.hermes/state.db (read via the hermes_session
205
+ adapter), not ~/.claude/projects JSONL, so the Claude-targeting scan
206
+ commands would scan the wrong tree and produce empty output.
207
+ """
208
+ _measure_facade = _compat.facade()
209
+ print("Token Optimizer — Hermes runtime detected.")
210
+ print()
211
+ print("This audit targets a Claude Code / Codex setup (it scans ~/.claude), so it")
212
+ print("will not run here and will not modify ~/.claude or your Hermes config.")
213
+ print()
214
+ print("On Hermes, use the Hermes-native commands instead:")
215
+ print(" measure.py hermes-summary — session cost/quality summary")
216
+ print(" measure.py hermes-rollup — collect sessions into trends")
217
+ print(" measure.py hermes-doctor — readiness + hook capability probe")
218
+ print(" measure.py hermes-install — wire Token Optimizer into ~/.hermes/plugins/")
219
+ print(" measure.py dashboard — open the Hermes dashboard (port 24844)")
220
+ print()
221
+ print("To force this skill onto a specific runtime, set TOKEN_OPTIMIZER_RUNTIME.")
222
+
223
+
224
+ def _antigravity_audit_notice() -> None:
225
+ """Explain why the Claude audit does not run under Antigravity, and where to go.
226
+
227
+ Printed instead of scanning/mutating ~/.claude when Antigravity is detected.
228
+ Antigravity sessions live in the read-only conversation store under
229
+ ~/.gemini (read via the antigravity_state adapter), not ~/.claude/projects
230
+ JSONL, so the Claude-targeting scan commands would scan the wrong tree and
231
+ produce empty output.
232
+ """
233
+ _measure_facade = _compat.facade()
234
+ print("Token Optimizer — Google Antigravity runtime detected.")
235
+ print()
236
+ print("This audit targets a Claude Code / Codex setup (it scans ~/.claude), so it")
237
+ print("will not run here and will not modify ~/.claude or your Antigravity config.")
238
+ print()
239
+ print("On Antigravity, use the Antigravity-native commands instead:")
240
+ print(" measure.py antigravity-summary — session cost/quality summary")
241
+ print(" measure.py antigravity-rollup — collect sessions into trends")
242
+ print(" measure.py antigravity-doctor — readiness + hook capability probe")
243
+ print(" measure.py antigravity-install — wire Token Optimizer into ~/.gemini/config/plugins/")
244
+ print(" measure.py antigravity-home — print resolved Antigravity home (override via TOKEN_OPTIMIZER_ANTIGRAVITY_HOME)")
245
+ print(" measure.py dashboard — open the Antigravity dashboard (port 24847)")
246
+ print()
247
+ print("To force this skill onto a specific runtime, set TOKEN_OPTIMIZER_RUNTIME.")
248
+
249
+
250
+ def _windows_profile_dir():
251
+ """The Windows account's profile dir as the OS records it, independent of
252
+ the USERPROFILE / HOME environment variables (Path.home() reads those):
253
+ SHGetKnownFolderPath(FOLDERID_Profile). None off Windows or on any failure,
254
+ never a guess such as %SystemDrive%\\Users\\%USERNAME% (profiles can live
255
+ on another drive, and a wrong guess would refuse a real user's scheduler)."""
256
+ _measure_facade = _compat.facade()
257
+ if _measure_facade.os.name != "nt":
258
+ return None
259
+ try:
260
+ import ctypes
261
+ import uuid
262
+ from ctypes import wintypes
263
+
264
+ class _GUID(ctypes.Structure):
265
+ _fields_ = [("Data1", wintypes.DWORD), ("Data2", wintypes.WORD),
266
+ ("Data3", wintypes.WORD), ("Data4", ctypes.c_ubyte * 8)]
267
+
268
+ raw = uuid.UUID("{5E6C858F-0E22-4760-9AFE-EA3317B67173}").bytes_le # FOLDERID_Profile
269
+ guid = _GUID.from_buffer_copy(raw)
270
+ out = ctypes.c_wchar_p()
271
+ shell32 = ctypes.windll.shell32
272
+ hr = shell32.SHGetKnownFolderPath(ctypes.byref(guid), 0, None, ctypes.byref(out))
273
+ try:
274
+ value = out.value if hr == 0 else None
275
+ finally:
276
+ ctypes.windll.ole32.CoTaskMemFree(out)
277
+ return _measure_facade.Path(value) if value else None
278
+ except Exception:
279
+ return None
280
+
281
+
282
+ def _real_account_home():
283
+ """The OS account's own home directory, never read from HOME/USERPROFILE:
284
+ the pwd entry for this uid on POSIX, the profile folder the OS records on
285
+ Windows. None where it cannot be known (no pwd entry, API failure)."""
286
+ _measure_facade = _compat.facade()
287
+ if _measure_facade._ACCOUNT_HOME_IS_WINDOWS:
288
+ return _measure_facade._windows_profile_dir()
289
+ try:
290
+ import pwd # POSIX only
291
+ raw = pwd.getpwuid(_measure_facade.os.getuid()).pw_dir
292
+ return _measure_facade.Path(raw) if raw else None
293
+ except Exception:
294
+ return None
295
+
296
+
297
+ def _same_path(a, b):
298
+ """True when two paths name the same directory: equal as typed (case-folded
299
+ on Windows), equal once symlinks resolve, or the same inode. HPC/NFS homes
300
+ often reach one directory through an automount symlink and a real mount
301
+ path, so no single comparison is enough on its own."""
302
+ _measure_facade = _compat.facade()
303
+ try:
304
+ if _measure_facade.os.path.normcase(_measure_facade.os.path.abspath(str(a))) == _measure_facade.os.path.normcase(_measure_facade.os.path.abspath(str(b))):
305
+ return True
306
+ except (OSError, ValueError, TypeError):
307
+ pass
308
+ try:
309
+ if _measure_facade.Path(a).resolve() == _measure_facade.Path(b).resolve():
310
+ return True
311
+ except (OSError, RuntimeError, ValueError):
312
+ pass
313
+ try:
314
+ return _measure_facade.os.path.samefile(str(a), str(b))
315
+ except (OSError, ValueError, TypeError):
316
+ return False
317
+
318
+
319
+ def _is_under(child, parent):
320
+ """``child`` is ``parent`` or inside it, compared resolved and as typed."""
321
+ _measure_facade = _compat.facade()
322
+ try:
323
+ _measure_facade.Path(child).resolve().relative_to(_measure_facade.Path(parent).resolve())
324
+ return True
325
+ except (ValueError, OSError, RuntimeError):
326
+ pass
327
+ try:
328
+ _measure_facade.Path(_measure_facade.os.path.normcase(_measure_facade.os.path.abspath(str(child)))).relative_to(
329
+ _measure_facade.os.path.normcase(_measure_facade.os.path.abspath(str(parent))))
330
+ return True
331
+ except (ValueError, OSError, RuntimeError, TypeError):
332
+ return False
333
+
334
+
335
+ def _foreign_home_override():
336
+ _measure_facade = _compat.facade()
337
+ return _measure_facade.os.environ.get(_measure_facade._FOREIGN_HOME_OVERRIDE_ENV, "").strip() == "1"
338
+
339
+
340
+ def _compute_home_redirected():
341
+ """True when the home this process derives its paths from (HOME on POSIX,
342
+ USERPROFILE on Windows, via Path.home()) is not the account's own home: a
343
+ test sandbox, a scratch e2e run, a second HOME on one account.
344
+
345
+ launchd / systemd --user / Task Scheduler jobs are per ACCOUNT, not per
346
+ HOME, and TO's labels are fixed (com.token-optimizer.dashboard, ...). A
347
+ redirected-HOME run that installs or restarts one of them re-points the
348
+ user's LIVE job at the throwaway home (seen 2026-10-19: an e2e run's
349
+ SessionStart re-bootstrapped the real dashboard agent to a scratch dir).
350
+
351
+ The Claude home is NOT compared: Claude Code supports CLAUDE_CONFIG_DIR
352
+ anywhere (claude_home()), and a real user with HOME at home and the config
353
+ on /opt or a volume must keep their dashboard, keep-warm, restart and
354
+ uninstall. The case that guard used to cover (real HOME, scratch
355
+ CLAUDE_CONFIG_DIR) is caught instead by _scheduler_job_points_elsewhere():
356
+ refuse only when an existing job belongs to a different install.
357
+
358
+ TOKEN_OPTIMIZER_ALLOW_FOREIGN_HOME_SCHEDULER=1 is the explicit escape hatch
359
+ for a setup that really does run the daemon from a relocated home."""
360
+ _measure_facade = _compat.facade()
361
+ if _measure_facade._foreign_home_override():
362
+ return False
363
+ real = _measure_facade._real_account_home()
364
+ if real is None:
365
+ return False
366
+ try:
367
+ return not _measure_facade._same_path(_measure_facade.HOME, real)
368
+ except Exception:
369
+ return False
370
+
371
+
372
+ def _daemon_snapshot_sandboxed():
373
+ """True when this process must not touch the per-account scheduler jobs
374
+ (dashboard daemon, keep-warm agent) AT ALL, uninstall included:
375
+
376
+ * an explicit TOKEN_OPTIMIZER_SNAPSHOT_DIR override (tests, sandboxes);
377
+ * HOME / USERPROFILE is not the account's real home (see
378
+ _compute_home_redirected). Removal goes by fixed label
379
+ (``launchctl bootout gui/<uid>/<label>``, ``schtasks /Delete /TN``,
380
+ ``systemctl --user disable``), so a scratch-HOME "uninstall" would kill
381
+ the user's live job just as surely as an install re-points it.
382
+
383
+ Uninstall and status paths check only this. Every path that writes,
384
+ reloads or restarts a job checks _scheduler_install_refused(), which adds
385
+ the existing-job check. Both inputs are frozen at import so later env
386
+ drift cannot separate the guard from the paths it protects.
387
+ """
388
+ _measure_facade = _compat.facade()
389
+ return bool(_measure_facade._SNAPSHOT_DIR_OVERRIDE) or _measure_facade._HOME_REDIRECTED
390
+
391
+
392
+ def _scheduler_install_refused():
393
+ """True when an install / restart / revive / repair must not run: the
394
+ process is sandboxed (above), or, from the account's real home, a job
395
+ already registered for this account points at a different install than
396
+ this process (another CLAUDE_CONFIG_DIR or data dir), so writing ours would
397
+ re-point it. A CLAUDE_CONFIG_DIR outside the home is fine on its own: with
398
+ no job, or with a job that is this install's, nothing is refused.
399
+ TOKEN_OPTIMIZER_ALLOW_FOREIGN_HOME_SCHEDULER=1 lifts the job check."""
400
+ _measure_facade = _compat.facade()
401
+ if _measure_facade._daemon_snapshot_sandboxed():
402
+ return True
403
+ if _measure_facade._foreign_home_override():
404
+ return False
405
+ return bool(_measure_facade._scheduler_job_points_elsewhere())
406
+
407
+
408
+ def _reset_job_guard_cache():
409
+ _measure_facade = _compat.facade()
410
+ _measure_facade._WINDOWS_TASK_PATHS_CACHE.clear()
411
+
412
+
413
+ def _windows_task_job_paths_cached():
414
+ _measure_facade = _compat.facade()
415
+ key = (_measure_facade._windows_task_job_paths, _measure_facade.WINDOWS_TASK_NAME)
416
+ hit = _measure_facade._WINDOWS_TASK_PATHS_CACHE.get(key)
417
+ now = _measure_facade.time.monotonic()
418
+ if hit and now - hit[0] < _measure_facade._WINDOWS_TASK_PATHS_TTL_S:
419
+ return hit[1]
420
+ paths = _measure_facade._windows_task_job_paths()
421
+ _measure_facade._WINDOWS_TASK_PATHS_CACHE.clear()
422
+ _measure_facade._WINDOWS_TASK_PATHS_CACHE[key] = (now, paths)
423
+ return paths
424
+
425
+
426
+ def _this_install_roots():
427
+ _measure_facade = _compat.facade()
428
+ roots = []
429
+ for value in (_measure_facade.CLAUDE_DIR, _measure_facade.RUNTIME_DIR, _measure_facade.SNAPSHOT_DIR, _measure_facade._RESOLVED_PLUGIN_DATA,
430
+ _measure_facade.Path(_measure_facade.__file__).resolve().parents[3]):
431
+ if value:
432
+ roots.append(_measure_facade.Path(value))
433
+ return roots
434
+
435
+
436
+ def _plist_job_paths(path):
437
+ _measure_facade = _compat.facade()
438
+ import plistlib
439
+ try:
440
+ with open(path, "rb") as fh:
441
+ data = plistlib.load(fh)
442
+ except Exception:
443
+ return []
444
+ if not isinstance(data, dict):
445
+ return []
446
+ out = [a for a in (data.get("ProgramArguments") or [])[1:] if isinstance(a, str)]
447
+ out += [data.get(k) for k in ("StandardOutPath", "StandardErrorPath", "WorkingDirectory")
448
+ if isinstance(data.get(k), str)]
449
+ return out
450
+
451
+
452
+ def _systemd_unit_job_paths(path):
453
+ _measure_facade = _compat.facade()
454
+ try:
455
+ text = _measure_facade.Path(path).read_text(encoding="utf-8", errors="replace")
456
+ except OSError:
457
+ return []
458
+ out = []
459
+ for line in text.splitlines():
460
+ key, _, value = line.partition("=")
461
+ key, value = key.strip(), value.strip()
462
+ if key in ("ExecStart", "WorkingDirectory"):
463
+ out.append(value.strip('"').split('" ', 1)[0].strip('"'))
464
+ elif key in ("StandardOutput", "StandardError") and value.startswith(("append:", "file:")):
465
+ out.append(value.split(":", 1)[1])
466
+ return out
467
+
468
+
469
+ def _windows_task_job_paths():
470
+ """<Command> (when it is not just an interpreter), <Arguments> tokens and
471
+ <WorkingDirectory> of this runtime's registered task. Read-only query."""
472
+ _measure_facade = _compat.facade()
473
+ try:
474
+ query = _measure_facade.subprocess.run(
475
+ ["schtasks", "/Query", "/TN", _measure_facade.WINDOWS_TASK_NAME, "/XML", "ONE"],
476
+ capture_output=True, text=True, errors="replace", timeout=10,
477
+ creationflags=_measure_facade._NO_WINDOW,
478
+ )
479
+ except (OSError, _measure_facade.subprocess.SubprocessError, NameError):
480
+ return []
481
+ if query.returncode != 0:
482
+ return []
483
+ raw = (query.stdout or "").replace("\x00", "")
484
+ out = []
485
+ for tag in ("Command", "Arguments", "WorkingDirectory"):
486
+ m = _measure_facade.re.search(r"<%s>(.*?)</%s>" % (tag, tag), raw, _measure_facade.re.S | _measure_facade.re.I)
487
+ if not m:
488
+ continue
489
+ value = m.group(1).strip()
490
+ if tag == "Command" and _measure_facade.re.split(r"[\\/]", value.strip('"'))[-1].lower().startswith("python"):
491
+ continue
492
+ out += [t.strip('"') for t in _measure_facade.re.findall(r'"[^"]*"|\S+', value)] if tag == "Arguments" \
493
+ else [value.strip('"')]
494
+ return [p for p in out if _measure_facade.re.match(r"^([A-Za-z]:[\\/]|[\\/])", p)]
495
+
496
+
497
+ def _scheduler_job_paths():
498
+ """{artifact: [absolute paths it runs or writes]} for every per-account job
499
+ this process could touch, read from where this process would write them."""
500
+ _measure_facade = _compat.facade()
501
+ jobs = {}
502
+ system = _measure_facade._normalized_platform()
503
+ if system == "Darwin":
504
+ for plist in (_measure_facade.PLIST_PATH, _measure_facade._keepwarm_scheduler_plist_path()):
505
+ if plist.is_file():
506
+ jobs[str(plist)] = _measure_facade._plist_job_paths(plist)
507
+ elif system == "Linux":
508
+ unit = _measure_facade._systemd_user_unit_path()
509
+ if unit.is_file():
510
+ jobs[str(unit)] = _measure_facade._systemd_unit_job_paths(unit)
511
+ elif system == "Windows":
512
+ paths = _measure_facade._windows_task_job_paths_cached()
513
+ if paths:
514
+ jobs["task:" + _measure_facade.WINDOWS_TASK_NAME] = paths
515
+ return jobs
516
+
517
+
518
+ def _scheduler_job_points_elsewhere():
519
+ """The first per-account job that belongs to a different install (none of
520
+ its paths sit under this process's Claude home, runtime home, data dirs or
521
+ plugin root) while at least one of them still exists, as
522
+ ``"<artifact> -> <existing path>"``; '' when there is none, when no job
523
+ exists, when the job only points at paths that are gone (a stale job is
524
+ repaired, not protected), or when it cannot be read (fail open)."""
525
+ _measure_facade = _compat.facade()
526
+ answer = ""
527
+ try:
528
+ roots = _measure_facade._this_install_roots()
529
+ for artifact, paths in _measure_facade._scheduler_job_paths().items():
530
+ paths = [p for p in paths if p]
531
+ if not paths or any(_measure_facade._is_under(p, r) for p in paths for r in roots):
532
+ continue
533
+ # A job is another install's only while that install still exists:
534
+ # at least one path it runs or writes is on disk. A dead job (account
535
+ # renamed by Migration Assistant, CLAUDE_CONFIG_DIR moved, old data
536
+ # dir deleted) points at nothing, and refusing to repair it would
537
+ # leave the dashboard broken forever with nobody to own it.
538
+ live = [p for p in paths if _measure_facade.os.path.exists(p)]
539
+ if live:
540
+ answer = "%s -> %s" % (artifact, live[0])
541
+ break
542
+ except Exception:
543
+ answer = ""
544
+ return answer
545
+
546
+
547
+ def _remote_lean_profile():
548
+ """True when this process runs in a Claude Code cloud VM and should skip
549
+ the work that cannot help there.
550
+
551
+ A cloud session is an ephemeral Ubuntu VM (root, no status line, no browser,
552
+ no launchd/systemd user bus, thrown away when the session is reclaimed). In
553
+ that host TO skips: the dashboard daemon install/revive/auto-update and the
554
+ background dashboard regen, keep-warm arm + scheduler repair, the status
555
+ line and hook self-heal writes into ~/.claude/settings.json, the
556
+ cleanupPeriodDays write, the script-install auto-updater, the marketplace
557
+ auto-update tip and the first-run welcome (a fresh VM is a "first run" every
558
+ session). The session-end flush runs inline instead of detached so the data
559
+ lands before the VM can go away. In-session features (compression, read
560
+ dedup, archive/expand, checkpoints, trends.db) are untouched.
561
+
562
+ ``TOKEN_OPTIMIZER_REMOTE_LEAN=0`` turns the profile off (debugging, or a
563
+ long-lived self-hosted VM that does have a desktop). Never raises.
564
+ """
565
+ _measure_facade = _compat.facade()
566
+ try:
567
+ if _measure_facade.os.environ.get("TOKEN_OPTIMIZER_REMOTE_LEAN", "").strip().lower() in ("0", "false", "no", "off"):
568
+ return False
569
+ return _measure_facade.is_claude_code_cloud()
570
+ except Exception:
571
+ return False
572
+
573
+
574
+ def _dashboard_meta_path(html_path):
575
+ """Tiny sidecar recording the (version, shape) a dashboard HTML was generated
576
+ with, so the SessionStart staleness check reads a ~40-byte JSON file instead
577
+ of scanning the 4-5MB HTML every session (the marker can sit megabytes deep
578
+ in __TOKEN_DATA__)."""
579
+ _measure_facade = _compat.facade()
580
+ return _measure_facade.Path(html_path).with_suffix(".meta.json")
581
+
582
+
583
+ def _parse_semver(v):
584
+ """(major, minor, patch) ints for a version string, or None if unparseable.
585
+ Tolerant: strips a leading 'v' and any -pre / +build suffix, pads missing
586
+ components with 0. Used only for precedence comparison, never display."""
587
+ _measure_facade = _compat.facade()
588
+ try:
589
+ core = str(v).strip().lstrip("vV").split("+", 1)[0].split("-", 1)[0]
590
+ parts = (core.split(".") + ["0", "0", "0"])[:3]
591
+ return tuple(int(x) for x in parts)
592
+ except (ValueError, AttributeError, TypeError):
593
+ return None
594
+
595
+
596
+ def _write_dashboard_meta(html_path):
597
+ """Write the (version, shape) sidecar next to a dashboard HTML we just wrote,
598
+ so the sidecar always names the build that produced the on-disk HTML. Every
599
+ writer of a shared dashboard MUST call this after writing, or the downgrade
600
+ guard reads a stale version and can be bypassed. Fail-soft; never raises.
601
+
602
+ atomic meta write: mkstemp + fchmod + os.replace, matching the HTML
603
+ write. A plain Path.write_text truncates-then-writes in place, so a concurrent
604
+ reader between the truncate and the final byte reads a torn/empty sidecar, and
605
+ an interleave of two writers can leave an (html_new, meta_old) pairing that
606
+ lets an OLDER concurrent build's downgrade guard misfire and clobber a NEWER
607
+ dashboard. os.replace makes each reader see one complete sidecar or the prior
608
+ one, never a partial. Callers MUST write this AFTER the HTML os.replace so the
609
+ sidecar never advertises a version whose HTML is not yet on disk."""
610
+ _measure_facade = _compat.facade()
611
+ _measure_facade._write_dashboard_meta_atomic(_measure_facade._dashboard_meta_path(html_path))
612
+
613
+
614
+ def _write_dashboard_meta_atomic(meta_path):
615
+ """Atomically write the current (version, shape) sidecar to ``meta_path``.
616
+ Shared by ``_write_dashboard_meta`` and the inline post-HTML write in
617
+ ``generate_standalone_dashboard`` so both take the identical torn-write-proof
618
+ path. Fail-soft; never raises (a failed sidecar must not break generation)."""
619
+ _measure_facade = _compat.facade()
620
+ meta_path = _measure_facade.Path(meta_path)
621
+ blob = _measure_facade.json.dumps({"version": _measure_facade.TOKEN_OPTIMIZER_VERSION, "shape": _measure_facade._DASHBOARD_SHAPE_MARKER})
622
+ try:
623
+ meta_path.parent.mkdir(parents=True, exist_ok=True)
624
+ tmp_fd, tmp_name = _measure_facade.tempfile.mkstemp(dir=str(meta_path.parent), prefix=".dashmeta-", suffix=".tmp")
625
+ fd_owned = False # True once fdopen's file object owns (and will close) tmp_fd
626
+ try:
627
+ if hasattr(_measure_facade.os, "fchmod"): # POSIX only (os.fchmod is absent on Windows)
628
+ _measure_facade.os.fchmod(tmp_fd, 0o600)
629
+ with _measure_facade.os.fdopen(tmp_fd, "w", encoding="utf-8") as f:
630
+ fd_owned = True
631
+ f.write(blob)
632
+ _measure_facade.os.replace(tmp_name, str(meta_path))
633
+ except BaseException:
634
+ # BaseException, not OSError: writers under a hook budget can raise
635
+ # _HookTimeout mid-write; clean up the temp then re-raise so the
636
+ # timeout still propagates (same contract as the HTML write).
637
+ # If we failed BEFORE fdopen took ownership (e.g. fchmod raised, or a
638
+ # budget fired between mkstemp and fdopen), the raw fd would leak;
639
+ # close it here. Once fdopen owns it, its `with` already closed it.
640
+ if not fd_owned:
641
+ try:
642
+ _measure_facade.os.close(tmp_fd)
643
+ except OSError:
644
+ pass
645
+ try:
646
+ _measure_facade.os.unlink(tmp_name)
647
+ except OSError:
648
+ pass
649
+ raise
650
+ except OSError:
651
+ pass
652
+
653
+
654
+ def _dashboard_on_disk_is_newer(html_path):
655
+ """True iff a REAL dashboard already on disk was written by a STRICTLY NEWER
656
+ Token Optimizer version than this process.
657
+
658
+ An older build must never overwrite a newer dashboard. Without this guard a
659
+ stale long-lived daemon or a still-running pre-upgrade session regenerates
660
+ the shared dashboard with pre-fix code and clobbers a just-shipped fix -- the
661
+ "fixed but still broken" report, where the fix ships but an old
662
+ in-memory process keeps overwriting the corrected file.
663
+
664
+ Fail-OPEN by design: a missing sidecar, an unparseable/dev version on either
665
+ side, or an absent/undersized (corrupt) HTML returns False (allow the write).
666
+ The HTML-integrity floor is the anti-wedge: the guard only protects a REAL
667
+ on-disk dashboard, so a lying/corrupt sidecar next to a broken HTML can never
668
+ permanently block regeneration -- the next writer repairs it and rewrites the
669
+ sidecar. Reads only the ~40-byte sidecar plus a cheap stat. Never raises.
670
+ Equal versions are NOT "newer", so same-version regen and legitimate upgrades
671
+ both proceed; only a strictly-older writer is blocked.
672
+
673
+ Residual (documented, not auto-recovered): a *valid* newer sidecar beside a
674
+ *valid* HTML always blocks older writers -- correct when a real newer build
675
+ wrote it; on the rare chance the version was corrupted upward next to intact
676
+ HTML, recovery is deleting the .meta.json sidecar."""
677
+ _measure_facade = _compat.facade()
678
+ try:
679
+ mine = _measure_facade._parse_semver(_measure_facade.TOKEN_OPTIMIZER_VERSION)
680
+ if mine is None:
681
+ return False
682
+ # Only guard a real, non-trivial dashboard. A missing/tiny HTML means
683
+ # there is nothing worth protecting -- allow the write so a broken file
684
+ # (even next to a lying sidecar) always self-heals.
685
+ try:
686
+ if _measure_facade.Path(html_path).stat().st_size < _measure_facade._DASHBOARD_MIN_VALID_BYTES:
687
+ return False
688
+ except OSError:
689
+ return False
690
+ meta_path = _measure_facade._dashboard_meta_path(html_path)
691
+ if not meta_path.exists():
692
+ return False
693
+ meta = _measure_facade.json.loads(meta_path.read_text(encoding="utf-8"))
694
+ if not isinstance(meta, dict):
695
+ return False
696
+ existing = _measure_facade._parse_semver(meta.get("version"))
697
+ if existing is None:
698
+ return False
699
+ return existing > mine
700
+ except Exception:
701
+ return False
702
+
703
+
704
+ def _dashboard_meta_is_fresh(meta):
705
+ """Freshness decision for the SessionStart staleness check, factored out so it
706
+ is directly testable. `meta` is the parsed sidecar dict. Fresh (no regen) iff:
707
+ - the on-disk build is STRICTLY NEWER than ours (an older session must not
708
+ regenerate/clobber a newer dashboard -- leave it to the newer build), OR
709
+ - version AND shape marker match ours exactly.
710
+ Anything else (older on disk, or a shape change) is stale -> regenerate."""
711
+ _measure_facade = _compat.facade()
712
+ if not isinstance(meta, dict):
713
+ return False
714
+ existing = _measure_facade._parse_semver(meta.get("version"))
715
+ mine = _measure_facade._parse_semver(_measure_facade.TOKEN_OPTIMIZER_VERSION)
716
+ if existing is not None and mine is not None and existing > mine:
717
+ return True
718
+ return (meta.get("version") == _measure_facade.TOKEN_OPTIMIZER_VERSION
719
+ and meta.get("shape") == _measure_facade._DASHBOARD_SHAPE_MARKER)
720
+
721
+
722
+ def _use_codex_session_adapter(filepath=None):
723
+ """True when session JSONL should be parsed with the Codex adapter."""
724
+ _measure_facade = _compat.facade()
725
+ return _measure_facade.detect_runtime() == "codex" or (filepath is not None and _measure_facade.codex_session.is_codex_session_path(filepath))
726
+
727
+
728
+ def _use_hermes_session_adapter():
729
+ """True when sessions should be loaded from the Hermes state.db adapter."""
730
+ _measure_facade = _compat.facade()
731
+ return _measure_facade.detect_runtime() == "hermes"
732
+
733
+
734
+ def _use_copilot_session_adapter():
735
+ """True when sessions should be loaded from the Copilot adapters."""
736
+ _measure_facade = _compat.facade()
737
+ return _measure_facade.detect_runtime() == "copilot"
738
+
739
+
740
+ def _use_cursor_session_adapter():
741
+ """True when sessions should be loaded from the Cursor adapters."""
742
+ _measure_facade = _compat.facade()
743
+ return _measure_facade.detect_runtime() == "cursor"
744
+
745
+
746
+ def _use_antigravity_session_adapter():
747
+ """True when sessions should be loaded from the Antigravity store adapter."""
748
+ _measure_facade = _compat.facade()
749
+ return _measure_facade.detect_runtime() == "antigravity"
750
+
751
+
752
+ def _use_grok_session_adapter():
753
+ """True when sessions should be loaded from the Grok Build adapter."""
754
+ _measure_facade = _compat.facade()
755
+ return _measure_facade.detect_runtime() == "grok"
756
+
757
+
758
+ def _fmt_context_window(size):
759
+ """Format context window size for display (e.g., '200K', '1M')."""
760
+ _measure_facade = _compat.facade()
761
+ if size >= 1_000_000:
762
+ return f"{size / 1_000_000:.0f}M" if size % 1_000_000 == 0 else f"{size / 1_000_000:.1f}M"
763
+ return f"{size // 1000}K"
764
+
765
+
766
+ def _strip_ansi(text):
767
+ """Remove ANSI/VT escape sequences from text destined for the terminal."""
768
+ _measure_facade = _compat.facade()
769
+ if not isinstance(text, str):
770
+ text = str(text) if text is not None else ""
771
+ text = _measure_facade._ANSI_ESCAPE_RE.sub("", text)
772
+ # Strip stray BEL characters left by malformed OSC sequences whose
773
+ # terminator survived the OSC branch (embedded ESC broke the match).
774
+ return _measure_facade._BEL_RE.sub("", text)
775
+
776
+
777
+ def _context_usage(usage):
778
+ """Select live executor usage, leaving aggregate usage for billing.
779
+
780
+ Advisor/server-tool responses can sum several executor reads in the
781
+ top-level usage. Only the final message iteration describes occupancy.
782
+ An unusable final executor falls back to the aggregate, never an older
783
+ executor (which may describe a different context). Ignore advisor tails.
784
+ """
785
+ _measure_facade = _compat.facade()
786
+ if isinstance(usage, dict) and isinstance(usage.get("iterations"), list):
787
+ for iteration in reversed(usage["iterations"]):
788
+ if isinstance(iteration, dict) and iteration.get("type") == "message":
789
+ if (_measure_facade._valid_context_usage(iteration)
790
+ and _measure_facade._context_token_count(iteration) > 0):
791
+ return iteration
792
+ break
793
+ return usage
794
+
795
+
796
+ def _valid_context_usage(usage):
797
+ """Reject corrupt present executor buckets before lossy int coercion.
798
+
799
+ Missing buckets are optional. TTL splits matter only when the flat
800
+ cache-write count is absent or zero, matching _context_token_count.
801
+ """
802
+ _measure_facade = _compat.facade()
803
+ values = [usage[key] for key in ("input_tokens", "cache_read_input_tokens",
804
+ "cache_creation_input_tokens") if key in usage]
805
+ if not _measure_facade._safe_int(usage.get("cache_creation_input_tokens")):
806
+ nested = usage.get("cache_creation", {})
807
+ if not isinstance(nested, dict):
808
+ return False
809
+ for key in ("ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"):
810
+ if key in nested:
811
+ values.append(nested[key])
812
+ if not nested.get(key) and key in usage:
813
+ values.append(usage[key])
814
+ try:
815
+ return all(_measure_facade.math.isfinite(float(value)) and float(value) >= 0
816
+ for value in values)
817
+ except (TypeError, ValueError, OverflowError):
818
+ return False
819
+
820
+
821
+ def _resume_usage(usage):
822
+ """The first executor tests whether the cache survived the pause.
823
+
824
+ Later executors may read cache written earlier in this same response;
825
+ that is not evidence that a keep-warm ping avoided the initial rewrite.
826
+ Unusable first-executor data keeps the aggregate comparison, not a later
827
+ executor that could hide a paid rewrite.
828
+ """
829
+ _measure_facade = _compat.facade()
830
+ if isinstance(usage, dict) and isinstance(usage.get("iterations"), list):
831
+ for iteration in usage["iterations"]:
832
+ if isinstance(iteration, dict) and iteration.get("type") == "message":
833
+ if (_measure_facade._valid_context_usage(iteration)
834
+ and _measure_facade._context_token_count(iteration) > 0):
835
+ return iteration
836
+ break
837
+ return usage
838
+
839
+
840
+ def _usage_buckets(usage):
841
+ """Billing buckets of one usage dict (or iteration), never raising."""
842
+ _measure_facade = _compat.facade()
843
+ if not isinstance(usage, dict):
844
+ return dict.fromkeys(_measure_facade._USAGE_BUCKET_KEYS, 0)
845
+ nested = usage.get("cache_creation", {})
846
+ if not isinstance(nested, dict):
847
+ nested = {}
848
+ cc_1h = _measure_facade._safe_int(nested.get("ephemeral_1h_input_tokens", 0)
849
+ or usage.get("ephemeral_1h_input_tokens", 0))
850
+ cc_5m = _measure_facade._safe_int(nested.get("ephemeral_5m_input_tokens", 0)
851
+ or usage.get("ephemeral_5m_input_tokens", 0))
852
+ return {
853
+ "inp": max(0, _measure_facade._safe_int(usage.get("input_tokens", 0))),
854
+ "out": max(0, _measure_facade._safe_int(usage.get("output_tokens", 0))),
855
+ "cr": max(0, _measure_facade._safe_int(usage.get("cache_read_input_tokens", 0))),
856
+ "cc": max(0, _measure_facade._safe_int(usage.get("cache_creation_input_tokens", 0))
857
+ or (cc_1h + cc_5m)),
858
+ "cc_1h": max(0, cc_1h),
859
+ "cc_5m": max(0, cc_5m),
860
+ }
861
+
862
+
863
+ def _billed_usage_parts(usage, model, tier=None):
864
+ """Split one response's usage into [(price_model, buckets), ...].
865
+
866
+ The first part is the executor (priced at the response model). Advisor
867
+ iterations (type "advisor_message") run on the advisor's own model, so
868
+ each becomes its own part priced at that model when the rate card knows
869
+ it, else at the executor model. Tokens are never dropped: when the
870
+ top-level usage already covers the advisor tokens they are moved out of
871
+ the executor part, otherwise (the documented shape, top-level is the
872
+ executor sum only) they are added on top.
873
+ """
874
+ _measure_facade = _compat.facade()
875
+ agg = _measure_facade._usage_buckets(usage)
876
+ iterations = usage.get("iterations") if isinstance(usage, dict) else None
877
+ if not isinstance(iterations, list):
878
+ return [(model, agg)]
879
+ executor_sum = dict.fromkeys(_measure_facade._USAGE_BUCKET_KEYS, 0)
880
+ advisor_sum = dict.fromkeys(_measure_facade._USAGE_BUCKET_KEYS, 0)
881
+ advisors = []
882
+ for iteration in iterations:
883
+ if not isinstance(iteration, dict):
884
+ continue
885
+ kind = iteration.get("type")
886
+ if kind == "message":
887
+ for k, v in _measure_facade._usage_buckets(iteration).items():
888
+ executor_sum[k] += v
889
+ elif kind == "advisor_message":
890
+ buckets = _measure_facade._usage_buckets(iteration)
891
+ if not any(buckets.values()):
892
+ continue
893
+ adv_model = iteration.get("model")
894
+ if not (isinstance(adv_model, str) and adv_model
895
+ and _measure_facade._is_priced_model(adv_model, tier)):
896
+ adv_model = model
897
+ advisors.append((adv_model, buckets))
898
+ for k, v in buckets.items():
899
+ advisor_sum[k] += v
900
+ if not advisors:
901
+ return [(model, agg)]
902
+ executor = dict(agg)
903
+ if all(agg[k] >= executor_sum[k] + advisor_sum[k] for k in _measure_facade._USAGE_BUCKET_KEYS):
904
+ executor = {k: agg[k] - advisor_sum[k] for k in _measure_facade._USAGE_BUCKET_KEYS}
905
+ return [(model, executor)] + advisors
906
+
907
+
908
+ def _price_usage_parts(parts, tier=None, per_request=None, ttl_split=None):
909
+ """USD for _billed_usage_parts output; cache writes priced by TTL split."""
910
+ _measure_facade = _compat.facade()
911
+ total = 0.0
912
+ for part_model, b in parts:
913
+ if ttl_split and (b["cc_1h"] or b["cc_5m"]):
914
+ total += _measure_facade._get_model_cost(part_model, b["inp"], b["out"], b["cr"], b["cc"],
915
+ tier=tier, cache_create_1h=b["cc_1h"],
916
+ cache_create_5m=b["cc_5m"], per_request=per_request)
917
+ else:
918
+ total += _measure_facade._get_model_cost(part_model, b["inp"], b["out"], b["cr"], b["cc"],
919
+ tier=tier, per_request=per_request)
920
+ return total
921
+
922
+
923
+ def _turn_prefix_cached(turn):
924
+ """Cached prefix a turn leaves behind: final executor when known (#287)."""
925
+ _measure_facade = _compat.facade()
926
+ if "ctx_cache" in turn:
927
+ return max(0, _measure_facade._safe_int(turn.get("ctx_cache")))
928
+ return _measure_facade._safe_int(turn.get("cache_read")) + _measure_facade._safe_int(turn.get("cache_creation"))
929
+
930
+
931
+ def _turn_resume_write(turn):
932
+ """Cache written when a turn starts: first executor when known (#287)."""
933
+ _measure_facade = _compat.facade()
934
+ if "resume_cache_creation" in turn:
935
+ return max(0, _measure_facade._safe_int(turn.get("resume_cache_creation")))
936
+ return _measure_facade._safe_int(turn.get("cache_creation"))
937
+
938
+
939
+ def _context_token_count(usage):
940
+ """Input footprint, including flat or TTL-split cache writes."""
941
+ _measure_facade = _compat.facade()
942
+ if not isinstance(usage, dict):
943
+ return 0
944
+ creation = _measure_facade._safe_int(usage.get("cache_creation_input_tokens"))
945
+ if not creation:
946
+ nested = usage.get("cache_creation")
947
+ if not isinstance(nested, dict):
948
+ nested = {}
949
+ creation = sum(_measure_facade._safe_int(nested.get(key) or usage.get(key)) for key in (
950
+ "ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens"))
951
+ return (_measure_facade._safe_int(usage.get("input_tokens"))
952
+ + _measure_facade._safe_int(usage.get("cache_read_input_tokens")) + creation)
953
+
954
+
955
+ def estimate_tokens_from_file(filepath):
956
+ """Estimate tokens by reading file content (character count / 4)."""
957
+ _measure_facade = _compat.facade()
958
+ try:
959
+ with open(filepath, "r", encoding="utf-8", errors="replace") as f:
960
+ content = f.read()
961
+ return int(len(content) / _measure_facade.CHARS_PER_TOKEN)
962
+ except (FileNotFoundError, PermissionError, OSError):
963
+ return 0
964
+
965
+
966
+ def _project_claude_dir():
967
+ """`<cwd>/.claude` when it exists and is a real directory, else None.
968
+
969
+ Never follows a symlink out of the tree and never raises: a cwd that has
970
+ been deleted underneath us (a stale shell) must degrade to "no project
971
+ scope", not blow up a report.
972
+ """
973
+ _measure_facade = _compat.facade()
974
+ try:
975
+ p = _measure_facade.Path.cwd() / ".claude"
976
+ if p.is_dir() and not p.is_symlink():
977
+ return p
978
+ except OSError:
979
+ pass
980
+ return None
981
+
982
+
983
+ def _skill_scan_dirs():
984
+ """Every directory Claude Code loads skills from for THIS session, in order.
985
+
986
+ Project-scoped skills (`<cwd>/.claude/skills`) are injected into the
987
+ skill listing for every session in that cwd, exactly like `~/.claude/skills`,
988
+ but measure.py only ever scanned the global dir. Any project using them was
989
+ under-reported (~5-7% on a measured real project) and the shortfall was
990
+ absorbed by the calibration-gap line as if it were unmeasurable overhead.
991
+
992
+ GLOBAL FIRST, deliberately: name maps built from this order let a global
993
+ skill win a name collision, and the dashboard ordering stays stable. The
994
+ project dir is skipped when it IS the global dir (running from `~`), so a
995
+ skill is never counted twice.
996
+ """
997
+ _measure_facade = _compat.facade()
998
+ dirs = [_measure_facade.CLAUDE_DIR / "skills"]
999
+ proj = _measure_facade._project_claude_dir()
1000
+ if proj is not None:
1001
+ try:
1002
+ if proj.resolve() != _measure_facade.CLAUDE_DIR.resolve():
1003
+ dirs.append(proj / "skills")
1004
+ except OSError:
1005
+ pass
1006
+ return dirs
1007
+
1008
+
1009
+ def _agent_scan_dirs():
1010
+ """Same idea for agents: `~/.claude/agents` plus `<cwd>/.claude/agents`."""
1011
+ _measure_facade = _compat.facade()
1012
+ dirs = [_measure_facade.CLAUDE_DIR / "agents"]
1013
+ proj = _measure_facade._project_claude_dir()
1014
+ if proj is not None:
1015
+ try:
1016
+ if proj.resolve() != _measure_facade.CLAUDE_DIR.resolve():
1017
+ dirs.append(proj / "agents")
1018
+ except OSError:
1019
+ pass
1020
+ return dirs
1021
+
1022
+
1023
+ def estimate_tokens_from_frontmatter(filepath):
1024
+ """Estimate tokens from YAML frontmatter only (between --- delimiters).
1025
+
1026
+ Parallel implementation exists in fleet-auditor/scripts/fleet.py
1027
+ (_estimate_skill_frontmatter_tokens). Both must stay in sync.
1028
+ """
1029
+ _measure_facade = _compat.facade()
1030
+ try:
1031
+ with open(filepath, "r", encoding="utf-8", errors="replace") as f:
1032
+ content = f.read()
1033
+ # Strip UTF-8 BOM that Windows editors may insert
1034
+ content = content.lstrip('\ufeff')
1035
+ # Extract frontmatter between first pair of ---
1036
+ if content.startswith("---"):
1037
+ end = content.find("---", 3)
1038
+ if end > 0:
1039
+ frontmatter = content[3:end]
1040
+ return max(int(len(frontmatter) / _measure_facade.CHARS_PER_TOKEN) + _measure_facade.SKILL_WRAPPER_OVERHEAD, 50)
1041
+ # No frontmatter found, use rough estimate
1042
+ return _measure_facade.TOKENS_PER_SKILL_APPROX
1043
+ except (FileNotFoundError, PermissionError, OSError):
1044
+ return _measure_facade.TOKENS_PER_SKILL_APPROX
1045
+
1046
+
1047
+ def count_lines(filepath):
1048
+ _measure_facade = _compat.facade()
1049
+ try:
1050
+ with open(filepath, "r", encoding="utf-8", errors="replace") as f:
1051
+ return sum(1 for _ in f)
1052
+ except (FileNotFoundError, PermissionError, OSError):
1053
+ return 0
1054
+
1055
+
1056
+ def resolve_real_path(filepath):
1057
+ """Resolve symlinks to avoid double-counting."""
1058
+ _measure_facade = _compat.facade()
1059
+ try:
1060
+ return filepath.resolve()
1061
+ except OSError:
1062
+ return filepath
1063
+
1064
+
1065
+ def _encode_project_dir_name(path_str):
1066
+ """Encode an absolute path the way Claude Code names its project dirs.
1067
+
1068
+ Claude Code replaces EVERY non-alphanumeric character with '-' (no collapsing
1069
+ of consecutive dashes). This matters on Windows, where a path like
1070
+ `D:\\Code\\my app` must become `D--Code-my-app` -- the old `/`-and-`_`-only
1071
+ replacement left the drive colon, backslashes, and spaces intact, so the
1072
+ encoded name never matched and `find_projects_dir` fell back to the most
1073
+ recently modified project across ALL projects (cross-project
1074
+ leak). A leading separator still yields the leading '-' on POSIX, and POSIX
1075
+ paths with spaces now encode correctly too.
1076
+ """
1077
+ _measure_facade = _compat.facade()
1078
+ return _measure_facade.re.sub(r"[^A-Za-z0-9]", "-", str(path_str))
1079
+
1080
+
1081
+ def _unvirtualize_msix_path(path_str):
1082
+ """Map an MSIX physical LocalCache path back to the logical AppData path."""
1083
+ _measure_facade = _compat.facade()
1084
+ text = str(path_str)
1085
+ m = _measure_facade._MSIX_REDIRECT_RE.match(text)
1086
+ if not m:
1087
+ return text
1088
+ sep = "\\" if "\\" in text else "/"
1089
+ return f"{m.group('home')}{sep}AppData{sep}{m.group('kind')}{m.group('rest')}"
1090
+
1091
+
1092
+ def cwd_to_project_dir_name():
1093
+ """Convert cwd to Claude Code project directory name format.
1094
+
1095
+ e.g. /Users/alex/my project -> -Users-alex-my-project
1096
+ D:\\Code\\my app -> D--Code-my-app (Windows)
1097
+ """
1098
+ _measure_facade = _compat.facade()
1099
+ return _measure_facade._encode_project_dir_name(_measure_facade._unvirtualize_msix_path(_measure_facade.Path.cwd()))
1100
+
1101
+
1102
+ def _project_dir_from_transcript(projects_base, transcript_path):
1103
+ """The project dir holding a transcript, when it lives under projects_base."""
1104
+ _measure_facade = _compat.facade()
1105
+ if not transcript_path:
1106
+ return None
1107
+ try:
1108
+ rel = _measure_facade.Path(transcript_path).resolve().relative_to(projects_base.resolve())
1109
+ except (OSError, ValueError, RuntimeError):
1110
+ return None
1111
+ if len(rel.parts) < 2:
1112
+ return None
1113
+ candidate = projects_base / rel.parts[0]
1114
+ return candidate if candidate.is_dir() else None
1115
+
1116
+
1117
+ def find_projects_dir(cwd=None, transcript_path=None, allow_mtime_guess=None):
1118
+ """Find the Claude Code projects directory for this session.
1119
+
1120
+ Most reliable first: the hook payload's transcript_path (its parent is the
1121
+ project dir by construction), then the payload cwd, then the process cwd,
1122
+ then $CLAUDE_PROJECT_DIR, each with MSIX paths mapped back to the logical
1123
+ AppData path (#265). Only then the most-recently-modified guess.
1124
+
1125
+ allow_mtime_guess=False skips that final guess and returns None instead:
1126
+ callers resolving a file Claude Code only loads from the CURRENT project
1127
+ (MEMORY.md, #301) must not be handed some other project's directory.
1128
+ """
1129
+ _measure_facade = _compat.facade()
1130
+ projects_base = _measure_facade.CLAUDE_DIR / "projects"
1131
+ if not projects_base.exists():
1132
+ return None
1133
+
1134
+ from_transcript = _measure_facade._project_dir_from_transcript(projects_base, transcript_path)
1135
+ if from_transcript is not None:
1136
+ return from_transcript
1137
+
1138
+ bases = []
1139
+ if cwd:
1140
+ bases.append(cwd)
1141
+ try:
1142
+ bases.append(_measure_facade.Path.cwd())
1143
+ except OSError:
1144
+ pass
1145
+ if _measure_facade.os.environ.get("CLAUDE_PROJECT_DIR"):
1146
+ bases.append(_measure_facade.os.environ["CLAUDE_PROJECT_DIR"])
1147
+
1148
+ for base in bases:
1149
+ for text in dict.fromkeys((_measure_facade._unvirtualize_msix_path(base), str(base))):
1150
+ expected_dir = projects_base / _measure_facade._encode_project_dir_name(text)
1151
+ if expected_dir.exists():
1152
+ return expected_dir
1153
+ # The user may be in a subdirectory of the project.
1154
+ path_cls = _measure_facade.PureWindowsPath if _measure_facade.re.match(r"^[A-Za-z]:[\\/]", text) else _measure_facade.Path
1155
+ for parent in list(path_cls(text).parents)[:5]:
1156
+ parent_dir = projects_base / _measure_facade._encode_project_dir_name(parent)
1157
+ if parent_dir.exists():
1158
+ return parent_dir
1159
+
1160
+ # Last resort: most recently modified (with warning)
1161
+ if not allow_mtime_guess:
1162
+ return None
1163
+ dirs = [d for d in projects_base.iterdir() if d.is_dir()]
1164
+ if not dirs:
1165
+ return None
1166
+
1167
+ def _safe_mtime(d):
1168
+ _measure_facade = _compat.facade()
1169
+ try:
1170
+ return d.stat().st_mtime
1171
+ except OSError:
1172
+ return 0
1173
+
1174
+ result = max(dirs, key=_safe_mtime)
1175
+ # stderr, never stdout: this runs inside hooks (SessionStart's ensure-health
1176
+ # path among them), where stdout becomes the model's additionalContext.
1177
+ print(f" [Warning] Could not match cwd to project dir. Using most recent: {result.name}",
1178
+ file=_measure_facade.sys.stderr)
1179
+ return result
1180
+
1181
+
1182
+ def get_session_baselines(limit=None):
1183
+ """Extract first-message token counts from recent JSONL session logs."""
1184
+ # Hermes: sessions live in ~/.hermes/state.db, not
1185
+ # ~/.claude/projects/*.jsonl. Return [] so the dashboard's baselines
1186
+ # row renders empty without scanning CLAUDE_DIR.
1187
+ _measure_facade = _compat.facade()
1188
+ if _measure_facade._use_hermes_session_adapter():
1189
+ return []
1190
+ # Antigravity: sessions live in the read-only conversation
1191
+ # store under ~/.gemini, not ~/.claude/projects/*.jsonl.
1192
+ if _measure_facade._use_antigravity_session_adapter():
1193
+ return []
1194
+ projects_dir = _measure_facade.find_projects_dir()
1195
+ if not projects_dir:
1196
+ return []
1197
+
1198
+ jsonl_files = sorted(
1199
+ _measure_facade.glob.glob(str(projects_dir / "*.jsonl")),
1200
+ key=_measure_facade.os.path.getmtime,
1201
+ reverse=True,
1202
+ )
1203
+
1204
+ baselines = []
1205
+ for jf in jsonl_files[:limit]:
1206
+ try:
1207
+ mtime = _measure_facade.os.path.getmtime(jf)
1208
+ first_usage = None
1209
+ with open(jf, "r", encoding="utf-8", errors="replace") as f:
1210
+ for line in f:
1211
+ try:
1212
+ data = _measure_facade.json.loads(line)
1213
+ if "message" in data and isinstance(data["message"], dict):
1214
+ msg = data["message"]
1215
+ if "usage" in msg:
1216
+ # Context size, not the advisor-summed bill (#287).
1217
+ first_usage = _measure_facade._context_token_count(
1218
+ _measure_facade._context_usage(msg["usage"]))
1219
+ break
1220
+ except (_measure_facade.json.JSONDecodeError, KeyError, TypeError):
1221
+ continue
1222
+
1223
+ if first_usage:
1224
+ baselines.append({
1225
+ "date": _measure_facade.datetime.fromtimestamp(mtime).isoformat(),
1226
+ "baseline_tokens": first_usage,
1227
+ })
1228
+ except (PermissionError, OSError):
1229
+ continue
1230
+
1231
+ return baselines