@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -1,7 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat
4
-
3
+ from . import _compat, coverage_report, dashboard_history, feature_health, holdout_report, structural_ledger, archive_health
5
4
 
6
5
  def _daemon_is_running():
7
6
  """Return True iff the dashboard daemon identity probe passes.
@@ -26,7 +25,6 @@ def _daemon_is_running():
26
25
  continue
27
26
  return False
28
27
 
29
-
30
28
  def _launch_opener(argv):
31
29
  """Run a browser opener detached from our terminal (#199).
32
30
 
@@ -57,7 +55,6 @@ def _launch_opener(argv):
57
55
  if rc != 0:
58
56
  raise _measure_facade.subprocess.CalledProcessError(rc, argv)
59
57
 
60
-
61
58
  def _open_in_browser(filepath):
62
59
  """Open a file in the default browser. Cross-platform.
63
60
 
@@ -82,7 +79,6 @@ def _open_in_browser(filepath):
82
79
  print("\n Could not auto-open browser. Open manually:")
83
80
  print(f" {url}")
84
81
 
85
-
86
82
  def _open_dashboard(fallback_filepath):
87
83
  """Open the dashboard, preferring the bookmarkable URL.
88
84
 
@@ -117,7 +113,6 @@ def _open_dashboard(fallback_filepath):
117
113
  # Daemon down: open the file directly
118
114
  _measure_facade._open_in_browser(fallback_filepath)
119
115
 
120
-
121
116
  def _serve_dashboard(filepath, port=None, host=None):
122
117
  """Serve the dashboard over HTTP for headless/remote access."""
123
118
  _measure_facade = _compat.facade()
@@ -128,7 +123,7 @@ def _serve_dashboard(filepath, port=None, host=None):
128
123
  filepath = _measure_facade.Path(filepath).resolve()
129
124
  serve_dir = str(filepath.parent)
130
125
  filename = filepath.name
131
-
126
+ _measure_facade._get_or_create_daemon_token()
132
127
  # Find an available port if the default is taken
133
128
  for attempt_port in range(port, port + 20):
134
129
  try:
@@ -283,7 +278,6 @@ def _serve_dashboard(filepath, port=None, host=None):
283
278
  self.send_error(413, "Request body too large")
284
279
  return
285
280
 
286
- # Read JSON body
287
281
  body = {}
288
282
  if content_len > 0:
289
283
  try:
@@ -291,6 +285,22 @@ def _serve_dashboard(filepath, port=None, host=None):
291
285
  except (_measure_facade.json.JSONDecodeError, ValueError):
292
286
  pass
293
287
 
288
+ if not isinstance(body, dict): body = {}
289
+ if path == "/api/regenerate":
290
+ choice = body.get("days", dashboard_history.load(_measure_facade.RUNTIME_DIR))
291
+ if not dashboard_history.valid(choice):
292
+ self._json_response(400, {"ok": False, "msg": "invalid history window"})
293
+ return
294
+ try:
295
+ days = dashboard_history.resolve_days(choice, _measure_facade.TRENDS_DB)
296
+ out = _measure_facade.generate_standalone_dashboard(days=days, quiet=True, force=True)
297
+ if out and "days" in body:
298
+ dashboard_history.save(_measure_facade.RUNTIME_DIR, choice)
299
+ self._json_response(200 if out else 500, {"ok": bool(out)})
300
+ except Exception:
301
+ self._json_response(500, {"ok": False, "msg": "regeneration failed"})
302
+ return
303
+
294
304
  if path == "/api/session-turns":
295
305
  raw_path = body.get("jsonl_path", "")
296
306
  if not raw_path:
@@ -436,7 +446,6 @@ def _serve_dashboard(filepath, port=None, host=None):
436
446
  except KeyboardInterrupt:
437
447
  print("\n Server stopped.")
438
448
 
439
-
440
449
  def _sanitize_dashboard_paths(data):
441
450
  """Redact home-directory prefixes from paths embedded in dashboard HTML.
442
451
 
@@ -469,7 +478,6 @@ def _sanitize_dashboard_paths(data):
469
478
 
470
479
  return data
471
480
 
472
-
473
481
  def _codex_state_summary():
474
482
  """Collect Codex runtime-state metrics for display, or None unless Codex.
475
483
 
@@ -541,7 +549,6 @@ def _codex_state_summary():
541
549
  pass
542
550
  return summary
543
551
 
544
-
545
552
  def codex_state_report(as_json=None):
546
553
  """Print the Codex runtime-state summary (subagents, memory, goals, signals)."""
547
554
  _measure_facade = _compat.facade()
@@ -612,7 +619,6 @@ def codex_state_report(as_json=None):
612
619
  f"avg compression to {comp['avg_ratio'] * 100:.0f}% of pre-compaction context")
613
620
  print()
614
621
 
615
-
616
622
  def generate_dashboard(coord_path):
617
623
  """Generate an interactive HTML dashboard from audit results."""
618
624
  _measure_facade = _compat.facade()
@@ -684,7 +690,7 @@ def generate_dashboard(coord_path):
684
690
  # Collect trends and health data
685
691
  print(" Collecting usage trends...")
686
692
  try:
687
- trends = _measure_facade._collect_trends_data(days=30)
693
+ trends = _measure_facade._collect_trends_data(days=dashboard_history.selected_days(_measure_facade.RUNTIME_DIR, _measure_facade.TRENDS_DB))
688
694
  except Exception:
689
695
  trends = None
690
696
  print(" Checking session health...")
@@ -704,28 +710,28 @@ def generate_dashboard(coord_path):
704
710
  print(" Analyzing context quality...")
705
711
  quality = _measure_facade._collect_quality_for_dashboard()
706
712
 
707
- # Collect hook installation status for dashboard toggles
708
713
  hook_status = _measure_facade._collect_hook_status_for_dashboard()
709
714
 
710
- # Collect management data for Manage tab. The full audit dashboard should
711
- # expose the same Codex skill/MCP controls as the standalone dashboard.
712
715
  management = _measure_facade._collect_management_data(components=components, trends=trends)
713
716
 
714
- # Savings data for dashboard. Merged view = measured runtime + realized
715
- # structural + opportunity (unclaimed) + estimated uncaptured runtime, all
716
- # tier-labelled. Wrapped so a slow/failed savings eval never blocks regen.
717
717
  print(" Collecting savings data...")
718
718
  savings_data = _measure_facade._dashboard_savings_data(days=30)
719
719
 
720
- # U6: tiered compression-coverage diagnostic (kept separate from savings;
721
- # shadow/opportunity ratios never feed the headline). Fail-open to empty.
720
+ # Savings-truth U6: lean-resume carry is a SHADOW diagnostic. It is emitted
721
+ # for review only and is never summed into any savings total.
722
+ try:
723
+ import lean_resume_carry as _lean_resume_carry
724
+ if isinstance(savings_data, dict):
725
+ savings_data["lean_resume_carry"] = _lean_resume_carry.summary(days=30)
726
+ except Exception:
727
+ if isinstance(savings_data, dict):
728
+ savings_data["lean_resume_carry"] = {"available": False, "evidence": "shadow"}
729
+
722
730
  try:
723
731
  compression_coverage = _measure_facade._get_compression_coverage(days=30)
724
732
  except Exception:
725
733
  compression_coverage = {"available": False, "tiers": {}, "first_read_proxy": None}
726
734
 
727
- # Tripwire verdict for the coverage panel (per-cohort live edit-rate +
728
- # auto-demotions). Read-only; never recomputes/demotes here. Fail-open.
729
735
  try:
730
736
  cohort_tripwire = _measure_facade._cohort_tripwire_state()
731
737
  except Exception:
@@ -764,7 +770,7 @@ def generate_dashboard(coord_path):
764
770
  # when the meter has never been read at all (a stale-but-present reading is
765
771
  # kept and dated on the card), and the template simply omits the card.
766
772
  try:
767
- runway = _measure_facade.runway_snapshot(days=30)
773
+ runway = _measure_facade.runway_snapshot(days=30, token_headline=savings_data.get("token_headline"))
768
774
  except Exception:
769
775
  runway = None
770
776
 
@@ -783,6 +789,9 @@ def generate_dashboard(coord_path):
783
789
  "savings": savings_data,
784
790
  "compression_coverage": compression_coverage,
785
791
  "cache_health": cache_health,
792
+ "feature_health": feature_health.collect(_measure_facade.TRENDS_DB),
793
+ "coverage_funnel": coverage_report.collect(_measure_facade.TRENDS_DB),
794
+ "holdout": holdout_report.collect(_measure_facade.TRENDS_DB),
786
795
  "auto_plan": auto_plan_flag,
787
796
  "generated_at": _measure_facade.datetime.now().isoformat(),
788
797
  "version": _measure_facade.TOKEN_OPTIMIZER_VERSION,
@@ -794,6 +803,11 @@ def generate_dashboard(coord_path):
794
803
 
795
804
  # Load template and inject data
796
805
  template = template_path.read_text(encoding="utf-8")
806
+ try: # U9: inline renderer modules kept beside the template (fail-open)
807
+ import dashboard_assets as _dashboard_assets
808
+ template = _dashboard_assets.inline(template, template_path.parent)
809
+ except Exception:
810
+ pass
797
811
  data_json = _measure_facade.json.dumps(data, ensure_ascii=True, default=str)
798
812
  data_json = data_json.replace("</", "<\\/") # Prevent </script> injection
799
813
  placeholder = "window.__TOKEN_DATA__ = null;"
@@ -848,13 +862,11 @@ def generate_dashboard(coord_path):
848
862
  _measure_facade._open_dashboard(fallback_filepath=out_path)
849
863
  return str(out_path)
850
864
 
851
-
852
865
  def _shell_script_path():
853
866
  """This script's resolved path, quoted to paste into Bash, PowerShell and cmd.exe."""
854
867
  _measure_facade = _compat.facade()
855
868
  return _measure_facade.shell_path(_measure_facade.Path(_measure_facade.__file__).resolve())
856
869
 
857
-
858
870
  def _measure_cli(*args):
859
871
  """The command that runs this script, for hints a user will paste into a shell.
860
872
 
@@ -869,7 +881,6 @@ def _measure_cli(*args):
869
881
  parts.extend(args)
870
882
  return " ".join(parts)
871
883
 
872
-
873
884
  def _runtime_cli(runtime, *args):
874
885
  """`_measure_cli` pinned to a runtime for hints.
875
886
 
@@ -885,7 +896,6 @@ def _runtime_cli(runtime, *args):
885
896
  parts.extend(args)
886
897
  return " ".join(parts)
887
898
 
888
-
889
899
  def _hint(text):
890
900
  """Make a printed hint pasteable from any directory.
891
901
 
@@ -897,13 +907,11 @@ def _hint(text):
897
907
  text = _measure_facade._ENV_PREFIXED_BARE_HINT.sub(lambda m: ((_measure_facade := _compat.facade()), _measure_facade._runtime_cli(m.group(1)))[1], text)
898
908
  return text.replace("python3 measure.py", _measure_facade._measure_cli())
899
909
 
900
-
901
910
  def _subagent_cache_cmd(action=None):
902
911
  """The `subagent-cache [action]` command users are told to run (advice, enable, undo)."""
903
912
  _measure_facade = _compat.facade()
904
913
  return _measure_facade._measure_cli("subagent-cache", *([action] if action else []))
905
914
 
906
-
907
915
  def _display_path(absolute_path):
908
916
  """Replace the user's home directory with ~ for display purposes.
909
917
 
@@ -918,7 +926,6 @@ def _display_path(absolute_path):
918
926
  return "~" + s[len(home):]
919
927
  return s
920
928
 
921
-
922
929
  def _collect_hook_status_for_dashboard():
923
930
  """Collect hook installation status for dashboard toggle panel."""
924
931
  _measure_facade = _compat.facade()
@@ -963,7 +970,6 @@ def _collect_hook_status_for_dashboard():
963
970
  },
964
971
  }
965
972
 
966
-
967
973
  def _collect_codex_hook_status_for_dashboard():
968
974
  """Collect Codex project hook status for dashboard toggle panel."""
969
975
  _measure_facade = _compat.facade()
@@ -1039,7 +1045,6 @@ def _collect_codex_hook_status_for_dashboard():
1039
1045
  },
1040
1046
  }
1041
1047
 
1042
-
1043
1048
  def _collect_copilot_hook_status_for_dashboard():
1044
1049
  """Hook status for the dashboard toggle panel under the Copilot runtime.
1045
1050
 
@@ -1105,7 +1110,6 @@ def _collect_copilot_hook_status_for_dashboard():
1105
1110
  },
1106
1111
  }
1107
1112
 
1108
-
1109
1113
  def _collect_cursor_hook_status_for_dashboard():
1110
1114
  """Hook status for the dashboard toggle panel under the Cursor runtime.
1111
1115
 
@@ -1160,7 +1164,6 @@ def _collect_cursor_hook_status_for_dashboard():
1160
1164
  },
1161
1165
  }
1162
1166
 
1163
-
1164
1167
  def _collect_grok_hook_status_for_dashboard():
1165
1168
  """Hook status for the dashboard toggle panel under the Grok Build runtime.
1166
1169
 
@@ -1211,7 +1214,6 @@ def _collect_grok_hook_status_for_dashboard():
1211
1214
  },
1212
1215
  }
1213
1216
 
1214
-
1215
1217
  def _collect_hermes_hook_status_for_dashboard():
1216
1218
  """Collect Hermes plugin hook status for dashboard toggle panel.
1217
1219
 
@@ -1266,7 +1268,6 @@ def _collect_hermes_hook_status_for_dashboard():
1266
1268
  },
1267
1269
  }
1268
1270
 
1269
-
1270
1271
  def _collect_antigravity_hook_status_for_dashboard():
1271
1272
  """Antigravity plugin hook status for the dashboard toggle panel.
1272
1273
 
@@ -1325,7 +1326,6 @@ def _collect_antigravity_hook_status_for_dashboard():
1325
1326
  },
1326
1327
  }
1327
1328
 
1328
-
1329
1329
  def _parse_skill_frontmatter(path: Path) -> dict:
1330
1330
  _measure_facade = _compat.facade()
1331
1331
  try:
@@ -1355,7 +1355,6 @@ def _parse_skill_frontmatter(path: Path) -> dict:
1355
1355
  meta["body_tokens"] = _measure_facade._estimate_tokens(text)
1356
1356
  return meta
1357
1357
 
1358
-
1359
1358
  def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, list[dict]]:
1360
1359
  _measure_facade = _compat.facade()
1361
1360
  disabled_paths = set()
@@ -1469,7 +1468,6 @@ def _collect_codex_skill_inventory(cfg: dict, *, project: Path) -> dict[str, lis
1469
1468
  disabled.sort(key=lambda item: ((_measure_facade := _compat.facade()), (item["source"], item["name"]))[1])
1470
1469
  return {"active": active, "disabled": disabled}
1471
1470
 
1472
-
1473
1471
  def _collect_codex_mcp_inventory(cfg: dict) -> list[dict]:
1474
1472
  _measure_facade = _compat.facade()
1475
1473
  servers = cfg.get("mcp_servers")
@@ -1494,7 +1492,6 @@ def _collect_codex_mcp_inventory(cfg: dict) -> list[dict]:
1494
1492
  })
1495
1493
  return sorted(items, key=lambda item: ((_measure_facade := _compat.facade()), item["name"])[1])
1496
1494
 
1497
-
1498
1495
  def _collect_codex_plugin_inventory(cfg: dict) -> list[dict]:
1499
1496
  _measure_facade = _compat.facade()
1500
1497
  plugins = cfg.get("plugins")
@@ -1508,12 +1505,10 @@ def _collect_codex_plugin_inventory(cfg: dict) -> list[dict]:
1508
1505
  items.append({"name": name, "enabled": enabled})
1509
1506
  return sorted(items, key=lambda item: ((_measure_facade := _compat.facade()), item["name"])[1])
1510
1507
 
1511
-
1512
1508
  def _codex_config_path() -> Path:
1513
1509
  _measure_facade = _compat.facade()
1514
1510
  return _measure_facade.runtime_home() / "config.toml"
1515
1511
 
1516
-
1517
1512
  def _safe_codex_config_path() -> Path:
1518
1513
  _measure_facade = _compat.facade()
1519
1514
  home = _measure_facade.runtime_home().resolve(strict=False)
@@ -1530,7 +1525,6 @@ def _safe_codex_config_path() -> Path:
1530
1525
  parent.mkdir(mode=0o700)
1531
1526
  return path
1532
1527
 
1533
-
1534
1528
  def _codex_config_lock():
1535
1529
  """Bounded portable lease for config.toml writes.
1536
1530
 
@@ -1547,7 +1541,6 @@ def _codex_config_lock():
1547
1541
  ) as acquired:
1548
1542
  yield acquired
1549
1543
 
1550
-
1551
1544
  def _skill_mgmt_lock():
1552
1545
  """Bounded portable lease serializing skill archive/restore mutations.
1553
1546
 
@@ -2047,6 +2040,7 @@ def plugin_cleanup(dry_run=None, quiet=None):
2047
2040
  shutil.move(str(item), str(dest))
2048
2041
  if not quiet:
2049
2042
  print(f" archived: {item.name} -> {archive_dir.name}/")
2043
+ structural_ledger.record_skill_action("archive", item.name, dest)
2050
2044
  actions_taken.append(f"archived duplicate local skill: {item.name}")
2051
2045
  except OSError as e:
2052
2046
  if not quiet:
@@ -2132,6 +2126,7 @@ def _manage_skill_locked(action, name):
2132
2126
  except OSError as e:
2133
2127
  print(f" [!] Failed to archive '{name}': {e}")
2134
2128
  return False
2129
+ structural_ledger.record_skill_action("archive", name, dst)
2135
2130
  print(f" Archived: {name} -> {archive_dir.name}/")
2136
2131
  return True
2137
2132
 
@@ -2175,6 +2170,7 @@ def _manage_skill_locked(action, name):
2175
2170
  except OSError as e:
2176
2171
  print(f" [!] Failed to restore '{name}': {e}")
2177
2172
  return False
2173
+ structural_ledger.record_skill_action("restore", name, dst)
2178
2174
  print(f" Restored: {name} from {ad.name}/")
2179
2175
  # Clean up empty archive dir
2180
2176
  try:
@@ -2278,6 +2274,8 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2278
2274
  # version-mismatch regen path so a freshly-updated plugin always
2279
2275
  # wins over a recently-written stale file.
2280
2276
  _measure_facade = _compat.facade()
2277
+ if days is None:
2278
+ days = dashboard_history.resolve_days(dashboard_history.load(_measure_facade.RUNTIME_DIR), _measure_facade.TRENDS_DB)
2281
2279
  if quiet and not force and _measure_facade.DASHBOARD_PATH.exists():
2282
2280
  try:
2283
2281
  age = _measure_facade.time.time() - _measure_facade.DASHBOARD_PATH.stat().st_mtime
@@ -2520,7 +2518,7 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2520
2518
  # setups or when the meter has never been read (a stale-but-present reading is
2521
2519
  # kept and dated on the card), and the template omits the card.
2522
2520
  try:
2523
- runway = _measure_facade.runway_snapshot(days=30)
2521
+ runway = _measure_facade.runway_snapshot(days=30, token_headline=savings_data.get("token_headline"))
2524
2522
  except Exception:
2525
2523
  runway = None
2526
2524
 
@@ -2536,7 +2534,11 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2536
2534
  "manage": management,
2537
2535
  "hooks": hook_status,
2538
2536
  "savings": savings_data,
2537
+ "archive_replacement_check": archive_health.replacement_check(_measure_facade),
2539
2538
  "cache_health": cache_health,
2539
+ "feature_health": feature_health.collect(_measure_facade.TRENDS_DB),
2540
+ "coverage_funnel": coverage_report.collect(_measure_facade.TRENDS_DB),
2541
+ "holdout": holdout_report.collect(_measure_facade.TRENDS_DB),
2540
2542
  "standalone": True,
2541
2543
  "auto_plan": True,
2542
2544
  "generated_at": _measure_facade.datetime.now().isoformat(),
@@ -2555,6 +2557,11 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2555
2557
  data = _measure_facade._sanitize_dashboard_paths(data)
2556
2558
 
2557
2559
  template = template_path.read_text(encoding="utf-8")
2560
+ try: # U9: inline renderer modules kept beside the template (fail-open)
2561
+ import dashboard_assets as _dashboard_assets
2562
+ template = _dashboard_assets.inline(template, template_path.parent)
2563
+ except Exception:
2564
+ pass
2558
2565
  data_json = _measure_facade.json.dumps(data, ensure_ascii=True, default=str)
2559
2566
  data_json = data_json.replace("</", "<\\/") # Prevent </script> injection
2560
2567
  placeholder = "window.__TOKEN_DATA__ = null;"
@@ -2659,8 +2666,32 @@ def _dispatch_dashboard(args):
2659
2666
  print(f"[Error] Invalid --port value: {args[i + 1]}")
2660
2667
  _measure_facade.sys.exit(1)
2661
2668
  serve = True
2669
+
2670
+ def _note_hook_bounded():
2671
+ """One stderr line when this run is bounded as a hook.
2672
+
2673
+ A piped-stdin invocation (an agent's shell tool, a runner script) is
2674
+ indistinguishable from a real hook, so the 20s budget can kill a heavy
2675
+ rebuild and the run exits 1 with no explanation -- the "dashboard
2676
+ quietly skips itself" report. Real hook launchers pass --quiet, so
2677
+ gating on it keeps hook logs clean while every non-quiet bounded run
2678
+ says why and names the --user escape hatch. stderr only: stdout stays
2679
+ clean for the `Dashboard:` line consumers parse.
2680
+ """
2681
+ if "--quiet" in args or "-q" in args:
2682
+ return
2683
+ print(
2684
+ "[Token Optimizer] dashboard: stdin is not a terminal, so this run "
2685
+ "is treated as a hook and the rebuild is capped at a "
2686
+ f"{_measure_facade._dashboard_hook_budget_seconds():g}s budget; it "
2687
+ "may be killed before it finishes or opens. Pass --user to force "
2688
+ "an interactive run.",
2689
+ file=_measure_facade.sys.stderr,
2690
+ )
2691
+
2662
2692
  if not cp:
2663
- days = 30
2693
+ choice = dashboard_history.load(_measure_facade.RUNTIME_DIR)
2694
+ explicit = False
2664
2695
  quiet = "--quiet" in args or "-q" in args
2665
2696
  # --force bypasses the 60s write throttle. The detached version-bump
2666
2697
  # self-heal passes it so a stale file just written by a killed regen
@@ -2669,12 +2700,20 @@ def _dispatch_dashboard(args):
2669
2700
  for i, a in enumerate(args):
2670
2701
  if a == "--days" and i + 1 < len(args):
2671
2702
  try:
2672
- days = int(args[i + 1])
2703
+ choice = 'all' if args[i + 1] == 'all' else int(args[i + 1])
2704
+ if not dashboard_history.valid(choice):
2705
+ raise ValueError()
2706
+ explicit = True
2673
2707
  except ValueError:
2674
- pass
2708
+ print("[Error] --days must be a positive integer or all")
2709
+ _measure_facade.sys.exit(1)
2710
+ days = dashboard_history.resolve_days(choice, _measure_facade.TRENDS_DB)
2711
+ force = force or explicit
2675
2712
  deadline = (
2676
2713
  None if (serve or not _measure_facade._running_under_hook()) else _measure_facade._install_hook_budget(_measure_facade._dashboard_hook_budget_seconds())
2677
2714
  )
2715
+ if deadline is not None:
2716
+ _note_hook_bounded()
2678
2717
  timed_out = False
2679
2718
  try:
2680
2719
  lock = (_measure_facade._dashboard_selfheal_build_lock()
@@ -2698,6 +2737,11 @@ def _dispatch_dashboard(args):
2698
2737
  # applies, so a forced heal never clobbers a newer dashboard).
2699
2738
  if timed_out:
2700
2739
  _measure_facade._spawn_detached_dashboard_selfheal(days=days, force=force)
2740
+ if out and explicit and not _measure_facade.os.environ.get("TOKEN_OPTIMIZER_DASHBOARD_SELFHEAL"):
2741
+ try:
2742
+ dashboard_history.save(_measure_facade.RUNTIME_DIR, choice)
2743
+ except OSError:
2744
+ pass
2701
2745
  if out and serve:
2702
2746
  _measure_facade._serve_dashboard(out, port=serve_port, host=serve_host)
2703
2747
  elif out and not quiet:
@@ -2706,6 +2750,8 @@ def _dispatch_dashboard(args):
2706
2750
  deadline = (
2707
2751
  None if (serve or not _measure_facade._running_under_hook()) else _measure_facade._install_hook_budget(_measure_facade._dashboard_hook_budget_seconds())
2708
2752
  )
2753
+ if deadline is not None:
2754
+ _note_hook_bounded()
2709
2755
  timed_out = False
2710
2756
  try:
2711
2757
  out = _measure_facade.generate_dashboard(cp)
@@ -3019,12 +3065,9 @@ def _query_trends_db(conn, days):
3019
3065
  "jsonl_path": jsonl_path,
3020
3066
  "topic": sr["topic"],
3021
3067
  "project": _measure_facade._clean_project_name(sr["project"]),
3022
- # cost_usd is THIS day's share; session_cost_usd is the whole session.
3023
3068
  "cost_usd": round(day_cost, 4),
3024
3069
  "session_cost_usd": round(session_total_cost, 4),
3025
- # input/output_tokens above are whole-session totals (the row
3026
- # describes the session); these are this day's share, the same
3027
- # numbers the day's total_input/total_output add up.
3070
+ # These token counts cover this day, not the whole session.
3028
3071
  "day_input_tokens": day_in,
3029
3072
  "day_output_tokens": day_out,
3030
3073
  "spans_days": len(du) > 1,
@@ -3034,16 +3077,21 @@ def _query_trends_db(conn, days):
3034
3077
  "model": _measure_facade._normalize_model_name(dom_model) or dom_model,
3035
3078
  "model_count": len(mu) if mu else 1,
3036
3079
  }
3037
- # Prefer stored quality score (persisted during collect), fall back to recomputation
3038
- if sr["quality_score"] is not None:
3039
- sd["quality_score"] = sr["quality_score"]
3040
- sd["quality_grade"] = sr["quality_grade"] or _measure_facade.score_to_grade(round(sr["quality_score"]))
3041
- sd["quality_band"] = _measure_facade.score_to_band(sr["quality_score"])
3080
+ # Legacy session_log quality fields have no score version.
3081
+ try:
3082
+ qc = _measure_facade._read_quality_cache(_measure_facade._quality_cache_path_for(_measure_facade.Path(jsonl_path))) or {}
3083
+ except (OSError, ValueError, TypeError):
3084
+ qc = {}
3085
+ if qc.get("score_version") == _measure_facade._QUALITY_SCORE_VERSION and qc.get("session_file") == _measure_facade.Path(jsonl_path).name:
3086
+ sd["quality_score"] = qc.get("score")
3087
+ sd["quality_grade"] = qc.get("grade", "?")
3088
+ sd["quality_measured"] = qc.get("measured", False)
3089
+ sd["quality_band"] = _measure_facade.score_to_band(qc["score"]) if sd["quality_measured"] else "Unmeasured"
3042
3090
  else:
3043
- sq = _measure_facade.score_session_quality(sd)
3044
- sd["quality_score"] = sq["score"]
3045
- sd["quality_grade"] = sq["grade"]
3046
- sd["quality_band"] = sq["band"]
3091
+ sd["quality_score"] = None
3092
+ sd["quality_grade"] = "?"
3093
+ sd["quality_measured"] = False
3094
+ sd["quality_band"] = "Unmeasured"
3047
3095
  d["session_details"].append(sd)
3048
3096
  if window_unpriced > 0:
3049
3097
  total_unpriced_sessions += 1
@@ -3055,14 +3103,13 @@ def _query_trends_db(conn, days):
3055
3103
  d["total_cost_usd"] = round(sum(float(sd.get("cost_usd") or 0.0) for sd in details), 4)
3056
3104
  d["cost_priced_tokens"] = sum(int(sd.get("cost_priced_tokens") or 0) for sd in details)
3057
3105
  d["cost_unpriced_tokens"] = sum(int(sd.get("cost_unpriced_tokens") or 0) for sd in details)
3058
- scores = [float(sd["quality_score"]) for sd in details if sd.get("quality_score") is not None]
3106
+ scores = [float(sd["quality_score"]) for sd in details if sd.get("quality_measured") and sd.get("quality_score") is not None]
3059
3107
  if scores:
3060
3108
  d["avg_quality_score"] = round(sum(scores) / len(scores), 1)
3061
- grades = [sd.get("quality_grade") for sd in details if sd.get("quality_grade")]
3109
+ grades = [sd.get("quality_grade") for sd in details if sd.get("quality_measured") and sd.get("quality_grade")]
3062
3110
  if grades:
3063
3111
  d["worst_grade"] = min(grades, key=lambda grade: ((_measure_facade := _compat.facade()), grade_rank.get(grade, 999))[1])
3064
3112
 
3065
- # Rolling quality trend from session_log
3066
3113
  quality_trend_rows = conn.execute(
3067
3114
  """SELECT date,
3068
3115
  AVG(quality_score) as avg_q,
@@ -3070,7 +3117,7 @@ def _query_trends_db(conn, days):
3070
3117
  MAX(quality_score) as max_q,
3071
3118
  COUNT(*) as n
3072
3119
  FROM session_log
3073
- WHERE date >= ? AND quality_score IS NOT NULL
3120
+ WHERE date >= ? AND quality_score IS NOT NULL AND quality_grade != '?'
3074
3121
  GROUP BY date ORDER BY date""",
3075
3122
  (cutoff,),
3076
3123
  ).fetchall()
@@ -3085,8 +3132,6 @@ def _query_trends_db(conn, days):
3085
3132
  for r in quality_trend_rows
3086
3133
  ]
3087
3134
 
3088
- # conn.close() removed — caller (_collect_trends_from_db) owns the connection
3089
- # and closes it in its finally block (double-close fix).
3090
3135
 
3091
3136
  # Pricing tier info for dashboard
3092
3137
  pricing_tier = _measure_facade._load_pricing_tier()
@@ -3314,13 +3359,19 @@ def _collect_git_commits(days=None):
3314
3359
  def _collect_trends_data(days=None):
3315
3360
  """Collect trends data, preferring SQLite DB when available.
3316
3361
 
3317
- Falls back to live JSONL parsing if DB doesn't exist or is empty.
3318
- """
3362
+ Falls back to live JSONL parsing if DB doesn't exist or is empty."""
3319
3363
  # Try SQLite first (faster, accumulated data)
3320
3364
  _measure_facade = _compat.facade()
3321
3365
  result = _measure_facade._collect_trends_from_db(days)
3322
3366
  if result is not None:
3323
- result["git_commits"] = _measure_facade._collect_git_commits(days)
3367
+ from . import first_call_context; result["first_call_context"] = first_call_context.collect(_measure_facade.TRENDS_DB, _measure_facade.SNAPSHOT_DIR); result["git_commits"] = _measure_facade._collect_git_commits(days)
3368
+ try:
3369
+ from . import setup_step, structural_value
3370
+ result["first_call_context"] = {**result["first_call_context"], "setup_steps": setup_step.collect(
3371
+ _measure_facade.TRENDS_DB, _measure_facade.SNAPSHOT_DIR, _measure_facade.CLAUDE_DIR,
3372
+ structural_value.card_resolver(_measure_facade))}
3373
+ except Exception:
3374
+ pass # the card renders without the measured steps
3324
3375
  return result
3325
3376
  # Fall back to live JSONL parsing
3326
3377
  result = _measure_facade._collect_trends_from_jsonl(days)
@@ -3332,7 +3383,7 @@ def _collect_trends_data(days=None):
3332
3383
  def _build_ttl_period_summary(period_days):
3333
3384
  """Build a compact TTL mix summary for a given period."""
3334
3385
  _measure_facade = _compat.facade()
3335
- trends = _measure_facade._collect_trends_data(days=period_days)
3386
+ from . import ttl_period; trends = ttl_period.base_trends(_measure_facade, period_days)
3336
3387
  if not trends:
3337
3388
  return {
3338
3389
  "label": f"{period_days}d: no cache-write data",
@@ -3521,6 +3572,8 @@ def _realized_savings_buckets(conn, cutoff, session_uuid=None, by_day=None):
3521
3572
  params.extend([session_uuid, session_uuid])
3522
3573
  se_sql = _measure_facade._BUCKET_SAVINGS_SQL[
3523
3574
  _measure_facade._counted_table(conn, "savings_events"), bool(by_day), session_uuid is not None]
3575
+ se_table = _measure_facade._counted_table(conn, "savings_events")
3576
+ if "detail" not in {r[1] for r in conn.execute(f"PRAGMA table_info({se_table})")}: se_sql = se_sql.replace(_measure_facade._counted_cap.reexpand_type(), "event_type")
3524
3577
  ce_sql = _measure_facade._BUCKET_COMPRESSION_SQL[
3525
3578
  _measure_facade._counted_table(conn, "compression_events"), bool(by_day), session_uuid is not None]
3526
3579
  se_rows = conn.execute(se_sql, tuple(params)).fetchall()
@@ -3579,14 +3632,14 @@ def _open_trends_db_readonly(timeout=None):
3579
3632
 
3580
3633
 
3581
3634
  def _dashboard_saved_tokens(summary):
3582
- """The dashboard's Tokens Saved headline: measured plus the estimated tier.
3583
-
3584
- Mirrors tokensSavedCardHtml in assets/dashboard.html exactly (same fields,
3585
- same `a || b` fallbacks), so the status bar and the dashboard never disagree.
3586
- """
3635
+ """Return the dashboard token total and its measured floor."""
3587
3636
  _measure_facade = _compat.facade()
3588
3637
  s = summary or {}
3589
3638
 
3639
+ if isinstance(s.get("action_savings"), dict) and isinstance(s.get("token_headline"), dict):
3640
+ from . import savings_story
3641
+ return savings_story.story_token_total(s), max(0, int(s.get("total_tokens") or 0))
3642
+
3590
3643
  def num(v):
3591
3644
  _measure_facade = _compat.facade()
3592
3645
  try:
@@ -3601,14 +3654,8 @@ def _dashboard_saved_tokens(summary):
3601
3654
  except AttributeError:
3602
3655
  return 0
3603
3656
 
3604
- estimated = (tok(s.get("mcp_cap_estimated"))
3605
- + tok(s.get("hint_followed") or s.get("hint_followed_estimated"))
3606
- + tok(s.get("verbosity_steer") or s.get("verbosity_steer_estimated"))
3607
- + tok(s.get("resume_lean_estimated"))
3608
- + tok(s.get("checkpoint_restore_estimated")))
3657
+ estimated = tok(s.get("hint_followed") or s.get("hint_followed_estimated"))
3609
3658
  measured = num(s.get("total_tokens", 0))
3610
- # The dashboard draws no Tokens Saved card only when nothing was measured
3611
- # AND nothing estimated exists -- estimates still surface on their own.
3612
3659
  return measured + estimated, measured
3613
3660
 
3614
3661
 
@@ -3623,9 +3670,8 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3623
3670
  try:
3624
3671
  conn = _measure_facade._open_trends_db_readonly()
3625
3672
  try:
3626
- # One read transaction: both bucket reads see the same committed rows (the
3627
- # 30-day headline below runs on its own connection, as the dashboard's does).
3628
3673
  conn.execute("BEGIN")
3674
+ has_counted = bool(conn.execute("SELECT 1 FROM counted_reread LIMIT 1").fetchone())
3629
3675
  days = _measure_facade._realized_savings_buckets(conn, cutoff, by_day=True)
3630
3676
  window = _measure_facade._realized_savings_buckets(conn, cutoff).get("", {"tokens": 0})
3631
3677
  sess = _measure_facade._realized_savings_buckets(conn, "", session_uuid=session_id).get(
@@ -3658,11 +3704,13 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3658
3704
  daily.append({"date": d, "tokens": int(b.get("tokens", 0)),
3659
3705
  "usd": float(b.get("usd", 0.0))})
3660
3706
  headline = _measure_facade._get_merged_savings(days=_measure_facade._STATUS_BAR_DAYS)
3707
+ from . import headline as headline_module
3708
+ counted = _measure_facade._counted_cumulative_summary(days=_measure_facade._STATUS_BAR_DAYS) if has_counted else {"available": False}
3709
+ headline["counted_period"] = counted
3710
+ headline["token_headline"] = headline_module.token_headline(headline)
3711
+ _measure_facade._apply_counted_oneshot_pricing(headline, counted)
3712
+ headline["action_savings"] = _measure_facade._action_savings_components(headline, counted)
3661
3713
  shown, measured = _measure_facade._dashboard_saved_tokens(headline)
3662
- # The headline pass fails open to zeros; when the window, netted the way the
3663
- # headline nets it, shows savings but the headline is zero, it failed: say so
3664
- # rather than cache a false 0. Single days are not compared, since a debit on
3665
- # one day can honestly cancel savings on another.
3666
3714
  if measured == 0 and int(window.get("tokens", 0)) > 0:
3667
3715
  return None, "savings database busy"
3668
3716
  return {
@@ -3728,11 +3776,8 @@ def _status_bar_read_cache(session_id):
3728
3776
  def _status_bar_start_refresh(session_id):
3729
3777
  """Start ONE detached `status-bar --sync` child. Returns True if started.
3730
3778
 
3731
- A lock file (O_EXCL) makes concurrent callers start at most one child; the
3732
- child removes it when done, and a lock older than 120 s counts as abandoned.
3733
- The lock holds a random owner token, passed to the child in the
3734
- TO_STATUS_BAR_LOCK_TOKEN environment variable; the child deletes the lock
3735
- only while it still holds that token.
3779
+ A guarded marker holds an owner token and PID. The child adopts it before
3780
+ computing and removes it only while it still owns that token.
3736
3781
  """
3737
3782
  _measure_facade = _compat.facade()
3738
3783
  token = _measure_facade._status_bar_acquire_lock(session_id)
@@ -3753,101 +3798,13 @@ def _status_bar_start_refresh(session_id):
3753
3798
 
3754
3799
 
3755
3800
  def _status_bar_acquire_lock(session_id):
3756
- """Take the session's refresh lock; its owner token, or None when it is held."""
3757
- _measure_facade = _compat.facade()
3758
- lock = _measure_facade._status_bar_lock_path(session_id)
3759
- token = _measure_facade.os.urandom(16).hex()
3760
- fd = None
3761
- try:
3762
- lock.parent.mkdir(parents=True, exist_ok=True)
3763
- try:
3764
- fd = _measure_facade.os.open(str(lock), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY)
3765
- except FileExistsError:
3766
- if _measure_facade.time.time() - lock.stat().st_mtime < _measure_facade._STATUS_BAR_LOCK_STALE_S:
3767
- return None
3768
- # Take an abandoned lock over by renaming it aside. Rename is atomic,
3769
- # so when two callers race only one moves the file; the other gets
3770
- # FileNotFoundError and backs off instead of deleting the winner's lock.
3771
- quarantine = lock.with_name(
3772
- f"{lock.name}.{_measure_facade.os.getpid()}.{_measure_facade.time.time_ns()}.stale")
3773
- try:
3774
- _measure_facade.os.rename(str(lock), str(quarantine))
3775
- except OSError:
3776
- return None
3777
- try:
3778
- moved_fresh = (_measure_facade.time.time() - _measure_facade.os.stat(str(quarantine)).st_mtime
3779
- < _measure_facade._STATUS_BAR_LOCK_STALE_S)
3780
- except OSError:
3781
- moved_fresh = False
3782
- if moved_fresh:
3783
- # Another caller replaced the stale lock between our check and the
3784
- # rename, so we moved its live lock. Put it back without
3785
- # overwriting anything (link fails if the name is taken) and back off.
3786
- _measure_facade._status_bar_put_back(quarantine, lock)
3787
- try:
3788
- quarantine.unlink()
3789
- except OSError:
3790
- pass
3791
- return None
3792
- try:
3793
- quarantine.unlink()
3794
- except OSError:
3795
- pass
3796
- try:
3797
- fd = _measure_facade.os.open(str(lock), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY)
3798
- except FileExistsError:
3799
- return None
3800
- written = _measure_facade.os.write(fd, token.encode("ascii"))
3801
- _measure_facade.os.close(fd)
3802
- fd = None
3803
- if written != len(token):
3804
- # A short write leaves a lock nobody can prove they own: remove ours now.
3805
- try:
3806
- lock.unlink()
3807
- except OSError:
3808
- pass
3809
- return None
3810
- return token
3811
- except OSError:
3812
- if fd is not None:
3813
- try:
3814
- _measure_facade.os.close(fd)
3815
- except OSError:
3816
- pass
3817
- try:
3818
- lock.unlink()
3819
- except OSError:
3820
- pass
3821
- return None
3801
+ from . import status_bar_lock
3802
+ return status_bar_lock.acquire(_compat.facade(), session_id)
3822
3803
 
3823
3804
 
3824
3805
  def _status_bar_release_lock(session_id, token):
3825
- """Delete the refresh lock only when it still holds `token`. Never raises.
3826
-
3827
- The lock is moved aside first (one atomic rename) and only then checked, so a
3828
- lock another process created after ours is never deleted by mistake: when the
3829
- moved file is not ours it goes back, unless a newer lock already took its name.
3830
- """
3831
- _measure_facade = _compat.facade()
3832
- if not token:
3833
- return False
3834
- lock = _measure_facade._status_bar_lock_path(session_id)
3835
- aside = lock.with_name(f"{lock.name}.{_measure_facade.os.getpid()}.{_measure_facade.time.time_ns()}.release")
3836
- try:
3837
- _measure_facade.os.rename(str(lock), str(aside))
3838
- except OSError:
3839
- return False
3840
- try:
3841
- mine = aside.read_text(encoding="ascii", errors="replace").strip() == token
3842
- except OSError:
3843
- mine = False
3844
- if not mine:
3845
- _measure_facade._status_bar_put_back(aside, lock)
3846
- try:
3847
- aside.unlink()
3848
- except OSError:
3849
- pass
3850
- return mine
3806
+ from . import status_bar_lock
3807
+ return status_bar_lock.release(_compat.facade(), session_id, token)
3851
3808
 
3852
3809
 
3853
3810
  def _status_bar_put_back(aside, lock):
@@ -4310,6 +4267,10 @@ def _status_bar_cli(args):
4310
4267
  child = sync and "--release-lock" in args
4311
4268
  sid = _measure_facade.sanitize_session_id(session)
4312
4269
  token = _measure_facade.os.environ.get(_measure_facade._STATUS_BAR_LOCK_TOKEN_ENV, "") if child else None
4270
+ if child:
4271
+ from . import status_bar_lock
4272
+ if not status_bar_lock.adopt(_measure_facade, sid, token):
4273
+ token, sync = None, False
4313
4274
  if sync and not child:
4314
4275
  # A direct --sync takes the same lock as the background refresh; when one is
4315
4276
  # already running, this answers from the cache instead of computing twice.
@@ -4356,3 +4317,4 @@ def _status_bar_finite(v):
4356
4317
  if isinstance(v, (list, tuple)):
4357
4318
  return [_measure_facade._status_bar_finite(x) for x in v]
4358
4319
  return v
4320
+