@alexgreensh/token-optimizer 5.13.72 → 5.13.74

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 (39) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -8
  4. package/hooks/sessionstart_runner.py +25 -0
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/assets/dashboard.html +20 -7
  7. package/skills/token-optimizer/assets/savings_story.js +10 -6
  8. package/skills/token-optimizer/references/cli-reference.md +9 -0
  9. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -2
  10. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +3 -1
  11. package/skills/token-optimizer/scripts/_measure/cache_policy.py +2 -79
  12. package/skills/token-optimizer/scripts/_measure/cli.py +24 -0
  13. package/skills/token-optimizer/scripts/_measure/continuity.py +12 -0
  14. package/skills/token-optimizer/scripts/_measure/daemon.py +77 -15
  15. package/skills/token-optimizer/scripts/_measure/install_baseline.py +157 -0
  16. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -3
  17. package/skills/token-optimizer/scripts/_measure/mod_action_diagnostics.py +24 -0
  18. package/skills/token-optimizer/scripts/_measure/mod_action_selftest.py +33 -0
  19. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +4 -4
  20. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +2 -2
  21. package/skills/token-optimizer/scripts/_measure/nudge_followthrough.py +334 -0
  22. package/skills/token-optimizer/scripts/_measure/own_price_card.py +3 -0
  23. package/skills/token-optimizer/scripts/_measure/pilot_report.py +349 -0
  24. package/skills/token-optimizer/scripts/_measure/pricing.py +15 -414
  25. package/skills/token-optimizer/scripts/_measure/quality_archive.py +5 -10
  26. package/skills/token-optimizer/scripts/_measure/routing_credit.py +60 -0
  27. package/skills/token-optimizer/scripts/_measure/routing_default.py +374 -0
  28. package/skills/token-optimizer/scripts/_measure/routing_savings.py +368 -0
  29. package/skills/token-optimizer/scripts/_measure/runway_all_in.py +42 -0
  30. package/skills/token-optimizer/scripts/_measure/savings.py +29 -247
  31. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  32. package/skills/token-optimizer/scripts/_measure/session_activity.py +128 -0
  33. package/skills/token-optimizer/scripts/_measure/ttl_period.py +59 -0
  34. package/skills/token-optimizer/scripts/cloud_kit.py +1 -4
  35. package/skills/token-optimizer/scripts/codex_doctor.py +1 -10
  36. package/skills/token-optimizer/scripts/hermes_doctor.py +1 -10
  37. package/skills/token-optimizer/scripts/hermes_install.py +1 -10
  38. package/skills/token-optimizer/scripts/injection.py +5 -2
  39. package/skills/token-optimizer/scripts/measure.py +4 -4
@@ -1231,7 +1231,7 @@ def _session_model_reprice(conn, cutoff, session_uuid=None, by_day=None, unprice
1231
1231
  return deltas, repriced_tokens, unmeasured_tokens
1232
1232
 
1233
1233
 
1234
- def _model_mix_shares(days=None, since=None):
1234
+ def _model_mix_shares(days=None, since=None, *, until=None):
1235
1235
  """Return {model: share_fraction} of total tokens over the window, + total.
1236
1236
 
1237
1237
  Reads model_daily (per-day per-model token totals). Shares sum to ~1.0.
@@ -1259,8 +1259,8 @@ def _model_mix_shares(days=None, since=None):
1259
1259
  out["activity_coverage"] = _measure_facade.activity_coverage(conn)
1260
1260
  rows = conn.execute(
1261
1261
  "SELECT model, COALESCE(SUM(total_tokens),0) FROM model_daily "
1262
- "WHERE date >= ? GROUP BY model",
1263
- (cutoff,),
1262
+ "WHERE date >= ? AND (? IS NULL OR date < ?) GROUP BY model",
1263
+ (cutoff, until, until),
1264
1264
  ).fetchall()
1265
1265
  finally:
1266
1266
  conn.close()
@@ -1538,7 +1538,7 @@ def _add_routing_buckets(dst, parts):
1538
1538
  dst["cache_create_5m"] = dst.get("cache_create_5m", 0) + m5
1539
1539
 
1540
1540
 
1541
- def _routing_pending_sessions(days=None, since=None):
1541
+ def _routing_pending_sessions(days=None, since=None, *, until=None):
1542
1542
  """Window sessions whose usage collect has not finished re-reading.
1543
1543
 
1544
1544
  A row counts when its transcript is still on disk and either its per-day
@@ -1563,7 +1563,8 @@ def _routing_pending_sessions(days=None, since=None):
1563
1563
  if "last_activity_day" in columns else "NULLIF(date, '')")
1564
1564
  rows = conn.execute(
1565
1565
  "SELECT jsonl_path, daily_usage_json, "
1566
- + ("usage_parser_version" if has_version else "NULL") + "," + last_activity +
1566
+ + ("usage_parser_version" if has_version else "NULL") + "," + last_activity
1567
+ + (",first_activity_day" if "first_activity_day" in columns else ",NULL") +
1567
1568
  " FROM session_log WHERE jsonl_path LIKE '%.jsonl'",
1568
1569
  ()).fetchall()
1569
1570
  finally:
@@ -1571,7 +1572,9 @@ def _routing_pending_sessions(days=None, since=None):
1571
1572
  projects = _measure_facade.os.path.normcase(_measure_facade.os.path.abspath(str(_measure_facade.CLAUDE_DIR / "projects"))) + _measure_facade.os.sep
1572
1573
  walked = not _measure_facade._use_codex_session_adapter()
1573
1574
  pending = 0
1574
- for path, du_raw, version, last_day in rows:
1575
+ for path, du_raw, version, last_day, first_day in rows:
1576
+ if until and first_day and str(first_day)[:10] >= until:
1577
+ continue
1575
1578
  daily_missing = du_raw is None
1576
1579
  stale = (has_version and walked
1577
1580
  and (version is None or int(version) < _measure_facade._USAGE_PARSER_VERSION)
@@ -1595,7 +1598,7 @@ def _routing_pending_sessions(days=None, since=None):
1595
1598
  return 0
1596
1599
 
1597
1600
 
1598
- def _routing_usage_by_model(days=None, since=None):
1601
+ def _routing_usage_by_model(days=None, since=None, *, until=None):
1599
1602
  """Token usage per model id and token class over the window.
1600
1603
 
1601
1604
  Returns {model_id: {class: tokens}} (classes in _ROUTING_CLASSES). Source per
@@ -1632,13 +1635,13 @@ def _routing_usage_by_model(days=None, since=None):
1632
1635
  undated_day = ""
1633
1636
  for day, models in du.items():
1634
1637
  day = undated_day if day == _measure_facade.UNDATED_USAGE_KEY else day
1635
- if not isinstance(models, dict) or str(day) < cutoff:
1638
+ if not isinstance(models, dict) or str(day) < cutoff or (until and str(day) >= until):
1636
1639
  continue
1637
1640
  for model, parts in models.items():
1638
1641
  if isinstance(parts, dict) and _measure_facade._normalize_model_name(model):
1639
1642
  _measure_facade._add_routing_buckets(out.setdefault(model, {}), parts)
1640
1643
  continue
1641
- if not first_day or first_day != last_day or first_day < cutoff:
1644
+ if not first_day or first_day != last_day or first_day < cutoff or (until and first_day >= until):
1642
1645
  continue
1643
1646
  totals = _measure_facade._safe_json_dict(amu_raw) or _measure_facade._safe_json_dict(mu_raw)
1644
1647
  mb = _measure_facade._safe_json_dict(mb_raw)
@@ -1758,409 +1761,7 @@ def set_pretool_baseline(args):
1758
1761
  print(f" [Error] Could not write baseline: {e}")
1759
1762
 
1760
1763
 
1761
- def _compute_model_routing_savings(days=None, since=None):
1762
- """Model-routing savings: realized (mix shift vs baseline) + potential (remaining Opus).
1763
-
1764
- REALIZED: compare current model mix against the install-era baseline (snapshot
1765
- model_mix, else the earliest model_daily window). If the user moved tokens off
1766
- expensive models, the counterfactual cost (current volume spread over the
1767
- baseline mix) minus the current cost, both on one standardized price
1768
- schedule, is the estimated saving. This is the pillar that can show a
1769
- realized win (e.g. Opus 94% -> 67%).
1770
- Models priced above the baseline's costliest model (a premium model the user
1771
- chose) are left out of the comparison and the rest renormalized, so they do not
1772
- cancel a real shift toward lighter models; `premium_share` and
1773
- `premium_cost_usd` report them separately.
1774
-
1775
- POTENTIAL: an assumption, not a measurement. A fixed share
1776
- (`routable_fraction`) of Opus fresh input and output is priced at the
1777
- Opus-to-Sonnet API rate delta. Opus usage without a class split is left out
1778
- and counted in `potential_unsplit_excluded_tokens`. Cache reads and
1779
- writes represent main-session history: switching models rebuilds that cache,
1780
- while routine subagent work carries its own smaller context. The result is
1781
- shown separately from concrete opportunities.
1782
-
1783
- Realized routing prices fresh input, cache creation, cache reads and output
1784
- by class. Usage without a class split stays outside both comparisons and
1785
- their coverage, and is reported as `unsplit_tokens`. Potential uses the model's
1786
- own generation card for fresh input and output, and the newest Sonnet card
1787
- for its target.
1788
- The class split comes from per-day, per-model session usage.
1789
-
1790
- Realized routing is a standardized family comparison: the remaining work's
1791
- class volumes per current family, and the same class volumes spread over the
1792
- baseline family shares, are valued on one fixed schedule (the newest card of
1793
- each family's tier) chosen independently of the window's volumes. A
1794
- generation change inside a family therefore cannot create routing credit.
1795
- The exact-card cost of the same work and its gap to the standardized value
1796
- are reported separately (`actual_cost_usd`, `generation_price_delta_usd`).
1797
- The schedule is assumed because the frozen baseline records no generations,
1798
- so the result is labelled "estimated".
1799
-
1800
- Models with no exact rate card are unpriced, not free (an unknown Claude
1801
- generation does not borrow its family's price): they are left out of the
1802
- comparison and reported as `unpriced_models`, `unpriced_tokens` and
1803
- `unpriced_share`. Explicitly free tiers (":free") are left out the same way
1804
- and reported as `free_models`.
1805
- Labelled estimated (realized) and opportunity (potential). Never raises.
1806
- """
1807
- # `zero` is returned only on no-data / error paths (no current mix, no
1808
- # baseline, or an exception). Label it "unavailable" so a $0 here reads as
1809
- # "couldn't compute" rather than a measured zero -- the success return below
1810
- # sets its own evidence="estimated" when comparable work remains.
1811
- _measure_facade = _compat.facade()
1812
- zero = {
1813
- "realized_cost_usd": 0.0, "potential_cost_usd": 0.0,
1814
- "potential_tokens": 0, "potential_tokens_monthly": 0,
1815
- "potential_billable_tokens": 0, "potential_by_class": {}, "unsplit_tokens": 0,
1816
- "potential_unsplit_excluded_tokens": 0,
1817
- "premium_models": [], "premium_share": 0.0, "premium_cost_usd": 0.0,
1818
- "unpriced_models": [], "unpriced_tokens": 0, "unpriced_share": 0.0,
1819
- "free_models": [], "free_tokens": 0,
1820
- "compared_share": 0.0,
1821
- "baseline_rate_basis": {}, "baseline_reference_priced": [],
1822
- "standardized_baseline_cost_usd": 0.0, "standardized_actual_cost_usd": 0.0,
1823
- "actual_cost_usd": 0.0, "generation_price_delta_usd": 0.0,
1824
- "baseline_opus_share": 0.0, "current_opus_share": 0.0,
1825
- "measured_baseline_opus_share": None,
1826
- "measured_baseline_realized_cost_usd": None,
1827
- "measured_baseline_source": None,
1828
- "measured_baseline_first_date": None,
1829
- "baseline_source": None, "evidence": "unavailable",
1830
- }
1831
- try:
1832
- current = _measure_facade._model_mix_shares(days=days, since=since)
1833
- zero["activity_coverage"] = current.get("activity_coverage", {"complete": True, "undated_sessions": 0})
1834
- cur_shares = current.get("shares", {})
1835
- cur_total = int(current.get("total_tokens", 0) or 0)
1836
- if not cur_shares or cur_total <= 0:
1837
- return zero
1838
-
1839
- # Baseline mix: the user's stated pre-TO baseline first, then the mix
1840
- # captured at install, the frozen baseline, else earliest history.
1841
- baseline_shares, baseline_source, baseline_stated, early_mix = None, None, False, None
1842
- explicit = _measure_facade._pretool_baseline_mix()
1843
- if explicit:
1844
- baseline_shares, baseline_source, baseline_stated = explicit, "pretool_baseline", True
1845
- else:
1846
- from . import baseline_provenance
1847
- baseline_shares, baseline_source, baseline_stated, early_mix = baseline_provenance.routing_baseline(_measure_facade)
1848
- if not baseline_shares:
1849
- return zero
1850
-
1851
- # While collect is still re-reading window sessions (an older usage
1852
- # parser, or per-day usage not yet rebuilt), their per-class usage is
1853
- # incomplete and the figure would move pass to pass. Report the count
1854
- # instead of a number.
1855
- pending = _measure_facade._routing_pending_sessions(days=days, since=since)
1856
- if pending:
1857
- return {**zero, "evidence": "pending", "pending_sessions": pending,
1858
- "baseline_source": baseline_source}
1859
-
1860
- # Rows of per-model, per-class usage. When the DB holds none (adapters
1861
- # that only record model totals), the model-daily mix stands in as
1862
- # unsplit tokens, reported outside comparison coverage.
1863
- usage = _measure_facade._routing_usage_by_model(days=days, since=since)
1864
- from_rows = bool(usage)
1865
- if not from_rows:
1866
- usage = {m: {"unsplit": share * cur_total} for m, share in cur_shares.items()}
1867
-
1868
- # Mix keys from the model-daily fallback are already family buckets.
1869
- fam_of = {m: (_measure_facade._normalize_model_name(m) if from_rows else m) for m in usage}
1870
- rates_cache = {}
1871
-
1872
- def _rates(model):
1873
- _measure_facade = _compat.facade()
1874
- if model not in rates_cache:
1875
- rates_cache[model] = _measure_facade._routing_class_rates(model)
1876
- return rates_cache[model]
1877
-
1878
- # Only a model with an exact rate card is compared. A model with no card
1879
- # is unpriced (not free) and an explicitly free tier is not credited as a
1880
- # saving: both keep their token counts, are reported, and stay out of
1881
- # every mix and cost below.
1882
- priced_usage = {}
1883
- unpriced_by_model = {}
1884
- free_by_model = {}
1885
- unsplit_tokens = 0.0
1886
- potential_unsplit_excluded = 0.0
1887
- for m, classes in usage.items():
1888
- if not fam_of[m]:
1889
- continue
1890
- if _rates(m) is not None:
1891
- unsplit_tokens += classes.get("unsplit", 0)
1892
- if fam_of[m] == "opus":
1893
- potential_unsplit_excluded += classes.get("unsplit", 0)
1894
- split = {k: v for k, v in classes.items() if k != "unsplit"}
1895
- if sum(split.values()) > 0:
1896
- priced_usage[m] = split
1897
- continue
1898
- tokens = sum(classes.get(k, 0) for k in _measure_facade._ROUTING_CLASSES)
1899
- bucket = free_by_model if _measure_facade._routing_model_status(m) == "free" else unpriced_by_model
1900
- bucket[m] = bucket.get(m, 0) + tokens
1901
-
1902
- fam_models = {}
1903
- for m in priced_usage:
1904
- fam_models.setdefault(fam_of[m], []).append(m)
1905
- fam_classes = {}
1906
- class_totals = {k: 0.0 for k in _measure_facade._ROUTING_CLASSES}
1907
- for fam, ms in fam_models.items():
1908
- dst = fam_classes[fam] = {k: 0.0 for k in _measure_facade._ROUTING_CLASSES}
1909
- for m in ms:
1910
- for k in _measure_facade._ROUTING_CLASSES:
1911
- dst[k] += priced_usage[m].get(k, 0)
1912
- class_totals[k] += priced_usage[m].get(k, 0)
1913
- pooled = sum(class_totals.values())
1914
-
1915
- def _unpriced_report():
1916
- _measure_facade = _compat.facade()
1917
- return [mid for mid, _t in sorted(unpriced_by_model.items(), key=lambda kv: -kv[1])]
1918
-
1919
- def _free_report():
1920
- _measure_facade = _compat.facade()
1921
- return [mid for mid, _t in sorted(free_by_model.items(), key=lambda kv: -kv[1])]
1922
-
1923
- unpriced_tokens = int(sum(unpriced_by_model.values()))
1924
- free_tokens = int(sum(free_by_model.values()))
1925
-
1926
- def _coverage_fields():
1927
- _measure_facade = _compat.facade()
1928
- total = unpriced_tokens + free_tokens + pooled + unsplit_tokens
1929
- return {
1930
- "unpriced_models": _unpriced_report(), "unpriced_tokens": unpriced_tokens,
1931
- "unpriced_share": round(unpriced_tokens / total, 4) if total > 0 else 0.0,
1932
- "free_models": _free_report(), "free_tokens": free_tokens,
1933
- "unsplit_tokens": int(round(unsplit_tokens)),
1934
- "potential_unsplit_excluded_tokens": int(round(potential_unsplit_excluded)),
1935
- "baseline_source": baseline_source,
1936
- }
1764
+ def _compute_model_routing_savings(days=30, since=None):
1765
+ from . import routing_credit
1766
+ return routing_credit.compute(days=days, since=since)
1937
1767
 
1938
- if pooled <= 0:
1939
- return {**zero, **_coverage_fields()}
1940
-
1941
- # STANDARDIZED ROUTING VALUATION. Realized routing measures a shift of work
1942
- # between model families, so both arms are valued on one fixed price
1943
- # schedule: one rate per family and token class, chosen without looking at
1944
- # how much of that family ran in the window. The frozen baseline records
1945
- # shares by family only (no generation), so the schedule is a documented
1946
- # reference-card scenario: each family at the newest generation card of
1947
- # its tier (legacy Sonnet counts as Sonnet; a provider model stands for
1948
- # itself). It is the same for present and absent families, so one token of
1949
- # any generation changes the result only by that token's own contribution,
1950
- # and a generation change within a family cannot become routing credit.
1951
- # What the work actually cost at the exact cards used is reported
1952
- # separately (`actual_cost_usd`, `generation_price_delta_usd`). Because the
1953
- # scenario is assumed, the result is labelled estimated. A baseline that
1954
- # recorded generations would replace the reference card in
1955
- # `_fixed_family_rates` for the families it covers.
1956
- fam_rate_cache = {}
1957
- fam_rate_basis = {}
1958
-
1959
- def _fixed_family_rates(fam):
1960
- _measure_facade = _compat.facade()
1961
- if fam in fam_rate_cache:
1962
- return fam_rate_cache[fam]
1963
- ref_model = _measure_facade._routing_reference_model(fam)
1964
- out = _rates(ref_model)
1965
- if out is None and fam_models.get(fam):
1966
- # No reference card for a family that did run: its lowest-sorted
1967
- # model id stands in, so the choice never depends on input order.
1968
- ref_model = sorted(fam_models[fam])[0]
1969
- out = _rates(ref_model)
1970
- if out is not None:
1971
- fam_rate_basis[fam] = f"reference:{ref_model}"
1972
- fam_rate_cache[fam] = out
1973
- return out
1974
-
1975
- def _renormalized(shares):
1976
- _measure_facade = _compat.facade()
1977
- kept = {f: s for f, s in shares.items() if s and s > 0 and _fixed_family_rates(f) is not None}
1978
- total = sum(kept.values())
1979
- return {f: s / total for f, s in kept.items()} if total > 0 else {}
1980
-
1981
- base_priced = _renormalized(baseline_shares)
1982
-
1983
- # Effective $/MTok of a family under the window's own class mix.
1984
- def _family_price(f):
1985
- _measure_facade = _compat.facade()
1986
- if pooled <= 0:
1987
- return 0.0
1988
- r = _fixed_family_rates(f)
1989
- return sum(class_totals[k] * r[k] for k in _measure_facade._ROUTING_CLASSES) / pooled
1990
-
1991
- # Models priced above the most expensive model of the baseline are the
1992
- # user's own choice, not routing: they are taken out of the comparison
1993
- # so it measures the shift toward lighter models. Their share and cost
1994
- # are reported separately. A model must be dearer than the baseline's
1995
- # costliest family on the window's pooled mix AND on the output card:
1996
- # cache-read rates alone do not rank tiers across generations (Sonnet 4.6
1997
- # reads cache at $0.30, Opus 5.5 at $0.20), so a lighter older model is
1998
- # never mistaken for a premium one.
1999
- ceiling_fam = max(base_priced, key=_family_price, default=None)
2000
- baseline_ceiling = _family_price(ceiling_fam) if ceiling_fam else 0.0
2001
- ceiling_output = _fixed_family_rates(ceiling_fam)["output"] if ceiling_fam else 0.0
2002
- premium = sorted(
2003
- f for f in fam_classes
2004
- if _family_price(f) > baseline_ceiling > 0 and _fixed_family_rates(f)["output"] > ceiling_output
2005
- )
2006
- premium_share = sum(cur_shares.get(f, 0.0) for f in premium)
2007
- premium_cost = sum(
2008
- classes.get(k, 0) * _rates(m)[k]
2009
- for m, classes in priced_usage.items() if fam_of[m] in premium
2010
- for k in _measure_facade._ROUTING_CLASSES
2011
- ) / 1_000_000
2012
-
2013
- # REALIZED: the remaining work's class volumes, per current family, valued
2014
- # on the standardized schedule, against the same total class volumes spread
2015
- # over the baseline family shares on that same schedule. Only the shift
2016
- # between families moves the number. Never negative. Premium and unpriced
2017
- # models are outside both arms.
2018
- kept_models = [m for m in priced_usage if fam_of[m] not in premium]
2019
- kept_totals = {k: sum(priced_usage[m].get(k, 0) for m in kept_models) for k in _measure_facade._ROUTING_CLASSES}
2020
- standardized_actual = sum(
2021
- priced_usage[m].get(k, 0) * _fixed_family_rates(fam_of[m])[k]
2022
- for m in kept_models for k in _measure_facade._ROUTING_CLASSES
2023
- ) / 1_000_000
2024
- standardized_baseline = sum(
2025
- kept_totals[k] * sum(s * _fixed_family_rates(f)[k] for f, s in base_priced.items())
2026
- for k in _measure_facade._ROUTING_CLASSES
2027
- ) / 1_000_000 if base_priced else 0.0
2028
- # Exact-card API-equivalent cost of the same work (each model's own card).
2029
- actual_cost = sum(
2030
- priced_usage[m].get(k, 0) * _rates(m)[k] for m in kept_models for k in _measure_facade._ROUTING_CLASSES
2031
- ) / 1_000_000
2032
- realized_cost = max(0.0, standardized_baseline - standardized_actual) if base_priced and kept_models else 0.0
2033
-
2034
- def _realized_for_baseline(shares):
2035
- base = _renormalized(shares or {})
2036
- if not base or not kept_models:
2037
- return 0.0
2038
- baseline_cost = sum(
2039
- kept_totals[k] * sum(s * _fixed_family_rates(f)[k] for f, s in base.items())
2040
- for k in _measure_facade._ROUTING_CLASSES
2041
- ) / 1_000_000
2042
- return max(0.0, baseline_cost - standardized_actual)
2043
-
2044
- measured_baseline = {}
2045
- if baseline_source == "pretool_baseline":
2046
- # The pre-activity migration retains the previously frozen baseline
2047
- # as baseline_state.json.pre-activity-v1[.N] beside the live file;
2048
- # its model_shares are the earliest measured mix, the honest
2049
- # measured alternative to a hand-entered pre-TO baseline.
2050
- archived = None
2051
- try:
2052
- for _ap in sorted(_measure_facade.SNAPSHOT_DIR.glob("baseline_state.json.pre-activity-v1*")):
2053
- try:
2054
- _ad = _measure_facade.json.loads(_ap.read_text(encoding="utf-8"))
2055
- except (_measure_facade.json.JSONDecodeError, OSError, ValueError):
2056
- continue
2057
- _ashares = _ad.get("model_shares") if isinstance(_ad, dict) else None
2058
- if isinstance(_ashares, dict) and _ashares.get("opus"):
2059
- archived = {"shares": _ashares,
2060
- "first_date": (_ad.get("window") or {}).get("start")}
2061
- break
2062
- except OSError:
2063
- archived = None
2064
- if archived:
2065
- measured_baseline = {
2066
- "opus_share": round(float(archived["shares"].get("opus") or 0.0), 4),
2067
- "source": "baseline_state_pre_activity",
2068
- "first_date": archived.get("first_date"),
2069
- "realized_cost_usd": round(_realized_for_baseline(archived["shares"]), 4),
2070
- }
2071
- else:
2072
- if early_mix is None:
2073
- try:
2074
- early_mix = _measure_facade._earliest_model_mix(
2075
- lookback_days=_measure_facade._BASELINE_EARLY_WINDOW_DAYS)
2076
- except Exception:
2077
- early_mix = None
2078
- early_shares = (early_mix or {}).get("shares") or {}
2079
- if early_shares:
2080
- measured_baseline = {
2081
- "opus_share": round(float(early_shares.get("opus", 0.0) or 0.0), 4),
2082
- "source": "history",
2083
- "first_date": (early_mix or {}).get("first_date"),
2084
- "realized_cost_usd": round(_realized_for_baseline(early_shares), 4),
2085
- }
2086
- compared_tokens = sum(kept_totals.values())
2087
- window_tokens = unpriced_tokens + free_tokens + pooled + unsplit_tokens
2088
-
2089
- # POTENTIAL: a fixed share of remaining Opus fresh input and output, priced
2090
- # at each Opus model's own card minus the current Sonnet card. It is
2091
- # computed apart from the realized figure: with no target card the
2092
- # potential is zero and the realized routing above is unaffected. Usage
2093
- # without a class split cannot be told apart as input or output, so it is
2094
- # left out and its count is reported.
2095
- target = _measure_facade._routing_target_model()
2096
- target_rates = _rates(target)
2097
- by_class = {k: {"tokens": 0, "usd": 0.0} for k in _measure_facade._ROUTING_CLASSES}
2098
- for m, classes in priced_usage.items():
2099
- if fam_of[m] != "opus":
2100
- continue
2101
- if target_rates is None:
2102
- continue
2103
- m_rates = _rates(m)
2104
- for k in ("fresh_input", "output"):
2105
- tok = classes.get(k, 0)
2106
- if tok:
2107
- by_class[k]["tokens"] += tok * _measure_facade._ROUTABLE_OPUS_FRACTION
2108
- by_class[k]["usd"] += tok * _measure_facade._ROUTABLE_OPUS_FRACTION * (m_rates[k] - target_rates[k]) / 1_000_000
2109
- potential_cost = max(0.0, sum(v["usd"] for v in by_class.values()))
2110
- potential_tokens = int(round(sum(v["tokens"] for v in by_class.values())))
2111
- potential_tokens_monthly = int(round(potential_tokens / max(days, 1) * 30))
2112
- potential_billable_tokens = int(round(sum(by_class[k]["tokens"] for k in _measure_facade._ROUTING_BILLABLE_CLASSES)))
2113
- opus_share = cur_shares.get("opus", 0.0)
2114
-
2115
- return {
2116
- "activity_coverage": zero["activity_coverage"],
2117
- "realized_cost_usd": round(realized_cost, 4),
2118
- "potential_cost_usd": round(potential_cost, 4),
2119
- # Routable tokens cover observed fresh input and output only.
2120
- "potential_tokens": potential_tokens,
2121
- "potential_tokens_monthly": potential_tokens_monthly,
2122
- "potential_billable_tokens": potential_billable_tokens,
2123
- "potential_token_classes": [k for k in _measure_facade._ROUTING_CLASSES if by_class[k]["tokens"]],
2124
- "potential_by_class": {
2125
- k: {"tokens": int(round(v["tokens"])), "usd": round(v["usd"], 4)}
2126
- for k, v in by_class.items() if v["tokens"] or v["usd"]
2127
- },
2128
- "potential_basis": "api_rate_equivalent",
2129
- "target_model": target,
2130
- "pricing_basis": "per_token_class_generation_card",
2131
- # Premium models (priced above the baseline's costliest model) are the
2132
- # user's own choice: excluded from realized routing, shown here.
2133
- "premium_models": premium,
2134
- "premium_share": round(premium_share, 4),
2135
- "premium_cost_usd": round(premium_cost, 4),
2136
- # Models with no exact rate card (unpriced) and explicitly free tiers are
2137
- # left out of the comparison, never priced at zero or at a stand-in rate.
2138
- **_coverage_fields(),
2139
- "baseline_opus_share": round(baseline_shares.get("opus", 0.0), 4),
2140
- "current_opus_share": round(opus_share, 4),
2141
- "measured_baseline_opus_share": measured_baseline.get("opus_share"),
2142
- "measured_baseline_realized_cost_usd": measured_baseline.get("realized_cost_usd"),
2143
- "measured_baseline_source": measured_baseline.get("source"),
2144
- "measured_baseline_first_date": measured_baseline.get("first_date"),
2145
- "baseline_source": baseline_source, "baseline_stated": baseline_stated,
2146
- "routable_fraction": _measure_facade._ROUTABLE_OPUS_FRACTION,
2147
- # Realized routing is a standardized comparison on a fixed price
2148
- # schedule (newest card per family) in both arms, because the baseline
2149
- # records no generations. That schedule is an assumption, so the
2150
- # result is an estimate. The exact-card cost of the same work and its
2151
- # gap to the standardized valuation are reported apart: the gap is
2152
- # price/generation, never routing.
2153
- "realized_basis": "standardized_reference_card",
2154
- "baseline_rate_basis": {f: fam_rate_basis[f] for f in sorted(set(base_priced) | set(fam_classes)) if f in fam_rate_basis},
2155
- "baseline_reference_priced": sorted(base_priced),
2156
- "standardized_baseline_cost_usd": round(standardized_baseline, 4),
2157
- "standardized_actual_cost_usd": round(standardized_actual, 4),
2158
- "actual_cost_usd": round(actual_cost, 4),
2159
- "generation_price_delta_usd": round(actual_cost - standardized_actual, 4),
2160
- # Share of the window's class tokens inside both arms (premium,
2161
- # unpriced and free models, and unsplit tokens are outside).
2162
- "compared_share": round(compared_tokens / window_tokens, 4) if window_tokens > 0 else 0.0,
2163
- "evidence": "estimated" if compared_tokens > 0 and base_priced else "unavailable",
2164
- }
2165
- except Exception:
2166
- return zero
@@ -5689,7 +5689,7 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
5689
5689
  # "start fresh (context is preserved)" is the stronger remedy than /compact, and
5690
5690
  # firing both would be noise. Only fall back to the /compact nudge if it didn't fire.
5691
5691
  fresh_msg = _measure_facade._maybe_fresh_session_nudge(result, cache_path, quality_data) if result["measured"] else None
5692
- remedy_fired = bool(fresh_msg)
5692
+ nudge_msg = None; remedy_fired = bool(fresh_msg)
5693
5693
  if not fresh_msg and result["measured"]:
5694
5694
  nudge_msg = _measure_facade._maybe_nudge(result, cache_path, quality_data)
5695
5695
  if nudge_msg:
@@ -5709,13 +5709,7 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
5709
5709
  # must survive even if only the fresh nudge fired this turn).
5710
5710
  if system_messages or fresh_msg:
5711
5711
  _measure_facade._write_quality_cache(cache_path, result)
5712
- # ONE JSON object, never a stream of them. Printing N separate
5713
- # {"systemMessage": ...} lines is NDJSON, and a host that parses hook
5714
- # stdout as a single JSON document rejects the whole payload -- Codex
5715
- # fails the hook outright ("hook returned invalid session start JSON
5716
- # output"), losing every message including the ones it could have shown.
5717
- # Joining them costs nothing and both hosts render the result identically.
5718
- _emitted_messages = []
5712
+ _emitted_messages = []; _emit_msgs = True
5719
5713
  if system_messages:
5720
5714
  # Gate the routine informational batch (quality/loop/fill warnings) under
5721
5715
  # context pressure.
@@ -5738,6 +5732,7 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
5738
5732
  if fresh_msg:
5739
5733
  _emitted_messages.append(fresh_msg)
5740
5734
  if _emitted_messages:
5735
+ from . import nudge_followthrough; nudge_followthrough.record_emitted(_measure_facade, _session_id, filepath, quality_data, fresh_msg, nudge_msg if _emit_msgs else None, advisory_msg if _emit_msgs else None)
5741
5736
  try:
5742
5737
  print(_measure_facade.json.dumps({"systemMessage": "\n\n".join(_emitted_messages)}))
5743
5738
  except Exception:
@@ -5767,12 +5762,12 @@ def quality_cache(throttle_seconds=None, warn_threshold=None, quiet=None, sessio
5767
5762
  _size_ok = _warn_tel is not None and _warn_tel["tokens"] >= _measure_facade._SIZE_NUDGE_MIN_TOKENS
5768
5763
  if result["score"] < 50:
5769
5764
  if _size_ok:
5770
- print(f"[Token Optimizer] Quality {result['score']}/100 (critical). /clear with checkpoint.")
5765
+ from . import nudge_followthrough; nudge_followthrough.record_emitted(_measure_facade, _session_id, filepath, quality_data, True, None, None); print(f"[Token Optimizer] Quality {result['score']}/100 (critical). /clear with checkpoint.")
5771
5766
  else:
5772
5767
  print(f"[Token Optimizer] Quality {result['score']}/100 (critical).")
5773
5768
  else:
5774
5769
  if _size_ok:
5775
- print(f"[Token Optimizer] Quality {result['score']}/100. /compact.")
5770
+ from . import nudge_followthrough; nudge_followthrough.record_emitted(_measure_facade, _session_id, filepath, quality_data, None, True, None); print(f"[Token Optimizer] Quality {result['score']}/100. /compact.")
5776
5771
  else:
5777
5772
  print(f"[Token Optimizer] Quality {result['score']}/100.")
5778
5773
  _measure_facade._write_quality_cache(cache_path, result)
@@ -0,0 +1,60 @@
1
+ """Calculate routing credit independently of routing guidance state."""
2
+ from datetime import date
3
+ from . import _compat, routing_default
4
+
5
+
6
+ def routing_enabled_since(data_dir):
7
+ enabled, _ = routing_default.routing_credit_window(data_dir=data_dir)
8
+ try:
9
+ return date.fromisoformat(enabled).isoformat()
10
+ except (ValueError, TypeError):
11
+ return None
12
+
13
+
14
+ def compute(days=30, since=None):
15
+ f = _compat.facade()
16
+ unrestricted = getattr(f, '_routing_unrestricted', None)
17
+ if unrestricted is None:
18
+ from . import routing_savings
19
+ unrestricted = routing_savings.unrestricted
20
+ return unrestricted(days=days, since=since)
21
+
22
+
23
+ def baseline(f):
24
+ """Choose the most specific measured baseline before any stated share."""
25
+ from . import baseline_provenance
26
+
27
+ frozen = f._get_baseline_state() or {}
28
+ shares = frozen.get('model_shares') or {}
29
+ stated_frozen = frozen.get('opus_share_source') == 'pretool_baseline'
30
+ window = frozen.get('window') or {}
31
+ coverage = window.get('coverage')
32
+ if not coverage and window.get('start') and window.get('end'):
33
+ coverage = baseline_provenance.window_coverage(
34
+ window['start'], window['end'], baseline_provenance.install_evidence(f))['coverage']
35
+ if shares and not stated_frozen and coverage == 'pre_install':
36
+ return shares, 'frozen_baseline', False, None
37
+
38
+ snap = baseline_provenance._read_json(f.SNAPSHOT_DIR / 'snapshot_before.json') or {}
39
+ mix = snap.get('model_mix') or {}
40
+ if mix.get('activity_basis') == 1 and mix.get('shares'):
41
+ return mix['shares'], 'snapshot', False, None
42
+
43
+ early = f._earliest_model_mix()
44
+ first = (early or {}).get('first_date')
45
+ install_date = getattr(f, '_install_date', lambda: None)()
46
+ boundary = install_date or str(snap.get('timestamp') or '')[:10] or date.today().isoformat()
47
+ if early and early.get('shares') and (not first or first < boundary):
48
+ return early['shares'], 'history', False, early
49
+
50
+ stated = f._pretool_baseline_mix()
51
+ if stated:
52
+ return stated, 'pretool_baseline', True, None
53
+ if shares and stated_frozen:
54
+ return shares, 'frozen_baseline', True, None
55
+ # Last resort: a window from after install already carries Token
56
+ # Optimizer's effect, so it never outranks a pre-install or stated mix.
57
+ # It is still better than no baseline; it is labeled post_install.
58
+ if shares and window.get('end'):
59
+ return shares, 'frozen_baseline', False, None
60
+ return None, None, False, None