@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
@@ -0,0 +1,339 @@
1
+ """Where each "before" baseline came from, and whether Token Optimizer was
2
+ already running inside it.
3
+
4
+ The transformation card and the routing estimate both compare today against an
5
+ earlier window of the user's own history. That window is only a true "before"
6
+ when it ends before the install. A fresh install with no older transcripts, a
7
+ rebuilt ledger, or a lost baseline file all leave an earliest window in which
8
+ the tool was already working, so the comparison understates the result. This
9
+ module finds the install date from the evidence on disk, classifies each
10
+ baseline window against it, and writes the sentence every surface shows.
11
+
12
+ Pure reads. Never raises.
13
+ """
14
+ import json
15
+ import re
16
+ import sqlite3
17
+ from datetime import datetime, timedelta
18
+
19
+ ROUTING_HISTORY_DAYS = 14
20
+ # Days of a baseline window that may fall after install before the window stops
21
+ # counting as pre-install (the install day itself, plus a short tail).
22
+ _TAIL_SHARE = 0.10
23
+ _INSTALL_PROOF = ("snapshot", "first_event")
24
+
25
+
26
+ def _day(value):
27
+ try:
28
+ return datetime.strptime(str(value)[:10], "%Y-%m-%d")
29
+ except (TypeError, ValueError):
30
+ return None
31
+
32
+
33
+ def _iso(day):
34
+ return day.strftime("%Y-%m-%d") if day else None
35
+
36
+
37
+ def _read_json(path):
38
+ try:
39
+ data = json.loads(path.read_text(encoding="utf-8"))
40
+ return data if isinstance(data, dict) else None
41
+ except (OSError, ValueError, TypeError, AttributeError):
42
+ return None
43
+
44
+
45
+ def _first_event_day(facade):
46
+ """Date of the earliest event Token Optimizer logged, or None."""
47
+ try:
48
+ if not facade.TRENDS_DB.exists():
49
+ return None
50
+ conn = facade._open_trends_db_readonly(timeout=1.0)
51
+ except Exception:
52
+ return None
53
+ found = []
54
+ try:
55
+ for table in ("savings_events", "compression_events"):
56
+ try:
57
+ row = conn.execute(
58
+ "SELECT MIN(timestamp) FROM " + table + " WHERE timestamp >= '2000'").fetchone()
59
+ except sqlite3.Error:
60
+ continue
61
+ day = _day(row[0]) if row and row[0] else None
62
+ if day:
63
+ found.append(day)
64
+ finally:
65
+ try:
66
+ conn.close()
67
+ except sqlite3.Error:
68
+ pass
69
+ return min(found) if found else None
70
+
71
+
72
+ def _earliest_session_day(facade):
73
+ try:
74
+ if not facade.TRENDS_DB.exists():
75
+ return None
76
+ conn = facade._init_trends_db()
77
+ try:
78
+ facade.ensure_activity_view(conn)
79
+ row = conn.execute("SELECT MIN(date) FROM session_activity WHERE date >= '2000'").fetchone()
80
+ finally:
81
+ conn.close()
82
+ return _day(row[0]) if row and row[0] else None
83
+ except Exception:
84
+ return None
85
+
86
+
87
+ def install_evidence(facade):
88
+ """{"date", "source"}: the earliest dated proof the tool was installed.
89
+
90
+ "snapshot" is the first-run baseline snapshot, "first_event" the earliest
91
+ logged event (it wins when a later audit re-took the snapshot). With
92
+ neither, the earliest session on record stands in as "earliest_session":
93
+ good enough to date a since-install total, but not proof of an install, so
94
+ no baseline window is classified against it.
95
+ """
96
+ proofs = []
97
+ try:
98
+ snap = _read_json(facade.SNAPSHOT_DIR / "snapshot_before.json")
99
+ day = _day((snap or {}).get("timestamp"))
100
+ if day:
101
+ proofs.append((day, "snapshot"))
102
+ except Exception:
103
+ pass
104
+ day = _first_event_day(facade)
105
+ if day:
106
+ proofs.append((day, "first_event"))
107
+ if proofs:
108
+ day, source = min(proofs, key=lambda item: item[0])
109
+ return {"date": _iso(day), "source": source}
110
+ day = _earliest_session_day(facade)
111
+ return {"date": _iso(day), "source": "earliest_session" if day else None}
112
+
113
+
114
+ def window_coverage(start, end, install):
115
+ """Classify the inclusive window [start, end] against the install date.
116
+
117
+ coverage: "pre_install" (a true before), "partial" (installed part-way
118
+ through), "post_install" (the tool ran for the whole window), or "unknown"
119
+ (no window, or no proof of when the tool was installed).
120
+ """
121
+ s, e = _day(start), _day(end)
122
+ install = install or {}
123
+ out = {"start": _iso(s), "end": _iso(e), "coverage": "unknown",
124
+ "install_date": install.get("date"), "install_source": install.get("source"),
125
+ "window_days": None, "post_install_days": None}
126
+ if not s or not e or e < s:
127
+ return out
128
+ days = (e - s).days + 1
129
+ out["window_days"] = days
130
+ d = _day(install.get("date"))
131
+ if not d or install.get("source") not in _INSTALL_PROOF:
132
+ return out
133
+ post = 0 if d > e else (e - max(s, d)).days + 1
134
+ out["post_install_days"] = post
135
+ if post <= max(1, int(days * _TAIL_SHARE)):
136
+ out["coverage"] = "pre_install"
137
+ elif d <= s:
138
+ out["coverage"] = "post_install"
139
+ else:
140
+ out["coverage"] = "partial"
141
+ return out
142
+
143
+
144
+ def _span(cov):
145
+ return "%s to %s" % (cov["start"], cov["end"]) if cov.get("start") and cov.get("end") else ""
146
+
147
+
148
+ def _transformation_copy(cov):
149
+ span = _span(cov)
150
+ where = " (%s)" % span if span else ""
151
+ state = cov["coverage"]
152
+ if state == "pre_install":
153
+ return ("compared with your own baseline from before you installed%s." % where, "")
154
+ lead = "compared with your earliest tracked month%s." % where
155
+ if state == "post_install":
156
+ note = ("Token Optimizer was already running in that month (installed %s), so this is the "
157
+ "change since then. Your usage from before install is not on record, so the full "
158
+ "before-and-after gap cannot be measured and this figure understates it."
159
+ % cov["install_date"])
160
+ elif state == "partial":
161
+ note = ("Token Optimizer was installed on %s, inside that month (%d of its %d days came "
162
+ "after install), so the true gap is larger and this figure understates it."
163
+ % (cov["install_date"], cov["post_install_days"], cov["window_days"]))
164
+ else:
165
+ note = ("The install date is not on record, so it is not known whether Token Optimizer "
166
+ "was already running in that month.")
167
+ if cov.get("pending_anchor") == "building":
168
+ note += (" A closer baseline is still being built from your older transcripts; "
169
+ "this figure will update when it is ready.")
170
+ return lead, note
171
+
172
+
173
+ def transformation(facade, baseline, weight_pool):
174
+ """Provenance of the transformation card's "before" arm.
175
+
176
+ anchor: "pinned_window" (the frozen early window, priced from transcripts),
177
+ "calendar_month" (earliest complete month still in the ledger) or
178
+ "frozen_session" (the frozen typical session, no work-unit pool).
179
+ """
180
+ try:
181
+ baseline = baseline or {}
182
+ window = baseline.get("window") or {}
183
+ anchor, start, end, pending = "frozen_session", window.get("start"), window.get("end"), None
184
+ if weight_pool:
185
+ label = str(weight_pool.get("anchor_month") or "")
186
+ month = re.fullmatch(r"(\d{4})-(\d{2})", label)
187
+ if month:
188
+ anchor = "calendar_month"
189
+ first = datetime(int(month.group(1)), int(month.group(2)), 1)
190
+ start = _iso(first)
191
+ end = _iso((first + timedelta(days=32)).replace(day=1) - timedelta(days=1))
192
+ state = _read_json(facade.SNAPSHOT_DIR / facade._PRETOOL_ANCHOR_FILE) or {}
193
+ if state.get("status") == "building":
194
+ pending = "building"
195
+ else:
196
+ anchor = "pinned_window"
197
+ dates = re.findall(r"\d{4}-\d{2}-\d{2}", label)
198
+ if len(dates) == 2:
199
+ start, end = dates
200
+ cov = window_coverage(start, end, install_evidence(facade))
201
+ try:
202
+ stated = baseline.get("opus_share_source") == "pretool_baseline"
203
+ share = float(baseline.get("opus_share") or 0)
204
+ except (TypeError, ValueError):
205
+ stated, share = False, 0.0
206
+ cov.update(anchor=anchor, pending_anchor=pending,
207
+ mix_source="stated" if stated else ("measured" if share > 0 else "current_mix"))
208
+ cov["lead"], cov["note"] = _transformation_copy(cov)
209
+ if cov["coverage"] in ("post_install", "partial"):
210
+ # The tool ran in the baseline month, so the comparison is with that
211
+ # month, never with a time before Token Optimizer.
212
+ unit = "request" if weight_pool else "session"
213
+ span = _span(cov)
214
+ cov["versus"] = "at your earliest month's cost per " + unit
215
+ cov["versus_label"] = "At your earliest month's cost per " + unit
216
+ cov["claim"] = ("At the cost per %s of your earliest tracked month%s, this period would "
217
+ "cost you this much more." % (unit, " (%s)" % span if span else ""))
218
+ cov["mix_note"] = {
219
+ "stated": "stated by you (set-baseline)",
220
+ "measured": "measured in your earliest tracked month",
221
+ "current_mix": "not measured, so your current mix is used on both sides",
222
+ }[cov["mix_source"]]
223
+ return cov
224
+ except Exception:
225
+ return None
226
+
227
+
228
+ def weight_pool_caveat(anchor_label, provenance):
229
+ """The method paragraph under a work-normalized transformation."""
230
+ text = (
231
+ "Work-normalized counterfactual: every API call you dispatched this "
232
+ "period, priced at the baseline's cost per call ("
233
+ + str(anchor_label) + "), at ONE constant rate card both eras -- so only how much "
234
+ "context each call carries (and how often the cache serves it) moves "
235
+ "the number; model-price and mix changes between eras are excluded and "
236
+ "disclosed separately, not claimed. Sessions are not used as the unit "
237
+ "because the lighter workflow itself splits the same work into more, "
238
+ "smaller sessions, which would count capacity gained as money saved. "
239
+ "The delta includes every volume mechanism at once (context "
240
+ "compression, lean output, loop prevention, continuity handovers), so "
241
+ "the metered and estimated pools are not added on top -- they would "
242
+ "double-count; the directly-metered floor still shows in its own card. "
243
+ "Delegated (subagent) work is excluded from this figure. The per-call delta "
244
+ "cannot separate Token Optimizer's effect from your own behaviour "
245
+ "drift -- the metered floor is the part we can prove action by action."
246
+ )
247
+ note = (provenance or {}).get("note")
248
+ return text + (" " + note if note else "")
249
+
250
+
251
+ def routing_baseline(facade):
252
+ """(shares, source, stated, early_mix) for realized routing when the user
253
+ has no stated baseline file: the mix captured at install, else the frozen
254
+ baseline (stable, and the same one the transformation card uses), else the
255
+ earliest days still in the ledger, which move if the ledger is rebuilt.
256
+ """
257
+ try:
258
+ snap = _read_json(facade.SNAPSHOT_DIR / "snapshot_before.json") or {}
259
+ mix = snap.get("model_mix") or {}
260
+ shares = (mix.get("shares") or {}) if mix.get("activity_basis") == 1 else {}
261
+ if shares:
262
+ return shares, "snapshot", False, None
263
+ except Exception:
264
+ pass
265
+ try:
266
+ frozen = _read_json(facade.SNAPSHOT_DIR / "baseline_state.json") or {}
267
+ shares = frozen.get("model_shares")
268
+ if (frozen.get("activity_basis") == 1 and isinstance(shares, dict)
269
+ and any(isinstance(v, (int, float)) and v > 0 for v in shares.values())):
270
+ return (dict(shares), "frozen_baseline",
271
+ frozen.get("opus_share_source") == "pretool_baseline", None)
272
+ except Exception:
273
+ pass
274
+ early = facade._earliest_model_mix()
275
+ if early:
276
+ return early["shares"], "history", False, early
277
+ return None, None, False, None
278
+
279
+
280
+ def _routing_window(facade, source):
281
+ if source == "snapshot":
282
+ snap = _read_json(facade.SNAPSHOT_DIR / "snapshot_before.json") or {}
283
+ end = _day(snap.get("timestamp"))
284
+ return (_iso(end - timedelta(days=ROUTING_HISTORY_DAYS)), _iso(end)) if end else (None, None)
285
+ if source == "frozen_baseline":
286
+ window = (_read_json(facade.SNAPSHOT_DIR / "baseline_state.json") or {}).get("window") or {}
287
+ return window.get("start"), window.get("end")
288
+ if source == "history":
289
+ first = _day((facade._earliest_model_mix() or {}).get("first_date"))
290
+ return (_iso(first), _iso(first + timedelta(days=ROUTING_HISTORY_DAYS))) if first else (None, None)
291
+ return None, None
292
+
293
+
294
+ def routing(facade, result):
295
+ """Provenance of the routing estimate's baseline mix, with display copy."""
296
+ try:
297
+ result = result or {}
298
+ source = result.get("baseline_source")
299
+ if not source:
300
+ return None
301
+ try:
302
+ pct = "%d%%" % round(float(result.get("baseline_opus_share") or 0) * 100)
303
+ except (TypeError, ValueError):
304
+ pct = ""
305
+ if source == "pretool_baseline" or result.get("baseline_stated"):
306
+ return {"source": source, "kind": "stated", "coverage": "stated",
307
+ "lead": "At your stated %s Opus baseline." % pct,
308
+ "short": "assuming %s Opus before Token Optimizer" % pct,
309
+ "ledger": "Estimated routing, at your stated %s Opus baseline" % pct}
310
+ install = install_evidence(facade)
311
+ if source == "snapshot" and install.get("source") == "snapshot":
312
+ # The mix was read from the days before the first-run snapshot.
313
+ start, end = _routing_window(facade, source)
314
+ cov = window_coverage(start, end, {"date": None, "source": None})
315
+ cov.update(coverage="pre_install", install_date=install["date"], install_source="snapshot")
316
+ else:
317
+ cov = window_coverage(*_routing_window(facade, source), install)
318
+ span = _span(cov)
319
+ when = " from %s" % span if span else ""
320
+ state = cov["coverage"]
321
+ if state == "pre_install":
322
+ lead = "Compared with your measured model mix before install (%s Opus%s)." % (pct, when)
323
+ short = "against your measured %s Opus mix before install" % pct
324
+ elif state in ("post_install", "partial"):
325
+ lead = ("Compared with your earliest measured model mix (%s Opus%s). Token Optimizer was "
326
+ "already running then (installed %s), so this is the shift since that period and "
327
+ "understates the shift since install." % (pct, when, cov["install_date"]))
328
+ short = ("against your earliest measured mix, %s Opus%s, with Token Optimizer already "
329
+ "running" % (pct, when))
330
+ else:
331
+ lead = ("Compared with your earliest measured model mix (%s Opus%s). The install date is "
332
+ "not on record, so it is not known whether Token Optimizer was already running "
333
+ "then." % (pct, when))
334
+ short = "against your earliest measured mix, %s Opus%s" % (pct, when)
335
+ cov.update(source=source, kind="measured", lead=lead, short=short,
336
+ ledger="Estimated routing, " + short)
337
+ return cov
338
+ except Exception:
339
+ return None