@alexgreensh/token-optimizer 5.13.68 → 5.13.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,661 @@
1
+ // Savings story (U9): the Savings tab, top to bottom. Savings are big and
2
+ // confident; the measured / estimated breakdown lives only in the folds.
3
+ // 1. Hero band: three huge numbers (30-day total with routing included,
4
+ // saved since install with routing included, tokens kept out of context).
5
+ // 2. Transformation (when the payload says ok) and "Your limits go further".
6
+ // 3. Still on the table: computable opportunities per period, warm accent,
7
+ // each with one action. Never part of a savings total.
8
+ // 4. The re-read card, cost per message only when it fell at least 10%, then
9
+ // the caller's row of folds.
10
+ // healthNotesHtml() renders the parts that moved to the Health tab.
11
+ //
12
+ // Inlined into dashboard.html at generation by scripts/dashboard_assets.py.
13
+ // Every reader is fail-open: a missing or malformed field drops its row or
14
+ // card, never throws. With no session_effect it returns '' and the Savings
15
+ // tab keeps its previous layout.
16
+ function savingsStoryOn(data) {
17
+ var se = data && data.savings && data.savings.session_effect;
18
+ return !!(se && se.available);
19
+ }
20
+
21
+ function savingsStoryFmt() {
22
+ function num(x) { var v = Number(x); return isFinite(v) ? v : 0; }
23
+ return {
24
+ num: num,
25
+ has: function(x) { return x != null && x !== '' && isFinite(Number(x)); },
26
+ // Whole dollars everywhere on the tab; cents stay in the ledger fold.
27
+ usd: function(v) {
28
+ v = num(v);
29
+ var a = Math.abs(v);
30
+ if (a > 0 && a < 1) return 'under $1'; // sign is carried by the label
31
+ return (v < 0 ? '-' : '') + '$' + Math.round(a).toLocaleString('en-US');
32
+ },
33
+ tok: function(v) {
34
+ v = num(v);
35
+ if (v >= 1e9) return (v / 1e9).toFixed(2) + 'B';
36
+ if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';
37
+ if (v >= 1e3) return Math.round(v / 1e3) + 'K';
38
+ return String(Math.round(v));
39
+ },
40
+ pct: function(f) { return (num(f) * 100).toFixed(1).replace(/\.0$/, '') + '%'; },
41
+ count: function(v) { return Math.round(num(v)).toLocaleString('en-US'); },
42
+ day: function(iso) {
43
+ if (!iso) return '';
44
+ var d = new Date(String(iso).length <= 10 ? iso + 'T00:00:00' : iso);
45
+ if (isNaN(d.getTime())) return '';
46
+ return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
47
+ },
48
+ fold: function(summary, body, cls) {
49
+ return '<details class="fold' + (cls ? ' ' + cls : '') + '"><summary>' + esc(summary) +
50
+ '</summary><div class="fold__body">' + body + '</div></details>';
51
+ }
52
+ };
53
+ }
54
+
55
+ // The hero rows: measured and estimated, each {key,label,usd,tok,why}. Shared
56
+ // by the hero card and the ledger fold so the two can never disagree.
57
+ function savingsStoryBands(data) {
58
+ var f = savingsStoryFmt(), num = f.num, has = f.has;
59
+ var s = (data && data.savings) || {};
60
+ var as = s.action_savings || {}, th = s.token_headline || {}, sd = s.structural_detail || {}, orr = s.output_reread || {};
61
+ var measuringNames = [];
62
+ var trimLedger = sd.method === 'trim_ledger';
63
+ var trims = trimLedger ? (sd.trims || []).filter(function(t) { return t && !t.closed_at && num(t.tokens_per_call) > 0; }) : [];
64
+ function trimName(tier) {
65
+ var group = trims.filter(function(x) { return (x.source === 'attested' || x.tier === 'estimated') === (tier === 'estimated'); })
66
+ .sort(function(a, b) { return String(b.ts).localeCompare(String(a.ts)); });
67
+ var t = group[0], when = t && group.every(function(x) { return String(x.ts).slice(0, 10) === String(t.ts).slice(0, 10); }) ? f.day(t.ts) : '';
68
+ var stepped = group.some(function(x) { return x.step_measured; });
69
+ return 'Setup cleanup' + (when ? ', ' + when : '') + (tier === 'estimated' ? (t && t.source === 'dated_archive' ? ' (realized, archive estimate)' : ' (realized, your figure)') : stepped ? ' (realized, measured)' : ' (realized, recorded)');
70
+ }
71
+ var trimMeasuredUsd = trimLedger ? num(sd.cost_saved_usd) : 0;
72
+ var trimMeasuredTok = trimLedger ? num(sd.tokens_saved) : 0;
73
+ var trimEst = (trimLedger && sd.estimated) || {};
74
+ var est = as.estimates_usd || {};
75
+ var outputInEst = num(est.verbosity_output_estimated);
76
+ var trimInEst = num(est.structural_estimated);
77
+ var reloadTok = num(th.reload_avoided_tokens);
78
+ var removedTok = has(th.context_removed_tokens)
79
+ ? num(th.context_removed_tokens) + num(th.output_not_generated_tokens)
80
+ : num(th.removed_tokens) - reloadTok;
81
+ var measured = [
82
+ { key: 'context', label: 'Context removed', usd: num(as.logged_usd) - trimMeasuredUsd + num(as.class_premium_usd),
83
+ tok: Math.max(0, removedTok - trimMeasuredTok), on: has(as.logged_usd) },
84
+ { key: 'rereads', label: 'Re-reads avoided', usd: as.reread_usd, tok: th.reread_tokens,
85
+ on: as.reread_available !== false && has(as.reread_usd) },
86
+ { key: 'setup_measured', label: trimName('measured'), usd: trimMeasuredUsd, tok: trimMeasuredTok, on: trimLedger && trimMeasuredUsd > 0 }
87
+ ];
88
+ var estimated = [
89
+ { key: 'setup_estimated', label: trimName('estimated'), usd: trimInEst, tok: trimEst.tokens_saved,
90
+ on: trimInEst > 0 },
91
+ { key: 'output_reread', label: 'Shorter answers, not re-read', usd: outputInEst, tok: orr.tokens_saved,
92
+ on: outputInEst > 0,
93
+ why: orr.control_net == null && orr.available ? 'Not yet compared against sessions without the nudge.' : '' },
94
+ { key: 'other', label: 'Other estimates', usd: num(as.estimated_usd) - outputInEst - trimInEst, tok: reloadTok,
95
+ on: Math.abs(num(as.estimated_usd) - outputInEst - trimInEst) > 0,
96
+ why: 'Loops stopped, sub-agent output, handovers and restores.' }
97
+ ];
98
+ function live(rows) {
99
+ return rows.filter(function(r) { return r.on && num(r.usd) !== 0; })
100
+ .sort(function(a, b) { return num(b.usd) - num(a.usd); });
101
+ }
102
+ measured = live(measured); estimated = live(estimated);
103
+ if (!trimLedger) measuringNames.push('setup cleanup');
104
+ if (!orr.available && !has(orr.cost_saved_usd)) measuringNames.push('shorter answers that are not re-read');
105
+ function sum(rows, k) { return rows.reduce(function(a, r) { return a + num(r[k]); }, 0); }
106
+ var mUsd = sum(measured, 'usd'), eUsd = sum(estimated, 'usd');
107
+ var totalUsd = mUsd + eUsd, totalTok = sum(measured, 'tok') + sum(estimated, 'tok');
108
+ return { measured: measured, estimated: estimated, measuringNames: measuringNames, trimLedger: trimLedger, trims: trims,
109
+ mUsd: mUsd, eUsd: eUsd, totalUsd: totalUsd, totalTok: totalTok };
110
+ }
111
+
112
+ function savingsStoryHtml(data) {
113
+ if (!savingsStoryOn(data)) return '';
114
+ var f = savingsStoryFmt(), num = f.num, has = f.has, usd = f.usd, tok = f.tok, pct = f.pct, count = f.count;
115
+ var s = data.savings || {};
116
+ var se = s.session_effect || {};
117
+ var ps = se.per_session || {};
118
+ var places = ps.by_place || {}, local = places.local || {}, cloud = places.cloud || {};
119
+ var cov = se.coverage || {};
120
+ var fleet = se.fleet || {};
121
+ var as = s.action_savings || {};
122
+ var th = s.token_headline || {};
123
+ var cp = s.counted_period || {};
124
+ var sd = s.structural_detail || {};
125
+ var orr = s.output_reread || {};
126
+ var mr = s.model_routing || {};
127
+ var days = Number(s.period_days) || 30;
128
+ var out = '';
129
+
130
+ // ---- 1. Hero: three huge numbers. The breakdown lives only in the folds. ----
131
+ // Measured and estimated savings, plus the routing estimate, are one number.
132
+ // Setup cleanup recorded by the trim ledger sits inside logged_usd (the
133
+ // structural pool always has), so it is its own row, taken out of
134
+ // "Context removed" once.
135
+ var B = savingsStoryBands(data);
136
+ var trimLedger = B.trimLedger, trims = B.trims, measured = B.measured, estimated = B.estimated;
137
+ var mUsd = B.mUsd, eUsd = B.eUsd, totalUsd = B.totalUsd, totalTok = B.totalTok;
138
+ var routing30 = has(mr.realized_cost_usd) ? num(mr.realized_cost_usd) : num(as.routing_usd);
139
+ if (!(routing30 > 0)) routing30 = 0;
140
+ var bigTotal = totalUsd + routing30;
141
+ function sum(rows, k) { return rows.reduce(function(a, r) { return a + num(r[k]); }, 0); }
142
+ if (measured.length || estimated.length) {
143
+ function cents(rows) { return rows.reduce(function(n, r) { return n + Math.round(num(r.usd) * 100); }, 0); }
144
+ function table(title, rows) {
145
+ if (!rows.length) return '';
146
+ return '<p><strong>' + title + ', ' + savingsCents(cents(rows) / 100) + '</strong></p><ul>' + rows.map(function(r) {
147
+ return '<li>' + esc(r.label) + ': ' + savingsCents(r.usd) + (num(r.tok) > 0 ? ', ' + tok(r.tok) + ' tokens' : '') +
148
+ (r.why ? '. ' + esc(r.why) : '') + '</li>';
149
+ }).join('') + '</ul>';
150
+ }
151
+ var overhead = se.overhead || {};
152
+ var carry = s.lean_resume_carry || {};
153
+ var incomplete = cp.pricing_complete === false || as.reread_pricing_complete === false;
154
+ var archive = (s.by_category || {}).tool_archive;
155
+ var bashExpand = (s.by_category || {}).bash_archive_reexpand;
156
+ var bashNet = Object.keys(s.by_category || {}).reduce(function(n, k) {
157
+ return n + ((/^bash_/.test(k) || k === 'build_output_compress' || k === 'crossturn_dedup') ? num((s.by_category[k] || {}).cost_saved_usd) : 0);
158
+ }, 0);
159
+ var basis = savingsRoutingBasis(data);
160
+ var routingRow = routing30 > 0 ? '<p><strong>Estimated, model routing, ' + savingsCents(routing30) + '</strong></p><ul><li>Model routing: ' + savingsCents(routing30) + '. ' +
161
+ esc(basis.lead) + ' Your current work priced at that mix, against what it actually cost.</li></ul>' : '';
162
+ var allCents = cents(measured) + cents(estimated) + Math.round(routing30 * 100);
163
+ var missing = num(cov.ran_no_ledger_sessions);
164
+ var coverage = num(cov.sessions) > 0 && num(cov.ran_sessions) > 0
165
+ ? '<p>Token Optimizer ran in ' + count(cov.ran_sessions) + ' of your ' + count(cov.sessions) + ' sessions.' +
166
+ (missing > 0 ? ' ' + count(missing) + ' of them ' + (missing === 1 ? 'is' : 'are') + ' not in the ledger yet, so the total understates.' : '') + '</p>' : '';
167
+ var setupDetail = '';
168
+ if (trimLedger) {
169
+ var valuedTrims = trims.filter(function(t) { return t.tier !== 'unattributed' && (num(t.cost_saved_usd) > 0 || num(t.projected_30d_usd) > 0); })
170
+ .sort(function(a, b) { return num(b.projected_30d_usd) - num(a.projected_30d_usd); });
171
+ var setupRows = setupCleanupGroups(sd).map(function(g) {
172
+ return '<li><span>' + esc(g.label) + '<span class="st-sub">' + esc(g.sub) + '</span></span><span class="st-v">' + savingsCents(g.usd) + '</span></li>';
173
+ }).join('');
174
+ var opts = sd.attested_options || [];
175
+ var formula = valuedTrims.map(function(t) {
176
+ return '<li>' + esc(t.label || t.item || 'Setup cleanup') + ': ' + count(num(t.tokens_per_call) * (t.step_measured ? num(t.step_share) : 1)) + ' tokens per call &times; ' + count(t.requests) +
177
+ (t.step_measured ? ' calls; priced on main-thread calls since the trim, at each call&rsquo;s cache-read rate' : ' calls since') + (num(t.projected_30d_usd) > 0 ? '. Estimated next 30 days at the recent rate: ' + (num(t.projected_30d_usd) < 1 ? '' : 'about ') + usd(t.projected_30d_usd) + '.' : '.') + '</li>';
178
+ }).join('');
179
+ if (setupRows) {
180
+ setupDetail = '<p><strong>Setup cleanup, item by item</strong></p><ul class="st-rows">' + setupRows + '</ul>' +
181
+ '<p>Trimming setup reduces repeated context on calls that load it. These amounts are already in the total.</p><ul>' + formula + '</ul>' +
182
+ (opts.length ? '<p>Your figure can be one of these sizes, priced the same way:</p><ul>' + opts.map(function(o) {
183
+ return '<li>' + count(o.tokens_per_call) + ' tokens per call: estimated ' + usd(o.projected_30d_usd) + ' per 30 days at the recent rate' + (o.chosen ? ' (shown)' : '') + '</li>';
184
+ }).join('') + '</ul>' : '');
185
+ }
186
+ }
187
+ var method = '<p><strong>Last ' + days + ' days, ' + savingsCents(allCents / 100) + '</strong>: measured ' + savingsCents(cents(measured) / 100) +
188
+ ', estimated ' + savingsCents(cents(estimated) / 100) + (routing30 > 0 ? ', routing ' + savingsCents(routing30) : '') + '.</p>' +
189
+ table('Measured, counted event by event', measured) +
190
+ table('Estimated, sized by a documented method', estimated) +
191
+ routingRow +
192
+ setupDetail +
193
+ (num((s.progressive_disclosure || {}).full_bash_fetches) > 0 ? '<p>Full command output fetched from the archive: ' + count(s.progressive_disclosure.full_bash_fetches) + ' outputs, about ' + tok(s.progressive_disclosure.full_bash_tokens) + ' tokens. This does not establish whether a command would otherwise have been re-run.</p>' : '') +
194
+ (num((s.keepwarm_estimated || {}).manual_pings) ? '<p>Manual warm-ups from the Claude Code mod: ' + count(s.keepwarm_estimated.manual_pings) + '. Their cost is included in the estimated keep-warm net.</p>' : '') +
195
+ (num((s.mod_compaction_actions || {}).events) + num(((s.by_category || {}).mod_clean || {}).events) + num(((s.by_category || {}).mod_clean_first || {}).events) ? '<p>Clean-up from the Claude Code mod: ' + count(num((s.mod_compaction_actions || {}).events) || (num(((s.by_category || {}).mod_clean || {}).events) + num(((s.by_category || {}).mod_clean_first || {}).events))) + ' actions. Compaction cost is deducted; later reads are counted through the next compaction, with one observed cache rebuild for clean-up first' + (num((s.mod_compaction_actions || {}).unpriced_events) ? '; ' + count(s.mod_compaction_actions.unpriced_events) + ' actions are not yet priced' : '') + '.</p>' : '') +
196
+ (num((s.mod_fresh_estimated || {}).events) ? '<p>Start fresh from the Claude Code mod: ' + count(s.mod_fresh_estimated.events) + ' actions. Estimated continuation value (old context less a rough handoff estimate; persistent setup may remain; median of comparable earlier sessions, capped at 10 turns): ' + (num(s.mod_fresh_estimated.unpriced_events) === num(s.mod_fresh_estimated.events) ? 'not yet available' : usd(s.mod_fresh_estimated.cost_saved_usd || 0)) + (num((as.estimates_usd || {}).mod_fresh_estimated) === 0 && num(s.mod_fresh_estimated.cost_saved_usd) > 0 ? ', shown separately to avoid overlap with handovers' : '') + (num(s.mod_fresh_estimated.unpriced_events) ? '; some actions need more history' : '') + '.</p>' : '') +
197
+ (archive ? '<p>Tool archive, net of re-expands: ' + usd(archive.cost_saved_usd) + ' once, before repeat-reads.</p>' : '') +
198
+ (bashExpand ? '<p>Bash compression, net of re-expands: ' + usd(bashNet) + ' once, before repeat-reads.</p>' : '') +
199
+ (num((as.estimates_usd || {}).expand_overhead) ? '<p>Estimated expand-command overhead: ' + usd(as.estimates_usd.expand_overhead) + '.</p>' : '') +
200
+ (num((as.estimates_usd || {}).handover_rerun) > 0 ? '<p>Continuity handovers, ' + usd(as.estimates_usd.handover_rerun) + ' (estimated): sessions resumed from a saved checkpoint re-read fewer stale files than sessions that started cold, and that gap is counted here.</p>' : '') +
201
+ (totalTok > 0 ? '<p>The ' + tok(totalTok) + ' tokens kept out of context are measured and estimated' + (num(th.reload_avoided_tokens) > 0 ? ': ' + tok(th.reload_avoided_tokens) + ' of them are estimated reloads avoided' : '') + '.</p>' : '') +
202
+ '<p>Measured rows come from the ledger: each removal, the cache rate the next call would have paid, and every later turn that would have re-read it, up to the session&rsquo;s next compaction.</p>' +
203
+ (s.token_type_breakdown && Object.keys(s.token_type_breakdown).length ? '<p>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.</p>' : '') +
204
+ savingsPerSessionHtml(ps, overhead) +
205
+ (incomplete ? '<p>Some older history has no exact price, so this total understates.</p>' : '') +
206
+ coverage +
207
+ (carry.available && num(carry.carry_cost_usd) > 0 ? '<p>Diagnostic, not counted' + ': the older target-session proxy suggested ' +
208
+ tok(carry.carry_tokens) + ' tokens, about ' + usd(carry.carry_cost_usd) + '. That proxy stays out of totals; receiver-linked estimates are counted separately.</p>' : '') +
209
+ '<p>Valued at API rates. On a subscription this is room inside your limits; nothing is refunded. Opportunity is never part of this total.</p>';
210
+ var SIh = savingsSinceInstall(data);
211
+ // While an upgrade re-reads older sessions the totals are partial: say so
212
+ // on each number it affects, with how many sessions are left.
213
+ var aiP = ((s.since_install || {}).all_in) || {};
214
+ var soFar30 = cp.remeasuring === true || mr.evidence === 'pending';
215
+ var soFarAll = aiP.remeasuring === true || aiP.routing_pending === true;
216
+ var left = Math.max(num(cp.remeasuring_sessions), num(aiP.remeasuring_sessions), num(aiP.routing_pending_sessions), mr.evidence === 'pending' ? num(mr.pending_sessions) : 0);
217
+ var soFar = function(on) { return on ? ', so far' : ''; };
218
+ out += '<div class="card st-hero">' +
219
+ '<h2 class="st-h">What Token Optimizer saved</h2>' +
220
+ '<div class="st-mega__row st-mega__row--hero">' +
221
+ '<div class="st-mega__item"><span class="st-mega st-mega--usd">' + usd(bigTotal) + '</span><span class="st-mega__unit">saved in the last ' + days + ' days' + soFar(soFar30) + '</span></div>' +
222
+ (SIh && SIh.all > 0 ? '<div class="st-mega__item"><span class="st-mega st-mega--usd">' + usd(SIh.all) + '</span><span class="st-mega__unit">saved since you installed' + soFar(soFarAll) + '</span></div>' : '') +
223
+ (totalTok > 0 ? '<div class="st-mega__item"><span class="st-mega st-mega--tok">' + tok(totalTok) + '</span><span class="st-mega__unit">tokens kept out of context in ' + days + ' days' + soFar(cp.remeasuring === true) + '</span></div>' : '') +
224
+ '</div>' +
225
+ (soFar30 || soFarAll ? '<p class="st-lead st-progress">Updating your history after an upgrade' + (left > 0 ? ' (' + count(left) + ' session' + (left === 1 ? '' : 's') + ' left)' : '') + '. These totals are in progress and will change when it finishes.</p>' : '') +
226
+ f.fold('How this is calculated', method + (SIh && SIh.all > 0 ? savingsSinceInstallBody(data, SIh) : '')) +
227
+ '</div>';
228
+ }
229
+
230
+ // ---- 1b. Transformation and limits: both big, both with their method in a fold ----
231
+ out += savingsTransformationHtml(data);
232
+ out += savingsLimitsHtml(data);
233
+
234
+ // ---- 1c. Still on the table: opportunity, never part of a savings total ----
235
+ out += savingsOnTableHtml(data);
236
+
237
+ // ---- 2. The re-read card ----
238
+ var cards = [];
239
+ var removedOnce = num(cp.removed_tokens), rereads = num(cp.reread_tokens);
240
+ if (removedOnce > 0 && rereads > 0) {
241
+ var carryN = rereads / removedOnce;
242
+ cards.push('<div class="card st-card st-reread">' +
243
+ '<h2 class="st-h">' + (as.reread_available !== false && has(as.reread_usd) && num(as.reread_usd) > 0 && bigTotal > 0 ? usd(as.reread_usd) + ' of your ' + usd(bigTotal) + ' came from re-reads avoided' : 'Removed once, saved on every later turn') + '</h2>' +
244
+ '<div class="st-reread__body"><p class="st-mega__item st-mega__item--card"><span class="st-mega st-mega--tok st-mega--card">' + Math.round(carryN) + '&times;</span><span class="st-mega__unit">re-reads avoided per token removed</span></p>' +
245
+ '<p class="st-lead"><strong>' + tok(removedOnce) + ' priced tokens removed</strong> became <strong>' + tok(rereads) + ' tokens not sent</strong> on later reads' + (has(cp.reread_usd) ? ', worth ' + usd(cp.reread_usd) + ' at API rates' : '') + '.</p></div>' +
246
+ '</div>');
247
+ }
248
+ if (cards.length) out += '<div class="st-grid">' + cards.join('') + '</div>';
249
+ out += savingsCostTrendHtml(s.cost_per_message_trend);
250
+
251
+ return out ? '<section class="st" aria-label="What Token Optimizer saved">' + out + '</section>' : '';
252
+ }
253
+
254
+ // "Apr to Jul" (years added when they differ or are needed), or ''.
255
+ function savingsMonthRange(period, joiner) {
256
+ period = period || {};
257
+ if (!(/^\d{4}-\d{2}$/.test(period.start || '') && /^\d{4}-\d{2}$/.test(period.end || ''))) return '';
258
+ function m(v) { return new Date(v + '-01T00:00:00').toLocaleDateString('en-US', { month: 'short' }); }
259
+ var sameYear = period.start.slice(0, 4) === period.end.slice(0, 4);
260
+ return m(period.start) + (sameYear ? '' : ' ' + period.start.slice(0, 4)) + (joiner || ' to ') + m(period.end) + (sameYear ? '' : ' ' + period.end.slice(0, 4));
261
+ }
262
+
263
+ // Exact dollars and cents, for the folds.
264
+ function savingsCents(v) {
265
+ v = savingsStoryFmt().num(v);
266
+ return (v < 0 ? '-$' : '$') + Math.abs(v).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
267
+ }
268
+
269
+ // Since-install fold: the measured / estimated / routing split and its baseline.
270
+ function savingsSinceInstallBody(data, SI) {
271
+ var f = savingsStoryFmt(), num = f.num, has = f.has, usd = f.usd, pct = f.pct, esc_ = esc;
272
+ var s = (data && data.savings) || {};
273
+ var ai = ((s.since_install || {}).all_in) || {};
274
+ var mr = s.model_routing || {};
275
+ var fleet = (s.session_effect || {}).fleet || {};
276
+ var ledgerShare = has(fleet.cost_share_net) ? num(fleet.cost_share_net) : (has(fleet.cost_share) ? num(fleet.cost_share) : null);
277
+ var basis = savingsRoutingBasis(data);
278
+ var period = savingsMonthRange(ai.routing_majority_period, ' to ');
279
+ var since = SI.date ? esc_(SI.date) : 'install';
280
+ var split = '<p><strong>Since ' + since + ', ' + savingsCents(SI.all) + '</strong></p><ul>' +
281
+ (SI.measured > 0 ? '<li>Measured: ' + savingsCents(SI.measured) + '. Context removed, cheaper cache writes and re-reads avoided, counted event by event.</li>' : '') +
282
+ (SI.estimated > 0 ? '<li>Estimated: ' + savingsCents(SI.estimated) + '. Setup cleanup from archives, handovers and other documented estimates.</li>' : '') +
283
+ (SI.routing > 0 ? '<li>Model routing, estimated: ' + savingsCents(SI.routing) + '. ' + esc_(basis.lead) + (period ? ' Most of it from ' + esc_(period) + '.' : '') + '</li>' : '') +
284
+ '</ul>';
285
+ var alt = SI.routing > 0 && basis.kind === 'stated' && has(ai.routing_measured_baseline_opus_share) && has(ai.routing_measured_baseline_realized_cost_usd)
286
+ ? '<p>Using the measured starting mix (' + (num(ai.routing_measured_baseline_opus_share) * 100).toFixed(2) + '% Opus), the routing estimate is ' + usd(ai.routing_measured_baseline_realized_cost_usd) + '.</p>' : '';
287
+ return split +
288
+ '<p>Providers do not publish how they weight models and cache reads inside a limit; API price is the closest public stand-in, so this is room inside your limits, not a refund.</p>' +
289
+ alt +
290
+ (SI.excluded ? '<p>Excluded since install: unverified lean-resume proxy ' + (has(SI.excluded.lean_resumes) ? usd(SI.excluded.lean_resumes) : 'not priced') + ', and verbosity ' + (has(SI.excluded.verbosity) ? usd(SI.excluded.verbosity) : 'not priced') + '.</p>' : '<p>Unverified lean-resume and verbosity estimates are excluded.</p>') +
291
+ (ledgerShare != null ? '<p>Counted ledger alone, as a share of the API-rate cost of the sessions where Token Optimizer ran: ' + pct(ledgerShare) + '.</p>' : '');
292
+ }
293
+
294
+ // Which baseline the since-install routing estimate compares against:
295
+ // 'stated' (the user's own pre-TO share) or 'measured' (the mix Token
296
+ // Optimizer recorded at install). Older payloads only carried a stated one.
297
+ function savingsRoutingBasis(data) {
298
+ var f = savingsStoryFmt(), has = f.has, num = f.num;
299
+ var s = (data && data.savings) || {};
300
+ var ai = ((s.since_install || {}).all_in) || {};
301
+ var mr = s.model_routing || {};
302
+ var src = ai.routing_baseline_source || mr.baseline_source;
303
+ var kind = (src === 'measured_at_install' || src === 'snapshot' || src === 'history') ? 'measured' : 'stated';
304
+ var share = has(ai.routing_baseline_opus_share) ? num(ai.routing_baseline_opus_share) : (has(mr.baseline_opus_share) ? num(mr.baseline_opus_share) : null);
305
+ var pct = share != null ? Math.round(share * 100) + '%' : '';
306
+ // Newer payloads say where the baseline came from and whether Token
307
+ // Optimizer was already running in it; that sentence replaces the fixed one.
308
+ var prov = ai.routing_baseline_provenance || mr.baseline_provenance;
309
+ if (prov && prov.lead && prov.ledger) return { kind: prov.kind === 'stated' ? 'stated' : 'measured', pct: pct, lead: String(prov.lead), ledger: String(prov.ledger) };
310
+ return {
311
+ kind: kind, pct: pct,
312
+ lead: kind === 'measured'
313
+ ? 'Compared with the model mix Token Optimizer recorded when you installed' + (pct ? ' (' + pct + ' Opus)' : '') + '.'
314
+ : 'At your stated ' + (pct ? pct + ' ' : '') + 'Opus baseline.',
315
+ ledger: kind === 'measured'
316
+ ? 'Estimated routing, against the model mix recorded at install' + (pct ? ' (' + pct + ' Opus)' : '')
317
+ : 'Estimated routing, at your stated ' + (pct ? pct + ' ' : '') + 'Opus baseline'
318
+ };
319
+ }
320
+
321
+ // No baseline yet: one line saying how far along it is, so the missing
322
+ // before-and-after card is explained. Nothing for any other state.
323
+ function savingsBaselineProgressHtml(ba) {
324
+ var f = savingsStoryFmt(), num = f.num, has = f.has, count = f.count;
325
+ var b = ba && ba.reason === 'insufficient_history' ? ba.baseline_building : null;
326
+ if (!b || typeof b !== 'object' || b.ready === true || !has(b.sessions_in_window) || !(num(b.sessions_needed) > 0)) return '';
327
+ var got = Math.max(0, num(b.sessions_in_window)), need = num(b.sessions_needed), left = Math.max(0, num(b.days_left));
328
+ var span = num(b.early_window_days) > 0 ? num(b.early_window_days) : 30;
329
+ var line;
330
+ if (left > 0) {
331
+ line = 'Building your baseline: ' + count(Math.min(got, need)) + ' of ' + count(need) + ' sessions, ' + count(left) + ' day' + (left === 1 ? '' : 's') + ' left. ' +
332
+ 'Your before-and-after comparison appears here when it is ready.';
333
+ } else if (got < need) {
334
+ line = 'Your first ' + count(span) + ' days on record had ' + count(got) + ' session' + (got === 1 ? '' : 's') + '. A stable baseline needs ' + count(need) + ', so the before-and-after comparison is not shown. Everything above is still counted.';
335
+ } else {
336
+ return '';
337
+ }
338
+ return '<div class="card st-card st-baseline-progress"><h2 class="st-h">Your transformation</h2><p class="st-lead">' + line + '</p></div>';
339
+ }
340
+
341
+ // Transformation: what this month would cost without Token Optimizer, against
342
+ // the user's own baseline from before install. Hidden unless the payload says ok.
343
+ function savingsTransformationHtml(data) {
344
+ var f = savingsStoryFmt(), num = f.num, has = f.has, usd = f.usd;
345
+ var ba = ((data && data.savings) || {}).before_after || {};
346
+ if (ba.transformation_state !== 'ok' || !(num(ba.monthly_savings_usd) > 0)) return savingsBaselineProgressHtml(ba);
347
+ var share = has(ba.transformation_pct) && num(ba.transformation_pct) > 0 ? Math.round(num(ba.transformation_pct) * 100) : 0;
348
+ // Where the "before" came from. Older payloads carry no provenance and keep the fixed sentence.
349
+ var prov = ba.baseline_provenance || {};
350
+ // The lead states the baseline; what it understates is spelled out in the fold.
351
+ var against = prov.lead ? esc(prov.lead) : 'compared with your own baseline from before you installed.';
352
+ // A work-normalized figure prices both periods at one fixed rate card, so its
353
+ // "now" side is not the user's spend: name the card and show the exact-card cost.
354
+ var wp = ba.session_weight_pool || {}, fr = wp.flat_rates || null;
355
+ var fixed = fr && has(fr.input) && has(fr.output) && has(fr.cache_read) && has(fr.cache_write);
356
+ var own = fixed && wp.price_basis === 'own_prices';
357
+ var rate = function(v) { return '$' + Number(num(v).toFixed(2)); };
358
+ var method = '<ul><li>' + (prov.versus_label ? esc(prov.versus_label) : 'Without Token Optimizer') + (own ? ', at your current prices' : fixed ? ', at the fixed price card' : '') + ': ' + savingsCents(ba.counterfactual_monthly_usd) + ' a month</li>' +
359
+ '<li>' + (own ? 'This period, at your current prices' : fixed ? 'This period, at the same fixed price card' : 'What you actually spent') + ': ' + savingsCents(ba.actual_monthly_usd) + ' a month</li>' +
360
+ '<li>Difference: ' + savingsCents(ba.monthly_savings_usd) + ' a month</li></ul>' +
361
+ (own ? '<p>Both sides are priced at your own current prices (per million tokens: ' + rate(fr.input) + ' input, ' + rate(fr.output) + ' output, ' + rate(fr.cache_read) + ' cache read, ' + rate(fr.cache_write) + ' cache write, averaged over the models you ran this period), so a price change between the two periods cannot count as a saving.</p>'
362
+ : fixed ? '<p>Both sides are priced at one fixed card (per million tokens: $' + num(fr.input) + ' input, $' + num(fr.output) + ' output, $' + num(fr.cache_read) + ' cache read, $' + num(fr.cache_write) + ' cache write), so a price change between the two periods cannot count as a saving. These are dollars at that card, not your bill.' +
363
+ (num(wp.engine_priced_actual_usd) > 0 ? ' At the prices of the models you actually used, this period comes to ' + savingsCents(wp.engine_priced_actual_usd) + ' at API rates.' : '') + '</p>' : '') +
364
+ (prov.note ? '<p>' + esc(prov.note) + '</p>' : '') +
365
+ (ba.before_mix_label ? '<p>' + (prov.mix_note ? 'Baseline model mix: ' + esc(ba.before_mix_label) + ', ' + esc(prov.mix_note) : 'Baseline mix before you installed: ' + esc(ba.before_mix_label)) + '. Now: ' + esc(ba.after_mix_label || 'your current mix') + '.</p>' : '') +
366
+ (ba.breakdown_caveat ? '<p>' + esc(ba.breakdown_caveat) + '</p>' : '');
367
+ return '<div class="card st-card st-transform">' +
368
+ '<h2 class="st-h">Your transformation</h2>' +
369
+ '<p class="st-mega__item st-mega__item--card"><span class="st-mega st-mega--usd st-mega--card">' + usd(ba.monthly_savings_usd) + '<span class="st-mega__per"> a month</span></span>' +
370
+ '</p><p class="st-lead">' + (prov.claim ? esc(prov.claim) : 'Without Token Optimizer, working the way you work now would cost you this much more, ' + against) +
371
+ (share > 0 ? ' That is ' + share + '% of what this work would have cost.' : '') + '</p>' +
372
+ f.fold('How this is calculated', method) +
373
+ '</div>';
374
+ }
375
+
376
+ // Limits with and without Token Optimizer: per window, the used share and what
377
+ // it would be without. Live windows first, then the last stored meter reading;
378
+ // with neither, the window grid is left out.
379
+ function savingsLimitWindows(rw, ratio, versus) {
380
+ // What the second number is measured against: a time without Token
381
+ // Optimizer, or (when it already ran in the baseline month) that month.
382
+ var vs = versus ? esc(versus) : 'without Token Optimizer';
383
+ var f = savingsStoryFmt(), num = f.num;
384
+ var names = { five_hour: '5-hour limit', seven_day: 'Weekly limit' };
385
+ function ok(w) {
386
+ return w && w.used_pct != null && isFinite(Number(w.used_pct)) && Number(w.used_pct) >= 0 && Number(w.used_pct) <= 100;
387
+ }
388
+ var live = (Array.isArray(rw.windows) ? rw.windows : []).filter(ok), rows = live, stored = false;
389
+ if (!rows.length) { rows = (Array.isArray(rw.last_known_windows) ? rw.last_known_windows : []).filter(ok); stored = rows.length > 0; }
390
+ if (!rows.length) return '';
391
+ // One row per window: name, a bar (solid = used now, striped = without
392
+ // Token Optimizer) and the two numbers as stat blocks.
393
+ var html = '<div class="st-limits">' + rows.map(function(w) {
394
+ var used = num(w.used_pct), rawWithout = used * ratio;
395
+ var name = names[w.key] || ((w.label || 'window') + ' limit');
396
+ name = name.charAt(0).toUpperCase() + name.slice(1);
397
+ var over = ratio > 0 && rawWithout > 100;
398
+ var without = ratio > 0 ? Math.min(100, Math.round(rawWithout)) : 0;
399
+ var label = Math.round(used) + '% used now' + (ratio > 0 ? (over ? ', over the limit ' + vs : ', ' + without + '% ' + vs) : '');
400
+ var stat = ratio > 0
401
+ ? (over
402
+ ? '<span class="st-limit__stat st-limit__stat--over">over the limit ' + vs + '</span>'
403
+ : '<span class="st-limit__stat"><span class="st-limit__num">' + without + '%</span> ' + vs + '</span>')
404
+ : '';
405
+ return '<div class="st-limit"><span class="st-limit__name">' + esc(name) + '</span>' +
406
+ '<span class="st-limit__meter" role="img" aria-label="' + esc(label) + '">' +
407
+ (ratio > 0 ? '<span class="st-limit__ghost" style="width:' + without + '%"></span>' : '') +
408
+ '<span class="st-limit__fill" style="width:' + Math.round(used) + '%"></span></span>' +
409
+ '<span class="st-limit__stat"><span class="st-limit__used">' + Math.round(used) + '%</span> used now</span>' + stat + '</div>';
410
+ }).join('') + '</div>';
411
+ var ts = Number(rw.meter_ts);
412
+ if (stored && isFinite(ts) && ts > 0) {
413
+ var when = new Date(ts * 1000).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
414
+ html += '<p class="st-sub">Last reading, ' + esc(when) + '.</p>';
415
+ }
416
+ return html;
417
+ }
418
+
419
+ function savingsLimitsHtml(data) {
420
+ var f = savingsStoryFmt(), num = f.num;
421
+ var rw = (data && data.runway) || null;
422
+ if (!rw || typeof rw !== 'object') return '';
423
+ var ba = ((data && data.savings) || {}).before_after || {};
424
+ var actual = num(ba.actual_monthly_usd), before = num(ba.counterfactual_monthly_usd);
425
+ var ratio = ba.transformation_state === 'ok' && actual > 0 && before > actual ? before / actual : 0;
426
+ var extra = ratio > 1 ? Math.round((1 - 1 / ratio) * 100) : 0;
427
+ var versus = (ba.baseline_provenance || {}).versus || '';
428
+ var windows = savingsLimitWindows(rw, ratio, versus);
429
+ if (!extra && !windows) return '';
430
+ var direct = num(rw.extra_work_pct);
431
+ var method = '<p>Your usage is a meter reading. The ' + (versus ? 'comparison ' + esc(versus) : 'without-Token-Optimizer comparison') + ' is an estimate using the same before-and-after basis as your transformation: counterfactual monthly cost divided by actual monthly cost, multiplied by the used percentage and capped at 100%. Providers do not publish the exact weighting of usage limits.</p>' +
432
+ (ratio ? '<p>' + savingsCents(before) + ' divided by ' + savingsCents(actual) + ' = &times;' + ratio.toFixed(2) + '.</p>' : '') +
433
+ (direct > 0 ? '<p>Separately, directly measured savings imply about ' + direct + '% more work per token.</p>' : '');
434
+ return '<div class="card st-card st-limits-card">' +
435
+ '<div class="st-limits__top"><h2 class="st-h">Your limits go further</h2>' + windows + '</div>' +
436
+ '<div class="st-limits__bottom">' + (extra ? '<p>&asymp;' + extra + '% more room in your limits</p>' : '') +
437
+ f.fold('How this is calculated', method) + '</div></div>';
438
+ }
439
+
440
+ // Still on the table: computable opportunities per period, each with one
441
+ // action. A part the data cannot size is left out. Never part of any
442
+ // savings total.
443
+ function savingsOnTableHtml(data) {
444
+ var f = savingsStoryFmt(), num = f.num, has = f.has, usd = f.usd, tok = f.tok, count = f.count;
445
+ var s = (data && data.savings) || {};
446
+ var days = Number(s.period_days) || 30;
447
+ var mr = s.model_routing || {};
448
+ var lb = s.skill_listing_budget;
449
+ var rows = [], how = [];
450
+ if (num(mr.potential_cost_usd) > 0) {
451
+ var target = String(mr.target_model || '');
452
+ var name = /sonnet/i.test(target) ? 'Sonnet' : /haiku/i.test(target) ? 'Haiku' : 'a lighter model';
453
+ var frac = has(mr.routable_fraction) ? Math.round(num(mr.routable_fraction) * 100) : null;
454
+ rows.push({ label: 'Model routing', action: 'Send routine work to ' + name, usd: num(mr.potential_cost_usd) });
455
+ how.push('<li>Model routing: if ' + (frac != null ? 'about ' + frac + '% of' : 'part of') + ' your Opus work ran on ' + name + ', new input and output priced at API rates. An assumption about your own work.</li>');
456
+ }
457
+ // The skill-listing row appears only when the user's own history sizes it;
458
+ // with no earlier listing to compare, it is left out (never "Measuring").
459
+ if (lb && typeof lb === 'object' && lb.available && num(lb.cost_usd) > 0) {
460
+ var bm = /^\d{4}-\d{2}$/.test(lb.baseline_month || '') ? new Date(lb.baseline_month + '-01T00:00:00').toLocaleDateString('en-US', { month: 'short', year: 'numeric' }) : '';
461
+ rows.push({ label: 'Skill listing', action: 'Trim the skill list budget', usd: num(lb.cost_usd) });
462
+ how.push('<li>Skill listing: your skill list grew from ' + count(lb.baseline_chars) + ' to ' + count(lb.current_chars) + ' characters per message' + (bm ? ' since ' + esc(bm) : '') +
463
+ '. Trimming it back is worth the ' + tok(lb.growth_tokens) + '-token difference &times; ' + count(lb.calls) + ' calls on this computer in the last ' + count(lb.period_days || days) + ' days &times; each call&rsquo;s cache-read price.</li>');
464
+ }
465
+ if (!rows.length) return '';
466
+ var total = rows.reduce(function(a, r) { return a + r.usd; }, 0);
467
+ return '<div class="card st-table">' +
468
+ '<h2 class="st-h">Still on the table</h2>' +
469
+ '<div class="st-table__body"><p class="st-mega__item st-mega__item--card">' +
470
+ '<span class="st-mega st-mega--warm st-mega--card">' + usd(total) + '</span><span class="st-mega__unit">more every ' + days + ' days, yours to claim</span></p>' +
471
+ '<div class="st-table__rows"><ul class="st-rows st-rows--card">' + rows.map(function(r) {
472
+ return '<li><span>' + esc(r.label) + '<span class="st-sub">' + esc(r.action) + '</span></span><span class="st-v">' + usd(r.usd) + '</span></li>';
473
+ }).join('') + '</ul>' +
474
+ f.fold('How each one is sized', '<ul>' + how.join('') + '</ul><p>Valued at API rates, per ' + days + ' days. None of this is in any savings total.</p>') +
475
+ '</div></div></div>';
476
+ }
477
+
478
+ // Cost per message: shown only when it fell at least 10% from the first month.
479
+ function savingsCostTrendHtml(raw) {
480
+ var trend = (raw || []).filter(function(p) {
481
+ return p && /^\d{4}-\d{2}$/.test(String(p.month)) && isFinite(Number(p.index)) && Number(p.index) >= 0;
482
+ });
483
+ if (trend.length < 2) return '';
484
+ var start = Number(trend[0].index), latest = Number(trend[trend.length - 1].index);
485
+ if (!(start > 0) || latest > start * 0.9) return '';
486
+ var down = Math.round((1 - latest / start) * 100);
487
+ var first = new Date(trend[0].month + '-01T00:00:00'), last = new Date(trend[trend.length - 1].month + '-01T00:00:00');
488
+ var since = first.toLocaleDateString('en-US', first.getFullYear() === last.getFullYear() ? { month: 'long' } : { month: 'long', year: 'numeric' });
489
+ var maxIndex = Math.max.apply(null, trend.map(function(p) { return Number(p.index); })) || 1;
490
+ var points = trend.map(function(p, i) { return (i * 500 / (trend.length - 1)).toFixed(1) + ',' + (90 - Number(p.index) / maxIndex * 80).toFixed(1); }).join(' ');
491
+ var ticks = trend.map(function(p, i) { if (i !== trend.length - 1 && i % Math.ceil(trend.length / 6)) return ''; var d = new Date(p.month + '-01T00:00:00'), x = 20 + i * 460 / (trend.length - 1); return '<text x="' + x.toFixed(1) + '" y="115" text-anchor="middle" fill="currentColor" font-size="11">' + esc(d.toLocaleDateString('en-US', {month:'short'})) + '</text>'; }).join('');
492
+ return '<div class="card wide st-card"><h2 class="st-h">Cost per message down ' + down + '% since ' + esc(since) + '</h2>' +
493
+ '<p class="st-lead">Indexed to the first month, at constant Opus prices for every model. This trend is not attributed to Token Optimizer.</p>' +
494
+ '<p>Start ' + Math.round(start) + ' &middot; Latest ' + Math.round(latest) + '</p>' +
495
+ '<svg viewBox="0 0 500 120" role="img" aria-label="Monthly cost per message index" style="width:100%;height:140px">' +
496
+ '<polyline fill="none" stroke="currentColor" stroke-width="3" points="' + points + '"></polyline>' + ticks + '</svg></div>';
497
+ }
498
+
499
+ function savingsPerSessionHtml(ps, overhead) {
500
+ var f = savingsStoryFmt(), num = f.num, has = f.has;
501
+ ps = ps || {};
502
+ var bp = ps.by_place || {};
503
+ var rows = [['On this computer', bp.local], ['Cloud sessions', bp.cloud]].filter(function(r) {
504
+ return r[1] && num(r[1].sessions) > 0 && has(r[1].net_median);
505
+ });
506
+ if (!rows.length && num(ps.sessions) > 0 && has(ps.net_median)) rows = [['All sessions', ps]];
507
+ if (!rows.length) return '';
508
+ overhead = overhead || {};
509
+ return '<p><strong>Per session, share of that session&rsquo;s own context that never got sent</strong></p><ul>' + rows.map(function(r) {
510
+ var v = r[1];
511
+ return '<li>' + r[0] + ': typical ' + f.pct(v.net_median) + (has(v.net_p75) ? ', top quarter ' + f.pct(v.net_p75) + ' or more' : '') +
512
+ ' (' + f.count(v.sessions) + ' sessions)</li>';
513
+ }).join('') + '</ul><p>Medians of sessions with ledger entries, after subtracting the notes Token Optimizer itself adds' +
514
+ (num(overhead.usd) > 0 ? ' (' + f.tok(overhead.reread_tokens) + ' tokens re-read, about ' + f.usd(overhead.usd) + ')' : '') +
515
+ '. Cloud means the session&rsquo;s events were rebuilt from its transcript because its hooks ran on another machine.</p>' +
516
+ (bp.local && bp.local.best && bp.local.best.filtered ? '<p>Best local session is selected among sessions with at least 20 turns because the unfiltered best was small.</p>' : '');
517
+ }
518
+
519
+ // Since-install total: every component plus the routing estimate. `all` is the
520
+ // big number; measured, estimated and routing are its split.
521
+ function savingsSinceInstall(data) {
522
+ var f = savingsStoryFmt(), num = f.num, has = f.has;
523
+ var si = ((data && data.savings) || {}).since_install || {};
524
+ var ai = si.all_in || {};
525
+ var c = ai.components_usd || {};
526
+ if (!(num(si.days) > 0)) return null;
527
+ var parts = [['Context removed', c.logged], ['Cheaper cache writes', c.class_premium], ['Re-reads avoided', c.reread], ['Estimates', ai.estimated_usd]]
528
+ .filter(function(p) { return num(p[1]) !== 0; });
529
+ if (!parts.length) return null;
530
+ var date = si.install_date ? new Date(si.install_date + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '';
531
+ var base = parts.reduce(function(a, p) { return a + num(p[1]); }, 0);
532
+ var routing = has(ai.routing_usd) ? num(ai.routing_usd) : num(c.routing_estimated) + num(c.routing_measured);
533
+ if (!(routing > 0)) routing = 0;
534
+ var all = has(ai.total_usd) ? num(ai.total_usd) : base + routing;
535
+ var estimated = num(ai.estimated_usd);
536
+ return { parts: parts, total: base, all: all, routing: routing, estimated: estimated, measured: all - estimated - routing,
537
+ days: num(si.days), date: date, excluded: si.excluded_usd || null };
538
+ }
539
+
540
+ // "Where your sessions ran" fold body, for the caller's row of folds.
541
+ function savingsCoverageFold(data) {
542
+ if (!savingsStoryOn(data)) return '';
543
+ var f = savingsStoryFmt();
544
+ var cov = data.savings.session_effect.coverage || {};
545
+ var classes = cov.classes || {};
546
+ var items = [
547
+ ['ledger', 'Counted in the ledger'], ['logged_no_ledger', 'Logged, no repeat-read record'],
548
+ ['ran_unlogged', 'Ran, not in the ledger yet'], ['not_ran', 'Token Optimizer did not run'],
549
+ ['unknown', 'Not scanned yet (transcript missing)']
550
+ ].filter(function(c) { return classes[c[0]] && f.num(classes[c[0]].sessions) > 0; });
551
+ if (!items.length) return '';
552
+ return f.fold('Where your sessions ran', '<ul>' + items.map(function(c) {
553
+ var k = classes[c[0]];
554
+ return '<li>' + c[1] + ': ' + f.count(k.sessions) + ' sessions, ' + f.pct(k.traffic_share) + ' of all your traffic</li>';
555
+ }).join('') + '</ul><p>A session counts as covered only on evidence: a ledger row, a logged event, or Token Optimizer&rsquo;s own note in its transcript.</p>');
556
+ }
557
+
558
+ // Health tab: context quality and hook time-outs, moved off the Savings tab.
559
+ function healthNotesHtml(data) {
560
+ if (!savingsStoryOn(data)) return '';
561
+ var f = savingsStoryFmt();
562
+ var out = '';
563
+ var qt = (data.trends && data.trends.quality_trend) || [];
564
+ var wsum = 0, wn = 0;
565
+ qt.forEach(function(r) {
566
+ var q = Number(r.avg_quality) || 0, n = Number(r.sessions) || 0;
567
+ if (q > 0 && n > 0) { wsum += q * n; wn += n; }
568
+ });
569
+ if (wn > 0) {
570
+ var avg = Math.round(wsum / wn);
571
+ var vals = qt.map(function(r) { return Number(r.avg_quality) || 0; }).filter(function(v) { return v > 0; });
572
+ var trend = '';
573
+ if (vals.length >= 6) {
574
+ var h = Math.floor(vals.length / 2);
575
+ var d = vals.slice(-h).reduce(function(a, b) { return a + b; }, 0) / h - vals.slice(0, h).reduce(function(a, b) { return a + b; }, 0) / h;
576
+ trend = d > 3 ? 'up over the period' : (d < -3 ? 'down over the period' : 'steady over the period');
577
+ }
578
+ out += '<div class="card wide st-health">' +
579
+ '<h2 class="st-h">Context quality</h2>' +
580
+ '<p class="st-big">Your context scored <span class="st-num">' + avg + '</span> out of 100 on average' + (trend ? ', ' + trend : '') + '.</p>' +
581
+ '<div class="st-ratio__track st-quality" role="img" aria-label="' + avg + ' out of 100"><span class="st-ratio__carry" style="width:' + Math.min(100, Math.max(0, avg)) + '%"></span></div>' +
582
+ f.fold('What this means', '<p>Averaged across your last ' + f.count(wn) + ' sessions. The score drops as context fills with stale reads, repeated output and old tool results; tighter context gives sharper answers and fewer compactions.</p>' +
583
+ '<p>The session table above scores single sessions.</p>') +
584
+ '</div>';
585
+ }
586
+ var hs = (data.savings || {}).hook_skips || {};
587
+ if (f.num(hs.overruns) > 0) {
588
+ out += '<div class="card wide st-health">' +
589
+ '<h2 class="st-h">Hook time limits</h2>' +
590
+ '<p class="st-lead">Hooks ran out of time ' + f.count(hs.overruns) + ' times' + (hs.where ? ' ' + esc(hs.where) : '') +
591
+ (f.num(hs.skipped_compressions) > 0 ? ' and skipped about ' + f.count(hs.skipped_compressions) + ' compressions (' + f.pct(hs.skip_rate) + ' of compressible output)' : '') +
592
+ '.</p>' +
593
+ '</div>';
594
+ }
595
+ return out;
596
+ }
597
+
598
+ // "Full ledger and history" fold body in story mode: the hero's own rows to
599
+ // the cent, then the since-install sums from the same components. Model
600
+ // routing is never added to either total.
601
+ function savingsLedgerHtml(data) {
602
+ if (!savingsStoryOn(data)) return '';
603
+ var f = savingsStoryFmt(), num = f.num;
604
+ var s = data.savings || {};
605
+ var B = savingsStoryBands(data);
606
+ var days = Number(s.period_days) || 30;
607
+ var mr = s.model_routing || {};
608
+ var routing30 = f.has(mr.realized_cost_usd) ? num(mr.realized_cost_usd) : num((s.action_savings || {}).routing_usd);
609
+ if (!(routing30 > 0)) routing30 = 0;
610
+ function cents(v) {
611
+ v = num(v);
612
+ return (v < 0 ? '-$' : '$') + Math.abs(v).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
613
+ }
614
+ function row(label, v, tokens) {
615
+ return '<li><span>' + esc(label) + (num(tokens) > 0 ? '<span class="st-sub">' + f.tok(tokens) + ' tokens</span>' : '') +
616
+ '</span><span class="st-v">' + cents(v) + '</span></li>';
617
+ }
618
+ var out = '<h3 class="ts-section-label">Last ' + days + ' days, to the cent</h3><ul class="st-rows">' +
619
+ B.measured.map(function(r) { return row(r.label + ' (measured)', r.usd, r.tok); }).join('') +
620
+ B.estimated.map(function(r) { return row(r.label + ' (estimated)', r.usd, r.tok); }).join('') +
621
+ (routing30 > 0 ? row('Model routing (estimated)', routing30, 0) : '') +
622
+ '<li><span><strong>Total</strong></span><span class="st-v"><strong>' + cents(B.totalUsd + routing30) + '</strong></span></li></ul>';
623
+ var SI = savingsSinceInstall(data);
624
+ if (SI) {
625
+ out += '<h3 class="ts-section-label st-gap">Since you installed' + (SI.date ? ' on ' + esc(SI.date) : '') + ' (' + f.count(SI.days) + ' days)</h3><ul class="st-rows">' +
626
+ SI.parts.map(function(p) { return row(p[0], p[1], 0); }).join('') +
627
+ (SI.routing ? row(savingsRoutingBasis(data).ledger, SI.routing, 0) : '') +
628
+ '<li><span><strong>Total</strong></span><span class="st-v"><strong>' + cents(SI.all) + '</strong></span></li></ul>';
629
+ }
630
+ var cp = s.counted_period || {};
631
+ if (cp.pricing_note) out += '<p>' + esc(cp.pricing_note) + '</p>';
632
+ return out;
633
+ }
634
+
635
+
636
+ // Setup cleanup rows: every valued trim grouped by day and evidence, plus the
637
+ // observed listing/connector reductions, so the rows sum exactly to the
638
+ // measured and estimated "Setup cleanup" lines of the 30-day breakdown.
639
+ function setupCleanupGroups(sd) {
640
+ var f = savingsStoryFmt(), num = f.num, groups = {}, order = [];
641
+ (sd.trims || []).forEach(function(t) {
642
+ if (!t || t.tier === 'unattributed' || !(num(t.cost_saved_usd) > 0)) return;
643
+ var kind = t.step_measured ? 'step' : t.source === 'dated_archive' ? 'archive' : (t.source === 'attested' || t.tier === 'estimated') ? 'figure' : 'audit';
644
+ var key = (f.day(t.ts) || 'undated') + '|' + kind;
645
+ if (!groups[key]) { groups[key] = {day: f.day(t.ts) || 'undated', kind: kind, tier: t.tier, items: [], usd: 0}; order.push(key); }
646
+ groups[key].items.push(t); groups[key].usd += num(t.cost_saved_usd);
647
+ });
648
+ var words = {step: 'measured by the first-call step', archive: 'estimated from archive', figure: 'your figure', audit: 'recorded by the audit'};
649
+ var out = order.map(function(k) {
650
+ var g = groups[k], one = g.items.length === 1, comps = g.items.map(function(t) { return t.component; });
651
+ var same = comps.every(function(c) { return c === comps[0]; });
652
+ return {label: one ? (g.items[0].label || g.items[0].item || g.items[0].component || 'Setup cleanup')
653
+ : g.items.length + ' ' + (same && comps[0] ? comps[0] : 'items'),
654
+ sub: g.day + ', ' + words[g.kind], usd: g.usd, tier: g.tier};
655
+ });
656
+ [['budget_observed', 'Skill listing reduction', 'observed on later calls'], ['connector_observed', 'Disconnected connectors', 'observed on later calls']].forEach(function(b) {
657
+ var o = sd[b[0]] || {};
658
+ if (num(o.usd) > 0) out.push({label: b[1], sub: b[2], usd: num(o.usd), tier: 'measured'});
659
+ });
660
+ return out.sort(function(a, b) { return b.usd - a.usd; });
661
+ }