@alexgreensh/token-optimizer 5.13.70 → 5.13.72

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 (40) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +3 -3
  4. package/hooks/sessionstart_runner.py +6 -0
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/assets/dashboard.html +361 -289
  7. package/skills/token-optimizer/assets/savings_story.js +140 -36
  8. package/skills/token-optimizer/references/cli-reference.md +1 -1
  9. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -3
  10. package/skills/token-optimizer/scripts/_measure/config_cache.py +63 -0
  11. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +3 -1
  12. package/skills/token-optimizer/scripts/_measure/counted_cap.py +4 -2
  13. package/skills/token-optimizer/scripts/_measure/coverage_report.py +11 -1
  14. package/skills/token-optimizer/scripts/_measure/dashboard.py +35 -64
  15. package/skills/token-optimizer/scripts/_measure/holdout_report.py +5 -1
  16. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +4 -0
  17. package/skills/token-optimizer/scripts/_measure/lifecycle.py +6 -7
  18. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +4 -3
  19. package/skills/token-optimizer/scripts/_measure/savings.py +11 -4
  20. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  21. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -0
  22. package/skills/token-optimizer/scripts/_measure/setup_observation_cache.py +99 -0
  23. package/skills/token-optimizer/scripts/_measure/setup_step.py +4 -5
  24. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +218 -0
  25. package/skills/token-optimizer/scripts/_measure/structural_report.py +25 -6
  26. package/skills/token-optimizer/scripts/_measure/structural_value.py +16 -10
  27. package/skills/token-optimizer/scripts/cloud_kit.py +1 -2
  28. package/skills/token-optimizer/scripts/codemap.py +33 -5
  29. package/skills/token-optimizer/scripts/codemap_hint.py +152 -11
  30. package/skills/token-optimizer/scripts/codemap_index.py +100 -11
  31. package/skills/token-optimizer/scripts/codemap_ledger.py +29 -0
  32. package/skills/token-optimizer/scripts/codex_doctor.py +3 -3
  33. package/skills/token-optimizer/scripts/hermes_doctor.py +3 -3
  34. package/skills/token-optimizer/scripts/hermes_install.py +3 -3
  35. package/skills/token-optimizer/scripts/statusline.js +157 -30
  36. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +0 -140
  37. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +0 -35
  38. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +0 -85
  39. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +0 -143
  40. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +0 -84
@@ -3548,12 +3548,12 @@ def _status_bar_key(session_id):
3548
3548
 
3549
3549
  def _status_bar_cache_path(session_id):
3550
3550
  _measure_facade = _compat.facade()
3551
- return _measure_facade._status_bar_dir() / f"{_measure_facade._status_bar_key(session_id)}.json"
3551
+ return _measure_facade._status_bar_dir() / "global.json"
3552
3552
 
3553
3553
 
3554
3554
  def _status_bar_lock_path(session_id):
3555
3555
  _measure_facade = _compat.facade()
3556
- return _measure_facade._status_bar_dir() / f"{_measure_facade._status_bar_key(session_id)}.refresh.lock"
3556
+ return _measure_facade._status_bar_dir() / "global.refresh.lock"
3557
3557
 
3558
3558
 
3559
3559
  def _realized_savings_buckets(conn, cutoff, session_uuid=None, by_day=None):
@@ -3705,6 +3705,7 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3705
3705
  "usd": float(b.get("usd", 0.0))})
3706
3706
  headline = _measure_facade._get_merged_savings(days=_measure_facade._STATUS_BAR_DAYS)
3707
3707
  from . import headline as headline_module
3708
+ from . import savings_headline as savings_headline_module
3708
3709
  counted = _measure_facade._counted_cumulative_summary(days=_measure_facade._STATUS_BAR_DAYS) if has_counted else {"available": False}
3709
3710
  headline["counted_period"] = counted
3710
3711
  headline["token_headline"] = headline_module.token_headline(headline)
@@ -3722,55 +3723,20 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3722
3723
  # The dashboard's headline (measured + estimated); the measured floor beside it.
3723
3724
  "total_30d_tokens": shown,
3724
3725
  "total_30d_measured_tokens": measured,
3726
+ # The shared headline the band, status line and dashboard hero quote.
3727
+ "savings_headline": savings_headline_module.build(headline),
3725
3728
  "computed_at": _measure_facade.time.time(),
3726
3729
  }, None
3727
3730
 
3728
3731
 
3729
3732
  def _status_bar_write_cache(session_id, savings, reason):
3730
- _measure_facade = _compat.facade()
3731
- d = _measure_facade._status_bar_dir()
3732
- d.mkdir(parents=True, exist_ok=True)
3733
- path = _measure_facade._status_bar_cache_path(session_id)
3734
- if savings is None:
3735
- # A failed refresh keeps the last good figures (they read as stale), never null them.
3736
- prior = _measure_facade._status_bar_read_cache(session_id)
3737
- if prior is not None and prior.get("savings") is not None:
3738
- return
3739
- tmp = path.with_name(f".{path.name}.{_measure_facade.os.getpid()}.tmp")
3740
- tmp.write_text(_measure_facade.json.dumps({
3741
- "schema": _measure_facade._STATUS_BAR_SCHEMA,
3742
- "computed_at": _measure_facade.time.time(),
3743
- "savings": savings,
3744
- "reason": reason,
3745
- }), encoding="utf-8")
3746
- _measure_facade.os.replace(tmp, path)
3747
- # Bound the directory: drop caches for sessions untouched for 30 days.
3748
- cutoff = _measure_facade.time.time() - _measure_facade._STATUS_BAR_CACHE_RETENTION_S
3749
- orphan_cutoff = _measure_facade.time.time() - 86400
3750
- try:
3751
- for f in d.iterdir():
3752
- try:
3753
- name = f.name
3754
- # Temp files and set-aside locks left by a crash go after a day.
3755
- orphan = name.endswith((".tmp", ".stale", ".release"))
3756
- if (orphan and f.stat().st_mtime < orphan_cutoff) or (
3757
- name.endswith(".json") and f.stat().st_mtime < cutoff):
3758
- f.unlink()
3759
- except OSError:
3760
- pass
3761
- except OSError:
3762
- pass
3733
+ from . import status_bar_refresh
3734
+ return status_bar_refresh.write_cache(_compat.facade(), session_id, savings, reason)
3763
3735
 
3764
3736
 
3765
3737
  def _status_bar_read_cache(session_id):
3766
- _measure_facade = _compat.facade()
3767
- try:
3768
- data = _measure_facade.json.loads(_measure_facade._status_bar_cache_path(session_id).read_text(encoding="utf-8"))
3769
- except (OSError, ValueError):
3770
- return None
3771
- if not isinstance(data, dict) or not isinstance(data.get("computed_at"), (int, float)):
3772
- return None
3773
- return data
3738
+ from . import status_bar_refresh
3739
+ return status_bar_refresh.read_cache(_compat.facade(), session_id)
3774
3740
 
3775
3741
 
3776
3742
  def _status_bar_start_refresh(session_id):
@@ -4150,6 +4116,7 @@ def status_bar_payload(session_id, transcript=None, sync=None):
4150
4116
  "savings": None,
4151
4117
  "savings_state": "unavailable",
4152
4118
  "savings_age_s": None,
4119
+ "savings_refresh_failed": False,
4153
4120
  "savings_reason": None,
4154
4121
  "refresh_started": False,
4155
4122
  "last_request_epoch": None,
@@ -4207,39 +4174,43 @@ def status_bar_payload(session_id, transcript=None, sync=None):
4207
4174
 
4208
4175
  try:
4209
4176
  if sync:
4210
- savings, reason = _measure_facade._status_bar_savings_or_reason(sid)
4211
- try:
4212
- _measure_facade._status_bar_write_cache(sid, savings, reason)
4213
- except OSError:
4214
- pass
4215
- out["savings"], out["savings_reason"] = savings, reason
4216
- out["savings_age_s"] = 0.0
4217
- out["savings_state"] = "fresh" if savings is not None else "unavailable"
4218
- return out
4219
- if not _measure_facade.Path(_measure_facade.TRENDS_DB).exists():
4177
+ from . import status_bar_refresh
4178
+ return status_bar_refresh.sync(_measure_facade, sid, out)
4179
+ cached = _measure_facade._status_bar_read_cache(sid)
4180
+ if cached is None and not _measure_facade.Path(_measure_facade.TRENDS_DB).exists():
4220
4181
  out["savings_reason"] = "no savings recorded yet"
4221
4182
  return out
4222
- cached = _measure_facade._status_bar_read_cache(sid)
4223
4183
  if cached is None:
4224
4184
  out["savings_state"] = "loading"
4225
4185
  out["savings_reason"] = "computing savings"
4226
4186
  out["refresh_started"] = _measure_facade._status_bar_start_refresh(sid)
4227
4187
  return out
4228
4188
  age = max(0.0, _measure_facade.time.time() - float(cached["computed_at"]))
4229
- out["savings"] = cached.get("savings")
4189
+ from . import status_bar_refresh
4190
+ out["savings"] = status_bar_refresh.for_session(_measure_facade, sid, cached.get("savings"))
4230
4191
  out["savings_reason"] = cached.get("reason") if out["savings"] is None else None
4231
4192
  out["savings_age_s"] = round(age, 1)
4232
- stale = age > _measure_facade._STATUS_BAR_CACHE_MAX_AGE_S
4193
+ out["savings_refresh_failed"] = bool(cached.get("refresh_failed", cached.get("stale")))
4194
+ db_exists = _measure_facade.Path(_measure_facade.TRENDS_DB).exists()
4195
+ # The cached "no savings" reason only means the database was missing at
4196
+ # that refresh; decide on the database as it is now, or it sticks forever.
4197
+ no_db_cached = cached.get("reason") == "no savings recorded yet"
4198
+ stale = bool(cached.get("stale")) or age > _measure_facade._STATUS_BAR_CACHE_MAX_AGE_S or not db_exists
4233
4199
  if out["savings"] is None:
4234
- out["savings_state"] = "unavailable"
4200
+ out["savings_state"] = "unavailable" if no_db_cached and not db_exists else "loading"
4201
+ if no_db_cached and db_exists:
4202
+ out["savings_reason"] = "computing savings"
4235
4203
  else:
4236
4204
  out["savings_state"] = "stale" if stale else "fresh"
4237
- if stale:
4205
+ if no_db_cached:
4206
+ start = db_exists
4207
+ else:
4208
+ start = stale and _measure_facade.time.time() - float(cached.get("last_attempt", 0)) >= status_bar_refresh.retry_delay(cached.get("failures", 0))
4209
+ if start:
4238
4210
  out["refresh_started"] = _measure_facade._status_bar_start_refresh(sid)
4239
4211
  except Exception:
4240
- out["savings"] = None
4241
- out["savings_state"] = "unavailable"
4242
- out["savings_reason"] = "savings unavailable"
4212
+ from . import status_bar_refresh
4213
+ out = status_bar_refresh.failed_payload(_measure_facade, sid, out)
4243
4214
  return out
4244
4215
 
4245
4216
 
@@ -4282,7 +4253,7 @@ def _status_bar_cli(args):
4282
4253
  # Killed by its budget: leave a reason for the band and free the lock.
4283
4254
  _measure_facade = _compat.facade()
4284
4255
  try:
4285
- _measure_facade._status_bar_write_cache(sid, None, "savings took too long to compute")
4256
+ _measure_facade._status_bar_write_cache(sid, None, "still counting savings")
4286
4257
  except OSError:
4287
4258
  pass
4288
4259
  _measure_facade._status_bar_release_lock(sid, token)
@@ -4292,8 +4263,8 @@ def _status_bar_cli(args):
4292
4263
  try:
4293
4264
  payload = _measure_facade.status_bar_payload(session, transcript=_opt("--transcript"), sync=sync)
4294
4265
  except Exception:
4295
- payload = {"schema": _measure_facade._STATUS_BAR_SCHEMA, "session_id": sid, "savings": None,
4296
- "savings_state": "unavailable", "savings_reason": "savings unavailable"}
4266
+ from . import status_bar_refresh
4267
+ payload = status_bar_refresh.failed_payload(_measure_facade, sid, {"schema": _measure_facade._STATUS_BAR_SCHEMA, "session_id": sid})
4297
4268
  finally:
4298
4269
  if token:
4299
4270
  _measure_facade._status_bar_release_lock(sid, token)
@@ -33,7 +33,11 @@ def wilson(k, n, confidence=CONFIDENCE):
33
33
  denom = 1.0 + z2 / n
34
34
  center = (point + z2 / (2.0 * n)) / denom
35
35
  half = (z / denom) * math.sqrt(point * (1.0 - point) / n + z2 / (4.0 * n * n))
36
- return point, max(0.0, center - half), min(1.0, center + half)
36
+ # At k == 0 the lower bound is exactly 0 and at k == n the upper bound is exactly 1; the two
37
+ # terms cancel only up to float rounding, which differs by platform (2.8e-17 on Linux and Windows).
38
+ low = 0.0 if k == 0 else max(0.0, center - half)
39
+ high = 1.0 if k == n else min(1.0, center + half)
40
+ return point, low, high
37
41
 
38
42
 
39
43
  def _quantile(sorted_values, q):
@@ -12,6 +12,10 @@ import time
12
12
 
13
13
 
14
14
  def process_info(pid):
15
+ # Keep-warm watches a terminal Claude through `ps`/`lsof`; Windows has neither, so there is no
16
+ # owner to find. Answering here keeps the Stop hook from spawning a `ps` that cannot exist.
17
+ if os.name != 'posix':
18
+ return None
15
19
  try:
16
20
  proc = subprocess.run(['ps', '-p', str(int(pid)), '-o', 'ppid=', '-o', 'lstart=', '-o', 'comm='],
17
21
  capture_output=True, text=True, timeout=1, check=True)
@@ -3461,13 +3461,10 @@ def _read_config_flag(key, default=None):
3461
3461
  cloud session whose home is fresh every time still sees the team's
3462
3462
  committed opt-outs. The user's own value always wins."""
3463
3463
  _measure_facade = _compat.facade()
3464
- try:
3465
- if _measure_facade.CONFIG_PATH.exists():
3466
- cfg = _measure_facade.json.loads(_measure_facade.CONFIG_PATH.read_text(encoding="utf-8"))
3467
- if isinstance(cfg, dict) and key in cfg:
3468
- return cfg[key]
3469
- except (_measure_facade.json.JSONDecodeError, OSError):
3470
- pass
3464
+ from . import config_cache
3465
+ cfg = {key: config_cache.current_tier()} if key == "pricing_tier" and config_cache.current_tier() is not None else config_cache.read(_measure_facade.CONFIG_PATH, _measure_facade.json)
3466
+ if key in cfg:
3467
+ return cfg[key]
3471
3468
  try:
3472
3469
  value = _measure_facade.project_config_value(key)
3473
3470
  if value is not None:
@@ -3534,6 +3531,8 @@ def _write_config_flag(key, value):
3534
3531
  _measure_facade.json.dump(cfg, f, indent=2)
3535
3532
  f.write("\n")
3536
3533
  _measure_facade.os.replace(tmp_path, str(_measure_facade.CONFIG_PATH))
3534
+ from . import config_cache
3535
+ config_cache.clear()
3537
3536
  tmp_path = None
3538
3537
  except OSError:
3539
3538
  pass
@@ -1,6 +1,7 @@
1
1
  """Validate and serialize the recovery state at a transcript boundary."""
2
2
  import hashlib
3
3
  import json
4
+ import os
4
5
  from collections import Counter, deque
5
6
 
6
7
 
@@ -10,7 +11,7 @@ def _anchor(handle, offset):
10
11
 
11
12
 
12
13
  def save(handle, offset, rec, **values):
13
- stat = __import__('os').fstat(handle.fileno())
14
+ stat = os.fstat(handle.fileno())
14
15
  position = handle.tell()
15
16
  anchor = _anchor(handle, offset)
16
17
  handle.seek(position)
@@ -25,7 +26,7 @@ def save(handle, offset, rec, **values):
25
26
 
26
27
  def restore(handle, checkpoint):
27
28
  try:
28
- stat = __import__('os').fstat(handle.fileno())
29
+ stat = os.fstat(handle.fileno())
29
30
  offset = int(checkpoint['offset'])
30
31
  if (offset < 0 or offset > stat.st_size or stat.st_dev != checkpoint['device']
31
32
  or stat.st_ino != checkpoint['inode'] or _anchor(handle, offset) != checkpoint['anchor']):
@@ -159,7 +160,7 @@ def status_telemetry(path, previous=None):
159
160
  def restore_codex(handle, checkpoint):
160
161
  """Restore Codex state only while the underlying file prefix still matches."""
161
162
  try:
162
- stat = __import__('os').fstat(handle.fileno())
163
+ stat = os.fstat(handle.fileno())
163
164
  offset = int(checkpoint['offset'])
164
165
  if (checkpoint.get('kind') != 'codex' or offset < 0 or offset > stat.st_size
165
166
  or stat.st_dev != checkpoint['device'] or stat.st_ino != checkpoint['inode']
@@ -1193,6 +1193,8 @@ def _dashboard_savings_data(days=None, include_billing_mode=None, fail_open=None
1193
1193
  "by_category": {}}
1194
1194
  savings_data.pop("mcp_cap_estimated", None)
1195
1195
  if source_failed:
1196
+ # Keep the bare fail-open shape: callers compare it verbatim to decide
1197
+ # whether the savings source produced a real payload.
1196
1198
  return savings_data
1197
1199
  try:
1198
1200
  from . import cost_per_message_trend
@@ -1221,6 +1223,11 @@ def _dashboard_savings_data(days=None, include_billing_mode=None, fail_open=None
1221
1223
  _measure_facade._apply_counted_oneshot_pricing(savings_data, savings_data["counted_period"])
1222
1224
  savings_data["action_savings"] = _measure_facade._action_savings_components(
1223
1225
  savings_data, savings_data["counted_period"])
1226
+ try:
1227
+ from . import savings_headline
1228
+ savings_data["savings_headline"] = savings_headline.build(savings_data)
1229
+ except Exception:
1230
+ savings_data["savings_headline"] = None
1224
1231
  if include_billing_mode:
1225
1232
  try:
1226
1233
  savings_data["billing_mode"] = _measure_facade.keepwarm_billing_mode()
@@ -3314,11 +3321,11 @@ def _estimate_cache_drop_savings(days=None):
3314
3321
  OPPORTUNITY tier: rebuilds that already happened, avoidable by resuming
3315
3322
  inside the TTL. Never summed into the realized total.
3316
3323
  """
3317
- _measure_facade = _compat.facade()
3324
+ _measure_facade = _compat.facade(); from . import config_cache
3318
3325
  zero = {"drop_sessions": 0, "est_drops": 0, "prefix_tokens": 0, "rebuilt_tokens": 0,
3319
3326
  "ttl_seconds": None, "cost_saved_usd": 0.0, "evidence": "opportunity"}
3320
3327
  try:
3321
- health = _measure_facade._cache_ttl_waste_cached(days=days) or {}
3328
+ health = {} if config_cache.cache_scan_skipped() else (_measure_facade._cache_ttl_waste_cached(days=days) or {})
3322
3329
  rebuild = health.get("rebuild") or {}
3323
3330
  events = int(rebuild.get("events", 0) or 0)
3324
3331
  tokens = int(rebuild.get("tokens", 0) or 0)
@@ -6211,7 +6218,8 @@ def _get_merged_savings(days=None, since=None):
6211
6218
  model_routing = _measure_facade._compute_model_routing_savings(days=days, since=since)
6212
6219
  model_routing["baseline_provenance"] = baseline_provenance.routing(_measure_facade, model_routing)
6213
6220
  output_waste = _measure_facade._estimate_output_waste(days=days)
6214
- cache_drop = {**_measure_facade._estimate_cache_drop_savings(days=days), **__import__("large_transcripts").count(_measure_facade.CLAUDE_DIR, days)}
6221
+ import large_transcripts
6222
+ cache_drop = {**_measure_facade._estimate_cache_drop_savings(days=days), **large_transcripts.count(_measure_facade.CLAUDE_DIR, days)}
6215
6223
  before_after = _measure_facade._estimate_before_after_savings(days=days, since=since, estimated_pools={
6216
6224
  "uncaptured_runtime": uncaptured,
6217
6225
  "behavioral_loops": behavioral,
@@ -7012,7 +7020,6 @@ def savings_report(days=None, as_json=None):
7012
7020
  print(" - Restore from progressive checkpoints (Smart Compaction)")
7013
7021
  print(" - Archive unused tools or skills")
7014
7022
 
7015
-
7016
7023
  def validate_impact(strategy=None, days=None, as_json=None):
7017
7024
  """Compare session metrics before vs after an optimization event.
7018
7025
 
@@ -0,0 +1,130 @@
1
+ """The one savings headline shared by the band, the status line and the dashboard.
2
+
3
+ Computes the contract object (briefs/ux-contract.md) from the same summary the
4
+ dashboard Savings hero reads: ``action_savings.total_usd`` plus the model
5
+ routing figure, and ``token_headline.total_tokens``. Every surface prints this
6
+ one object so they can never quote different dollars for the same window.
7
+
8
+ usd_week stays null: there is no honest weekly figure yet and 30 days are never
9
+ prorated into one. display is null whenever no threshold is met, which is how
10
+ surfaces know to show no number at all.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import math
15
+
16
+ # The dashboard's Savings deep link. Claude's daemon serves on 24842; callers
17
+ # on another runtime may pass dashboard_url to build().
18
+ DASHBOARD_SAVINGS_URL = "http://localhost:24842/token-optimizer#savings"
19
+
20
+ _WEEK_MIN_USD = 20.0
21
+ _MONTH_MIN_USD = 60.0
22
+ _TOKENS_MIN = 1_000_000
23
+
24
+
25
+ def _usd(value):
26
+ """A finite dollar figure, or None."""
27
+ try:
28
+ v = float(value)
29
+ except (TypeError, ValueError):
30
+ return None
31
+ return v if math.isfinite(v) else None
32
+
33
+
34
+ def _count(value):
35
+ """A non-negative integer token count, or 0."""
36
+ try:
37
+ return max(0, int(float(value or 0)))
38
+ except (TypeError, ValueError, OverflowError):
39
+ return 0
40
+
41
+
42
+ def _usd_text(value):
43
+ """Whole dollars with a thousands separator: 1234.4 -> '$1,234'."""
44
+ return "${:,.0f}".format(value)
45
+
46
+
47
+ def _token_text(value):
48
+ """One decimal for K/M/B, matching the dashboard's token format."""
49
+ v = float(value or 0)
50
+ if v >= 1e9:
51
+ return "{:.1f}B".format(v / 1e9)
52
+ if v >= 1e6:
53
+ return "{:.1f}M".format(v / 1e6)
54
+ if v >= 1e3:
55
+ return "{:.1f}K".format(v / 1e3)
56
+ return "{:,.0f}".format(v)
57
+
58
+
59
+ def _display(usd_30d, usd_week, tokens_30d, url):
60
+ """Pick the one number a surface may show, or None."""
61
+ if usd_week is not None and usd_week >= _WEEK_MIN_USD:
62
+ kind = "week"
63
+ amount = _usd_text(usd_week)
64
+ short = "Saved {} this week".format(amount)
65
+ long = "{} saved this week".format(amount)
66
+ elif usd_30d >= _MONTH_MIN_USD:
67
+ kind = "30d"
68
+ amount = _usd_text(usd_30d)
69
+ tok = _token_text(tokens_30d)
70
+ short = "Saved {}/30d".format(amount)
71
+ long = "{} saved in 30 days".format(amount)
72
+ if tokens_30d > 0:
73
+ short += " · {} kept out".format(tok)
74
+ long += " · {} tokens kept out of context".format(tok)
75
+ elif tokens_30d >= _TOKENS_MIN:
76
+ kind = "tokens"
77
+ tok = _token_text(tokens_30d)
78
+ short = "{} tokens kept out of context".format(tok)
79
+ long = short
80
+ else:
81
+ return None
82
+ return {"kind": kind, "short": short, "long": long, "url": url}
83
+
84
+
85
+ def build(summary, dashboard_url=DASHBOARD_SAVINGS_URL):
86
+ """The savings_headline contract object for one savings summary.
87
+
88
+ `summary` is the dashboard's savings payload (or the status-bar headline
89
+ built from the same inputs): action_savings, model_routing and
90
+ token_headline. Missing pieces read as zero, which lands on display null.
91
+ Never raises.
92
+ """
93
+ try:
94
+ s = summary if isinstance(summary, dict) else {}
95
+ action = s.get("action_savings") or {}
96
+ if not isinstance(action, dict):
97
+ action = {}
98
+ routing = s.get("model_routing") or {}
99
+ if not isinstance(routing, dict):
100
+ routing = {}
101
+ headline = s.get("token_headline") or {}
102
+ if not isinstance(headline, dict):
103
+ headline = {}
104
+ if "total_tokens" not in headline:
105
+ # The dashboard payload also nests the same object under runway.
106
+ runway = s.get("runway") or {}
107
+ if isinstance(runway, dict):
108
+ nested = runway.get("token_headline") or {}
109
+ if isinstance(nested, dict):
110
+ headline = nested
111
+
112
+ total = _usd(action.get("total_usd")) or 0.0
113
+ # The hero adds the routing estimate on top of the action total; the
114
+ # same figure sits in model_routing.realized_cost_usd (action_savings'
115
+ # routing_usd is copied from it).
116
+ routing_usd = _usd(routing.get("realized_cost_usd"))
117
+ if routing_usd is None:
118
+ routing_usd = _usd(action.get("routing_usd"))
119
+ usd_30d = total + max(0.0, routing_usd or 0.0)
120
+ tokens_30d = _count(headline.get("total_tokens"))
121
+ usd_week = None
122
+ url = dashboard_url if isinstance(dashboard_url, str) and dashboard_url else DASHBOARD_SAVINGS_URL
123
+ return {
124
+ "usd_30d": usd_30d,
125
+ "usd_week": usd_week,
126
+ "tokens_30d": tokens_30d,
127
+ "display": _display(usd_30d, usd_week, tokens_30d, url),
128
+ }
129
+ except Exception:
130
+ return {"usd_30d": 0.0, "usd_week": None, "tokens_30d": 0, "display": None}
@@ -4037,6 +4037,9 @@ def _run_upgrade_drain(days=None, quiet=None):
4037
4037
  """Body of `measure.py upgrade-drain`: one uncapped collect (usage re-parse,
4038
4038
  per-day usage, counted ledger and markers), then release the lock."""
4039
4039
  _measure_facade = _compat.facade()
4040
+ # Scoped to this run: the CLI exits right after, but an in-process caller (a test, an embedding host)
4041
+ # must not keep every later collect_sessions() in drain mode.
4042
+ previous_flag = _measure_facade.os.environ.get("TOKEN_OPTIMIZER_UPGRADE_DRAIN")
4040
4043
  _measure_facade.os.environ["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = "1"
4041
4044
  try:
4042
4045
  with upgrade_drain_control.running(_measure_facade) as held:
@@ -4049,6 +4052,10 @@ def _run_upgrade_drain(days=None, quiet=None):
4049
4052
  return 0
4050
4053
  finally:
4051
4054
  _measure_facade._upgrade_drain_release_lock()
4055
+ if previous_flag is None:
4056
+ _measure_facade.os.environ.pop("TOKEN_OPTIMIZER_UPGRADE_DRAIN", None)
4057
+ else:
4058
+ _measure_facade.os.environ["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = previous_flag
4052
4059
 
4053
4060
 
4054
4061
  def collect_sessions(days=None, quiet=None, rebuild=None):
@@ -0,0 +1,99 @@
1
+ """Persist first-call observations without storing transcript text or paths."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import time
6
+ import uuid
7
+ from pathlib import Path
8
+
9
+ from . import first_call_context, setup_step
10
+
11
+
12
+ class Cache:
13
+ def __init__(self, data_dir):
14
+ self.path = Path(data_dir) / 'setup-observations-v1.json'
15
+ self.entries = {}
16
+ self.dirty = False
17
+ self.pending = 0
18
+ try:
19
+ self.version = _version()
20
+ except OSError:
21
+ self.version = None
22
+ try:
23
+ data = json.loads(self.path.read_text(encoding='utf-8'))
24
+ if self.version is not None and data.get('version') == self.version and isinstance(data.get('entries'), dict):
25
+ self.entries = data.get('entries', {})
26
+ except (OSError, ValueError, TypeError, AttributeError):
27
+ pass
28
+ try:
29
+ for tmp in self.path.parent.glob('.setup-observations-v1.json.*.tmp'):
30
+ if time.time() - tmp.stat().st_mtime > 86400:
31
+ tmp.unlink()
32
+ except OSError:
33
+ pass
34
+
35
+ def observe(self, path):
36
+ path = Path(path)
37
+ key = hashlib.sha256(os.fsencode(str(path))).hexdigest()
38
+ try:
39
+ stat = path.stat()
40
+ signature = [stat.st_size, stat.st_mtime_ns]
41
+ entry = self.entries.get(key)
42
+ if isinstance(entry, dict) and 'observation' in entry and entry.get('signature') == signature and _valid(entry['observation']):
43
+ return entry.get('observation')
44
+ observation = setup_step.observe_step(first_call_context.transcript(path), lambda v: round(len(v) / 4))
45
+ after = path.stat()
46
+ if signature == [after.st_size, after.st_mtime_ns] and time.time_ns() - after.st_mtime_ns >= 2_000_000_000:
47
+ self.entries[key] = {'signature': signature, 'observation': observation}
48
+ self.dirty = True
49
+ self.pending += 1
50
+ if self.pending >= 200:
51
+ self.save()
52
+ return observation
53
+ except (OSError, ValueError, TypeError):
54
+ if key in self.entries:
55
+ del self.entries[key]
56
+ self.dirty = True
57
+ return None
58
+
59
+ def save(self):
60
+ if not self.dirty or self.version is None:
61
+ return
62
+ tmp = self.path.with_name('.%s.%s.tmp' % (self.path.name, uuid.uuid4().hex))
63
+ try:
64
+ tmp.write_text(json.dumps({'version': self.version, 'entries': self.entries}), encoding='utf-8')
65
+ for attempt in range(3):
66
+ try:
67
+ os.replace(tmp, self.path)
68
+ break
69
+ except PermissionError:
70
+ if attempt == 2:
71
+ raise
72
+ time.sleep(.02 * (attempt + 1))
73
+ self.dirty = False
74
+ self.pending = 0
75
+ except OSError:
76
+ pass
77
+ finally:
78
+ try:
79
+ tmp.unlink(missing_ok=True)
80
+ except OSError:
81
+ pass
82
+
83
+
84
+ def _valid(observation):
85
+ if observation is None:
86
+ return True
87
+ return (isinstance(observation, dict) and isinstance(observation.get('month'), str)
88
+ and isinstance(observation.get('total'), int) and isinstance(observation.get('components'), dict)
89
+ and all(isinstance(k, str) and isinstance(v, int) for k, v in observation['components'].items())
90
+ and isinstance(observation.get('ts'), str)
91
+ and (observation.get('model') is None or isinstance(observation.get('model'), str)))
92
+
93
+
94
+ def _version():
95
+ files = [Path(first_call_context.__file__), Path(setup_step.__file__)]
96
+ stamps = [hashlib.sha256(p.read_bytes()).hexdigest() for p in files]
97
+ commands = sorted(first_call_context._optimizer_commands())
98
+ digest = hashlib.sha256(json.dumps(commands).encode('utf-8')).hexdigest()
99
+ return {'schema': 1, 'estimator': 'round(len/4)', 'commands': digest, 'code': stamps}
@@ -183,7 +183,7 @@ def measured_epochs(db_path, data_dir, claude_dir=None, card_fn=None):
183
183
 
184
184
  def collect(db_path, data_dir, claude_dir=None, card_fn=None, keep_carried=False):
185
185
  """Steps for every dated trim, from the user's own ledger and transcripts. Read-only."""
186
- from . import first_call_context, structural_ledger as ledger
186
+ from . import setup_observation_cache, structural_ledger as ledger
187
187
  path = Path(db_path) if db_path else None
188
188
  if path is None or not path.is_file():
189
189
  return {"available": False, "why": "no ledger"}
@@ -201,15 +201,14 @@ def collect(db_path, data_dir, claude_dir=None, card_fn=None, keep_carried=False
201
201
  with sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0) as conn:
202
202
  rows = conn.execute("SELECT DISTINCT jsonl_path, api_calls FROM session_log "
203
203
  "WHERE jsonl_path IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
204
+ cache = setup_observation_cache.Cache(data_dir)
204
205
  for name, api_calls in rows:
205
- try:
206
- obs = observe_step(first_call_context.transcript(Path(name)), lambda v: round(len(v) / 4))
207
- except (OSError, ValueError, TypeError):
208
- continue
206
+ obs = cache.observe(name)
209
207
  epoch = ledger.to_epoch(obs.get("ts")) if obs else None
210
208
  if obs and epoch is not None:
211
209
  sessions.append({"ts_epoch": epoch, "total": obs["total"], "components": obs["components"],
212
210
  "api_calls": api_calls, "model": obs.get("model")})
211
+ cache.save()
213
212
  rate_fn = None
214
213
  if card_fn is not None:
215
214
  def rate_fn(model):