@alexgreensh/token-optimizer 5.13.70 → 5.13.71

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 (28) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +2 -2
  4. package/package.json +1 -1
  5. package/skills/token-optimizer/assets/dashboard.html +361 -289
  6. package/skills/token-optimizer/assets/savings_story.js +140 -36
  7. package/skills/token-optimizer/references/cli-reference.md +1 -1
  8. package/skills/token-optimizer/scripts/_measure/__init__.py +2 -2
  9. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +3 -1
  10. package/skills/token-optimizer/scripts/_measure/counted_cap.py +4 -2
  11. package/skills/token-optimizer/scripts/_measure/coverage_report.py +11 -1
  12. package/skills/token-optimizer/scripts/_measure/dashboard.py +3 -0
  13. package/skills/token-optimizer/scripts/_measure/holdout_report.py +5 -1
  14. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +4 -0
  15. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +4 -3
  16. package/skills/token-optimizer/scripts/_measure/savings.py +9 -2
  17. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  18. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -0
  19. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  20. package/skills/token-optimizer/scripts/codex_doctor.py +2 -2
  21. package/skills/token-optimizer/scripts/hermes_doctor.py +2 -2
  22. package/skills/token-optimizer/scripts/hermes_install.py +2 -2
  23. package/skills/token-optimizer/scripts/statusline.js +144 -30
  24. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +0 -140
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +0 -35
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +0 -85
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +0 -143
  28. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +0 -84
@@ -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):
@@ -486,7 +486,7 @@ _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
486
486
  "skills/token-optimizer/scripts/_measure/" + name for name in (
487
487
  '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
488
488
  'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
489
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'keepwarm_prefix.py', 'keepwarm_response_filter.py', 'keepwarm_guard.py', 'keepwarm_guard_server.py', 'keepwarm_fork.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py')
489
+ 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py')
490
490
  )
491
491
 
492
492
 
@@ -69,10 +69,10 @@ _MEASURE_PACKAGE_FILES = (
69
69
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
70
70
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
71
71
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
72
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
72
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/savings_headline.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
73
73
  )
74
74
  _MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
75
- _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
75
+ _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
76
76
  _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
77
77
 
78
78
 
@@ -359,10 +359,10 @@ _MEASURE_PACKAGE_FILES = (
359
359
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
360
360
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
361
361
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
362
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
362
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/savings_headline.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
363
363
  )
364
364
  _MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
365
- _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
365
+ _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
366
366
  _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
367
367
 
368
368
 
@@ -102,10 +102,10 @@ _MEASURE_PACKAGE_FILES = (
102
102
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
103
103
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
104
104
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
105
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
105
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py", "_measure/headline.py", "_measure/counted_position.py", "_measure/counted_pricing_v5.py", "_measure/transcript_backfill.py", "_measure/counted_subagents.py", "_measure/lean_resume_threshold.py", "_measure/output_reread.py", "_measure/session_effect.py", "_measure/structural_ledger.py", "_measure/structural_archives.py", "_measure/structural_listing.py", "_measure/structural_report.py", "_measure/structural_seed.py", "_measure/structural_value.py", "_measure/rework_metrics.py", "_measure/session_best.py", "_measure/savings_story.py", "_measure/savings_headline.py", "_measure/counted_orphans.py", "_measure/counted_cap.py", "_measure/archive_void_evidence.py", "_measure/cost_per_message_trend.py", "_measure/lean_resume_receivers.py", "_measure/routing_period.py", "_measure/fixture_context.py", "_measure/transcript_product.py", "_measure/periphery_exposure.py", "_measure/structure_funnel.py", "_measure/setup_attachment_counter.py", "_measure/first_read_outcomes.py", "_measure/setup_budget_monitor.py", "_measure/setup_connector_ledger.py", "_measure/first_call_context.py", "_measure/timestamp_cache.py", "_measure/token_type_split.py", "_measure/evidence_parallel.py", "_measure/ttl_period.py", "_measure/first_read_revive.py", "_measure/mcp_archive_tripwire.py", "_measure/compaction_survival.py", "_measure/archive_void_codex.py", "_measure/compression_fixture_void.py", "_measure/feature_health.py", "_measure/archive_health.py", "_measure/coverage_report.py", "_measure/file_refetch.py", "_measure/holdout_report.py", "_measure/structural_dedupe.py", "_measure/setup_step.py", "_measure/baseline_provenance.py", "_measure/own_price_card.py",
106
106
  )
107
107
  _MEASURE_PACKAGE_FILES += ('_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py')
108
- _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/keepwarm_prefix.py', '_measure/keepwarm_response_filter.py', '_measure/keepwarm_guard.py', '_measure/keepwarm_guard_server.py', '_measure/keepwarm_fork.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
108
+ _MEASURE_PACKAGE_FILES += ('_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py',)
109
109
  _MEASURE_PACKAGE_FILES += ('_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py',)
110
110
 
111
111
 
@@ -1,18 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  // Token Optimizer - Claude Code Status Line (two-row layout)
3
3
  //
4
- // Row 1: model | effort | project | context bar used% | ContextQ:grade(score)
5
- // Row 2: Eff:grade(score) | warnings | Compacts:N(observing) | duration | Agents
4
+ // Row 1: model | effort | project | context bar used% | Quality grade(score)
5
+ // Row 2: savings headline | warnings | duration | Agents | limits
6
6
  //
7
7
  // Install: python3 measure.py setup-quality-bar
8
8
  // The quality score is updated by a UserPromptSubmit hook every ~2 minutes.
9
9
  // Reads from the most recent per-session quality-cache-*.json for accuracy.
10
10
  // Effort level comes from the stdin payload (data.effort.level) when Claude
11
11
  // Code provides it, falling back to settings.json effortLevel on older versions.
12
+ // The savings segment is read from the status-bar JSON cache that
13
+ // `measure.py status-bar` writes under SNAPSHOT_DIR/status-bar/; this script
14
+ // never spawns Python (it runs on every render).
12
15
 
13
16
  const fs = require('fs');
14
17
  const path = require('path');
15
18
  const os = require('os');
19
+ const crypto = require('crypto');
16
20
  const { execFileSync } = require('child_process');
17
21
 
18
22
  // --- Self-disabling guard ---
@@ -124,6 +128,105 @@ function _claudeHome() {
124
128
  }
125
129
  const CLAUDE_HOME = _claudeHome();
126
130
 
131
+ // ---- OSC 8 hyperlink support ----
132
+ // Emit \x1b]8;;URL\x07TEXT\x1b]8;;\x07 only where the terminal is known to
133
+ // render it; everywhere else the segment stays plain text (the approved
134
+ // artboard's fallback). TOKEN_OPTIMIZER_HYPERLINKS=0/1 forces either way.
135
+ // tmux/screen are treated as unsupported: passthrough needs allow-passthrough
136
+ // AND a capable outer terminal, neither of which is detectable here.
137
+ function _supportsOsc8() {
138
+ try {
139
+ const env = process.env;
140
+ const override = String(env.TOKEN_OPTIMIZER_HYPERLINKS || '').trim().toLowerCase();
141
+ if (override === '0' || override === 'false' || override === 'off') return false;
142
+ if (override === '1' || override === 'true' || override === 'on') return true;
143
+ if (env.TMUX || env.STY) return false;
144
+ const tp = String(env.TERM_PROGRAM || '').toLowerCase();
145
+ if (['iterm.app', 'wezterm', 'kitty', 'ghostty', 'vscode', 'visual studio code',
146
+ 'hyper', 'tabby', 'warpterminal', 'alacritty', 'rio', 'contour',
147
+ 'mintty', 'cursor', 'windsurf'].includes(tp)) return true;
148
+ if (tp === 'apple_terminal') return false;
149
+ if (env.WT_SESSION || env.KONSOLE_VERSION || env.ALACRITTY_WINDOW_ID ||
150
+ env.ALACRITTY_LOG || env.KITTY_WINDOW_ID || env.GHOSTTY_RESOURCES_DIR) return true;
151
+ if (/foot|wezterm|kitty|alacritty|ghostty|contour|rio/.test(String(env.TERM || '').toLowerCase())) return true;
152
+ const vte = parseInt(env.VTE_VERSION || '0', 10);
153
+ if (vte >= 5000) return true;
154
+ return false;
155
+ } catch (e) {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ // ---- Status-bar cache (savings headline) ----
161
+ // measure.py resolves SNAPSHOT_DIR as TOKEN_OPTIMIZER_SNAPSHOT_DIR, else
162
+ // <plugin-data>/data, else <runtime>/_backups/token-optimizer. The status line
163
+ // has no CLAUDE_PLUGIN_DATA, so mirror the quality-cache fan-out: check every
164
+ // candidate status-bar dir and keep the freshest cache file for this session.
165
+ function _statusBarDirs() {
166
+ const dirs = [];
167
+ const snap = String(process.env.TOKEN_OPTIMIZER_SNAPSHOT_DIR || '').trim();
168
+ if (snap) dirs.push(path.join(snap, 'status-bar'));
169
+ for (const v of [process.env.CLAUDE_PLUGIN_DATA, process.env.TOKEN_OPTIMIZER_PLUGIN_DATA]) {
170
+ const p = String(v || '').trim();
171
+ if (p) dirs.push(path.join(p, 'data', 'status-bar'));
172
+ }
173
+ try {
174
+ const dataRoot = path.join(CLAUDE_HOME, 'plugins', 'data');
175
+ for (const d of fs.readdirSync(dataRoot)) {
176
+ if (d.includes('token-optimizer')) {
177
+ dirs.push(path.join(dataRoot, d, 'data', 'status-bar'));
178
+ }
179
+ }
180
+ } catch (e) {}
181
+ dirs.push(path.join(CLAUDE_HOME, '_backups', 'token-optimizer', 'status-bar'));
182
+ return dirs;
183
+ }
184
+
185
+ // Python twin of sanitize_session_id + _status_bar_key: strip unsafe chars,
186
+ // "unknown" under 6, and long ids are shortened with a sha256 suffix.
187
+ function _statusBarSessionKey(sessionId) {
188
+ let sid = sessionId === null || sessionId === undefined ? '' : String(sessionId);
189
+ sid = sid.replace(/[^a-zA-Z0-9_-]/g, '');
190
+ if (sid.length < 6) sid = 'unknown';
191
+ if (sid.length <= 100) return sid;
192
+ const hash = crypto.createHash('sha256').update(sid, 'utf8').digest('hex').slice(0, 16);
193
+ return sid.slice(0, 64) + '-' + hash;
194
+ }
195
+
196
+ // The freshest status-bar cache's savings_headline.display, or null.
197
+ // Freshness is decided on computed_at across all candidate dirs BEFORE
198
+ // reading display, so a newer "below threshold" cache correctly hides an
199
+ // older number that no longer applies.
200
+ function _statusBarHeadlineDisplay(sessionId) {
201
+ try {
202
+ const key = _statusBarSessionKey(sessionId);
203
+ if (!key || key === 'unknown') return null;
204
+ let best = null, bestTs = -1;
205
+ for (const dir of _statusBarDirs()) {
206
+ try {
207
+ const file = path.join(dir, key + '.json');
208
+ const raw = fs.readFileSync(file, 'utf8');
209
+ const data = JSON.parse(raw);
210
+ if (!data || typeof data !== 'object') continue;
211
+ const ts = Number(data.computed_at);
212
+ const tsOrMtime = Number.isFinite(ts) ? ts : fs.statSync(file).mtimeMs / 1000;
213
+ if (tsOrMtime <= bestTs) continue;
214
+ bestTs = tsOrMtime;
215
+ best = data;
216
+ } catch (e) {}
217
+ }
218
+ const headline = best && best.savings && best.savings.savings_headline;
219
+ const display = headline && headline.display;
220
+ if (display && typeof display === 'object' &&
221
+ typeof display.short === 'string' && display.short) {
222
+ return display;
223
+ }
224
+ return null;
225
+ } catch (e) {
226
+ return null;
227
+ }
228
+ }
229
+
127
230
  // Host parse (Claude Code 2.1.296 Dd/FOo): scientific notation and thousand
128
231
  // separators first, then a decimal prefix. NaN or <= 0 is invalid and IGNORED
129
232
  // (the next source applies). Mirrors measure.py _host_parse_int; shared vectors
@@ -463,7 +566,7 @@ process.stdin.on('end', () => {
463
566
  // Keep the score's value-color (green/yellow/orange/red) regardless of
464
567
  // staleness; the `~` prefix is the only stale indicator so the number
465
568
  // stays readable. (Dimming the whole score made it barely visible.)
466
- const tag = q.measured === false ? `ContextQ:~${score}` : `ContextQ:${stale ? '~' : ''}${grade}(${score})`;
569
+ const tag = q.measured === false ? `Quality ~${score}` : `Quality ${stale ? '~' : ''}${grade} ${score}`;
467
570
  if (score >= 85) {
468
571
  qScore = `${SEP}\x1b[32m${tag}${RESET}`;
469
572
  } else if (score >= 75) {
@@ -475,7 +578,7 @@ process.stdin.on('end', () => {
475
578
  }
476
579
  }
477
580
  } else {
478
- qScore = `${SEP}${DIM}ContextQ:--${RESET}`;
581
+ qScore = `${SEP}${DIM}Quality --${RESET}`;
479
582
  }
480
583
 
481
584
  const dirname = path.basename(dir);
@@ -494,7 +597,22 @@ process.stdin.on('end', () => {
494
597
  ].filter(Boolean);
495
598
 
496
599
  // ---- ROW 2: Session details ----
600
+ // The savings headline leads the row so packRows keeps it on the first
601
+ // physical line when the terminal is narrow. It comes from the status-bar
602
+ // cache (never a Python spawn) and is omitted entirely when the shared
603
+ // headline's display is null.
497
604
  const row2Parts = [];
605
+ const savingsDisplay = _statusBarHeadlineDisplay(sessionId);
606
+ let savingsSeg = null;
607
+ if (savingsDisplay) {
608
+ const label = `${savingsDisplay.short} ↗`;
609
+ const url = typeof savingsDisplay.url === 'string' && savingsDisplay.url
610
+ ? savingsDisplay.url : null;
611
+ savingsSeg = (url && _supportsOsc8())
612
+ ? `\x1b[32m\x1b]8;;${url}\x07${label}\x1b]8;;\x07${RESET}`
613
+ : `\x1b[32m${label}${RESET}`;
614
+ row2Parts.push(savingsSeg);
615
+ }
498
616
 
499
617
  // U3: near-zero-cost "resumable checkpoint" existence signal.
500
618
  // When the SessionStart pointer fired (a relevance-cleared checkpoint
@@ -510,24 +628,12 @@ process.stdin.on('end', () => {
510
628
  const flag = JSON.parse(fs.readFileSync(flagPath, 'utf8'));
511
629
  const ts = typeof flag.ts === 'number' ? flag.ts : NaN;
512
630
  if (isFinite(ts) && (Date.now() - ts) < (30 * 60 * 1000)) {
513
- row2Parts.push(`\x1b[36m⤸resumable${RESET}`);
631
+ row2Parts.push(`\x1b[36m⤸ resumable${RESET}`);
514
632
  }
515
633
  }
516
634
  }
517
635
  } catch (e) {}
518
636
 
519
- // SessionEfficiency
520
- if (q) {
521
- const se = q.session_efficiency;
522
- if (se != null) {
523
- const seScore = Math.round(se);
524
- const seGrade = q.session_efficiency_grade || gradeFor(seScore);
525
- row2Parts.push(`${DIM}Eff:${seGrade}(${seScore})${RESET}`);
526
- }
527
- } else {
528
- row2Parts.push(`${DIM}Eff:--${RESET}`);
529
- }
530
-
531
637
  // Biggest drag: the actual signal pulling the score down — context fill,
532
638
  // compactions, or the dominant waste cause — computed upstream by weighted
533
639
  // deficit, not guessed from waste keys here.
@@ -555,16 +661,11 @@ process.stdin.on('end', () => {
555
661
  }
556
662
  }
557
663
 
558
- // Recovery thresholds remain shadow-only until calibrated.
664
+ // Compactions only when there were any: "Compacts:0" announced nothing.
559
665
  if (q) {
560
666
  const c = q.compactions;
561
- if (c != null) {
562
- if (c > 0) {
563
- // Recovery evidence is shadow-only, even for older cached flags.
564
- row2Parts.push(`${DIM}Compacts:${c}(observing)${RESET}`);
565
- } else {
566
- row2Parts.push(`\x1b[32mCompacts:0${RESET}`);
567
- }
667
+ if (c != null && c > 0) {
668
+ row2Parts.push(`${DIM}compacted ${c}×${RESET}`);
568
669
  }
569
670
  }
570
671
 
@@ -580,7 +681,12 @@ process.stdin.on('end', () => {
580
681
  }
581
682
 
582
683
  // Active agents
583
- const stripAnsi = s => String(s).replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
684
+ // stripAnsi must drop OSC sequences (\x1b]…\x07 / \x1b]…\x1b\\) as well as
685
+ // CSI: the savings segment is an OSC 8 hyperlink whose raw bytes would
686
+ // otherwise count toward the packed-row width.
687
+ const stripAnsi = s => String(s)
688
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '')
689
+ .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '').replace(/[\x00-\x1f]/g, '');
584
690
  if (cacheMatchesSession && q.active_agents && q.active_agents.length > 0) {
585
691
  const running = q.active_agents.filter(a => a.status === 'running');
586
692
  if (running.length > 0) {
@@ -616,11 +722,13 @@ process.stdin.on('end', () => {
616
722
  pct >= 90 ? '\x1b[5;31m' : pct >= 75 ? '\x1b[38;5;208m' : pct >= 50 ? '\x1b[33m' : '\x1b[32m';
617
723
  if (fiveHour) {
618
724
  const p = Math.ceil(fiveHour.used_percentage);
619
- row2Parts.push(`${limitColor(p)}5h:${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
725
+ row2Parts.push(`${limitColor(p)}5 hours ${p}%${fmtReset(fiveHour.resets_at)}${RESET}`);
620
726
  }
621
727
  if (sevenDay) {
622
728
  const p = Math.ceil(sevenDay.used_percentage);
623
- row2Parts.push(`${DIM}7d:${p}%${RESET}`);
729
+ // Same pressure colours as the 5-hour window: a weekly limit near the
730
+ // cap is the most important number on the line, not a dim footnote.
731
+ row2Parts.push(`${limitColor(p)}week ${p}%${RESET}`);
624
732
  }
625
733
 
626
734
  // Responsive layout: when Claude Code exports COLUMNS (v2.1.153+), greedily pack
@@ -645,12 +753,18 @@ process.stdin.on('end', () => {
645
753
  // fields (row 1), never wrapped, whatever COLUMNS says.
646
754
  const _slim = (process.env.TOKEN_OPTIMIZER_STATUS_BAR_SIZE || '').trim().toLowerCase() === 'slim';
647
755
  if (_slim) {
648
- process.stdout.write(row1Segs.join(SEP));
756
+ // Slim prints row 1 only, so the savings pill is appended there or it
757
+ // would never be seen.
758
+ process.stdout.write(savingsSeg ? row1Segs.concat([savingsSeg]).join(SEP) : row1Segs.join(SEP));
649
759
  } else if (_width) {
650
760
  const rows = [...packRows(row1Segs, _width), ...packRows(row2Parts, _width)];
651
761
  process.stdout.write(rows.join('\n'));
652
762
  } else {
653
- process.stdout.write(`${row1Segs.join(SEP)}\n${row2Parts.join(SEP)}`);
763
+ // Row 2 can be legitimately empty (no savings display, no quality cache,
764
+ // no limits): emit one line rather than a dangling blank second row.
765
+ const row1Text = row1Segs.join(SEP);
766
+ const row2Text = row2Parts.join(SEP);
767
+ process.stdout.write(row2Text ? `${row1Text}\n${row2Text}` : row1Text);
654
768
  }
655
769
  } catch (e) {
656
770
  // Silent fail - never break the status line