@alexgreensh/token-optimizer 5.13.69 → 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 (151) 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/token-optimizer/assets/dashboard.html +399 -509
  11. package/skills/token-optimizer/assets/savings_story.js +661 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  14. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  15. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  16. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  19. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  20. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  21. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  23. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  24. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  25. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  26. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  28. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  29. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  30. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  31. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  36. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  37. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  38. package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
  39. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  40. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  41. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  42. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  43. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  44. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  46. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  47. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  48. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  50. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  54. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  55. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  56. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  57. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  58. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  59. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  60. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  61. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  62. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  63. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  64. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  65. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  66. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  67. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  68. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  69. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  70. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  71. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  72. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  73. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  74. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  75. package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
  76. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  77. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  78. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  79. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  80. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  81. package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
  82. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  83. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  84. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  85. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  86. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  91. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  92. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  93. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  94. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  95. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  96. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  97. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  98. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  99. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  100. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  101. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  102. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  103. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  104. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  105. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  106. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  107. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  108. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  109. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  110. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  111. package/skills/token-optimizer/scripts/codemap.py +274 -0
  112. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  113. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  114. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  115. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  116. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  117. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  118. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  119. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  120. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  121. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  122. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  123. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  124. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  125. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  126. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  127. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  128. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  129. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  130. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  132. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  133. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  134. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  135. package/skills/token-optimizer/scripts/holdout.py +136 -0
  136. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  137. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  138. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  139. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  140. package/skills/token-optimizer/scripts/measure.py +34 -76
  141. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  142. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  143. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  144. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  145. package/skills/token-optimizer/scripts/session_store.py +49 -99
  146. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  147. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  148. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  149. package/skills/token-optimizer/scripts/statusline.js +1 -1
  150. package/skills/token-optimizer/scripts/structural.py +25 -0
  151. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -20,7 +20,6 @@
20
20
  @media (prefers-reduced-motion: reduce) {
21
21
  *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; scroll-behavior: auto !important; }
22
22
  }
23
-
24
23
  /* ========== THEME TOKENS ==========
25
24
  Dark is the DEFAULT and is pixel-unchanged: every value below is the exact
26
25
  literal the dashboard already shipped, just lifted into a named token. The
@@ -135,7 +134,6 @@
135
134
  --glow-sm: 0 0 10px var(--c-accent-glow);
136
135
  --glow-text: 0 0 8px rgba(0, 240, 255, 0.6);
137
136
  }
138
-
139
137
  /* ========== LIGHT THEME ==========
140
138
  Same visual language (cyan-accent technical dashboard), inverted lightness.
141
139
  Activation order (no FOUC, see inline boot script in <head>):
@@ -274,7 +272,7 @@ th, td { padding: 10px !important; }
274
272
  gap: 8px; font-family: var(--font-mono); font-size: 14px;
275
273
  color: var(--c-accent-cyan); user-select: none; padding: 6px 0;
276
274
  }
277
- .fold > summary::-webkit-details-marker { display: none; }
275
+ .fold > summary { position:relative; min-height:40px; } .fold__body { opacity:1; transform:translateY(0); transition:opacity .18s ease-out, transform .18s ease-out; } @starting-style { .fold[open] > .fold__body { opacity:0; transform:translateY(4px); } } .fold > summary::-webkit-details-marker { display: none; }
278
276
  .fold > summary::before {
279
277
  content: "\25B8"; font-size: 11px; display: inline-block;
280
278
  transition: transform .15s ease;
@@ -396,13 +394,12 @@ h1, h2, h3, h4 { font-weight: 400; }
396
394
  text-transform: uppercase;
397
395
  letter-spacing: 0.1em;
398
396
  font-size: 15px;
399
- border-left: 2px solid transparent;
397
+ border-radius: 6px;
400
398
  }
401
399
 
402
400
  .nav-item:hover, .nav-item.active {
403
401
  color: var(--c-text-main);
404
402
  background: var(--c-accent-soft);
405
- border-left-color: var(--c-accent-cyan);
406
403
  text-shadow: var(--glow-text);
407
404
  }
408
405
 
@@ -431,7 +428,7 @@ h1, h2, h3, h4 { font-weight: 400; }
431
428
 
432
429
  .user-profile i {
433
430
  font-family: var(--font-mono);
434
- font-style: italic;
431
+ font-style: normal;
435
432
  color: var(--c-accent-cyan);
436
433
  }
437
434
 
@@ -1375,9 +1372,8 @@ input:checked + .slider:before {
1375
1372
  .metric-unit {
1376
1373
  font-family: var(--font-sans);
1377
1374
  font-weight: 500;
1378
- font-size: 24px;
1379
- color: var(--c-text-dim);
1380
- letter-spacing: 0.03em;
1375
+ font-size: 22px;
1376
+ color: var(--c-text-main);
1381
1377
  }
1382
1378
  .metric-sub.tight {
1383
1379
  font-size: 18px;
@@ -1392,18 +1388,17 @@ input:checked + .slider:before {
1392
1388
  .ts-divider { height: 1px; background: var(--c-border); margin: var(--s-4) 0 var(--s-3); }
1393
1389
 
1394
1390
  .ts-section-label {
1395
- font-family: var(--font-mono);
1396
- font-size: 13px;
1397
- color: var(--c-text-dim);
1398
- text-transform: uppercase;
1399
- letter-spacing: 0.08em;
1391
+ font-family: var(--font-sans);
1392
+ font-size: 17px;
1393
+ font-weight: 600;
1394
+ color: var(--c-text-main);
1400
1395
  margin-bottom: var(--s-2);
1401
1396
  display: flex;
1402
1397
  justify-content: space-between;
1403
1398
  align-items: baseline;
1404
1399
  gap: var(--s-3);
1405
1400
  }
1406
- .ts-section-label .muted { text-transform: none; letter-spacing: 0; color: var(--c-text-faint); font-size: 12px; }
1401
+ .ts-section-label .muted { color: var(--c-text-main); font-weight: 400; font-size: 14px; }
1407
1402
 
1408
1403
  /* spent-vs-saved combined bar: one row, two proportional segments. */
1409
1404
  .sv-bar {
@@ -1424,9 +1419,9 @@ input:checked + .slider:before {
1424
1419
 
1425
1420
  .ts-foot {
1426
1421
  margin-top: var(--s-4);
1427
- font-family: var(--font-mono);
1428
- font-size: 12px;
1429
- color: var(--c-text-faint);
1422
+ font-family: var(--font-sans);
1423
+ font-size: 15px;
1424
+ color: var(--c-text-main);
1430
1425
  line-height: 1.6;
1431
1426
  text-wrap: pretty;
1432
1427
  }
@@ -1546,7 +1541,6 @@ input:checked + .slider:before {
1546
1541
  .rec-callout {
1547
1542
  background: var(--c-surface);
1548
1543
  border: 1px solid var(--c-border);
1549
- border-left: 3px solid var(--c-accent-cyan);
1550
1544
  border-radius: 8px;
1551
1545
  padding: var(--s-3) var(--s-4);
1552
1546
  margin-bottom: var(--s-2);
@@ -1714,6 +1708,99 @@ input:checked + .slider:before {
1714
1708
  border: 1px solid var(--c-border);
1715
1709
  }
1716
1710
 
1711
+ /* ========== SAVINGS STORY (U9, assets/savings_story.js) ==========
1712
+ Card titles are headings (no small-caps labels above them). Sans for words,
1713
+ mono only for standalone figures; numbers inside sentences use the sans face
1714
+ with tabular figures. Secondary lines stay in --c-text-main for readability. */
1715
+ html { -webkit-font-smoothing: antialiased; font-variant-numeric: tabular-nums; } h1,h2,h3 { text-wrap: balance; } p,li { text-wrap: pretty; } .st-enter .st > * { animation: st-enter .32s ease-out both; } .st-enter .st > :nth-child(2) { animation-delay:90ms; } .st-enter .st > :nth-child(3) { animation-delay:180ms; } .st-enter .st > :nth-child(4) { animation-delay:270ms; } .st-enter .st > :nth-child(5) { animation-delay:360ms; } .st-enter .st > :nth-child(6) { animation-delay:450ms; } @keyframes st-enter { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:translateY(0); } } @media (prefers-reduced-motion:reduce) { .st-enter .st > * { animation:none; } .fold__body { transition:none; } .fold > summary::before { transition:none; } } .st { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--s-3); margin-bottom: var(--s-3); } .st .card.wide { grid-column: auto; }
1716
+ .st .card { padding: var(--s-4); border: 0; box-shadow: 0 0 0 1px rgba(255,255,255,.09), 0 2px 6px rgba(0,0,0,.12); } [data-theme="light"] .st .card { box-shadow: 0 0 0 1px rgba(0,0,0,.08), 0 2px 5px rgba(0,0,0,.06); } .st .st-table { box-shadow: 0 0 0 1px rgba(251,191,36,.4), 0 0 44px rgba(251,191,36,.1); }
1717
+ .st .st-limits-card { padding: 12px var(--s-4); } .st-limits__top { display:flex; align-items:baseline; flex-wrap:wrap; gap: 8px 24px; } .st-limits__bottom { display:flex; align-items:center; justify-content:space-between; gap:16px; font-size:14px; } .st-limits__bottom .fold { margin:0; } .st-transform .st-mega__item { gap:0; } .st-transform .st-lead { max-width:65ch; margin-top:8px; } .st-transform .fold, .st-hero .fold { margin-top:0; } .st-table__body > .st-mega__item { margin-top:0; } .st-reread__body { display:flex; align-items:center; gap:32px; } .st-reread__body .st-lead { margin:0; } .st-h { font: 600 20px/1.3 var(--font-sans); color: var(--c-text-main); display: flex; align-items: center; flex-wrap: wrap; gap: var(--s-2) 12px; }
1718
+ .st-tag { font: 500 13px/1 var(--font-sans); letter-spacing: 0.01em; color: var(--c-text-main); border: 1px solid var(--c-border-strong); border-radius: 999px; padding: 5px 10px; }
1719
+ .st-num { font-family: var(--font-sans); font-weight: 600; font-variant-numeric: tabular-nums; color: var(--c-accent-cyan); white-space: nowrap; }
1720
+ .st-v { font-family: var(--font-mono); font-variant-numeric: tabular-nums; color: var(--c-text-main); text-align: right; white-space: nowrap; }
1721
+ .st-lead { font-size: 17px; line-height: 1.6; color: var(--c-text-main); margin-top: var(--s-3); max-width: 60ch; text-wrap: pretty; }
1722
+ .st-lead strong { font-weight: 600; }
1723
+ .st-big { font: 400 22px/1.45 var(--font-sans); color: var(--c-text-main); margin-top: var(--s-3); text-wrap: pretty; }
1724
+ .st-big .st-num { font-size: 34px; }
1725
+ .st-hero { padding: var(--s-4) !important; }
1726
+ /* The big numbers: the Tokens Saved card's display treatment (thin mono,
1727
+ saturated savings green or accent cyan, soft glow in dark mode). */
1728
+ .st-mega__row { display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--s-3) var(--s-6, 48px); margin: var(--s-3) 0 12px; }
1729
+ .st-mega__item { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
1730
+ .st-mega__item--card { margin-top: var(--s-3); }
1731
+ .st-mega { font: 300 clamp(72px, 8.4vw, 116px)/0.9 var(--font-mono); letter-spacing: -0.035em; font-variant-numeric: tabular-nums; white-space: nowrap; }
1732
+ .st-mega--usd { color: var(--c-savings); text-shadow: 0 0 26px rgba(74,222,128,0.34), 0 0 2px rgba(74,222,128,0.4); }
1733
+ .st-mega--tok { color: var(--c-accent-cyan); text-shadow: 0 0 26px rgba(0,240,255,0.32), 0 0 2px rgba(0,240,255,0.4); }
1734
+ .st-mega--card { font-size: clamp(60px, 5.6vw, 84px); }
1735
+ .st-mega__unit { font: 500 19px/1.3 var(--font-sans); color: var(--c-text-main); }
1736
+ [data-theme="light"] .st-mega { text-shadow: none; }
1737
+ .st-bar { display: flex; gap: 3px; height: 8px; border-radius: 4px; overflow: hidden; opacity: 0.85; }
1738
+ .st-bar__m { background: var(--c-savings); border-radius: 7px 0 0 7px; }
1739
+ .st-bar__e { background: repeating-linear-gradient(135deg, var(--c-savings) 0 3px, transparent 3px 7px); box-shadow: inset 0 0 0 1.5px var(--c-savings); border-radius: 0 7px 7px 0; }
1740
+ .st-bands { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--s-2) var(--s-5); margin-top: var(--s-3); }
1741
+ .st-legend { display: flex; align-items: center; gap: 10px; font: 600 17px/1.3 var(--font-sans); color: var(--c-text-main); }
1742
+ .st-legend .st-v { margin-left: auto; font-size: 19px; font-weight: 500; }
1743
+ .st-sw { width: 14px; height: 14px; border-radius: 3px; flex: none; }
1744
+ .st-sw.st-m { background: var(--c-savings); }
1745
+ .st-sw.st-e { background: repeating-linear-gradient(135deg, var(--c-savings) 0 2px, transparent 2px 4px); box-shadow: inset 0 0 0 1.5px var(--c-savings); }
1746
+ .st-rows { list-style: none; margin-top: var(--s-2); border-top: 1px solid var(--c-border); }
1747
+ .st-rows li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--s-3); padding: 9px 0; border-bottom: 1px solid var(--c-border); font-size: 16px; line-height: 1.4; color: var(--c-text-main); }
1748
+ .st-rows--card { margin-top: var(--s-3); }
1749
+ .st-sub { display: block; font: 400 14px/1.5 var(--font-sans); color: var(--c-text-main); margin-top: 2px; }
1750
+ .st-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; gap: var(--s-3); }
1751
+ .st-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: var(--s-5); }
1752
+ .st-mega__row--hero { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); align-items: start; gap: var(--s-4); }
1753
+ .st-mega__row--hero .st-mega { font-size: clamp(60px, 6.2vw, 96px); }
1754
+ .st-mega__note { font: 600 17px/1.3 var(--font-sans); color: var(--c-savings); }
1755
+ .st-mega--route { color: var(--c-info); text-shadow: 0 0 26px rgba(96,165,250,0.36), 0 0 2px rgba(96,165,250,0.4); }
1756
+ .st-mega--warm { color: var(--c-warning-2); text-shadow: 0 0 28px rgba(251,191,36,0.38), 0 0 2px rgba(251,191,36,0.45); }
1757
+ .st-table { border: 0; box-shadow: 0 0 0 1px rgba(251,191,36,0.35), 0 0 44px rgba(251,191,36,0.10); }
1758
+ [data-theme="light"] .st-table { box-shadow: 0 0 0 1px rgba(150,95,0,.3), 0 2px 5px rgba(0,0,0,.06); }
1759
+ .st-table__body { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); gap: var(--s-3) var(--s-5); align-items: center; }
1760
+ .st-table__rows .st-rows--card { margin-top: 0; }
1761
+ .st-bar__title { font: 600 17px/1.3 var(--font-sans); color: var(--c-text-main); margin: var(--s-4) 0 var(--s-2); }
1762
+ .st-grid > :last-child:nth-child(odd) { grid-column: 1 / -1; }
1763
+ .st-ratio__track { display: block; height: 12px; border-radius: 6px; background: var(--c-elev-3); overflow: hidden; }
1764
+ .st-ratio__carry { display: block; height: 100%; border-radius: 6px; background: var(--c-accent-cyan); }
1765
+ .st-quality { margin-top: var(--s-3); max-width: 640px; }
1766
+ .st-cov { font-size: 17px; line-height: 1.6; color: var(--c-text-main); padding: 0 var(--s-1); max-width: 90ch; }
1767
+ .st-morerow { display: flex; flex-wrap: wrap; gap: 0 var(--s-4); padding: var(--s-2) var(--s-1) 0; border-top: 1px solid var(--c-border); margin-bottom: var(--s-4); }
1768
+ .st-morerow > .fold { margin-top: 0; }
1769
+ .st-morerow > .fold[open] { flex-basis: 100%; }
1770
+ .st-morerow > .fold > summary { font-size: 15px; }
1771
+ .st-morerow .fold__body { max-width: none; }
1772
+ .st-health { margin-top: var(--s-3); }
1773
+ .st-gap { margin-top: var(--s-4); }
1774
+ .st-limits { display: grid; gap: 10px; flex: 1 1 520px; min-width: 0; }
1775
+ .st-limit { display: grid; grid-template-columns: max-content minmax(120px, 1fr) max-content max-content; align-items: center; gap: 8px 20px; font: 500 15px/1.3 var(--font-sans); color: var(--c-text-main); }
1776
+ .st-limit__name { font-weight: 600; }
1777
+ .st-limit__meter { position: relative; height: 10px; border-radius: 999px; overflow: hidden; background: var(--c-elev-3); box-shadow: inset 0 0 0 1px var(--c-border); }
1778
+ .st-limit__ghost, .st-limit__fill { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 999px; transition-property: width; transition-duration: 600ms; transition-timing-function: cubic-bezier(0.2, 0, 0, 1); }
1779
+ .st-limit__ghost { background: repeating-linear-gradient(135deg, var(--c-warning-2) 0 3px, transparent 3px 7px); opacity: 0.7; }
1780
+ .st-limit__fill { background: var(--c-accent-cyan); box-shadow: 0 0 10px var(--c-accent-cyan); }
1781
+ .st-limit__stat { display: inline-flex; align-items: baseline; gap: 6px; white-space: nowrap; }
1782
+ .st-limit__stat--over { color: var(--c-warning-2); font-weight: 600; }
1783
+ @media (max-width: 720px) { .st-limit { grid-template-columns: 1fr max-content max-content; } .st-limit__meter { grid-column: 1 / -1; grid-row: 2; } }
1784
+ .st-mega__per { font: 500 clamp(20px, 2vw, 26px)/1 var(--font-sans); letter-spacing: 0; text-shadow: none; color: var(--c-text-main); }
1785
+ .st-limit__used, .st-limit__num { font: 500 24px/1 var(--font-mono); font-variant-numeric: tabular-nums; text-shadow: 0 0 18px currentColor; } .st-limit__used { color: var(--c-accent-cyan); }
1786
+ .st-limit__num { color: var(--c-warning-2); }
1787
+ @media (max-width: 900px) {
1788
+ .st-grid, .st-bands, .st-mega__row--hero, .st-table__body, .st-cols { grid-template-columns: 1fr; }
1789
+ .st-grid > :last-child:nth-child(odd) { grid-column: auto; }
1790
+ .st-mega__row--hero .st-mega { font-size: 72px; }
1791
+ }
1792
+ @media (max-width: 520px) {
1793
+ .st-limits__bottom, .st-reread__body { flex-wrap:wrap; } .st-limits__bottom { gap:0 16px; } .st-reread__body { gap:8px; }
1794
+ .st .card { padding: var(--s-3); }
1795
+ .st-hero { padding: var(--s-4) var(--s-3) var(--s-3) !important; }
1796
+ .st-hero .st-rows { display: none; }
1797
+ .st-bands { gap: var(--s-2); }
1798
+ .st-mega, .st-mega__row--hero .st-mega { font-size: 64px; }
1799
+ .st-mega--card { font-size: 56px; }
1800
+ .st-mega__row { gap: var(--s-3); }
1801
+ .st-morerow { flex-direction: column; }
1802
+ }
1803
+
1717
1804
  /* ========== RESPONSIVE ========== */
1718
1805
  @media (max-width: 1024px) {
1719
1806
  .layout { grid-template-columns: 200px 1fr; }
@@ -1728,8 +1815,14 @@ input:checked + .slider:before {
1728
1815
  padding: var(--s-3);
1729
1816
  }
1730
1817
  .main-col { padding: var(--s-3); }
1818
+ .nav-col .brand { margin-bottom: var(--s-2); font-size: 20px; }
1819
+ .nav-menu { flex-direction: row; overflow-x: auto; gap: 4px; margin: 0 calc(-1 * var(--s-3)); padding: 0 var(--s-3) 2px; scrollbar-width: none; }
1820
+ .nav-menu::-webkit-scrollbar { display: none; }
1821
+ .nav-menu .nav-item { flex: none; white-space: nowrap; padding: 8px 12px; gap: 8px; }
1822
+ .nav-menu .nav-separator { display: none; }
1823
+ .user-profile { display: none; }
1731
1824
  .dashboard-grid { grid-template-columns: 1fr; }
1732
- .stat-row { grid-template-columns: 1fr; }
1825
+ .stat-row { grid-template-columns: 1fr !important; } /* rows set 3 columns inline */
1733
1826
  }
1734
1827
  /* ========== HOOK TOGGLES ========== */
1735
1828
  .hook-toggle { position: relative; display: inline-block; width: 44px; height: 24px; flex-shrink: 0; }
@@ -2405,6 +2498,29 @@ function memCountSuffix(mr) { return mr && mr.scan_partial ? '+' : ''; }
2405
2498
  function isNoInstructionHost(data) {
2406
2499
  return !!data && (data.runtime === 'cursor' || data.runtime === 'antigravity');
2407
2500
  }
2501
+ // U8: the removed pool is split by what it is, never called "fresh" (it holds
2502
+ // resume and output tokens). Old payloads without the split keep one total.
2503
+ function tokenSplitText(h, fmt) {
2504
+ var parts = [];
2505
+ if (h.context_removed_tokens != null) {
2506
+ parts.push('~' + fmt(h.context_removed_tokens || 0) + ' context removed');
2507
+ if (h.output_not_generated_tokens) parts.push('~' + fmt(h.output_not_generated_tokens) + ' output not generated');
2508
+ if (h.reload_avoided_tokens) parts.push('~' + fmt(h.reload_avoided_tokens) + ' reload avoided');
2509
+ } else {
2510
+ parts.push('~' + fmt(h.removed_tokens || 0) + ' removed');
2511
+ }
2512
+ parts.push(h.reread_available ? '~' + fmt(h.reread_tokens || 0) + ' re-reads avoided' : 're-reads unavailable');
2513
+ return parts.join(' &middot; ');
2514
+ }
2515
+ /*@include savings_story.js*//*@include first_call_context.js*/
2516
+ // Feature health card (Health tab): assets/feature_health.js.
2517
+ /*@include feature_health.js*/
2518
+ // Command-output coverage card (Health tab): assets/coverage_funnel.js.
2519
+ /*@include coverage_funnel.js*/
2520
+ // Control-group card (Health tab, shown only when the holdout is on): assets/holdout_card.js.
2521
+ /*@include holdout_card.js*/
2522
+ /*@include keepwarm_health.js*/
2523
+
2408
2524
  function hostRefreshHtml(data) {
2409
2525
  return tcliHtml('<span class="update-cmd">TOKEN_OPTIMIZER_RUNTIME=' + esc(data.runtime) + ' python3 measure.py dashboard --user</span>');
2410
2526
  }
@@ -2841,7 +2957,7 @@ var DB = (function() {
2841
2957
  label: 'First-Read Skeleton (serve, not just measure)',
2842
2958
  what: "When on, validated CODE cohorts are served a structural skeleton (signatures/imports) on first read instead of the full file. When off, those cohorts are measured only and served full.",
2843
2959
  value: "A large first-read code file comes back as a compact API skeleton, with the full content one `expand` away. As of v5.11.27 markdown/prose is NOT skeletoned -- only code.",
2844
- how: "Requires the master switch on. The full original is archived first and recoverable via `expand <key>`, a ranged Read, or a direct Edit. A runtime tripwire auto-demotes a cohort back to measure-only if its live edit-rate exceeds the gate.",
2960
+ how: "When enabled, the target is read in full and bounded maps of related files may be added. Outcome comparisons are diagnostic; existing cohort demotions remain in place.",
2845
2961
  risk: "Low. Code skeletons preserve structure; the full file is always recoverable. Set TOKEN_OPTIMIZER_FIRST_READ_ACTIVE=0 (or toggle here) to serve full content while keeping measurement.",
2846
2962
  env_var: 'TOKEN_OPTIMIZER_FIRST_READ_ACTIVE'
2847
2963
  }
@@ -3131,10 +3247,11 @@ var DB = (function() {
3131
3247
  memoryExists = true;
3132
3248
  }
3133
3249
  var barsHtml = vals.map(function(v, i) {
3250
+ if (i === 1 && !memoryExists) return '';
3134
3251
  var w = logBar(v);
3135
3252
  var fixedClass = i === vals.length - 1 ? ' fixed' : '';
3136
3253
  var pctText = (v / ctxWindow * 100).toFixed(1) + '%';
3137
- var valText = (i === 1 && !memoryExists) ? '—' : fn(v) + ' (' + pctText + ')';
3254
+ var valText = fn(v) + ' (' + pctText + ')';
3138
3255
  return '<div class="bar-row">' +
3139
3256
  '<span class="bar-label">' + barLabels[i] + '</span>' +
3140
3257
  '<div class="bar-track"><div class="bar-fill' + fixedClass + '" style="width:' + w + '%"></div></div>' +
@@ -3181,15 +3298,15 @@ var DB = (function() {
3181
3298
  fn(ctrl) + ' of your ' + fn(total) + ' tokens are controllable. No specific token-saving optimizations identified, but check the behavioral recommendations below.';
3182
3299
  }
3183
3300
 
3184
- // Component cards (expandable)
3185
3301
  var componentData = getComponentDetails(data);
3186
3302
  var cardsHtml = '';
3187
3303
  componentData.forEach(function(comp, ci) {
3304
+ if (comp.key === 'memory_md' && comp.tokens === 0 && c.memory_md && c.memory_md.exists === false) return;
3188
3305
  cardsHtml += '<div class="component-card" data-comp="' + ci + '">' +
3189
3306
  '<div class="component-card-header">' +
3190
3307
  '<span class="cc-name">' + esc(comp.name) + '</span>' +
3191
3308
  '<span class="cc-right">' +
3192
- '<span class="cc-tokens">' + (comp.key === 'memory_md' && comp.tokens === 0 && c.memory_md && c.memory_md.exists === false ? '—' : fn(comp.tokens) + ' tokens') + '</span>' +
3309
+ '<span class="cc-tokens">' + fn(comp.tokens) + ' tokens</span>' +
3193
3310
  '<span class="chevron">&#9662;</span></span></div>' +
3194
3311
  '<div class="component-card-sub">' + esc(comp.sub) + '</div>' +
3195
3312
  '<div class="component-card-detail" id="comp-detail-' + ci + '">' +
@@ -3475,12 +3592,7 @@ var DB = (function() {
3475
3592
  var untrackedTokens = (denom > modelTotal) ? (denom - modelTotal) : 0;
3476
3593
  var out = '';
3477
3594
  if (isCodex) {
3478
- out += '<p style="font-size:13px;color:var(--c-text-dim);font-family:var(--font-mono);margin-bottom:var(--s-2);">Codex model names are read from session logs when available. Unknown future model IDs are shown by name but left unpriced until rates are known.</p>';
3479
- } else if (modelCount <= 1) {
3480
- var singleModel = Object.keys(modelMix)[0] || 'unknown';
3481
- out += '<p style="font-size:13px;color:var(--c-text-dim);font-family:var(--font-mono);margin-bottom:var(--s-2);">All sessions use ' + esc(singleModel) + '. Consider defaulting agents to haiku (5x cheaper) or sonnet for data-gathering tasks.</p>';
3482
- } else {
3483
- out += '<p style="font-size:13px;color:var(--c-text-dim);font-family:var(--font-mono);margin-bottom:var(--s-2);">Haiku is 5x cheaper for data-gathering. If you see mostly Opus, consider defaulting agents to Sonnet/Haiku.</p>';
3595
+ out += '<p style="font-size:15px;color:var(--c-text-main);margin-bottom:var(--s-2);">Codex model names are read from session logs when available. Unknown future model IDs are shown by name but left unpriced until rates are known.</p>';
3484
3596
  }
3485
3597
  out += '<div class="model-bar">';
3486
3598
  modelOrder.forEach(function(m) {
@@ -3523,110 +3635,34 @@ var DB = (function() {
3523
3635
  return out;
3524
3636
  }
3525
3637
 
3526
- // Tokens Saved card: a savings hero + a spent-vs-saved bar + a model-mix-as-
3527
- // usage bar + footer. Hoisted to module scope so BOTH renderTrends and
3528
- // renderSavings render it identically without duplicating the body logic.
3529
- // Reads trends data from the global `data`; the savings object is passed as
3530
- // `savings` (data.savings in renderTrends, the in-scope `s` in renderSavings).
3531
- // SPENT = deduplicated fresh input + output on actual activity days.
3532
- // Cache reads and writes are excluded. NOT sum(model_mix):
3533
- // model_mix can omit unattributed tokens. Fail-open to that sum rather than 0.
3534
- // SAVED = savings.total_tokens. Fail-open: measured AND estimated both ≤ 0 →
3535
- // return '' (omit card entirely); either > 0 → render (estimates still show
3536
- // when the measured floor is zero). SAVED > 0 but SPENT missing/zero →
3537
- // render hero + footer only.
3538
- // The model-mix "where the spent went" bar reconciles to SPENT via a trailing
3539
- // "untracked" segment for SPENT - sum(model_mix) (tokens billed without a
3540
- // model tag). Returns '' when the card should not render.
3638
+ // Share the Savings story calculation and period, including its eligibility rules.
3541
3639
  function tokensSavedCardHtml(savings) {
3542
3640
  var s = savings || {};
3543
- var tsSavedTokens = Number(s.total_tokens) || 0;
3544
- // Estimated-tier tokens (kept OUT of the measured SAVED total by
3545
- // _get_savings_summary). Surfaced in the footer as the estimated slice,
3546
- // labelled with whichever estimated categories are present, and they keep
3547
- // the card alive when the measured floor is zero.
3548
- // Field names match _get_merged_savings' re-export: mcp_cap_estimated
3549
- // keeps its suffix; hint_followed and verbosity_steer drop the _estimated
3550
- // suffix (the summary's *_estimated locals are re-keyed without it).
3551
- // Fallback: also try the _estimated suffix in case _get_savings_summary's
3552
- // fallback path (no re-key) is active.
3553
- var tsEstItems = [];
3554
- (function pushEst(obj, label) {
3555
- var tk = Number(obj && obj.tokens_saved) || 0;
3556
- if (tk > 0) tsEstItems.push({ label: label, tokens: tk });
3557
- })(s.mcp_cap_estimated, 'MCP caps');
3558
- (function pushEst(obj, label) {
3559
- var tk = Number(obj && obj.tokens_saved) || 0;
3560
- if (tk > 0) tsEstItems.push({ label: label, tokens: tk });
3561
- })(s.hint_followed || s.hint_followed_estimated, 'hint-served reads');
3562
- (function pushEst(obj, label) {
3563
- var tk = Number(obj && obj.tokens_saved) || 0;
3564
- if (tk > 0) tsEstItems.push({ label: label, tokens: tk });
3565
- })(s.verbosity_steer || s.verbosity_steer_estimated, 'verbosity nudges');
3566
- (function pushEst(obj, label) {
3567
- var tk = Number(obj && obj.tokens_saved) || 0;
3568
- if (tk > 0) tsEstItems.push({ label: label, tokens: tk });
3569
- })(s.resume_lean_estimated, 'lean resumes');
3570
- (function pushEst(obj, label) {
3571
- var tk = Number(obj && obj.tokens_saved) || 0;
3572
- if (tk > 0) tsEstItems.push({ label: label, tokens: tk });
3573
- })(s.checkpoint_restore_estimated, 'checkpoint restores');
3574
- var tsEstTokens = tsEstItems.reduce(function(a, b) { return a + b.tokens; }, 0);
3575
- var tsEstLabelList = tsEstItems.map(function(it) { return it.label; }).join(', ');
3576
- if (tsSavedTokens <= 0 && tsEstTokens <= 0) return '';
3577
- var tsTrends = data.trends || {};
3578
- var tsSpentBasis = tsTrends.spent_token_basis || {};
3579
- var tsModelMix = tsTrends.model_mix || {};
3580
- var tsModelTotal = 0;
3581
- for (var tsMk in tsModelMix) { tsModelTotal += tsModelMix[tsMk]; }
3582
- var tsIsCodex = data.runtime === 'codex';
3583
- var tsPeriodDays = Number(tsTrends.period_days) || Number(s.period_days) || 30;
3584
- // Missing dated coverage must not be replaced by lifetime model totals.
3585
- var tsReportedTotal = Number(tsTrends.total_tokens) || 0;
3586
- var tsSpentTokens = Object.prototype.hasOwnProperty.call(tsTrends, 'total_tokens') ? Math.max(0, tsReportedTotal) : tsModelTotal;
3587
- // (tsWouldSendTotal / percentages are computed below, AFTER the estimated
3588
- // tier is summed: the card headlines the FULL saved total in every state.)
3589
- // FULL saved total = measured floor + estimated tier. The headline is
3590
- // ALWAYS the full number, never the floor alone; the measured-vs-estimated
3591
- // split stays visible right under it so the honesty travels with the size,
3592
- // and the %-prevented / spent-vs-saved bar / would-send total are all
3593
- // computed against the same full figure.
3594
- var tsFullSaved = tsSavedTokens + tsEstTokens;
3595
- var tsWouldSendTotal = tsSpentTokens + tsFullSaved;
3596
- var tsSavedPct = (tsWouldSendTotal > 0) ? Math.round(tsFullSaved / tsWouldSendTotal * 100) : 0;
3597
- var tsSpentPct = 100 - tsSavedPct; // no 101% rounding
3598
- var tsSplitShort = fn(tsSavedTokens) + ' measured' + (tsEstTokens > 0 ? ' + ' + fn(tsEstTokens) + ' estimated' : '');
3599
-
3600
- var out = '<div class="card wide"><div class="card-header"><span>Tokens Saved</span><span class="label">Last ' + tsPeriodDays + ' days · measured + estimated</span></div>';
3601
- // HERO: total tokens saved, savings-green, mono, tabular-nums.
3602
- out += '<div style="display:flex;align-items:baseline;gap:var(--s-3);flex-wrap:wrap;margin-top:var(--s-2)"><div class="metric-large savings-hero">' + fn(tsFullSaved) + '</div><div class="metric-unit">tokens saved</div></div>';
3603
- out += '<div class="metric-sub tight" style="margin-top:2px;">' + fn(tsFullSaved) + ' saved · ' + tsSplitShort + '</div>';
3604
- if (tsSpentTokens > 0) {
3605
- out += '<div class="metric-sub tight">Token Optimizer prevented <span class="pct">≈' + tsSavedPct + '%</span> of the tokens this workload would otherwise have sent. Claude <code>/stats</code>-compatible spent: <b>' + fn(tsSpentTokens) + '</b>; tokens never sent: <b>' + fn(tsFullSaved) + '</b> (' + tsSplitShort + ').</div>';
3606
- // Spent vs Saved bar: one row, two proportional segments (spent+saved).
3607
- out += '<div class="ts-divider"></div>';
3608
- out += '<div class="ts-section-label"><span>Spent vs Saved</span><span class="muted">without Token Optimizer: ≈' + fn(tsWouldSendTotal) + '</span></div>';
3609
- out += '<div class="sv-bar" title="spent ' + fn(tsSpentTokens) + ' + saved ' + fn(tsFullSaved) + ' (' + tsSplitShort + ') = ' + fn(tsWouldSendTotal) + ' would-be total">';
3610
- out += '<div class="sv-seg spent" style="width:' + tsSpentPct + '%">spent · ' + fn(tsSpentTokens) + '</div>';
3611
- out += '<div class="sv-seg saved" style="width:' + tsSavedPct + '%">saved · ' + fn(tsFullSaved) + '</div>';
3612
- out += '</div>';
3613
- out += '<div class="sv-caption">Without Token Optimizer you\'d have sent <b>≈' + fn(tsWouldSendTotal) + '</b> to do the same work.</div>';
3614
- // Model mix relabeled as USAGE: where the SPENT went. Bar + legend
3615
- // reconcile to SPENT via a trailing "untracked" segment for tokens
3616
- // billed without a model tag (SPENT - sum(model_mix)).
3617
- if (tsModelTotal > 0) {
3618
- out += '<div class="ts-divider"></div>';
3619
- out += '<div class="ts-section-label"><span>Where the ' + fn(tsSpentTokens) + ' you spent went</span><span class="muted">which models do the work</span></div>';
3620
- out += modelMixBodyHtml(tsModelMix, tsIsCodex, tsSpentTokens);
3621
- }
3622
- } else {
3623
- // SAVED exists but SPENT is unknown (no billable total AND no
3624
- // model_mix). Render the hero + footer only.
3625
- out += '<div class="metric-sub tight">Token Optimizer saved <b>' + fn(tsFullSaved) + '</b> tokens that never had to be sent (' + tsSplitShort + ').</div>';
3626
- }
3627
- // Footer: metered floor + optional estimated-slice sentence + plan note.
3628
- out += '<div class="ts-foot"><span class="tier">Measured + estimated.</span> ' + fn(tsSavedTokens) + ' of these tokens are metered action by action (the floor)' + (tsEstTokens > 0 ? '; ≈' + fn(tsEstTokens) + ' are estimated (' + esc(tsEstLabelList) + ') and are included in the headline, labelled.' : '.') + (tsSpentBasis.basis ? ' Spent basis: ' + esc(tsSpentBasis.basis) + '.' : '') + ' Subscription plan — counted in tokens, no per-token cost.</div>';
3629
- out += '</div>';
3641
+ var storyAvailable = typeof savingsStoryOn === 'function' && savingsStoryOn(data);
3642
+ var bands = typeof savingsStoryBands === 'function' ? savingsStoryBands(data) : null;
3643
+ var total = bands ? bands.totalTok : Number((s.token_headline || {}).total_tokens) || 0;
3644
+ if (total <= 0) return '';
3645
+ var formatTokens = typeof savingsStoryFmt === 'function' ? savingsStoryFmt().tok : fn;
3646
+ var removed = Number((s.token_headline || {}).removed_tokens) || 0;
3647
+ var trends = data.trends || {};
3648
+ var mix = trends.model_mix || {};
3649
+ var modelTotal = 0;
3650
+ for (var model in mix) { modelTotal += Number(mix[model]) || 0; }
3651
+ var spent = Object.prototype.hasOwnProperty.call(trends, 'total_tokens') ? Math.max(0, Number(trends.total_tokens) || 0) : modelTotal;
3652
+ var days = Number(s.period_days) || 30;
3653
+ var out = '<div class="card wide"><div class="card-header"><span>Tokens Saved</span></div>';
3654
+ out += '<div style="display:flex;align-items:baseline;gap:var(--s-3);flex-wrap:wrap;margin-top:var(--s-2)"><div class="metric-large savings-hero">' + formatTokens(total) + '</div><div class="metric-unit">tokens kept out of context in the last ' + days + ' days</div></div>';
3655
+ var types = s.token_type_breakdown || {};
3656
+ var typeRows = [['cache_reread', 'Modeled cache re-reads avoided'], ['cache_write', 'Modeled cache writes avoided'], ['fresh', 'Fresh input and output avoided']];
3657
+ typeRows = typeRows.filter(function(row) { return typeof types[row[0]] === 'number' && isFinite(types[row[0]]); });
3658
+ if (typeRows.length) out += '<div class="ts-divider"></div><h3 class="ts-section-label">Tokens by type, partial ledger</h3><div class="st-bands">' + typeRows.map(function(row) {
3659
+ return '<div class="st-band">' + row[1] + '<br><strong>' + formatTokens(types[row[0]]) + '</strong></div>';
3660
+ }).join('') + '</div>';
3661
+ if (modelTotal > 0) {
3662
+ out += '<div class="ts-divider"></div><h3 class="ts-section-label">Model usage</h3>';
3663
+ out += modelMixBodyHtml(mix, data.runtime === 'codex', spent > 0 ? spent : modelTotal);
3664
+ }
3665
+ out += '<div class="ts-foot">' + (storyAvailable ? 'Same figure as the Savings card.<br>' : '') + formatTokens(removed) + ' tokens removed once.</div></div>';
3630
3666
  return out;
3631
3667
  }
3632
3668
 
@@ -3645,9 +3681,9 @@ var DB = (function() {
3645
3681
  '</div>' +
3646
3682
  '<div class="last-updated">Last updated: ' + esc(ts) + '</div>';
3647
3683
 
3648
- // Runway leads here too: on a rate-limited plan "how much of my allowance is
3649
- // left" is the first question a trends view should answer, before any chart.
3650
- html += runwayCardHtml();
3684
+ html += tokensSavedCardHtml(data.savings || {}) + runwayCardHtml();
3685
+ // Context before the first message is not a saving: it lives here, not on Savings.
3686
+ if (typeof firstCallContextHtml === 'function') html += firstCallContextHtml((t || {}).first_call_context);
3651
3687
 
3652
3688
  if (!t) {
3653
3689
  var collectNote = isCodex
@@ -3704,21 +3740,30 @@ var DB = (function() {
3704
3740
  .filter(function(label) { return !!label; })
3705
3741
  .join(' | ');
3706
3742
 
3707
- var tokenLabel = isCodex ? 'Measured/Estimated Tokens' : 'Billable Tokens';
3743
+ var tokenLabel = isCodex ? 'Measured/Estimated Tokens' : 'Deduplicated Fresh Input + Output';
3708
3744
  var tokenNote = isCodex
3709
3745
  ? 'Codex logs use token_count snapshots when present; older sessions fall back to local estimates.'
3710
- : 'Fresh input + cache writes + output (what your invoice bills at full rate).';
3746
+ : 'Deduplicated usage; the raw token classes below use a different basis.';
3711
3747
  var pop = t.population_metrics || {};
3712
3748
  var eligibleCacheHit = Number(pop.cache_eligible_main_hit_rate);
3713
- var avgCacheDisplay = Number.isFinite(eligibleCacheHit) && pop.cache_eligible_main_sessions
3714
- ? Math.round(eligibleCacheHit * 100) : avgCacheHit;
3715
- var cacheLabel = isCodex ? 'Cached Input Share' : 'Main-work cache hit rate';
3749
+ // Claude: lead with the token-weighted rate across every scanned session;
3750
+ // the per-session averages become secondary lines.
3751
+ var overallCacheHit = Number((data.cache_health || {}).overall_cache_hit_rate);
3752
+ var cacheOverall = !isCodex && (data.cache_health || {}).overall_cache_hit_rate != null && Number.isFinite(overallCacheHit) && overallCacheHit >= 0;
3753
+ var avgCacheDisplay = cacheOverall ? (overallCacheHit * 100).toFixed(1).replace(/\.0$/, '')
3754
+ : (Number.isFinite(eligibleCacheHit) && pop.cache_eligible_main_sessions ? Math.round(eligibleCacheHit * 100) : avgCacheHit);
3755
+ var cacheLabel = isCodex ? 'Cached Input Share' : (cacheOverall ? 'Cache hit rate (all tokens)' : 'Main-work cache hit rate');
3756
+ var cacheSessionLines = cacheOverall
3757
+ ? (pop.cache_eligible_main_sessions ? '<div style="font-size:12px;color:var(--c-text-main);margin-top:6px">Average session, 20+ messages: ' + Math.round((Number(pop.cache_eligible_main_hit_rate) || 0) * 100) + '%</div>' : '') +
3758
+ (pop.cache_ineligible_sessions ? '<div style="font-size:12px;color:var(--c-text-main);margin-top:2px">Average short or delegated session: ' + Math.round((Number(pop.cache_ineligible_hit_rate) || 0) * 100) + '%</div>' : '') +
3759
+ '<div style="font-size:11px;color:var(--c-text-dim);margin-top:2px">Session lines average each session&rsquo;s own rate; the big number weights every token.</div>'
3760
+ : '<div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + (pop.cache_eligible_main_sessions || 0) + ' cache-building main-work sessions · ' + (pop.cache_ineligible_sessions || 0) + ' short/delegated sessions at ' + Math.round((Number(pop.cache_ineligible_hit_rate) || 0) * 100) + '%</div>';
3716
3761
  var cacheNote = isCodex
3717
3762
  ? 'Share of logged input tokens Codex says were cached_input_tokens. Similar to a cache hit rate, but Codex does not expose cache-write TTL or write-size fields.'
3718
- : 'Main-work sessions with 20+ messages. Above 90% is normal for longer sessions.';
3763
+ : (cacheOverall ? '' : 'Main-work sessions with 20+ messages.');
3719
3764
  var tokenBreakdownNote = isCodex
3720
3765
  ? 'fresh:' + fn(t.total_fresh_input || 0) + ' · cached input:' + fn(t.total_cache_read || 0) + ' · out:' + fn(t.total_output_tokens || 0)
3721
- : 'fresh:' + fn(t.total_fresh_input || 0) + ' · cache-write:' + fn(t.total_cache_create || 0) + ' · out:' + fn(t.total_output_tokens || 0);
3766
+ : 'raw fresh:' + fn(t.total_fresh_input || 0) + ' · cache-write:' + fn(t.total_cache_create || 0) + ' · out:' + fn(t.total_output_tokens || 0);
3722
3767
  var codexCostNote = '';
3723
3768
  if (isCodex && typeof t.total_cost_usd === 'number') {
3724
3769
  codexCostNote = '<div style="font-size:10px;color:var(--c-text-dim);margin-top:2px">API-equivalent known cost: $' + t.total_cost_usd.toFixed(2);
@@ -3732,7 +3777,7 @@ var DB = (function() {
3732
3777
  }
3733
3778
  var cacheExtra = isCodex
3734
3779
  ? '<div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + cacheNote + '</div>'
3735
- : '<div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">Cache writes: ' + esc(globalTtlMix) + '</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + esc(globalTtlSessionLabel) + '</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + esc(ttlPeriodSummary || 'TTL period summary unavailable') + '</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + cacheNote + '</div>';
3780
+ : '<div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">Cache writes: ' + esc(globalTtlMix) + '</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + esc(globalTtlSessionLabel) + '</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + esc(ttlPeriodSummary || 'TTL period summary unavailable') + '</div>' + (cacheNote ? '<div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + cacheNote + '</div>' : '');
3736
3781
 
3737
3782
  html += '<div class="stat-row" style="grid-template-columns:repeat(3,1fr);margin-bottom:var(--s-3)">' +
3738
3783
  '<div class="stat-card"><div class="stat-card-value">' + t.session_count + '</div><div class="stat-card-label">All logged sessions (' + t.period_days + 'd)</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + (pop.main_work_sessions || 0) + ' main-work · ' + (pop.delegated_sessions || 0) + ' delegated/subagent</div></div>' +
@@ -3742,19 +3787,11 @@ var DB = (function() {
3742
3787
  '<div class="stat-row" style="grid-template-columns:repeat(3,1fr)">' +
3743
3788
  '<div class="stat-card"><div class="stat-card-value">' + Math.round(t.avg_duration_minutes || 0) + 'm</div><div class="stat-card-label">Avg duration, all logged</div></div>' +
3744
3789
  '<div class="stat-card"><div class="stat-card-value">' + fn((t.avg_input_tokens || 0) + (t.avg_output_tokens || 0)) + '</div><div class="stat-card-label">Avg tokens, all logged sessions</div></div>' +
3745
- '<div class="stat-card"><div class="stat-card-value" style="color:var(--c-savings-strong, #22c55e)">' + avgCacheDisplay + (avgCacheDisplay !== 'N/A' ? '%' : '') + '</div><div class="stat-card-label">' + cacheLabel + '</div><div style="font-size:11px;color:var(--c-text-dim);margin-top:4px">' + (pop.cache_eligible_main_sessions || 0) + ' cache-building main-work sessions · ' + (pop.cache_ineligible_sessions || 0) + ' short/delegated sessions at ' + Math.round((Number(pop.cache_ineligible_hit_rate) || 0) * 100) + '%</div>' + cacheExtra + '</div>' +
3790
+ (avgCacheDisplay === 'N/A' ? '' : '<div class="stat-card"><div class="stat-card-value" style="color:var(--c-savings-strong, #22c55e)">' + avgCacheDisplay + '%</div><div class="stat-card-label">' + cacheLabel + '</div>' + cacheSessionLines + cacheExtra + '</div>') +
3746
3791
  '</div>';
3747
3792
 
3748
- // Shared data for skills sections
3749
3793
  var skillsDetail = (data.snapshot && data.snapshot.components && data.snapshot.components.skills_detail) || {};
3750
3794
 
3751
- // Tokens Saved card: the full card (hero + spent-vs-saved + model-mix-as-
3752
- // usage + footer). Rendered in BOTH Trends and Savings (sharing the
3753
- // hoisted tokensSavedCardHtml + modelMixBodyHtml helpers). Replaces the
3754
- // former standalone Model Mix card — the model-mix-as-usage section is
3755
- // now inside the Tokens Saved card, reconciled to the billable SPENT.
3756
- // Fail-open: returns '' only when measured AND estimated are both ≤ 0.
3757
- html += tokensSavedCardHtml(data.savings || {});
3758
3795
 
3759
3796
  // Daily breakdown with date navigation
3760
3797
  var daily = t.daily || [];
@@ -3805,9 +3842,9 @@ var DB = (function() {
3805
3842
  topSkills.forEach(function(entry) {
3806
3843
  var w = Math.max(3, (entry[1] / maxSkill) * 100);
3807
3844
  var sd = skillsDetail[entry[0]];
3808
- var tokNote = sd ? sd.frontmatter_tokens + ' tok' : '~100 tok';
3845
+ var tokNote = sd && typeof sd.frontmatter_tokens === 'number' ? ' (' + sd.frontmatter_tokens + ' frontmatter tokens)' : '';
3809
3846
  html += '<div class="bar-row" data-skill-name="' + esc(entry[0]) + '" style="cursor:pointer;">' +
3810
- '<span class="bar-label" style="width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + esc(entry[0]) + ' (' + tokNote + ')">' + esc(entry[0]) + '</span>' +
3847
+ '<span class="bar-label" style="width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="' + esc(entry[0] + tokNote) + '">' + esc(entry[0]) + '</span>' +
3811
3848
  '<div class="bar-track"><div class="bar-fill" style="width:' + w + '%"></div></div>' +
3812
3849
  '<span class="bar-value" style="width:60px;text-align:right;">' + entry[1] + ' sess</span></div>';
3813
3850
  });
@@ -3817,11 +3854,10 @@ var DB = (function() {
3817
3854
  // Never-used skills with expandable detail (half-folded)
3818
3855
  var neverUsed = t.skills ? t.skills.never_used : [];
3819
3856
  if (!isCodex && neverUsed.length > 0) {
3820
- var overhead = t.skills.never_used_overhead || (neverUsed.length * 100);
3821
3857
  var PREVIEW_COUNT = 4;
3822
- html += '<div class="card wide"><div class="card-header"><span>Not Invoked (' + neverUsed.length + ' skills)</span><span class="label">~' + fn(overhead) + ' tokens/session</span></div>' +
3858
+ html += '<div class="card wide"><div class="card-header"><span>Not Invoked (' + neverUsed.length + ' skills)</span></div>' +
3823
3859
  '<p style="font-size:13px;color:var(--c-text-dim);font-family:var(--font-mono);margin-bottom:var(--s-2);">' +
3824
- 'No Skill call or slash command for these in the window. Each still loads ~100 tokens of frontmatter every session. A skill you drive by slash command counts as invoked; if one you use often shows here, open an issue. Click a skill for details, or "Quick Wins" to archive.</p>';
3860
+ 'No Skill call or slash command for these in the window. A skill you drive by slash command counts as invoked; if one you use often shows here, open an issue. Click a skill for details, or "Quick Wins" to archive.</p>';
3825
3861
 
3826
3862
  function buildSkillRow(name) {
3827
3863
  var sd = skillsDetail[name];
@@ -3829,7 +3865,7 @@ var DB = (function() {
3829
3865
  '<div class="skill-detail-header">' +
3830
3866
  '<input type="checkbox" class="skill-archive-check" data-skill="' + esc(name) + '" title="Select to archive">' +
3831
3867
  '<span class="skill-name">' + esc(name) + '</span>' +
3832
- '<span class="skill-tokens">' + (sd ? sd.frontmatter_tokens + ' tok' : '~100 tok') + '</span>' +
3868
+ (sd && typeof sd.frontmatter_tokens === 'number' ? '<span class="skill-tokens">' + sd.frontmatter_tokens + ' frontmatter tokens</span>' : '') +
3833
3869
  '<span class="expand-arrow">\u25B6</span>' +
3834
3870
  '</div>' +
3835
3871
  '<div class="skill-detail-body"><div class="skill-detail-content">';
@@ -4015,7 +4051,7 @@ var DB = (function() {
4015
4051
  }
4016
4052
 
4017
4053
  function gapSummary(avgGap, maxGap) {
4018
- if (avgGap == null && maxGap == null) return 'n/a';
4054
+ if (avgGap == null && maxGap == null) return '';
4019
4055
  if (avgGap == null) return 'max ' + fmtGap(maxGap);
4020
4056
  if (maxGap == null) return 'avg ' + fmtGap(avgGap);
4021
4057
  return 'avg ' + fmtGap(avgGap) + ' | max ' + fmtGap(maxGap);
@@ -4143,7 +4179,7 @@ var DB = (function() {
4143
4179
  (isCodex ? '' : '<td style="font-family:var(--font-mono);font-size:11px;">' + esc(ttlStr) + '</td>') +
4144
4180
  '<td style="font-family:var(--font-mono);font-size:11px;">' + esc(pacingStr) + '</td>' +
4145
4181
  '<td style="color:var(--c-accent-cyan);font-family:var(--font-mono);font-size:12px;">' + costStr + '</td>' +
4146
- '<td><span class="quality-badge ' + qBadgeClass + '">' + qGrade + ' (' + qs + ')</span></td>' +
4182
+ '<td><span class="quality-badge ' + qBadgeClass + '">' + (sd.quality_measured === false ? (sd.quality_score == null ? '--' : '~' + qs) : qGrade + ' (' + qs + ')') + '</span></td>' +
4147
4183
  '<td style="color:var(--c-text-dim);font-size:11px;">' + esc(modelStr) + '</td>' +
4148
4184
  '<td style="color:var(--c-text-dim);font-size:12px;" title="' + esc(sdTopic) + '">' + esc(sdTopic.length > 35 ? sdTopic.slice(0,33) + '\u2026' : sdTopic) + '</td>' +
4149
4185
  '</tr>';
@@ -4274,6 +4310,11 @@ var DB = (function() {
4274
4310
  '</div>' +
4275
4311
  '</div>';
4276
4312
  }).join('');
4313
+ // With the story module inlined, windows render as "X% used / would be Y%
4314
+ // without" (live, else the last stored reading); the older per-window cards
4315
+ // remain only for a template without it.
4316
+ var rwLimitsHtml = '';
4317
+ if (typeof savingsLimitWindows === 'function') { rwLimitsHtml = savingsLimitWindows(rw); rwCards = ''; }
4277
4318
  // Savings remain available when the quota meter has no weekly reading.
4278
4319
  var standaloneWeek = rw.weekly_full_value;
4279
4320
  if (standaloneWeek && Number(standaloneWeek.saved_usd) >= 15 &&
@@ -4302,9 +4343,9 @@ var DB = (function() {
4302
4343
  var rwCostCut = Number(rw.per_session_cost_reduction_pct);
4303
4344
  var rwCostCutDisplay = isFinite(rwCostCut) ? Math.round(rwCostCut / 5) * 5 : null;
4304
4345
  var rwSpentTokens = Number(rw.tokens_consumed);
4305
- var rwSavedTokens = Number(rw.tokens_saved);
4346
+ var rwSavedTokens = Number(rw.context_tokens_saved);
4306
4347
  var rwTokenFloorPct = (isFinite(rwSpentTokens) && rwSpentTokens > 0 && isFinite(rwSavedTokens) && rwSavedTokens > 0)
4307
- ? Math.round(rwSavedTokens / (rwSpentTokens + rwSavedTokens) * 100)
4348
+ ? Math.round((1 - 1 / Number(rw.context_multiplier)) * 1000) / 10
4308
4349
  : null;
4309
4350
  var rwEfficiencyHeadline = rwHasCostEfficiency
4310
4351
  ? '<div class="metric-large" style="text-wrap:balance;text-shadow:none;"><em style="font-style:normal;color:var(--c-accent-cyan);">&asymp;' + rwEfficiencyMult.toFixed(1) + '&times;</em> work per dollar</div>'
@@ -4365,25 +4406,13 @@ var DB = (function() {
4365
4406
  : 'Context &times;' + rw.context_multiplier + ' and ' + rwRoutingMethod + ' give a per-token throughput multiplier, shown separately from the window headroom and dollar figures.';
4366
4407
  rwEfficiencyMethod += rwRoutingScope;
4367
4408
  var rwTokenFloorDetail = (rwTokenFloorPct !== null)
4368
- ? '<div class="plain-line">About <strong>' + fn(rwSavedTokens) + '</strong> tokens never had to be sent, roughly ' + rwTokenFloorPct + '% of what would have been.</div>'
4409
+ ? '<div class="plain-line">Estimated <strong>~' + fn(rwSavedTokens) + '</strong> tokens kept out of context &middot; ' + tokenSplitText(rw.token_headline || {}, fn) + ', roughly ' + rwTokenFloorPct + '% of would-be input and output including cache.' + (rw.tokens_consumed_basis_complete === false ? ' Traffic coverage is incomplete.' : '') + '</div>'
4369
4410
  : '';
4370
4411
  var rwTokenFloorMethod = (rwTokenFloorPct !== null)
4371
- ? 'Separate measured token floor: ' + fn(rwSavedTokens) + ' never sent on ' + fn(rwSpentTokens) + ' <code>/stats</code>-compatible spent, &asymp;' + rwTokenFloorPct + '% of the would-be token load.'
4412
+ ? 'Estimated savings on ' + fn(rwSpentTokens) + ' input and output tokens, including cache reads and writes; repeat reads assume the same trajectory until compaction.'
4372
4413
  : '';
4373
- // Tier chip reflects the USD spine's measured-vs-estimated boundary:
4374
- // context $ is metered, routing $ is an estimated counterfactual.
4375
- // When routing savings contribute, the dollar figure is estimated; when
4376
- // only context $ contributes, it is measured. None -> no chip change.
4377
- var usdTierChip = (rw.saved_usd_tier === 'measured') ? 'METERED $'
4378
- : (rw.saved_usd_tier === 'estimated') ? 'ESTIMATED $' : 'ESTIMATED';
4379
4414
  html += '<div class="card" style="margin-bottom:18px;border-color:rgba(0,240,255,.28);box-shadow:0 4px 20px rgba(0,0,0,.3),0 0 40px rgba(0,240,255,.05);">' +
4380
- // Header row: the label and the tier chip sit on ONE line. Left as bare
4381
- // siblings the chip inherits the label's block layout and stretches to the
4382
- // full card width, which reads as a broken banner.
4383
- '<div style="display:flex;align-items:center;gap:var(--s-2);flex-wrap:wrap;">' +
4384
- '<span class="label">Your plan goes further</span>' +
4385
- '<span style="font-size:12px;letter-spacing:.12em;color:var(--c-text-dim);border:1px solid var(--c-border);border-radius:20px;padding:3px 12px;white-space:nowrap;">' + usdTierChip + '</span>' +
4386
- '</div>' +
4415
+ '<h2 class="st-h">Your limits go further</h2>' +
4387
4416
  // No glow on this headline. `.metric-large` carries a text-shadow built
4388
4417
  // from --c-border-strong, which is a light veil on dark but resolves to a
4389
4418
  // DARK halo in light mode, so the words read as smudged rather than lit.
@@ -4400,9 +4429,8 @@ var DB = (function() {
4400
4429
  // Per-window bars when the meter is fresh enough; otherwise a note so the
4401
4430
  // card degrades instead of vanishing (the multiplier + savings above still
4402
4431
  // stand without the live meter).
4403
- (rwCards
4404
- ? '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:var(--s-3);">' + rwCards + '</div>'
4405
- : '<div style="padding:var(--s-3);border:1px dashed var(--c-border);border-radius:8px;color:var(--c-text-dim);font-size:15px;line-height:1.5;text-wrap:pretty;">Your live 5-hour and weekly limit view refreshes while you are actively working &mdash; it reappears here on your next session.</div>') +
4432
+ rwLimitsHtml +
4433
+ (rwCards ? '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:var(--s-3);">' + rwCards + '</div>' : '') +
4406
4434
  // Freshness of the WINDOW reading itself (not the dashboard build). The
4407
4435
  // meter only refreshes while Claude Code is actively running, so a
4408
4436
  // dashboard opened later shows the last real reading -- label it with its
@@ -4441,10 +4469,10 @@ var DB = (function() {
4441
4469
  : '';
4442
4470
  return '<div style="margin-top:var(--s-3);font-size:13px;color:' + col + ';">' +
4443
4471
  (stale ? '⚠ ' : '') + 'Window reading as of ' + esc(whenStr) + ' (' + ageStr + ').' + staleNote +
4444
- ' <button id="to-regen-btn" onclick="window.__TOKEN_REGENERATE&&window.__TOKEN_REGENERATE()" ' +
4472
+ (window.location.protocol === 'file:' ? (window.__TOKEN_FILE_DAEMON_LIVE ? ' Open ' + DAEMON_URL + '/token-optimizer for live numbers.' : ' Run <code>python3 skills/token-optimizer/scripts/measure.py setup-daemon</code> to see live numbers.') : ' <button id="to-regen-btn" onclick="window.__TOKEN_REGENERATE&&window.__TOKEN_REGENERATE()" ' +
4445
4473
  'style="margin-left:8px;padding:2px 10px;font:inherit;font-size:12px;cursor:pointer;' +
4446
4474
  'background:transparent;color:inherit;border:1px solid currentColor;border-radius:4px;">' +
4447
- 'Regenerate savings</button>' +
4475
+ 'Regenerate savings</button>') +
4448
4476
  '<span id="to-regen-msg" style="margin-left:8px;"></span>' +
4449
4477
  '<span id="to-live-stamp" hidden style="margin-left:8px;font-size:12px;color:var(--c-savings-alt, #10b981);"></span>' +
4450
4478
  // Persistent regenerate failure surfaces here, not in the tiny
@@ -4454,7 +4482,6 @@ var DB = (function() {
4454
4482
  '<div id="to-regen-error" hidden style="margin-top:10px;padding:10px 14px;font-size:15px;font-weight:500;color:var(--c-waste);background:rgba(255,95,95,.08);border:1px solid rgba(255,95,95,.35);border-radius:8px;line-height:1.5;text-wrap:pretty;"></div></div>';
4455
4483
  })() +
4456
4484
  '<div style="margin-top:var(--s-4);padding-top:var(--s-3);border-top:1px solid var(--c-border);font-size:15px;color:var(--c-text-main);line-height:1.6;text-wrap:pretty;">' +
4457
- 'Your window usage is measured. The savings comparison is an estimate.' +
4458
4485
  // Technical method lives in a fold. rw.proxy is the single source of the
4459
4486
  // measured-vs-estimated boundary AND the ledger detail; we add only the
4460
4487
  // one fact proxy can't carry -- the headline figure is its own unit, not
@@ -4478,7 +4505,6 @@ var DB = (function() {
4478
4505
  function renderSavings() {
4479
4506
  var el = document.getElementById('view-savings');
4480
4507
  if (!el) return;
4481
- // Live refresh must not close the explanation someone is reading.
4482
4508
  var openFolds = Array.from(el.querySelectorAll('details[open] > summary')).map(function(summary) {
4483
4509
  return summary.textContent;
4484
4510
  });
@@ -4530,7 +4556,6 @@ var DB = (function() {
4530
4556
  if (v >= 1e3) return Math.round(v / 1e3) + 'K';
4531
4557
  return String(Math.round(v));
4532
4558
  }
4533
- // Foldable "read more". Pass body as ready HTML (wrap prose in <p>...</p>).
4534
4559
  // Native <details> means click-to-unfold works with no event wiring.
4535
4560
  function fold(summary, bodyHtml) {
4536
4561
  // summary is escaped (it is always plain label text); bodyHtml is trusted
@@ -4549,11 +4574,12 @@ var DB = (function() {
4549
4574
  // ---- mechanism pillars (structural / runtime / behavioral). Behavioral holds only
4550
4575
  // what you're actually getting (realized routing + estimated loop prevention); cache-drop
4551
4576
  // and output-waste are OPPORTUNITY (avoidable waste TO does not yet prevent), not here. ----
4552
- var mce = s.mcp_cap_estimated || {}, ce = s.contamination_exit || {}, hr = s.handover_rerun || {};
4577
+ var ce = s.contamination_exit || {}, hr = s.handover_rerun || {};
4553
4578
  var rs = s.retrieval_serve || {};
4554
- var rle = s.resume_lean_estimated || {};
4555
- var vs = s.verbosity_steer || {};
4556
- var cr = s.checkpoint_restore_estimated || {};
4579
+ var rle = {}; // The avoided reload is diagnostic, not a credited saving.
4580
+ var vs = {};
4581
+ var vo = {};
4582
+ var cr = {}; // Historical restore sizes may include injected context.
4557
4583
  var cp = s.counted_period || {};
4558
4584
  var rereadMo = cp.available ? mo(cp.reread_usd) : 0;
4559
4585
  var hf = s.hint_followed || {};
@@ -4566,32 +4592,29 @@ var DB = (function() {
4566
4592
  var avoidedSearchN = hfHasData ? (Number(hf.events) || 0) : (Number(rs.served_sessions) || 0);
4567
4593
  var avoidedSearchUnit = hfHasData ? 'hints used' : 'served';
4568
4594
  var structMo = mo(sd.cost_saved_usd);
4569
- var runtimeMo = Math.max(0, mo(s.total_cost_usd) - structMo) + mo(unc.cost_saved_usd) + mo(mce.cost_saved_usd);
4570
- // behavioral holds every estimated behavioral item (routing + loops + the cohort
4595
+ var runtimeMo = Math.max(0, mo(s.total_cost_usd) - structMo) + mo(unc.cost_saved_usd);
4596
+ // behavioral holds every estimated behavioral item (loops + the cohort
4571
4597
  // estimators + avoided-search), so the pillars (struct + runtime + behavioral)
4572
4598
  // always reconcile exactly to gettingMo (measured + estimated). Every estItems
4573
4599
  // entry maps to exactly one pillar: loops/sub-agent/mcp_cap -> runtime;
4574
4600
  // heeded/handover/avoided-search/lean-resumes -> behavioral.
4575
- var behavMo = mo(mr.realized_cost_usd) + mo(beh.cost_saved_usd) + mo(ce.cost_saved_usd) + mo(hr.cost_saved_usd) + avoidedSearchMo + mo(rle.cost_saved_usd) + mo(vs.cost_saved_usd) + mo(cr.cost_saved_usd);
4576
- // ---- trust tiers: measured / estimated / opportunity. Opportunity NEVER folds into the headline. ----
4577
- // Measured = billable events we metered (runtime compression + realized model routing).
4578
- // Routing joins the measured tier only when its valuation is measured; the
4579
- // standardized newest-card schedule makes it an estimate (Other estimates).
4580
- var routingEstimated = mr.evidence === 'estimated';
4581
- var measuredMo = mo(s.total_cost_usd) + (routingEstimated ? 0 : mo(mr.realized_cost_usd));
4601
+ var behavMo = mo(beh.cost_saved_usd) + mo(ce.cost_saved_usd) + mo(hr.cost_saved_usd) + avoidedSearchMo + mo(rle.cost_saved_usd) + mo(vs.cost_saved_usd) + mo(cr.cost_saved_usd);
4602
+ // ---- trust tiers: measured / estimated / opportunity. Opportunity and the
4603
+ // routing assumption NEVER fold into the headline. ----
4604
+ // Measured = billable events we metered (runtime compression).
4605
+ var measuredMo = mo(s.total_cost_usd);
4582
4606
  // Estimated = genuine TO-realized counterfactuals grounded in YOUR behavior; each carries a sample size.
4583
- // (Pillars + estimated reconcile to gettingMo: mcp_cap folds into runtime.)
4607
+ // Pillars and estimated amounts reconcile to gettingMo.
4584
4608
  var estItems = [
4585
- { key: 'routing_estimated', label: 'model routing', amt: routingEstimated ? mo(mr.realized_cost_usd) : 0, n: (mr.baseline_reference_priced || []).length, unit: 'model families on one newest-card price list' },
4586
4609
  { key: 'behavioral_estimate', label: 'loops prevented', amt: mo(beh.cost_saved_usd), n: Number(beh.loop_events) || 0, unit: 'events' },
4587
4610
  { key: 'uncaptured_runtime', label: 'sub-agent runtime', amt: mo(unc.cost_saved_usd), n: Number(unc.subagent_dispatches) || 0, unit: 'dispatches' },
4588
- { key: 'mcp_cap_estimated', label: 'MCP output cap', amt: mo(mce.cost_saved_usd), n: Number(mce.events) || 0, unit: 'capped results' },
4589
4611
  { key: 'contamination_exit', label: 'avoided rework (heeded nudges)', amt: mo(ce.cost_saved_usd), n: Number(ce.heeded_sessions) || 0, unit: 'heeded', conf: ce.confidence },
4590
4612
  { key: 'handover_rerun', label: 'continuity handover', amt: mo(hr.cost_saved_usd), n: Number(hr.restored_sessions) || 0, unit: 'restored', conf: hr.confidence },
4591
4613
  { key: 'avoided_search', label: 'avoided search (hints)', amt: avoidedSearchMo, n: avoidedSearchN, unit: avoidedSearchUnit, conf: hfHasData ? 'trigger observed, size estimated' : rs.confidence },
4592
- { key: 'resume_lean_estimated', label: 'lean resumes (cold reload avoided)', amt: mo(rle.cost_saved_usd), n: Number(rle.events) || 0, unit: 'resumes' },
4593
4614
  { key: 'checkpoint_restore_estimated', label: 'checkpoint restores (working-set re-reads)', amt: mo(cr.cost_saved_usd), n: Number(cr.events) || 0, unit: 'restores' },
4594
- { key: 'verbosity_steer', label: 'concise output nudges', amt: mo(vs.cost_saved_usd), n: Number(vs.events) || 0, unit: 'nudges' }
4615
+ { key: 'verbosity_steer', label: 'concise output nudges', amt: mo(vs.cost_saved_usd), n: Number(vs.events) || 0, unit: 'nudges' },
4616
+ { key: 'verbosity_output_estimated', label: 'shorter replies and their re-reads (net of un-nudged replies)', amt: mo(vo.cost_saved_usd), n: Number(vo.events) || 0, unit: 'calibrated nudges',
4617
+ conf: vo.basis === 'no_reduction_net_of_control' ? 'no reduction net of the control' : (vo.basis === 'not_measured' && vo.events ? 'NOT MEASURED: no un-nudged control yet' : undefined) }
4595
4618
  ].filter(function(it){ return it.amt > 0 || it.conf; });
4596
4619
  var estimatedMo = estItems.reduce(function(a, b){ return a + b.amt; }, 0);
4597
4620
  // What you're getting = measured + estimated (both real value; estimated shown split-out, never hidden).
@@ -4600,9 +4623,9 @@ var DB = (function() {
4600
4623
  // retain the component calculation above until their next regeneration.
4601
4624
  var actionSavings = s.action_savings;
4602
4625
  if (actionSavings) {
4603
- measuredMo = mo(actionSavings.logged_usd) + mo(actionSavings.routing_measured_usd);
4626
+ measuredMo = mo(actionSavings.logged_usd) + mo(actionSavings.class_premium_usd || 0);
4604
4627
  rereadMo = mo(actionSavings.reread_usd);
4605
- estimatedMo = mo(actionSavings.estimated_usd) + mo(actionSavings.routing_estimated_usd);
4628
+ estimatedMo = mo(actionSavings.estimated_usd);
4606
4629
  gettingMo = mo(actionSavings.total_usd);
4607
4630
  }
4608
4631
  // Whole-cent display values from the payload: the parts shown on the card
@@ -4614,11 +4637,11 @@ var DB = (function() {
4614
4637
  var estSumCents = Object.keys(de).reduce(function(a, k) { return a + de[k]; }, 0);
4615
4638
  exactCents = {
4616
4639
  total: dispCents.total_cents,
4617
- logged: dc.logged + dc.routing_measured,
4640
+ logged: dc.logged + (Number(dc.class_premium) || 0),
4641
+ premium: Number(dc.class_premium) || 0,
4618
4642
  reread: dc.reread,
4619
- other: estSumCents + dc.routing_estimated,
4643
+ other: estSumCents,
4620
4644
  est: de,
4621
- routingEstimated: dc.routing_estimated,
4622
4645
  avoidedKey: actionSavings.avoided_search_source
4623
4646
  };
4624
4647
  }
@@ -4627,14 +4650,20 @@ var DB = (function() {
4627
4650
  }
4628
4651
  function estCents(item) {
4629
4652
  var key = item.key === 'avoided_search' ? exactCents.avoidedKey : item.key;
4630
- return key === 'routing_estimated' ? exactCents.routingEstimated : exactCents.est[key];
4653
+ return exactCents.est[key];
4631
4654
  }
4632
4655
  // Opportunity = realizable if you act; never realized, never summed into "getting".
4633
4656
  // output-waste is $ here; cache-drop is shown separately in TOKENS (re-written prefix) —
4634
4657
  // its $ is Anthropic-specific (OpenAI/OpenCode cache writes are free), but the token count
4635
4658
  // is a provider-neutral fact, matching Claude Code's own token-denominated display.
4636
4659
  var recl = s.stale_reads_reclaimable || {};
4637
- var cdTokensMo = Math.round((Number(cd.est_drops) || 0) * (Number(cd.prefix_tokens) || 0) / Math.max(days, 1) * 30);
4660
+ var cdTokensMo = Math.round((Number(cd.rebuilt_tokens) > 0 ? Number(cd.rebuilt_tokens)
4661
+ : (Number(cd.est_drops) || 0) * (Number(cd.prefix_tokens) || 0)) / Math.max(days, 1) * 30);
4662
+ // The cache TTL this user's own writes show: 1 hour (Claude Code) or 5 minutes.
4663
+ var cdShortTtl = Number(cd.ttl_seconds) > 0 && Number(cd.ttl_seconds) < 3600;
4664
+ var cdCacheName = cdShortTtl ? 'the 5-minute cache' : (Number(cd.ttl_seconds) >= 3600 ? 'the 1-hour cache' : 'the cache window');
4665
+ var cdResume = cdShortTtl ? 'Resume within 5 minutes' : 'Resume within the hour';
4666
+ var cdRebuilds = Number(cd.est_drops) || 0;
4638
4667
  // The big opportunity number holds only evidence-backed items (unused skills,
4639
4668
  // stale re-reads, full-file Writes). Routing rests on an assumed share of your
4640
4669
  // Opus work, so it gets its own line below the number and is never added in.
@@ -4663,117 +4692,33 @@ var DB = (function() {
4663
4692
  var routingTarget = mr.target_model || "Sonnet";
4664
4693
  var unusedSkills = Number(sp.unused_skills) || 0;
4665
4694
  var currOpus = Math.round((Number(mr.current_opus_share) || 0) * 100);
4695
+ var fmtPct = function(x) { return Math.round((Number(x) || 0) * 1000) / 10; };
4696
+ var routingRealizedMo = mo(actionSavings && actionSavings.routing_usd != null
4697
+ ? actionSavings.routing_usd : mr.realized_cost_usd);
4698
+ var routingBaselinePct = fmtPct(mr.baseline_opus_share);
4699
+ var routingAssumption = (mr.baseline_provenance && mr.baseline_provenance.short) ? String(mr.baseline_provenance.short)
4700
+ : mr.baseline_source === 'pretool_baseline'
4701
+ ? 'assuming ' + routingBaselinePct + '% Opus before Token Optimizer'
4702
+ : (mr.baseline_opus_share != null
4703
+ ? 'against a measured ' + routingBaselinePct + '% Opus baseline'
4704
+ : 'against an Opus baseline');
4705
+ var routingAltShare = mr.measured_baseline_opus_share;
4706
+ var routingAltMo = mr.measured_baseline_realized_cost_usd != null ? mo(mr.measured_baseline_realized_cost_usd) : null;
4666
4707
  var ts = data.generated_at ? new Date(data.generated_at).toLocaleString() : 'unknown';
4708
+ // U9: the savings story leads when the payload carries session_effect;
4709
+ // older payloads (or a template without the inlined module) keep the
4710
+ // previous layout unchanged.
4711
+ var story = '';
4712
+ try { story = (typeof savingsStoryHtml === 'function') ? savingsStoryHtml(data) : ''; } catch (e) { story = ''; }
4667
4713
 
4668
4714
  var html = '<div class="section-header">' +
4669
- '<div class="label">Value</div><h1>Savings</h1>' +
4670
- '<p>Your savings, with the time period and method shown for each total.</p>' +
4715
+ (story ? '<h1>Savings</h1>' : '<div class="label">Value</div><h1>Savings</h1>' +
4716
+ '<p>Your savings, with the time period and method shown for each total.</p>') +
4671
4717
  '</div>' +
4672
4718
  '<div class="last-updated">Updated ' + esc(ts) + ' &middot; refreshes after every session</div>';
4673
4719
 
4674
- html += runwayCardHtml();
4675
-
4676
- // ---- HERO: the before/after transformation (THE headline). Current activity priced at
4677
- // your pre-TO per-session weight + mix vs actual — comprehensive (volume + structural +
4678
- // routing + sub-agents), grounded in your own earliest-vs-recent sessions. ----
4679
- var ba = s.before_after || {};
4680
- if (Number(ba.monthly_savings_usd) > 0) {
4681
- var wp = ba.session_weight_pool || null;
4682
- var wpUnit = (wp && wp.work_unit === 'message') ? 'message' : 'API call';
4683
- var oldCost = Number(ba.counterfactual_monthly_usd) || 0;
4684
- var nowCost = Number(ba.actual_monthly_usd) || 0;
4685
- // Use the displayed saving so a spend-capped headline cannot retain the
4686
- // larger, uncapped percentage implied by the counterfactual arms.
4687
- var shownSaving = Number(ba.monthly_savings_usd) || 0;
4688
- var costCut = oldCost > 0 ? Math.max(0, shownSaving / oldCost * 100) : 0;
4689
- // A neutral add-back reprice (routing pending or unavailable) shrinks the
4690
- // transformation figure without any visible reason -- say why, plainly.
4691
- var baRepriceBasis = ba.compression_reprice_basis;
4692
- var baRepriceNote = (baRepriceBasis === 'routing_pending')
4693
- ? 'Model-mix repricing is paused while sessions finish re-measuring, so the add-backs in this estimate show their measured value.'
4694
- : (baRepriceBasis === 'routing_unavailable'
4695
- ? 'Model-mix repricing could not be measured, so the add-backs in this estimate show their measured value.'
4696
- : '');
4697
- html += '<div class="card wide savings-transformation" style="padding:var(--s-4);margin-bottom:var(--s-3);">' +
4698
- '<div class="label">Transformation &middot; last ' + days + ' days &middot; estimated</div>' +
4699
- '<div class="savings-amount">' + money(ba.monthly_savings_usd) +
4700
- '<span class="savings-unit"> saved &middot; ~' + Math.round(costCut) + '% lower cost</span></div>' +
4701
- '<p class="lede">Your recent workload compared with your earlier way of working, at the same token prices.</p>' +
4702
- '<div class="savings-split"><span>Now <strong>' + money(nowCost) + '</strong></span>' +
4703
- '<span>Earlier workflow <strong>' + money(oldCost) + '</strong></span></div>' +
4704
- '<div class="plain-line">Overlaps with the action savings below. Do not add the two totals.</div>' +
4705
- (baRepriceNote ? '<div class="plain-line">' + baRepriceNote + '</div>' : '') +
4706
- fold('How this is estimated',
4707
- countedList([ba.savings_capped && ba.savings_cap_note ? esc(ba.savings_cap_note) : '']) +
4708
- (wp
4709
- ? '<p>Baseline: <strong>' + esc(wp.anchor_month) + '</strong>. We compare cost per ' + wpUnit +
4710
- ' at constant prices, then apply the difference to the <strong>' +
4711
- (Number(wp.now_units) || 0).toLocaleString() + '</strong> ' + wpUnit +
4712
- 's in this period. Current cost: ' + money(Number(wp.after_cost_per_unit)) +
4713
- ' per ' + wpUnit + '; baseline: ' + money(Number(wp.before_cost_per_unit)) + '.</p>' +
4714
- '<p>More, smaller sessions are not counted as dollar savings. Changes in model prices and model mix are excluded. ' +
4715
- 'Delegated work attached to a main session is included in its cost; it is not added again.</p>'
4716
- : '<p>We price your frozen baseline session using your earlier and current model and cache patterns, ' +
4717
- 'then scale the difference to this period. Context savings and normalized delegated work complete the estimate.</p>') +
4718
- '<p>This comparison includes changes in your own habits. It cannot isolate Token Optimizer’s contribution. ' +
4719
- 'An API call is a workload proxy, not a measure of task difficulty or quality.</p>' +
4720
- '<p>' + billingCaption + '</p>') +
4721
- '</div>';
4722
- } else if (ba.baseline_building) {
4723
- // New install: no frozen baseline yet, so the headline transformation can't be
4724
- // computed. Explain WHY (it uses the user's OWN history, never a fake anchor) and
4725
- // show progress, instead of silently rendering nothing and leaving only the small
4726
- // measured floor below (which reads as "TO only saved me $X").
4727
- var bb = ba.baseline_building;
4728
- var sNeed = Number(bb.sessions_needed) || 30;
4729
- var sHave = Math.min(sNeed, Number(bb.sessions_in_window) || 0);
4730
- var dLeft = Number(bb.days_left) || 0;
4731
- var pct = sNeed > 0 ? Math.min(100, Math.round(sHave / sNeed * 100)) : 0;
4732
- html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);border:1px solid var(--c-accent-blue);box-shadow:0 0 0 1px rgba(0,102,255,0.12);">' +
4733
- '<div class="label" style="margin-bottom:var(--s-2);color:var(--c-accent-cyan);">Your savings baseline is still building</div>' +
4734
- '<div class="lede">Token Optimizer measures your savings against <strong>your own</strong> pre-optimization baseline, frozen from your first ' + (Number(bb.early_window_days) || 30) + ' days of real sessions. It never uses anyone else\'s numbers, and never freezes a half-formed anchor.</div>' +
4735
- '<div class="lede" style="margin-top:var(--s-2);"><strong>' + sHave + ' of ~' + sNeed + ' sessions</strong> collected in your baseline window' + (dLeft > 0 ? ', about <strong>' + dLeft + ' day' + (dLeft === 1 ? '' : 's') + '</strong> until it locks in' : '') + '. Until then, the figure below is the directly-metered floor, not your full savings.</div>' +
4736
- '<div style="margin-top:var(--s-4);height:8px;background:rgba(255,255,255,0.08);border-radius:4px;overflow:hidden;"><div style="height:100%;width:' + pct + '%;background:var(--c-accent-cyan);box-shadow:0 0 12px var(--c-accent-glow);transition:width .3s;"></div></div>' +
4737
- '</div>';
4738
- } else if (ba.reason === 'net_negative') {
4739
- // Baseline is frozen, but efficiency was flat-to-negative this period (now costs about
4740
- // the same as — or slightly more than — the frozen baseline would have). We show NO
4741
- // counterfactual headline (a saving we didn't make), just an honest neutral note plus
4742
- // the arms; the directly-metered floor card below still reports realized savings. This
4743
- // is the net<=0 branch — parity with OpenClaw/OpenCode.
4744
- html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4745
- '<div class="label" style="margin-bottom:var(--s-2);">At or above your baseline this period</div>' +
4746
- '<div class="lede">Your recent sessions cost about what your frozen baseline would have — est. <strong>' + money(ba.actual_monthly_usd) + '</strong> now vs <strong>' + money(ba.counterfactual_monthly_usd) + '</strong> the old way in the last ' + days + ' days. There is no net saving to headline this period, so we are not showing one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4747
- '</div>';
4748
- } else if (ba.reason === 'flat') {
4749
- // Both work-unit methods sit within a few percent of spend: no
4750
- // measurable whole-workload change, so no headline and no scary number.
4751
- html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4752
- '<div class="label" style="margin-bottom:var(--s-2);">No measurable change in cost per unit of work</div>' +
4753
- '<div class="plain-line">Your recent work costs about the same per request as before install (' + money(ba.actual_monthly_usd) + ' now vs ' + money(ba.counterfactual_monthly_usd) + ' the old way over ' + days + ' days). The savings below are counted action by action.</div>' +
4754
- '</div>';
4755
- } else if (ba.reason === 'methods_disagree') {
4756
- // The two independent work-unit methods (per-API-call and per-message)
4757
- // landed more than 10% apart, so neither figure is trustworthy enough to
4758
- // headline. Show both, headline nothing; the metered floor card below
4759
- // still reports realized savings. Same neutral-card shape as
4760
- // net_negative, with signed money for the cross-check figure.
4761
- var swp = ba.session_weight_pool || {};
4762
- var swpCross = swp.crosscheck || {};
4763
- var mainUsd = Number(swp.transformation_usd) || 0;
4764
- var crossUsd = Number(swpCross.transformation_usd) || 0;
4765
- var mainUnit = swp.work_unit === 'message' ? 'per-message' : 'per-API-call';
4766
- var crossUnit = swpCross.unit === 'api_call' ? 'per-API-call' : 'per-message';
4767
- var signedMoney = function (n) {
4768
- var v = Number(n) || 0;
4769
- return (v < 0 ? '-' : '') + money(Math.abs(v));
4770
- };
4771
- html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4772
- '<div class="label" style="margin-bottom:var(--s-2);">Two estimates disagree this period</div>' +
4773
- '<div class="lede">The ' + mainUnit + ' estimate is <strong>' + signedMoney(mainUsd) + '</strong> and the ' + crossUnit +
4774
- ' estimate is <strong>' + signedMoney(crossUsd) + '</strong> over ' + days + ' days. They are too far apart to headline either one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4775
- '</div>';
4776
- }
4720
+ html += story || runwayCardHtml();
4721
+ var storyHead = html; html = '';
4777
4722
 
4778
4723
  // ---- Tokens Saved card: the full card (hero + spent-vs-saved + model-
4779
4724
  // mix-as-usage + footer). Rendered as the 2nd card in the Savings view,
@@ -4781,15 +4726,14 @@ var DB = (function() {
4781
4726
  // "Counted directly" measured-floor card below. Also rendered in the
4782
4727
  // Trends view — both call the shared hoisted tokensSavedCardHtml helper
4783
4728
  // so the card is identical across views. SPENT = trends.total_tokens
4784
- // (billable total), SAVED = savings.total_tokens. See tokensSavedCardHtml
4729
+ // (billable total); the savings total comes from savingsStoryBands. See tokensSavedCardHtml
4785
4730
  // for the full fail-open spec. ----
4786
4731
  // Add only rereads to the one-shot ledger. Adding the counted-period total
4787
4732
  // would count its initial removals twice and discard unmatched logged events.
4788
4733
  html += '<div style="display:flex;gap:var(--s-3);flex-wrap:wrap;margin-bottom:var(--s-3);">';
4789
4734
  var periodLabel = runRate ? 'last ' + days + ' days' : trackedDays + ' days tracked';
4790
4735
  var heroAmt = gettingMo;
4791
- // One plain visible line only when some of the total could not be priced; every
4792
- // other counting note lives in the card's "Breakdown and method" fold.
4736
+ // Incomplete pricing is disclosed here; the full method is in the fold.
4793
4737
  var actionPricingIncomplete = !!(cp.reread_pricing_note ||
4794
4738
  (actionSavings && actionSavings.reread_prices_available === false) || cp.reread_prices_available === false ||
4795
4739
  Number(s.compression_unpriced_tokens) > 0 ||
@@ -4797,18 +4741,17 @@ var DB = (function() {
4797
4741
  html += '<div class="card savings-actions" style="flex:2;min-width:min(100%,320px);padding:var(--s-4);">' +
4798
4742
  '<div class="label">Action savings &middot; ' + periodLabel + '</div>' +
4799
4743
  '<div class="savings-amount">' + (exactCents ? moneyCents(exactCents.total) : money(periodValue(heroAmt))) + '<span class="savings-unit"> logged + estimated</span></div>' +
4744
+ (s.token_headline ? '<p class="plain-line">~' + fmtTok(s.token_headline.total_tokens) + ' tokens kept out of context &middot; ' + tokenSplitText(s.token_headline, fmtTok) + ' (estimated)' + (s.token_headline.refresh_incomplete_events || s.token_headline.unmeasured_events ? ', incomplete coverage' : '') + '.</p>' : '') +
4800
4745
  '<div class="savings-split"><span>Logged actions <strong>' + (exactCents ? moneyCents(exactCents.logged) : money(periodValue(measuredMo))) + '</strong></span>' +
4801
- '<span>Repeat reads avoided <strong>' +
4802
- (actionSavings && actionSavings.reread_available === false ? 'Unavailable' :
4803
- ((actionSavings && actionSavings.reread_prices_available === false) || cp.reread_prices_available === false ?
4804
- 'Unpriced' : '~' + (exactCents ? moneyCents(exactCents.reread) : money(periodValue(rereadMo))))) + '</strong></span>' +
4746
+ ((!cp.available && !(actionSavings && actionSavings.reread_available === true)) || (actionSavings && (actionSavings.reread_available === false || actionSavings.reread_prices_available === false)) || cp.reread_prices_available === false ? '' :
4747
+ '<span>Repeat reads avoided <strong>~' + (exactCents ? moneyCents(exactCents.reread) : money(periodValue(rereadMo))) + '</strong></span>') +
4805
4748
  '<span>Other estimates <strong>~' + (exactCents ? moneyCents(exactCents.other) : money(periodValue(estimatedMo))) + '</strong></span></div>' +
4749
+ (Number(routingRealizedMo) > 0
4750
+ ? '<p class="plain-line"><strong>Model routing:</strong> ~' + money(periodValue(routingRealizedMo)) + esc(per) +
4751
+ ' ' + esc(routingAssumption) + (currOpus ? ' (now ' + currOpus + '% Opus)' : '') + '. Not in this total.</p>' : '') +
4806
4752
  (actionPricingIncomplete
4807
4753
  ? '<p class="plain-line">Some older history has no exact price, so this is a priced subtotal.</p>'
4808
4754
  : (!cp.available ? '<p class="plain-line">Repeat reads are not available here. Logged actions are still counted.</p>' : '')) +
4809
- (mr.evidence === 'pending'
4810
- ? '<p class="plain-line routing-pending">Model routing: re-measuring (' + Number(mr.pending_sessions || 0).toLocaleString() +
4811
- ' session' + (Number(mr.pending_sessions) === 1 ? '' : 's') + ' left). It is added to this total when the re-measurement finishes.</p>' : '') +
4812
4755
  // Usage without a token-class split (Cursor totals, model-daily-only
4813
4756
  // history, legacy rows) sits outside both routing arms. Say so instead of
4814
4757
  // letting an empty or partial routing figure read as complete coverage.
@@ -4817,6 +4760,7 @@ var DB = (function() {
4817
4760
  ' tokens without a token-class split are left out of model routing.</p>' : '') +
4818
4761
  fold('Breakdown and method',
4819
4762
  countedList([
4763
+ s.token_type_breakdown && Object.keys(s.token_type_breakdown).length ? 'Token types cover only ledger events with recorded turn classes. Repeat reads are modeled as cache reads except for detected cache rebuilds; write totals include detected rebuilds and initial removals recorded at a write rate. Unclassified tokens are excluded.' : '',
4820
4764
  'Includes the later benefit of context removed during this period. Initial removals are counted once.',
4821
4765
  cp.reread_pricing_note ? esc(cp.reread_pricing_note) : '',
4822
4766
  actionSavings && actionSavings.total_clamped ? 'Signed adjustments give a net total of ' +
@@ -4831,13 +4775,19 @@ var DB = (function() {
4831
4775
  Math.round(Number(s.reprice_detail.unpriced_tokens)).toLocaleString() +
4832
4776
  ' logged tokens ran on models with no known rate; their dollar value is not included.' : '',
4833
4777
  op.removal_events > 0 ? 'Initial removals above are priced at the input rate, a minimum.' +
4834
- (Number(op.class_premium_usd) >= 0.005
4835
- ? ' The next call billed new context at a cache-write rate for ' +
4836
- Math.round(Number(op.class_events) || 0).toLocaleString() + ' removals: about ' +
4837
- money(Number(op.class_premium_usd)) + ' more, not in the total.' : '') : '',
4778
+ (actionSavings && 'class_premium_usd' in actionSavings
4779
+ ? (Number(actionSavings.class_premium_usd) >= 0.005
4780
+ ? ' The next call billed new context at a cache-write rate for ' +
4781
+ Math.round(Number(op.class_events) || 0).toLocaleString() + ' removals. That write-class premium, ' +
4782
+ (exactCents ? moneyCents(exactCents.premium) : money(periodValue(mo(actionSavings.class_premium_usd)))) +
4783
+ ', is measured and included in Logged actions.' : '')
4784
+ : (Number(op.class_premium_usd) >= 0.005
4785
+ ? ' The next call billed new context at a cache-write rate for ' +
4786
+ Math.round(Number(op.class_events) || 0).toLocaleString() + ' removals: about ' +
4787
+ money(Number(op.class_premium_usd)) + ' more, not in the total.' : '')) : '',
4838
4788
  !cp.available ? 'Repeat-read coverage is unavailable here; logged actions are still included.' : ''
4839
4789
  ]) +
4840
- '<p>Logged actions include output trims, context reductions, setup changes and, when your earlier model mix is priced from your own usage, routing savings. ' +
4790
+ '<p>Logged actions include output trims, context reductions and setup changes. ' +
4841
4791
  'Prices may be allocated from each session’s recorded model mix.</p>' +
4842
4792
  '<p>Repeat reads use recorded later turns up to each session’s next compaction. ' +
4843
4793
  'This assumes the removed context would otherwise have stayed until that compaction. ' +
@@ -4852,7 +4802,10 @@ var DB = (function() {
4852
4802
  ((mr.baseline_reference_priced || []).length
4853
4803
  ? '<p>Routing compares your earlier and current mix on one price list, the newest card of each family (' +
4854
4804
  esc(mr.baseline_reference_priced.map(function(f) { return f.charAt(0).toUpperCase() + f.slice(1); }).join(', ')) +
4855
- '), because your earlier mix records no model generations. The figure is listed under estimates.</p>' : '') +
4805
+ '), because your earlier mix records no model generations. It is shown separately from the totals above.</p>' : '') +
4806
+ (routingAltShare != null
4807
+ ? '<p>Measured alternative: your earliest tracked month had ' + fmtPct(routingAltShare) + '% Opus' +
4808
+ (routingAltMo != null ? '; the same comparison gives ~' + money(periodValue(routingAltMo)) + esc(per) : '') + '.</p>' : '') +
4856
4809
  (Math.abs(mo(mr.generation_price_delta_usd)) >= 0.01
4857
4810
  ? '<p>At the exact cards you ran, the same work cost about ' + money(Math.abs(mo(mr.generation_price_delta_usd))) +
4858
4811
  (Number(mr.generation_price_delta_usd) > 0 ? ' more' : ' less') +
@@ -4880,27 +4833,36 @@ var DB = (function() {
4880
4833
  var sia = (si && si.all_in) || null;
4881
4834
  if (sia && Number(sia.total_usd) > 0) {
4882
4835
  var siaParts = sia.components_usd || {};
4883
- var siaRouting = (Number(siaParts.routing_measured) || 0) + (Number(siaParts.routing_estimated) || 0);
4836
+ var siaRouting = Number(sia.routing_usd) || ((Number(siaParts.routing_measured) || 0) + (Number(siaParts.routing_estimated) || 0));
4837
+ var siaRoutingNote = (sia.routing_baseline_provenance && sia.routing_baseline_provenance.short) ? String(sia.routing_baseline_provenance.short)
4838
+ : sia.routing_baseline_opus_share != null
4839
+ ? ((sia.routing_baseline_source === 'stated' || sia.routing_baseline_source === 'pretool_baseline' ? 'assuming ' : 'against a measured ') +
4840
+ fmtPct(sia.routing_baseline_opus_share) + '% Opus' +
4841
+ (sia.routing_baseline_source === 'stated' || sia.routing_baseline_source === 'pretool_baseline' ? ' before Token Optimizer' : ' baseline'))
4842
+ : 'an estimate';
4884
4843
  var siaPending = sia.routing_pending || sia.remeasuring;
4885
4844
  var siaLeft = Math.max(Number(sia.routing_pending_sessions) || 0, Number(sia.remeasuring_sessions) || 0);
4886
4845
  html += '<div class="card savings-history" style="flex:1;min-width:min(100%,260px);padding:var(--s-4);">' +
4887
4846
  '<div class="label">Saved since ' + esc(prettyDate(si.install_date)) + '</div>' +
4888
4847
  '<div class="savings-amount">' + money(sia.total_usd) +
4889
4848
  (siaPending ? ' <span class="remeasuring-tag" style="font-size:0.45em;color:var(--c-text-dim);">so far</span>' : '') + '</div>' +
4890
- (siaPending ? '<p class="plain-line remeasuring">Re-measuring older history (' + siaLeft.toLocaleString() +
4849
+ (siaPending ? '<p class="plain-line remeasuring">Updating older history (' + siaLeft.toLocaleString() +
4891
4850
  ' session' + (siaLeft === 1 ? '' : 's') + ' left). This total will grow when they finish.</p>' : '') +
4892
- '<p class="plain-line">Same four parts as the monthly total, added up since install.</p>' +
4851
+ '<p class="plain-line">Same parts as the monthly total, added up since install.</p>' +
4893
4852
  fold('Breakdown and history',
4894
- '<p>Model routing: <strong>' + money(siaRouting) + '</strong> (estimated).</p>' +
4853
+ '<p>Model routing: <strong>' + money(siaRouting) + '</strong> (' + esc(siaRoutingNote) + '), not in the total above.</p>' +
4854
+ (sia.routing_measured_baseline_opus_share != null
4855
+ ? '<p>Measured alternative: your earliest tracked month had ' + fmtPct(sia.routing_measured_baseline_opus_share) + '% Opus' +
4856
+ (sia.routing_measured_baseline_realized_cost_usd != null ? '; the same comparison gives ' + money(sia.routing_measured_baseline_realized_cost_usd) : '') + '.</p>' : '') +
4895
4857
  (Number(sia.routing_unsplit_tokens) > 0
4896
4858
  ? '<p>' + Number(sia.routing_unsplit_tokens).toLocaleString() +
4897
4859
  ' tokens without a token-class split are left out of model routing.</p>' : '') +
4898
4860
  '<p>Repeat reads avoided: <strong>' + money(siaParts.reread) + '</strong> (modeled).</p>' +
4899
- '<p>Logged actions: <strong>' + money(siaParts.logged) + '</strong>.</p>' +
4861
+ '<p>Logged actions: <strong>' + money((Number(siaParts.logged) || 0) + (Number(siaParts.class_premium) || 0)) + '</strong>.</p>' +
4900
4862
  '<p>Other estimates: <strong>' + money(sia.estimated_usd) + '</strong>.</p>' +
4901
- ((Number(cc.total_usd) > 0 || cc.available) ?
4863
+ ((Number(cc.total_usd) > 0 || cc.available) && cc.prices_available !== false ?
4902
4864
  '<p>Context trimming on its own (initial removals + repeat reads): ' +
4903
- (cc.prices_available === false ? 'Unpriced' : money(Math.max(0, Number(cc.total_usd) || 0))) + '.</p>' : '') +
4865
+ money(Math.max(0, Number(cc.total_usd) || 0)) + '.</p>' : '') +
4904
4866
  countedList([
4905
4867
  cc.pricing_note ? esc(cc.pricing_note) : '',
4906
4868
  cc.media_note ? esc(cc.media_note) : ''
@@ -4908,14 +4870,14 @@ var DB = (function() {
4908
4870
  '<p>Tracked over ' + Number(si.days || 0).toLocaleString() + ' days. Historical entries remain after their source transcripts rotate.</p>' +
4909
4871
  '<p>' + billingCaption + '</p>') +
4910
4872
  '</div>';
4911
- } else if (Number(cc.total_usd) > 0 || (cc.available && Number(cc.events) > 0)) {
4873
+ } else if (cc.prices_available !== false && (Number(cc.total_usd) > 0 || (cc.available && Number(cc.events) > 0))) {
4912
4874
  html += '<div class="card savings-history" style="flex:1;min-width:min(100%,260px);padding:var(--s-4);">' +
4913
4875
  '<div class="label">Context savings &middot; all time</div>' +
4914
- '<div class="savings-amount">' + (cc.prices_available === false ? 'Unpriced' : money(Math.max(0, Number(cc.total_usd) || 0))) +
4876
+ '<div class="savings-amount">' + money(Math.max(0, Number(cc.total_usd) || 0)) +
4915
4877
  (cc.remeasuring ? ' <span class="remeasuring-tag" style="font-size:0.45em;color:var(--c-text-dim);">so far</span>' : '') + '</div>' +
4916
- (cc.remeasuring ? '<p class="plain-line remeasuring">Re-measuring (' + Number(cc.remeasuring_sessions || 0).toLocaleString() +
4878
+ (cc.remeasuring ? '<p class="plain-line remeasuring">Updating history (' + Number(cc.remeasuring_sessions || 0).toLocaleString() +
4917
4879
  ' session' + (Number(cc.remeasuring_sessions) === 1 ? '' : 's') + ' left). This subtotal is in progress and will change when they finish.</p>' : '') +
4918
- '<p class="plain-line">' + (cp.available ? '<strong>' + (cp.prices_available === false ? 'Unpriced' : money(cp.total_usd)) + '</strong> from removals in the last ' + days + ' days. ' : '') +
4880
+ '<p class="plain-line">' + (cp.available && cp.prices_available !== false ? '<strong>' + money(cp.total_usd) + '</strong> from removals in the last ' + days + ' days. ' : '') +
4919
4881
  'Overlaps with action savings.</p>' +
4920
4882
  fold('History and coverage',
4921
4883
  countedList([
@@ -4925,8 +4887,8 @@ var DB = (function() {
4925
4887
  Number(cc.total_usd) < 0 ? 'Signed net: ' + money(cc.total_usd) + '. Savings headline is floored at zero.' : '',
4926
4888
  'Excludes routing, setup and other estimates.'
4927
4889
  ]) +
4928
- '<p>' + (cc.oneshot_prices_available === false ? 'Unpriced' : money(cc.oneshot_usd)) + ' initial removals + ' +
4929
- (cc.reread_prices_available === false ? 'Unpriced' : money(cc.reread_usd)) + ' modeled repeat reads.</p>' +
4890
+ (cc.oneshot_prices_available === false ? '' : '<p>' + money(cc.oneshot_usd) + ' initial removals.</p>') +
4891
+ (cc.reread_prices_available === false ? '' : '<p>' + money(cc.reread_usd) + ' modeled repeat reads.</p>') +
4930
4892
  '<p>Stored history since ' + esc(prettyDate(cc.window_start)) + '. ' +
4931
4893
  'Same removal-date method as the period total. Historical entries remain after their source transcripts rotate.</p>' +
4932
4894
  '<p>Repeat reads assume the removed context would otherwise have stayed until the session’s next compaction. ' +
@@ -4943,25 +4905,49 @@ var DB = (function() {
4943
4905
  }
4944
4906
  html += '</div>';
4945
4907
  html += fold('Token savings and model usage', tokensSavedCardHtml(s));
4908
+ var ledgerHtml = html;
4909
+ html = storyHead + (story ? '' : ledgerHtml);
4946
4910
 
4947
4911
  // ---- SAVE MORE: suggestions, promoted right under the hero ----
4948
4912
  var parts = [];
4949
4913
  if ((Number(sp.cost_saved_usd) || 0) > 0 && unusedSkills > 0) {
4950
- parts.push('Review ' + unusedSkills + ' skill' + (unusedSkills === 1 ? '' : 's') + ' not invoked in this window. Archiving what you no longer need is worth about ' + moneyCents(oppCents.structural) + per + ', automatically, from then on.');
4914
+ parts.push('Review ' + unusedSkills + ' skill' + (unusedSkills === 1 ? '' : 's') + ' not invoked in this window.');
4951
4915
  }
4952
4916
  if ((Number(recl.cost_usd) || 0) > 0) {
4953
4917
  parts.push('Avoid re-reading files that have not changed, or add them to .contextignore. ' + (Number(recl.tokens) || 0).toLocaleString() + ' tokens of stale re-reads across ' + (Number(recl.sessions) || 0).toLocaleString() + ' sessions are worth about ' + moneyCents(oppCents.reclaimable) + per + '.');
4954
4918
  }
4955
- if ((Number(mr.potential_cost_usd) || 0) > 0) {
4919
+ if (!story && (Number(mr.potential_cost_usd) || 0) > 0) {
4956
4920
  parts.push('Route routine work to lighter models and keep Opus for the work that needs it. The routing line above shows the size of that assumption.');
4957
4921
  }
4958
4922
  if (cdTokensMo > 0) {
4959
- parts.push('Resume within the hour, or batch related work before stepping away. ' + (Number(cd.drop_sessions) || 0) + ' of your sessions idled past the cache window and re-wrote the prefix, about ' + cdTokensMo.toLocaleString() + ' tokens' + per + (cdCostMo > 0 ? ', worth about ' + money(cdCostMo) + per + ' at API rates' : '') + '.');
4923
+ parts.push(cdResume + ', or batch related work before stepping away. ' + (Number(cd.drop_sessions) || 0) + ' of your sessions idled past ' + cdCacheName + ' and re-wrote the prefix' + (cdRebuilds > 0 ? ' ' + cdRebuilds.toLocaleString() + ' time' + (cdRebuilds === 1 ? '' : 's') : '') + ', about ' + cdTokensMo.toLocaleString() + ' tokens' + per + (cdCostMo > 0 ? ', worth about ' + money(cdCostMo) + per + ' at API rates' : '') + '.');
4960
4924
  }
4961
4925
  if ((Number(ow.cost_saved_usd) || 0) > 0) {
4962
4926
  parts.push('Favor targeted Edits over full-file Writes. About ' + (Number(ow.avoidable_writes) || 0) + ' of your Writes could have been Edits, worth about ' + moneyCents(oppCents.output) + per + ' in output.');
4963
4927
  }
4964
- if (parts.length > 0) {
4928
+ var moreFolds = [];
4929
+ if (story) {
4930
+ // U9: nothing else on the tab. Opportunity, coverage detail, the previous
4931
+ // cards and diagnostics sit in one row of folds at the bottom; the
4932
+ // whole-workload comparison is no longer shown here.
4933
+ if (parts.length > 0) {
4934
+ moreFolds.push('<details class="fold"><summary>Room to save more</summary><div class="fold__body">' +
4935
+ '<p>More changes you could make to your setup or habits, beyond Still on the table. None of this is in any total above.</p>' +
4936
+ parts.map(function(p) { return '<p>' + esc(p) + '</p>'; }).join('') +
4937
+ (data.runtime !== 'cursor' && data.runtime !== 'antigravity' ? '<p>Run <strong>/token-optimizer</strong> and follow its suggestions to claim it.</p>' : '') +
4938
+ '</div></details>');
4939
+ }
4940
+ var covFold = (typeof savingsCoverageFold === 'function') ? savingsCoverageFold(data) : '';
4941
+ if (covFold) moreFolds.push(covFold);
4942
+ // The previous action-savings, since-install and Tokens Saved cards are not
4943
+ // shown in story mode: they still add routing to their totals and count
4944
+ // tokens on another basis, so they would contradict the hero.
4945
+ var ledgerBody = (typeof savingsLedgerHtml === 'function') ? savingsLedgerHtml(data) : ledgerHtml;
4946
+ var mixTotal = 0, mix = (data.trends && data.trends.model_mix) || {};
4947
+ for (var mixK in mix) { mixTotal += Number(mix[mixK]) || 0; }
4948
+ if (mixTotal > 0 && typeof modelMixBodyHtml === 'function') ledgerBody += '<h3 class="ts-section-label st-gap">Which models did the work</h3>' + modelMixBodyHtml(mix, data.runtime === 'codex', mixTotal);
4949
+ moreFolds.push('<details class="fold"><summary>Full ledger and history</summary><div class="fold__body">' + ledgerBody + '</div></details>');
4950
+ } else if (parts.length > 0) {
4965
4951
  html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);border:1px solid var(--c-amber);box-shadow:0 0 0 1px rgba(217,164,65,0.18), 0 0 44px rgba(217,164,65,0.12);">';
4966
4952
  html += '<div class="label" style="margin-bottom:var(--s-2);color:var(--c-amber);letter-spacing:0.08em;">Money on the table &middot; opportunity</div>';
4967
4953
  if (opportunityMo > 0) {
@@ -4975,11 +4961,11 @@ var DB = (function() {
4975
4961
  }
4976
4962
  if (cdTokensMo > 0) {
4977
4963
  html += '<div class="cache-drop-opportunity" style="margin-top:var(--s-3);font-family:var(--font-mono);font-size:17px;line-height:1.6;color:var(--c-text-main);max-width:820px;">' +
4978
- 'Cache drops (an opportunity, not a measurement): ' + (Number(cd.drop_sessions) || 0) + ' sessions idled past the cache window and re-wrote ~' + fmtTok(cdTokensMo) + ' tokens' + esc(per) + ' of prefix' +
4964
+ 'Cache drops (an opportunity, not a measurement): ' + (Number(cd.drop_sessions) || 0) + ' sessions idled past ' + cdCacheName + ' and re-wrote ~' + fmtTok(cdTokensMo) + ' tokens' + esc(per) + ' of prefix' +
4979
4965
  (cdCostMo > 0 ? ', about <span style="color:var(--c-amber);">' + money(cdCostMo) + esc(per) + '</span> at API rates' : '') + '.' +
4980
4966
  '</div>';
4981
4967
  html += '<div class="plain-line">Not part of the savings number above.</div>';
4982
- html += fold('How the cache drop figure is priced', '<p>Cache write rate minus the cache read it would have cost, at the models you ran. It is not part of the number above.</p>');
4968
+ html += fold('How the cache drop figure is priced', '<p>Each rebuild is the prefix the cache had held before the gap, priced at its own cache write rate (1 hour or 5 minutes) minus the cache read it would have cost, at the models you ran and at API rates. It is not part of the number above.</p>' + ((Number(cd.unscanned_large_sessions) || 0) > 0 ? '<p>' + Number(cd.unscanned_large_sessions) + ' very large session' + (Number(cd.unscanned_large_sessions) === 1 ? ' was' : 's were') + ' not scanned; savings there are understated.</p>' : ''));
4983
4969
  }
4984
4970
  if (routingPotentialMo > 0) {
4985
4971
  html += '<div class="routing-assumption" style="margin-top:var(--s-3);font-family:var(--font-mono);font-size:17px;line-height:1.6;color:var(--c-text-main);max-width:820px;">' +
@@ -5040,7 +5026,7 @@ var DB = (function() {
5040
5026
  trendTxt = dd > 3 ? 'trending up' : (dd < -3 ? 'trending down' : 'holding steady');
5041
5027
  }
5042
5028
  }
5043
- if (avgQ !== null) {
5029
+ if (avgQ !== null && !story) {
5044
5030
  var barPct = Math.min(100, Math.max(0, avgQ));
5045
5031
  html += '<div class="card wide" style="margin-top:var(--s-3);"><div class="card-header"><span>Context quality &middot; 30-day average</span>' +
5046
5032
  (trendTxt ? '<span class="label">' + esc(trendTxt) + '</span>' : '') + '</div>';
@@ -5086,44 +5072,13 @@ var DB = (function() {
5086
5072
  bucket.forEach(function(e) { ccHtml += covRow(e); });
5087
5073
  ccHtml += '</div>';
5088
5074
  });
5089
- var pr = cc.first_read_proxy;
5090
- if (pr) {
5091
- var ready = pr.promotion_ready;
5092
- ccHtml += '<div style="margin-top:var(--s-3);padding-top:var(--s-2);border-top:1px solid rgba(255,255,255,0.08);">' +
5093
- '<div style="font-weight:500;">First-read skeleton — safety check</div>' +
5094
- '<div class="plain-line">' + (Number(pr.edits_after_read) || 0) + ' of ' + (Number(pr.shadow_reads) || 0) +
5095
- ' large files were edited soon after the read (' + (Number(pr.edit_rate_pct) || 0).toFixed(1) + '%). ' +
5096
- 'Currently <strong>' + (ready ? 'ready to promote' : 'still measuring') + '</strong>.</div>' +
5097
- fold('How this check works', '<p>' +
5098
- 'Of ' + (Number(pr.shadow_reads) || 0) + ' large files where a skeleton would have saved tokens, ' +
5099
- (Number(pr.edits_after_read) || 0) + ' were edited soon after the read &mdash; an edit rate of ' +
5100
- '<span style="font-family:var(--font-mono);color:' + (ready ? 'var(--c-accent-cyan)' : 'var(--c-text-main)') + ';">' + (Number(pr.edit_rate_pct) || 0).toFixed(1) + '%</span>. ' +
5101
- 'Skeletons turn on automatically only once this stays under ' + (Number(pr.promotion_gate_pct) || 15) + '% (the model rarely needed the full file).</p>') +
5102
- '</div>';
5103
- }
5104
- // Runtime tripwire: per-cohort LIVE edit-rate + any auto-demotions.
5075
+ // Existing demotions remain until explicitly reviewed.
5105
5076
  var tw = cc.cohort_tripwire || {};
5106
- var twCohorts = tw.cohorts || [];
5107
5077
  var twDemoted = tw.demoted || [];
5108
- if (twCohorts.length || twDemoted.length) {
5078
+ if (twDemoted.length) {
5109
5079
  ccHtml += '<div style="margin-top:var(--s-3);padding-top:var(--s-2);border-top:1px solid rgba(255,255,255,0.08);">' +
5110
- '<div style="font-weight:500;">Active cohort tripwire &mdash; live quality guard</div>' +
5111
- fold('How the tripwire works', '<p>Each promoted cohort’s live edit-after-skeleton rate. A cohort auto-demotes to measure-only if it crosses 15% (no flapping &mdash; re-promote is manual or by the next backfill).</p>');
5112
- twCohorts.forEach(function(c) {
5113
- var dem = !!c.demoted;
5114
- // T9: interpolated cohorts (promoted on a thin sample via an adjacent
5115
- // passing band) carry a higher exposure risk — label them so the
5116
- // edit-rate is read with that context.
5117
- var interp = c.basis === 'interpolated';
5118
- ccHtml += '<div style="display:flex;justify-content:space-between;gap:var(--s-3);padding:4px 0;' + (dem ? 'opacity:0.72;' : '') + '">' +
5119
- '<span>' + esc(String(c.language)) + ' &middot; ' + esc(String(c.band)) +
5120
- (interp ? ' <span title="Promoted on a thin sample because an adjacent size band of the same language passed the full gate. Higher exposure; tighter tripwire floor." style="font-size:11px;color:var(--c-text-dim);border:1px solid var(--c-border-strong, rgba(255,255,255,0.2));border-radius:4px;padding:1px 5px;">interpolated</span>' : '') +
5121
- (dem ? ' <span style="font-size:11px;color:var(--c-warning);border:1px solid rgba(230,162,60,0.4);border-radius:4px;padding:1px 5px;">demoted</span>' : '') + '</span>' +
5122
- '<span style="font-family:var(--font-mono);color:var(--c-text-dim);">' +
5123
- (Number(c.skeletons) || 0) + ' reads &middot; ' + (Number(c.followups) || 0) + ' edits &middot; ' +
5124
- (Number(c.edit_rate_pct) || 0).toFixed(1) + '%</span>' +
5125
- '</div>';
5126
- });
5080
+ '<div style="font-weight:500;">First-read cohorts</div>' +
5081
+ fold('How this works', '<p>Existing demotions stay in place. Outcome comparisons run in shadow and do not automatically promote or demote cohorts.</p>');
5127
5082
  if (twDemoted.length) {
5128
5083
  var demStr = twDemoted.map(function(c) { return esc(String(c[0])) + ':' + esc(String(c[1])); }).join(', ');
5129
5084
  ccHtml += '<div style="font-size:13px;color:var(--c-text-dim);margin-top:4px;">' +
@@ -5133,7 +5088,8 @@ var DB = (function() {
5133
5088
  ccHtml += '</div>';
5134
5089
  }
5135
5090
  ccHtml += '</div>';
5136
- html += ccHtml;
5091
+ if (story) moreFolds.push('<details class="fold"><summary>Compression coverage (diagnostic)</summary><div class="fold__body">' + ccHtml + '</div></details>');
5092
+ else html += ccHtml;
5137
5093
  }
5138
5094
 
5139
5095
  // ---- Cache Health: TTL-expiry watchdog (opportunity tier). Observed
@@ -5218,89 +5174,9 @@ var DB = (function() {
5218
5174
  chHtml += '</div>';
5219
5175
  if (!CACHE_HEALTH_HIDDEN) html += chHtml;
5220
5176
 
5221
- // ---- Keep-warm cache automation panel: intentionally hidden (2026-07-03).
5222
- // In probe-only mode it renders $0 realized / $0 spend / $0 NET, which reads
5223
- // as "zero value" / broken to users. The keepwarm data is still computed
5224
- // (measure.py keepwarm_cache_health_block) and carried in
5225
- // data.cache_health.keepwarm; restore the panel by reverting this hunk.
5226
- var kw = null;
5227
- if (kw) {
5228
- var kwState = kw.state || 'platform-gap';
5229
- var kwBadge = ({
5230
- 'active-probe': 'probe-only · active',
5231
- 'active-sustain': 'sustain · active',
5232
- 'off-subscription': 'off · subscription',
5233
- 'demoted-by-tripwire': 'off · tripwire',
5234
- 'platform-gap': 'platform gap'
5235
- })[kwState] || kwState;
5236
- var kwHtml = '<div class="card wide" style="margin-top:var(--s-3);"><div class="card-header">' +
5237
- '<span>Keep-warm cache automation</span>' +
5238
- '<span class="label" style="border:1px solid rgba(255,255,255,0.12);border-radius:4px;padding:1px 5px;">' + esc(kwBadge) + '</span>' +
5239
- '</div>';
5240
- if (kwState === 'platform-gap') {
5241
- kwHtml += '<div style="margin-top:var(--s-2);font-size:13px;color:var(--c-text-dim);line-height:1.6;">' +
5242
- esc(kw.note || 'Keep-warm ships for Claude Code only.') + '</div>';
5243
- } else if (kwState === 'off-subscription') {
5244
- kwHtml += '<div style="margin-top:var(--s-2);font-size:13px;color:var(--c-text-dim);line-height:1.6;">' +
5245
- esc(kw.honest_line || 'Keep-warm is off on subscription billing: pings spend quota and recover no write premium.') + '</div>';
5246
- } else {
5247
- if (kwState === 'demoted-by-tripwire') {
5248
- kwHtml += '<div style="margin-top:var(--s-2);font-size:13px;color:var(--c-amber, #d9a441);line-height:1.6;">' +
5249
- 'Auto-demoted to OFF by the tripwire (rolling 7d realized/spend ≤ 1.0). Re-enable with keepwarm-enable to reset the ladder.</div>';
5250
- }
5251
- // Realized vs spend vs NET (30d) — NET prominent.
5252
- var net = Number(kw.net_usd) || 0;
5253
- var netColor = net >= 0 ? 'var(--c-savings, #4ade80)' : 'var(--c-waste, #f87171)';
5254
- kwHtml += '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:var(--s-3);margin-top:var(--s-2);">' +
5255
- '<div><div style="font-size:12px;color:var(--c-text-dim);">Realized (30d)</div>' +
5256
- '<div style="font-family:var(--font-mono);font-size:20px;">$' + (Number(kw.realized_usd) || 0).toFixed(2) + '</div></div>' +
5257
- '<div><div style="font-size:12px;color:var(--c-text-dim);">Ping spend (30d)</div>' +
5258
- '<div style="font-family:var(--font-mono);font-size:20px;color:var(--c-text-dim);">$' + (Number(kw.spend_usd) || 0).toFixed(2) + '</div></div>' +
5259
- '<div><div style="font-size:12px;color:var(--c-text-dim);">NET (30d)</div>' +
5260
- '<div style="font-family:var(--font-mono);font-size:20px;color:' + netColor + ';">$' + net.toFixed(2) + '</div></div>' +
5261
- '<div><div style="font-size:12px;color:var(--c-text-dim);">Tripwire ratio (7d)</div>' +
5262
- '<div style="font-family:var(--font-mono);font-size:20px;">' + (kw.tripwire_ratio_7d == null ? 'n/a' : (Number(kw.tripwire_ratio_7d)).toFixed(2)) + '</div></div>' +
5263
- '</div>';
5264
- if (!kw.has_pings) {
5265
- kwHtml += '<div style="margin-top:var(--s-2);font-size:12px;color:var(--c-text-dim);">No keep-warm pings yet — numbers fill in once an eligible paused session is probe-refreshed.</div>';
5266
- }
5267
- // Health signal.
5268
- var hh = kw.health || {};
5269
- if (Number(hh.total_pings) > 0) {
5270
- kwHtml += '<div style="margin-top:var(--s-2);font-size:12px;color:' + (hh.alarm ? 'var(--c-waste, #f87171)' : 'var(--c-text-dim)') + ';">' +
5271
- 'Pings on never-resumed pauses: ' + (Number(hh.pings_on_never_resumed) || 0) + '/' + (Number(hh.total_pings) || 0) +
5272
- ' (' + Math.round((Number(hh.fraction) || 0) * 100) + '%)' + (hh.alarm ? ' — ALARM (>50%)' : '') + '</div>';
5273
- }
5274
- // Predictor transparency (feature names; relevant when sustain activates).
5275
- var feats = kw.predictor_features || [];
5276
- if (kwState === 'active-sustain' && feats.length) {
5277
- kwHtml += '<div style="margin-top:var(--s-2);font-size:12px;color:var(--c-text-dim);line-height:1.5;">' +
5278
- 'Sustain predictor (threshold ' + (Number(kw.predictor_threshold) || 0).toFixed(2) + '): ' +
5279
- feats.map(function(f) { return esc(f); }).join(', ') + '</div>';
5280
- }
5281
- // Top sessions by realized.
5282
- var ts2 = kw.top_sessions || [];
5283
- if (ts2.length) {
5284
- kwHtml += '<div style="margin-top:var(--s-3);"><div style="font-size:12px;color:var(--c-text-dim);margin-bottom:6px;">Top sessions by realized</div>' +
5285
- '<table style="width:100%;border-collapse:collapse;font-size:12px;">' +
5286
- '<thead><tr style="color:var(--c-text-dim);text-align:left;">' +
5287
- '<th style="padding:4px 6px;">Session</th><th style="padding:4px 6px;">Realized $</th>' +
5288
- '<th style="padding:4px 6px;">Spend $</th><th style="padding:4px 6px;">Pings</th></tr></thead><tbody>';
5289
- ts2.forEach(function(t) {
5290
- kwHtml += '<tr style="border-top:1px solid rgba(255,255,255,0.06);">' +
5291
- '<td style="padding:4px 6px;font-family:var(--font-mono);">' + esc(String(t.session_id || '').slice(0, 28)) + '</td>' +
5292
- '<td style="padding:4px 6px;font-family:var(--font-mono);">$' + (Number(t.realized_usd) || 0).toFixed(2) + '</td>' +
5293
- '<td style="padding:4px 6px;font-family:var(--font-mono);color:var(--c-text-dim);">$' + (Number(t.spend_usd) || 0).toFixed(2) + '</td>' +
5294
- '<td style="padding:4px 6px;font-family:var(--font-mono);">' + (Number(t.pings) || 0) + '</td></tr>';
5295
- });
5296
- kwHtml += '</tbody></table></div>';
5297
- }
5298
- }
5299
- kwHtml += '</div>';
5300
- html += kwHtml;
5301
- }
5177
+ if (moreFolds.length) html += '<div class="st-morerow">' + moreFolds.join('') + '</div>';
5302
5178
 
5303
- el.innerHTML = html;
5179
+ if (el.classList && el.dataset) { el.classList.toggle('st-enter', !el.dataset.storyRendered); el.dataset.storyRendered = '1'; } el.innerHTML = html;
5304
5180
  el.querySelectorAll('details > summary').forEach(function(summary) {
5305
5181
  if (openFolds.indexOf(summary.textContent) >= 0) summary.parentElement.open = true;
5306
5182
  });
@@ -5320,8 +5196,12 @@ var DB = (function() {
5320
5196
  '</div>' +
5321
5197
  '<div class="last-updated">Last updated: ' + esc(ts) + '</div>';
5322
5198
 
5199
+ if (typeof keepwarmHealthHtml === 'function') html += keepwarmHealthHtml(data);
5323
5200
  if (!h) {
5324
5201
  html += '<div class="empty-state">No health data available. This usually means no ' + esc(data.runtime_label || 'Claude Code') + ' processes are currently running.</div>';
5202
+ try { if (typeof featureHealthHtml === 'function') html += featureHealthHtml(data); } catch (e) {}
5203
+ try { if (typeof coverageFunnelHtml === 'function') html += coverageFunnelHtml(data); } catch (e) {}
5204
+ try { if (typeof holdoutHtml === 'function') html += holdoutHtml(data); } catch (e) {}
5325
5205
  el.innerHTML = html;
5326
5206
  return;
5327
5207
  }
@@ -5335,6 +5215,13 @@ var DB = (function() {
5335
5215
  '<p style="font-size:13px;color:var(--c-text-dim);margin-bottom:0;">Codex process version comparison is not exposed reliably in local session data, so version/outdated rows are hidden. This tab focuses on running sessions, hook health, and context quality.</p></div>';
5336
5216
  }
5337
5217
 
5218
+ // Archive replacement self-check (scripts/archive_verify.py)
5219
+ var arc = data.archive_replacement_check;
5220
+ if (arc && arc.status === 'warning') {
5221
+ html += '<div class="card wide" style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.2)"><div class="card-header"><span>Tool archive not applied</span><span class="label">' + esc(String(arc.full_streak)) + ' in a row</span></div>' +
5222
+ '<p style="font-size:13px;line-height:1.5;margin-bottom:0;">' + esc(arc.message || '') + '</p></div>';
5223
+ }
5224
+
5338
5225
  // Running sessions table
5339
5226
  var sessions = h.running_sessions || [];
5340
5227
  html += '<div class="card wide"><div class="card-header"><span>Running Sessions</span><span class="label">' + sessions.length + ' active</span></div>';
@@ -5540,6 +5427,11 @@ var DB = (function() {
5540
5427
  });
5541
5428
  html += '</div>';
5542
5429
  }
5430
+ // U9: context quality and hook time limits moved here from the Savings tab.
5431
+ try { if (typeof healthNotesHtml === 'function') html += healthNotesHtml(data); } catch (e) {}
5432
+ try { if (typeof featureHealthHtml === 'function') html += featureHealthHtml(data); } catch (e) {}
5433
+ try { if (typeof coverageFunnelHtml === 'function') html += coverageFunnelHtml(data); } catch (e) {}
5434
+ try { if (typeof holdoutHtml === 'function') html += holdoutHtml(data); } catch (e) {}
5543
5435
 
5544
5436
  el.innerHTML = html;
5545
5437
  }
@@ -5573,15 +5465,13 @@ var DB = (function() {
5573
5465
  return it && it.state !== 'not_applicable';
5574
5466
  });
5575
5467
  var urWins = ur.wins || [];
5576
- if (urItems.length > 0 || !ur.present) {
5468
+ if (urItems.length > 0) {
5577
5469
  html += '<div class="card wide"><div class="card-header"><span>From your own usage</span>' +
5578
5470
  (ur.measured_ts
5579
5471
  ? '<span class="label">measured ' + esc(timeAgo(new Date(ur.measured_ts * 1000))) + ', last ' + esc(String(ur.window_days || 30)) + ' days</span>'
5580
5472
  : '') +
5581
5473
  '</div>' +
5582
- (!ur.present || urItems.length === 0
5583
- ? '<div style="color:var(--c-text-dim);font-size:14px;">Measuring in the background, check back after your next session</div>'
5584
- : '');
5474
+ '';
5585
5475
  var urCap = function(s) { s = String(s || ''); return s.charAt(0).toUpperCase() + s.slice(1); };
5586
5476
  urItems.forEach(function(it, urIdx) {
5587
5477
  // The card header already draws a line above the first row.
@@ -6102,7 +5992,7 @@ var DB = (function() {
6102
5992
  var onCount = 0;
6103
5993
  var offRecommended = 0;
6104
5994
  v5Names.forEach(function(n) {
6105
- if (v5Features[n].enabled) onCount++;
5995
+ if (n === 'keepwarm') return; if (v5Features[n].enabled) onCount++;
6106
5996
  else if (v5Features[n].recommended) offRecommended++;
6107
5997
  });
6108
5998
 
@@ -6115,7 +6005,7 @@ var DB = (function() {
6115
6005
  '<div class="card-header" style="padding:18px var(--s-3);">' +
6116
6006
  '<span style="font-size:22px;font-weight:700;">' + v5Title + '</span>' +
6117
6007
  '<span class="label" style="font-size:14px;background:' + headerColor + ';color:var(--c-bg);padding:6px 12px;border-radius:4px;font-weight:700;">' +
6118
- onCount + '/' + v5Names.length + ' ON' +
6008
+ onCount + '/' + v5Names.filter(function(n) { return n !== 'keepwarm'; }).length + ' ON' +
6119
6009
  '</span>' +
6120
6010
  '</div>' +
6121
6011
  '<p style="font-size:17px;color:var(--c-text-main);padding:0 var(--s-3) var(--s-2);line-height:1.6;">' +
@@ -6124,7 +6014,7 @@ var DB = (function() {
6124
6014
  '</p>';
6125
6015
 
6126
6016
  v5Names.forEach(function(fname) {
6127
- var f = v5Features[fname];
6017
+ var f = v5Features[fname]; if (fname === 'keepwarm') { html += '<div class="hook-row" style="padding:20px var(--s-3);border-top:1px solid var(--c-border);">Keep-warm: paused while we prove it is safe and saves you money</div>'; return; }
6128
6018
  var unavailable = !!f.unavailable || f.source === 'codex api gap';
6129
6019
  var managedByHooks = !!f.managed_by_hooks || (isCodex && (f.source === 'codex hook' || f.source === 'codex opt-in' || f.source === 'codex hook-managed'));
6130
6020
  var riskBg = 'var(--c-badge-savings)';
@@ -7564,24 +7454,15 @@ document.addEventListener('DOMContentLoaded', function() {
7564
7454
  }, 60000);
7565
7455
  }
7566
7456
 
7567
- // Probe for our custom API server before init.
7568
- // When served from the daemon (http://localhost:*), a relative /api/health works.
7569
- // When viewed as file://, stay in static read-only mode to avoid CORS noise.
7457
+ // Probe the daemon; file pages stay read-only.
7570
7458
  var DAEMON_URL = data.runtime === 'codex' ? 'http://localhost:24843' : 'http://localhost:24842';
7571
7459
  function _setApiLive(baseUrl) {
7572
7460
  window.__TOKEN_API_LIVE = true;
7573
7461
  window.__TOKEN_API_BASE = baseUrl || '';
7574
7462
  }
7575
- // v5.4.19: helper that all mutating API calls must use. Adds the per-install
7576
- // CSRF token header so the server accepts the request. Without this, POSTs
7577
- // are rejected with 403 -- that's the whole point of the CSRF hardening.
7578
- //
7579
- // Surface auth errors as a distinct message
7580
- // rather than letting callers hit r.json() on a text body ("Forbidden:
7581
- // invalid token") and seeing a confusing JSON parse error. The helper
7582
- // intercepts 403 responses and rejects with an Error whose .authError flag
7583
- // lets call sites show a reload-page hint.
7463
+ // All mutations carry the per-install token and surface authorization failures.
7584
7464
  window.__TOKEN_API_POST = function(path, body) {
7465
+ if (window.location && window.location.protocol === 'file:') return Promise.reject(new Error('Open the live dashboard to make changes.'));
7585
7466
  var base = window.__TOKEN_API_BASE || '';
7586
7467
  var headers = { 'Content-Type': 'application/json' };
7587
7468
  if (window.__TOKEN_API_TOKEN) headers['X-TO-Token'] = window.__TOKEN_API_TOKEN;
@@ -7601,6 +7482,21 @@ document.addEventListener('DOMContentLoaded', function() {
7601
7482
  });
7602
7483
  };
7603
7484
 
7485
+ function waitForRegen(result, message) {
7486
+ if (!result.ok) return Promise.reject(new Error('Could not update the dashboard. Please try again.'));
7487
+ if (!result.job_id) return Promise.resolve();
7488
+ function poll() {
7489
+ return window.__TOKEN_API_POST('/api/regenerate/status', {job_id: result.job_id})
7490
+ .then(function(r) { return r.json(); }).then(function(state) {
7491
+ if (message) message.textContent = state.progress || 'Updating the dashboard.';
7492
+ if (state.state === 'done') return;
7493
+ if (state.state !== 'running') throw new Error('Could not update the dashboard. Please try again.');
7494
+ return new Promise(function(resolve) { setTimeout(resolve, 1000); }).then(poll);
7495
+ });
7496
+ }
7497
+ return poll();
7498
+ }
7499
+
7604
7500
  window.__TOKEN_LOAD_HISTORY = function(choice, message) {
7605
7501
  if (choice === 'all') { try { localStorage.setItem('to-daily-range', 'all'); } catch (e) {} }
7606
7502
  if (!window.__TOKEN_API_LIVE) {
@@ -7611,25 +7507,23 @@ document.addEventListener('DOMContentLoaded', function() {
7611
7507
  function attempt(retried) {
7612
7508
  window.__TOKEN_API_POST('/api/regenerate', {days: choice}).then(function(r) { return r.json(); })
7613
7509
  .then(function(result) {
7614
- if (!result.ok) throw new Error(result.msg || 'Regeneration failed');
7510
+ return waitForRegen(result, message);
7511
+ }).then(function() {
7615
7512
  try { sessionStorage.setItem('to-history-return', '1'); } catch (e) {}
7616
7513
  location.reload();
7617
7514
  }).catch(function(err) {
7618
7515
  if (err.authError && !retried) {
7619
7516
  _fetchToken(window.__TOKEN_API_BASE || '').then(function() { attempt(true); })
7620
- .catch(function(e) { message.textContent = 'Could not load history: ' + e.message; });
7621
- } else message.textContent = 'Could not load history: ' + err.message;
7517
+ .catch(function() { message.textContent = 'Could not load history. Please try again.'; });
7518
+ } else message.textContent = 'Could not load history. Please try again.';
7622
7519
  });
7623
7520
  }
7624
7521
  if (window.__TOKEN_API_TOKEN) attempt(false);
7625
7522
  else _fetchToken(window.__TOKEN_API_BASE || '').then(function() { attempt(false); })
7626
- .catch(function(e) { message.textContent = 'Could not load history: ' + e.message; });
7523
+ .catch(function() { message.textContent = 'Could not load history. Please try again.'; });
7627
7524
  };
7628
7525
 
7629
- // Manual regeneration. The background freshness regen is stale-while-revalidate:
7630
- // it serves the current file and refreshes for NEXT time, so a reader who wants
7631
- // current numbers now would have to reload twice and never knows that. This is
7632
- // synchronous on the daemon side and reloads on success, so one click is enough.
7526
+ // Manual regeneration waits for the background job before reloading.
7633
7527
  window.__TOKEN_REGENERATE = function() {
7634
7528
  var btn = document.getElementById('to-regen-btn');
7635
7529
  var msg = document.getElementById('to-regen-msg');
@@ -7653,16 +7547,15 @@ document.addEventListener('DOMContentLoaded', function() {
7653
7547
  }
7654
7548
  function fail(e) {
7655
7549
  btn.disabled = false; btn.textContent = was;
7656
- var txt = (e && e.authError)
7657
- ? 'Auth failed after a token refresh — reload the page.'
7658
- : ('Failed: ' + ((e && e.message) || e || 'unknown error'));
7550
+ var txt = (e && e.authError) ? 'Authentication failed. Reload the page and try again.' : 'Could not update the dashboard. Please try again.';
7659
7551
  if (msg) msg.textContent = '';
7660
7552
  if (errBox) { errBox.textContent = txt; errBox.hidden = false; }
7661
7553
  else if (msg) { msg.textContent = txt; }
7662
7554
  }
7663
7555
  function succeed(d) {
7664
- if (d && d.ok) { location.reload(); return; }
7665
- fail({ message: ((d && d.msg) || 'unknown error') });
7556
+ return waitForRegen(d || {}, msg).then(function() {
7557
+ location.reload();
7558
+ }).catch(fail);
7666
7559
  }
7667
7560
  // At most ONE 403->refetch->retry. Without the cap a persistently-bad token
7668
7561
  // loops forever; without the retry a stale/empty page token silently 403'd
@@ -7706,17 +7599,14 @@ document.addEventListener('DOMContentLoaded', function() {
7706
7599
  }
7707
7600
  if (typeof fetch === 'function') {
7708
7601
  var isHttp = window.location.protocol.indexOf('http') === 0;
7709
- if (!isHttp) {
7710
- startApp();
7711
- return;
7712
- }
7713
- var probe = '/api/health';
7602
+ var base = isHttp ? '' : DAEMON_URL;
7603
+ var probe = base + '/api/health';
7714
7604
  try {
7715
- fetch(probe, { method: 'GET' })
7716
- .then(function(r) { return r.json(); })
7605
+ fetch(probe, isHttp ? { method: 'GET' } : { method: 'GET', mode: 'no-cors' })
7606
+ .then(function(r) { return !isHttp && r.type === 'opaque' ? {ok: true} : r.json(); })
7717
7607
  .then(function(d) {
7718
7608
  if (d && d.ok) {
7719
- var base = '';
7609
+ if (!isHttp) { window.__TOKEN_FILE_DAEMON_LIVE = true; return; }
7720
7610
  _setApiLive(base);
7721
7611
  return _fetchToken(base);
7722
7612
  }