@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) 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 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -952,7 +952,7 @@ def _counted_session_cache_mix(conn, session_uuid, tier_data, memo, rate_key=Non
952
952
  return mix
953
953
 
954
954
 
955
- def _counted_rollup_rows(rows, conn=None, mix_memo=None):
955
+ def _counted_rollup_rows(rows, conn=None, mix_memo=None, *, for_close=False):
956
956
  """Only per-row verified prices are eligible; retain all stored token evidence.
957
957
 
958
958
  A stored row without a current per-turn price keeps its signed repeat-read
@@ -1012,6 +1012,10 @@ def _counted_rollup_rows(rows, conn=None, mix_memo=None):
1012
1012
  or (row["source"] == "mk" and not current)):
1013
1013
  out["estimated_magnitude_events"] += 1
1014
1014
  out["refresh_incomplete_events"] += bool(detail.get("refresh_incomplete"))
1015
+ if for_close:
1016
+ # Persist the unrounded daily amount. The lifetime sum rounds once.
1017
+ out["total_usd"] = out["oneshot_usd"] + out["reread_usd"]
1018
+ return out
1015
1019
  out["oneshot_usd"] = round(out["oneshot_usd"], 6)
1016
1020
  out["oneshot_class_premium_usd"] = round(out["oneshot_class_premium_usd"], 6)
1017
1021
  out["reread_miss_premium_usd"] = round(out["reread_miss_premium_usd"], 6)
@@ -1048,21 +1052,10 @@ def _counted_cumulative_summary(days=None, now=None):
1048
1052
  start = end - _measure_facade.timedelta(days=max(1, int(days))) if days is not None else None
1049
1053
  conn = _measure_facade._init_trends_db()
1050
1054
  try:
1051
- excluded = set()
1052
- if _measure_facade._ensure_counted_views(conn):
1053
- excluded.update(r[0] for r in conn.execute(
1054
- "SELECT 'se:'||id FROM main.savings_events EXCEPT "
1055
- "SELECT 'se:'||id FROM counted_savings_events"))
1056
- excluded.update(r[0] for r in conn.execute(
1057
- "SELECT 'ce:'||id FROM main.compression_events EXCEPT "
1058
- "SELECT 'ce:'||id FROM counted_compression_events"))
1055
+ from . import counted_closes
1056
+ selected, stored, candidates, orphaned = counted_closes.selected_rows(_measure_facade, conn)
1059
1057
  rows = []
1060
- stored = _measure_facade._counted_stored_rows(conn)
1061
- candidates = _measure_facade._counted_candidate_events(conn)
1062
- orphaned = _measure_facade._counted_pricing_v5.orphaned_keys(stored.values(), {c[0] for c in candidates}, conn)
1063
- for row in stored.values():
1064
- if row["event_key"] in excluded or row["event_key"] in orphaned:
1065
- continue
1058
+ for row in selected:
1066
1059
  if start is not None:
1067
1060
  if row["source"] == "mk":
1068
1061
  try:
@@ -1107,8 +1100,7 @@ def _counted_cumulative_summary(days=None, now=None):
1107
1100
  # provisional, so the card reports re-measurement instead of a final
1108
1101
  # figure. Rows with no session can never be re-scored and are left
1109
1102
  # to the coverage notes.
1110
- awaiting = [row for row in rows if row.get("session_uuid")
1111
- and _measure_facade._counted_row_awaits_rescore(row)]
1103
+ awaiting = counted_closes.awaiting_rescore(_measure_facade, rows)
1112
1104
  remeasuring_sessions = len({row["session_uuid"] for row in awaiting})
1113
1105
  media_rows = [row for row in rows if row["source"] == "md"]
1114
1106
  media_priced = [row for row in media_rows if int(row["tokens"] or 0) > 0]
@@ -1228,6 +1220,11 @@ def _dashboard_savings_data(days=None, include_billing_mode=None, fail_open=None
1228
1220
  savings_data["savings_headline"] = savings_headline.build(savings_data)
1229
1221
  except Exception:
1230
1222
  savings_data["savings_headline"] = None
1223
+ try:
1224
+ from . import poc_commands
1225
+ poc_commands.on_savings_refresh(_measure_facade, savings_data)
1226
+ except Exception:
1227
+ pass
1231
1228
  if include_billing_mode:
1232
1229
  try:
1233
1230
  savings_data["billing_mode"] = _measure_facade.keepwarm_billing_mode()
@@ -1297,7 +1294,7 @@ def _net_realized_savings(rows, reprice_deltas):
1297
1294
  # a counterfactual (file not read within the follow-up window).
1298
1295
  for name in ("setup_optimization", "mcp_cap", "hint_followed", "verbosity_steer",
1299
1296
  "resume_lean", "checkpoint_restore", "verbosity_steer_measured",
1300
- "codemap_lookup", "keepwarm_estimated", "nudge_followed"):
1297
+ "codemap_lookup", "keepwarm_estimated", "autocompact_window_estimated", "nudge_followed"):
1301
1298
  entry = popped[name] = by_category.pop(name, None)
1302
1299
  if entry:
1303
1300
  total_tokens -= int(entry.get("tokens_saved", 0) or 0)
@@ -1350,7 +1347,7 @@ def _get_savings_summary(days=None, since=None):
1350
1347
  boundary (e.g. the subscription limit reset). When *since* is None / empty,
1351
1348
  the rolling cutoff is computed from *days* as before.
1352
1349
  """
1353
- _measure_facade = _compat.facade(); from . import keepwarm_economics, mod_fresh_booking, mod_compaction_booking, nudge_followthrough
1350
+ _measure_facade = _compat.facade(); from . import keepwarm_economics, mod_fresh_booking, mod_compaction_booking, nudge_followthrough, autocompact_advice; autocompact_advice.refresh_if_allowed(_measure_facade)
1354
1351
  try:
1355
1352
  conn = _measure_facade._init_trends_db()
1356
1353
  try:
@@ -1368,7 +1365,7 @@ def _get_savings_summary(days=None, since=None):
1368
1365
  # _session_model_reprice.
1369
1366
  unpriced_reprice = {}
1370
1367
  reprice_deltas, repriced_tokens, unmeasured_tokens = _measure_facade._session_model_reprice(
1371
- conn, cutoff, unpriced_out=unpriced_reprice); reprice_deltas.pop("nudge_followed", None)
1368
+ conn, cutoff, unpriced_out=unpriced_reprice); reprice_deltas.pop("nudge_followed", None); reprice_deltas.pop("autocompact_window_estimated", None)
1372
1369
  tier_data = _measure_facade.PRICING_TIERS.get(_measure_facade._load_pricing_tier(), _measure_facade.PRICING_TIERS["anthropic"])
1373
1370
  resume_fix = _measure_facade._counted_pricing_v5.resume_lean_reprice(conn, _measure_facade._counted_table(conn, "savings_events"), cutoff,
1374
1371
  lambda model: _measure_facade._counted_exact_card(model, tier_data))
@@ -1390,16 +1387,17 @@ def _get_savings_summary(days=None, since=None):
1390
1387
 
1391
1388
  daily_avg = total_cost / days if days > 0 else 0.0
1392
1389
 
1393
- return {
1390
+ _summary_out = {
1394
1391
  "total_tokens": total_tokens,
1395
1392
  "total_cost_usd": round(total_cost, 4),
1396
1393
  "total_events": total_events,
1397
1394
  "by_category": by_category,
1395
+ "category_labels": {k: _measure_facade._SAVINGS_CATEGORY_LABELS.get(k, k) for k in by_category},
1398
1396
  "daily_avg_usd": round(daily_avg, 4),
1399
1397
  "period_days": days,
1400
1398
  # A1: one-time first-trim (compare). Reported separately, NEVER summed
1401
1399
  # into the realized total (structural_savings is the ongoing model).
1402
- "one_time_setup": one_time, "keepwarm_estimated": keepwarm_economics.headline_pool(_measure_facade, cutoff), "mod_fresh_estimated": mod_fresh_booking.summary(_measure_facade, cutoff), "mod_compaction_actions": mod_compaction_booking.summary(_measure_facade, cutoff),
1400
+ "one_time_setup": one_time, "keepwarm_estimated": keepwarm_economics.headline_pool(_measure_facade, cutoff), "autocompact_window_estimated": dict(popped['autocompact_window_estimated'], label=autocompact_advice.LABEL) if popped['autocompact_window_estimated'] else None, "mod_fresh_estimated": mod_fresh_booking.summary(_measure_facade, cutoff), "mod_compaction_actions": mod_compaction_booking.summary(_measure_facade, cutoff),
1403
1401
  # U-G: observed-trigger / estimated-magnitude avoided-search from
1404
1402
  # proactive hints. Estimated tier, never in the realized total.
1405
1403
  "hint_followed_estimated": hint_followed_est, "nudge_followed": popped["nudge_followed"],
@@ -1422,23 +1420,19 @@ def _get_savings_summary(days=None, since=None):
1422
1420
  # Nudged replies and their later rereads, net of matched un-nudged
1423
1421
  # replies (U5). Estimated tier; the booked rows are reference only.
1424
1422
  "verbosity_output_estimated": verbosity_output_est,
1425
- # True when at least one event's dollars moved because its event-time
1426
- # model stamp disagreed with its own session's recorded model mix. The
1427
- # figure is then a rate ALLOCATION, not a pure event-time meter, so
1428
- # every consumer must label it "estimated" (see _window_overage_usd).
1423
+ # Event-time vs session-mix allocation disclosure; apply expand_round_trip & feature_net.
1429
1424
  "repriced_to_session_mix": repriced_to_session_mix,
1430
1425
  "reprice_detail": {
1431
1426
  "repriced_tokens": int(repriced_tokens),
1432
- # NOT MEASURED: no joinable session row, so no mix to price
1433
- # against. These keep their event-time price; nothing is invented.
1434
1427
  "unmeasured_tokens": int(unmeasured_tokens),
1435
- # Saved tokens that ran on models with no exact rate card: counted
1436
- # as tokens, priced at zero.
1437
1428
  "unpriced_tokens": int(round(unpriced_reprice.get("tokens", 0))),
1438
1429
  "delta_usd": round(sum(reprice_deltas.values()), 4),
1439
1430
  "basis": "session_log.model_usage_json token-weighted mix",
1440
1431
  },
1441
1432
  }
1433
+ from . import limit_units as _lu
1434
+ _lu.apply_round_trip_and_feature_net(_summary_out, labels=_measure_facade._SAVINGS_CATEGORY_LABELS, conn=None, cutoff=cutoff)
1435
+ return _summary_out
1442
1436
  except Exception:
1443
1437
  return {
1444
1438
  "total_tokens": 0,
@@ -2297,8 +2291,8 @@ def runway_snapshot(days=None, now=None, token_headline=None):
2297
2291
  token_parts = token_headline
2298
2292
  except Exception:
2299
2293
  token_parts = _compat.facade()._headline.token_headline({})
2300
- from . import runway_all_in; conn = _measure_facade._init_trends_db()
2301
- try: direct_pct = runway_all_in.safe_extra_work(_measure_facade, conn, days)
2294
+ from . import runway_all_in, limit_units as _lu; conn = _measure_facade._init_trends_db()
2295
+ try: direct_pct = runway_all_in.safe_extra_work(_measure_facade, conn, days); _lu_plan = _lu.plan_limits_summary(_measure_facade, conn, days, summary=locals().get("token_source"))
2302
2296
  finally: conn.close()
2303
2297
  context_saved = token_parts["total_tokens"]
2304
2298
  context_mult = (consumed + context_saved) / consumed if consumed > 0 else 1.0
@@ -2384,7 +2378,8 @@ def runway_snapshot(days=None, now=None, token_headline=None):
2384
2378
  merged_ctx = float(wm.get("total_cost_usd", 0.0) or 0.0)
2385
2379
  rt = float((wm.get("model_routing") or {}).get("realized_cost_usd", 0.0) or 0.0)
2386
2380
  repriced = bool(wm.get("repriced_to_session_mix"))
2387
- est_add = max(0.0, float((wm.get("resume_lean_verified") or {}).get("cost_saved_usd") or 0.0))
2381
+ est_add = (max(0.0, float((wm.get("resume_lean_verified") or {}).get("cost_saved_usd") or 0.0))
2382
+ + float((wm.get("cold_guard_estimated") or {}).get("cost_saved_usd") or 0.0))
2388
2383
  except Exception:
2389
2384
  pass
2390
2385
  try:
@@ -2416,11 +2411,9 @@ def runway_snapshot(days=None, now=None, token_headline=None):
2416
2411
  pass
2417
2412
  if not counted_window:
2418
2413
  ctx = merged_ctx
2419
- # Fold the estimated-tier levers back into the shown dollar. This
2420
- # flips the tier to "estimated" (est_added below) -- honest: the
2421
- # trigger is counterfactual even though the magnitude is metered.
2414
+ # A signed adjustment makes the window total an estimate.
2422
2415
  ctx += est_add
2423
- est_added = est_add > 0.0
2416
+ est_added = est_add != 0.0
2424
2417
  # The full-workload figure replaces the metered sum only when it
2425
2418
  # is larger: a flat or negative workload month must never hide
2426
2419
  # savings that were actually measured this week.
@@ -2576,10 +2569,8 @@ def runway_snapshot(days=None, now=None, token_headline=None):
2576
2569
  "window_savings_basis": (
2577
2570
  "full workload, exact subscription week" if weekly_full else
2578
2571
  "counted transcript window" if _wk_counted else "flat savings ledger fallback"),
2579
- # period_days scopes the throughput MULTIPLIERS (context/routing), not
2580
- # the per-window dollars: each window now prices overage over its OWN
2581
- # span (weekly = 7d), so the dollars are window-real, not a slice.
2582
- "period_days": days,
2572
+ # period_days scopes throughput multipliers; limit_units uses the same currency on both sides.
2573
+ "period_days": days, "limit_units": _lu_plan,
2583
2574
  "meter_age_s": meters.get("age_s"),
2584
2575
  "meter_ts": meters.get("ts"),
2585
2576
  "meter_stale": meter_stale,
@@ -5888,23 +5879,25 @@ def _action_savings_components(summary, reread=None):
5888
5879
  Observed hints replace the retrieval estimate as soon as a hint fires.
5889
5880
  Opportunity and the separate whole-workload comparison are not additive.
5890
5881
  """
5891
- _measure_facade = _compat.facade(); from . import mod_fresh_booking
5882
+ from . import mod_fresh_booking, savings_story
5883
+ _measure_facade = _compat.facade()
5892
5884
  estimates = {
5893
5885
  key: (0.0 if key in ("verbosity_steer", "verbosity_output_estimated", "resume_lean_estimated", "checkpoint_restore_estimated") else float((((summary.get("structural_detail") or {}).get("estimated") if key == "structural_estimated" else summary.get(key)) or {}).get("cost_saved_usd", 0) or 0))
5894
5886
  for key in (
5895
5887
  "behavioral_estimate", "uncaptured_runtime",
5896
5888
  "contamination_exit", "handover_rerun", "resume_lean_estimated", "resume_lean_verified",
5897
- "checkpoint_restore_estimated", "verbosity_steer", "verbosity_output_estimated", "structural_estimated", "keepwarm_estimated",
5889
+ "checkpoint_restore_estimated", "verbosity_steer", "verbosity_output_estimated", "structural_estimated", "keepwarm_estimated", "autocompact_window_estimated",
5898
5890
  )
5899
5891
  }
5900
- if summary.get("nudge_followed") is not None: estimates["nudge_followed"] = float((summary.get("nudge_followed") or {}).get("cost_saved_usd", 0) or 0)
5892
+ for key in ("nudge_followed", "cold_guard_estimated"):
5893
+ if summary.get(key) is not None:
5894
+ estimates[key] = float(summary[key].get("cost_saved_usd") or 0)
5901
5895
  overhead = ((summary.get("session_effect") or {}).get("overhead") or {}); estimates["mod_fresh_estimated"] = mod_fresh_booking.additive(summary.get("mod_fresh_estimated"), summary.get("handover_rerun"))
5902
5896
  estimates["expand_overhead"] = -max(0.0, float(overhead.get("expand_usd") or 0))
5903
5897
  hints = summary.get("hint_followed") or {}
5904
5898
  avoided_source = "hint_followed" if int(hints.get("events") or 0) > 0 else "retrieval_serve"
5905
5899
  estimates[avoided_source] = float(
5906
5900
  (summary.get(avoided_source) or {}).get("cost_saved_usd", 0) or 0)
5907
- from . import savings_story
5908
5901
  logged = float(summary.get("total_cost_usd", 0) or 0) - savings_story.verbosity_logged(summary)
5909
5902
  routing_data = summary.get("model_routing") or {}
5910
5903
  routing = float(routing_data.get("realized_cost_usd", 0) or 0)
@@ -5954,19 +5947,17 @@ def _get_merged_savings(days=None, since=None):
5954
5947
  come from compression_events. If a key somehow appears in both, savings_events
5955
5948
  wins — compression_events rows are skipped for that key.
5956
5949
  """
5950
+ from . import cold_guard
5957
5951
  _measure_facade = _compat.facade()
5958
5952
  since = since or savings_story.install_anchor()
5959
5953
  savings = _measure_facade._get_savings_summary(days=days, since=since)
5960
5954
  compression = _measure_facade._get_compression_summary(days=days, since=since)
5961
-
5962
5955
  by_category = dict(savings.get("by_category", {}))
5963
5956
  total_tokens = int(savings.get("total_tokens", 0) or 0)
5964
5957
  total_cost = float(savings.get("total_cost_usd", 0.0) or 0.0)
5965
5958
  total_events = int(savings.get("total_events", 0) or 0)
5966
5959
 
5967
- # The compression summary prices each row using its model or session mix.
5968
5960
  fallback_cost_per_mtok = _measure_facade._estimate_compression_cost_per_mtok()
5969
-
5970
5961
  _add_tok, _add_cost, _add_events = _measure_facade._merge_v5_compression(
5971
5962
  by_category, compression.get("by_feature", {}), fallback_cost_per_mtok)
5972
5963
  total_tokens += _add_tok
@@ -6026,9 +6017,14 @@ def _get_merged_savings(days=None, since=None):
6026
6017
  verified_lean = lean_resume_carry.verified_summary(days=days, since=since)
6027
6018
  except Exception:
6028
6019
  verified_lean = None
6029
-
6020
+ for _k, _v in by_category.items():
6021
+ if isinstance(_v, dict):
6022
+ _v.setdefault("label", _measure_facade._SAVINGS_CATEGORY_LABELS.get(_k, _k))
6023
+ from . import limit_units as _lu
6024
+ _fnet = _lu.apply_round_trip_and_feature_net({"by_category": dict(by_category), "total_tokens": total_tokens, "total_cost_usd": total_cost, "total_events": total_events}, labels=_measure_facade._SAVINGS_CATEGORY_LABELS)
6030
6025
  return {
6031
6026
  "resume_lean_verified": verified_lean,
6027
+ "feature_net": _fnet["feature_net"], "round_trip_unknown": savings.get("round_trip_unknown", 0), "expand_round_trip_tokens": savings.get("expand_round_trip_tokens", 0), "expand_round_trip_usd": savings.get("expand_round_trip_usd", 0.0),
6032
6028
  "total_tokens": total_tokens,
6033
6029
  "total_cost_usd": round(total_cost, 4),
6034
6030
  "total_events": total_events,
@@ -6037,6 +6033,7 @@ def _get_merged_savings(days=None, since=None):
6037
6033
  "compression_unpriced_credit_tokens": sum(int(v.get("unpriced_credit_tokens", 0) or 0) for v in by_category.values()),
6038
6034
  "compression_unpriced_debit_tokens": sum(int(v.get("unpriced_debit_tokens", 0) or 0) for v in by_category.values()),
6039
6035
  "by_category": by_category,
6036
+ "category_labels": {k: _measure_facade._SAVINGS_CATEGORY_LABELS.get(k, k) for k in by_category},
6040
6037
  "daily_avg_usd": round(total_cost / max(days, 1), 4),
6041
6038
  "period_days": days,
6042
6039
  "pricing_detail": {
@@ -6086,7 +6083,8 @@ def _get_merged_savings(days=None, since=None):
6086
6083
  # $ is already inside realized tool_archive (re-pops netted); not summed.
6087
6084
  "progressive_disclosure": _measure_facade._progressive_disclosure_summary(days=days),
6088
6085
  # A1: one-time first-trim, surfaced separately, never in the realized total.
6089
- "one_time_setup": savings.get("one_time_setup"), "keepwarm_estimated": savings.get("keepwarm_estimated"), "mod_fresh_estimated": savings.get("mod_fresh_estimated"), "mod_compaction_actions": savings.get("mod_compaction_actions"),
6086
+ "one_time_setup": savings.get("one_time_setup"), "keepwarm_estimated": savings.get("keepwarm_estimated"), "autocompact_window_estimated": savings.get("autocompact_window_estimated"), "mod_fresh_estimated": savings.get("mod_fresh_estimated"), "mod_compaction_actions": savings.get("mod_compaction_actions"),
6087
+ cold_guard.ESTIMATE_KEY: cold_guard.estimate(_measure_facade, days=days, since=since, handover=handover_rerun, mod_fresh=savings.get("mod_fresh_estimated")),
6090
6088
  # U-G: deterministically-triggered avoided-search from proactive hints
6091
6089
  # (observed hint->read), estimated magnitude. Estimated tier, never realized.
6092
6090
  "hint_followed": savings.get("hint_followed_estimated"), "nudge_followed": savings.get("nudge_followed"),
@@ -6148,18 +6146,15 @@ def _savings_since_install():
6148
6146
  # cards agree about what "estimated" contains. cache_drop and
6149
6147
  # output_waste are OPPORTUNITY (avoidable waste TO does not yet prevent),
6150
6148
  # so they are excluded here, along with the unsupported MCP-cap estimate.
6149
+ from . import mod_fresh_booking
6151
6150
  estimated = sum(
6152
6151
  float((full.get(k) or {}).get("cost_saved_usd", 0) or 0)
6153
6152
  for k in (
6154
- "behavioral_estimate", "uncaptured_runtime",
6155
- "contamination_exit", "handover_rerun", "resume_lean_verified",
6153
+ "behavioral_estimate", "uncaptured_runtime", "contamination_exit",
6154
+ "handover_rerun", "resume_lean_verified", "keepwarm_estimated", "autocompact_window_estimated", "nudge_followed", "cold_guard_estimated",
6156
6155
  )
6157
- )
6158
- # Avoided-search: prefer the hint->read estimate (hint_followed; the
6159
- # trigger is observed, the avoided-search magnitude is not metered);
6160
- # fall back to the cohort estimate (retrieval_serve)
6161
- # only before any hint has fired, so the two are never summed — the
6162
- # exact dedup rule the dashboard applies (dashboard.html renderSavings).
6156
+ ) + mod_fresh_booking.additive(full.get("mod_fresh_estimated"), full.get("handover_rerun"))
6157
+ # Avoided-search: prefer hint_followed once any hint has fired, else retrieval_serve.
6163
6158
  hf = full.get("hint_followed") or {}
6164
6159
  rs = full.get("retrieval_serve") or {}
6165
6160
  avoided = hf if int(hf.get("events") or 0) > 0 else rs
@@ -6243,7 +6238,9 @@ def _live_savings_payload(days=None):
6243
6238
  cache_health = {"available": False, "tier": "opportunity"}
6244
6239
  try:
6245
6240
  if isinstance(cache_health, dict):
6241
+ from . import keepwarm_auto
6246
6242
  cache_health["keepwarm"] = _measure_facade.keepwarm_cache_health_block(days=days)
6243
+ cache_health["keepwarm_auto"] = keepwarm_auto.health_block(_measure_facade)
6247
6244
  except Exception:
6248
6245
  pass
6249
6246
  # Window/runway card (5h/7d): include it in the LIVE payload so an open dashboard
@@ -6275,10 +6272,9 @@ def _live_savings_payload(days=None):
6275
6272
  def _headline_tripwire(measured_usd, events, days):
6276
6273
  """Flag a measured-savings collapse that activity does not explain.
6277
6274
 
6278
- Keeps one reading per day. If the measured total fell below half of the
6279
- most recent earlier reading while the number of savings events stayed at
6280
- 70%+ of it, the likely cause is a calculation change, not less saving, and
6281
- a message is returned so the report says so instead of quietly shrinking.
6275
+ Keeps one reading per day. If the measured total fell more than 10% from
6276
+ the most recent earlier reading while at least 90% of the events remain,
6277
+ return a message asking the user to report the possible calculation change.
6282
6278
  Returns None otherwise. Never raises."""
6283
6279
  _measure_facade = _compat.facade()
6284
6280
  try:
@@ -6295,8 +6291,8 @@ def _headline_tripwire(measured_usd, events, days):
6295
6291
  hist[key] = rows[-14:]
6296
6292
  _measure_facade._write_baseline_state(path, hist)
6297
6293
  if (prior and float(prior.get("usd") or 0) >= 20
6298
- and measured_usd < 0.5 * float(prior["usd"])
6299
- and events >= 0.7 * int(prior.get("events") or 0)):
6294
+ and measured_usd < 0.9 * float(prior["usd"])
6295
+ and events >= 0.9 * int(prior.get("events") or 0)):
6300
6296
  return (f"Measured savings fell from ${float(prior['usd']):,.0f} ({prior['date']}) to "
6301
6297
  f"${measured_usd:,.0f} while activity held steady. That usually means a "
6302
6298
  f"calculation change, not less saving. Please report it.")
@@ -6325,10 +6321,11 @@ def _reread_savings_for_window(days):
6325
6321
 
6326
6322
  def savings_report(days=None, as_json=None):
6327
6323
  """Display savings from logged actions and the counted repeat-read cohort."""
6328
- _measure_facade = _compat.facade()
6324
+ from . import cold_guard
6325
+ _measure_facade = _compat.facade(); from . import autocompact_advice; autocompact_advice.refresh_if_allowed(_measure_facade, explicit=True)
6329
6326
  summary = _measure_facade._get_merged_savings(days=days)
6330
- # Use the same stored removal cohort as the dashboard. Its counted benefit
6331
- # survives transcript rotation and never needs another transcript walk.
6327
+ cold_guard.on_savings_refresh(_measure_facade, summary)
6328
+ # Use the dashboard's stored removal cohort, which survives transcript rotation.
6332
6329
  try:
6333
6330
  summary["counted_period"] = _measure_facade._counted_cumulative_summary(days=days)
6334
6331
  except Exception:
@@ -6339,6 +6336,9 @@ def savings_report(days=None, as_json=None):
6339
6336
  summary["action_savings"] = _measure_facade._action_savings_components(
6340
6337
  summary, summary["reread_avoided"])
6341
6338
 
6339
+ from . import counted_headline
6340
+ summary["counted_headline"] = counted_headline.build(_measure_facade)
6341
+ summary["overall_headline"] = overall = counted_headline.build_overall(_measure_facade)
6342
6342
  if as_json:
6343
6343
  print(_measure_facade.json.dumps(summary, indent=2))
6344
6344
  return
@@ -6377,10 +6377,14 @@ def savings_report(days=None, as_json=None):
6377
6377
  _est_cents = _shown["estimates_cents"]
6378
6378
  _money = _measure_facade._format_cents
6379
6379
 
6380
- print("\n Token Optimizer Savings Report")
6380
+ since_display = (overall or summary["counted_headline"])["display"]
6381
+ print(since_display["long"] if since_display else "Since-install savings are still being counted.")
6382
+ print(f"\n Last {days} days ({start} to {end})")
6381
6383
  print(f" {'=' * 58}")
6382
- print(f" Period: Last {days} days ({start} to {end})")
6383
6384
  print(_compat.facade()._headline.cli_headline(summary["token_headline"], days, summary.get("session_effect")))
6385
+ keepwarm = summary.get("keepwarm_estimated")
6386
+ if keepwarm and keepwarm.get("events"):
6387
+ print(f" Keep-warm net, last {days} days: {_measure_facade._signed_usd(keepwarm['cost_saved_usd'])} estimated at API rates.")
6384
6388
 
6385
6389
  # Headline transformation. With the session-weight pool live it is the
6386
6390
  # work-normalized (per-API-call, constant-price) figure; otherwise the legacy
@@ -6710,8 +6714,8 @@ def savings_report(days=None, as_json=None):
6710
6714
  label = "retrieval"
6711
6715
  print(f" + est. avoided search ({label}): ~${_money(_est_cents[avoided_source])}{per} "
6712
6716
  f"({detail}) [estimated]")
6713
-
6714
- print(f" = ALL IN: ~${all_in}{per} (measured + modeled + estimated)")
6717
+ cold_guard.print_estimate(summary, _est_cents, _money, per)
6718
+ from . import autocompact_advice; autocompact_advice.print_savings_line(summary, _est_cents, per, _money); print(f" = ALL IN: ~${all_in}{per} (measured + modeled + estimated)")
6715
6719
  if routing_pending:
6716
6720
  print(" i ALL IN leaves out model routing; the assumption stays separate.")
6717
6721
  if summary["action_savings"].get("reread_pricing_complete") is False:
@@ -6720,16 +6724,6 @@ def savings_report(days=None, as_json=None):
6720
6724
  net_total = _mo(summary["action_savings"]["net_total_usd"])
6721
6725
  print(f" i signed adjustments give a net total of ~${net_total:.2f}{per}; "
6722
6726
  "the headline has a $0 floor")
6723
- try:
6724
- since = _measure_facade._savings_since_install()
6725
- except Exception:
6726
- since = None
6727
- since_all_in = (since or {}).get("all_in") or {}
6728
- if float(since_all_in.get("total_usd") or 0) > 0:
6729
- so_far = " so far" if since_all_in.get("routing_pending") or since_all_in.get("remeasuring") else ""
6730
- print(f" = SINCE INSTALL ({since['install_date']}, {since['days']} days): "
6731
- f"~${since_all_in['total_usd']:,.2f}{so_far} (same parts, added up)")
6732
-
6733
6727
  # Informational (not summed): one-time first-trim + progressive disclosure.
6734
6728
  one_time = summary.get("one_time_setup") or {}
6735
6729
  if int(one_time.get("tokens_saved", 0) or 0) > 0:
@@ -1,9 +1,7 @@
1
- """The one savings headline shared by the band, the status line and the dashboard.
1
+ """The rolling 30-day savings headline for older clients.
2
2
 
3
- Computes the contract object (briefs/ux-contract.md) from the same summary the
4
- dashboard Savings hero reads: ``action_savings.total_usd`` plus the model
5
- routing figure, and ``token_headline.total_tokens``. Every surface prints this
6
- one object so they can never quote different dollars for the same window.
3
+ Uses action savings, realized routing, and the token headline for the same window.
4
+ The stable since-install headline lives in counted_headline.
7
5
 
8
6
  usd_week stays null: there is no honest weekly figure yet and 30 days are never
9
7
  prorated into one. display is null whenever no threshold is met, which is how
@@ -67,8 +65,8 @@ def _display(usd_30d, usd_week, tokens_30d, url):
67
65
  kind = "30d"
68
66
  amount = _usd_text(usd_30d)
69
67
  tok = _token_text(tokens_30d)
70
- short = "Saved {}/30d".format(amount)
71
- long = "{} saved in 30 days".format(amount)
68
+ short = "Saved {} in the last 30 days".format(amount)
69
+ long = "{} saved in the last 30 days".format(amount)
72
70
  if tokens_30d > 0:
73
71
  short += " · {} kept out".format(tok)
74
72
  long += " · {} tokens kept out of context".format(tok)
@@ -86,8 +84,7 @@ def build(summary, dashboard_url=DASHBOARD_SAVINGS_URL):
86
84
  """The savings_headline contract object for one savings summary.
87
85
 
88
86
  `summary` is the dashboard's savings payload (or the status-bar headline
89
- built from the same inputs): action_savings, model_routing and
90
- token_headline. Missing pieces read as zero, which lands on display null.
87
+ built from the same inputs). Missing pieces read as zero, which lands on display null.
91
88
  Never raises.
92
89
  """
93
90
  try:
@@ -95,9 +92,6 @@ def build(summary, dashboard_url=DASHBOARD_SAVINGS_URL):
95
92
  action = s.get("action_savings") or {}
96
93
  if not isinstance(action, dict):
97
94
  action = {}
98
- routing = s.get("model_routing") or {}
99
- if not isinstance(routing, dict):
100
- routing = {}
101
95
  headline = s.get("token_headline") or {}
102
96
  if not isinstance(headline, dict):
103
97
  headline = {}
@@ -109,22 +103,24 @@ def build(summary, dashboard_url=DASHBOARD_SAVINGS_URL):
109
103
  if isinstance(nested, dict):
110
104
  headline = nested
111
105
 
112
- total = _usd(action.get("total_usd")) or 0.0
113
- # The hero adds the routing estimate on top of the action total; the
114
- # same figure sits in model_routing.realized_cost_usd (action_savings'
115
- # routing_usd is copied from it).
116
- routing_usd = _usd(routing.get("realized_cost_usd"))
117
- if routing_usd is None:
118
- routing_usd = _usd(action.get("routing_usd"))
119
- usd_30d = total + max(0.0, routing_usd or 0.0)
106
+ routing = s.get("model_routing")
107
+ realized = _usd(routing.get("realized_cost_usd")) if isinstance(routing, dict) else None
108
+ if realized is None:
109
+ realized = _usd(action.get("routing_usd"))
110
+ usd_30d = _usd(action.get("total_usd")) or 0.0
111
+ if realized is not None and realized > 0:
112
+ # Apply the headline floor after routing offsets any action costs.
113
+ action_net = _usd(action.get("net_total_usd"))
114
+ usd_30d = max(0.0, (usd_30d if action_net is None else action_net) + realized)
120
115
  tokens_30d = _count(headline.get("total_tokens"))
121
116
  usd_week = None
122
117
  url = dashboard_url if isinstance(dashboard_url, str) and dashboard_url else DASHBOARD_SAVINGS_URL
123
118
  return {
119
+ "label": "last 30 days",
124
120
  "usd_30d": usd_30d,
125
121
  "usd_week": usd_week,
126
122
  "tokens_30d": tokens_30d,
127
123
  "display": _display(usd_30d, usd_week, tokens_30d, url),
128
124
  }
129
125
  except Exception:
130
- return {"usd_30d": 0.0, "usd_week": None, "tokens_30d": 0, "display": None}
126
+ return {"label": "last 30 days", "usd_30d": 0.0, "usd_week": None, "tokens_30d": 0, "display": None}
@@ -173,8 +173,11 @@ def full_bash_fetch_totals(conn, cutoff, legacy_rows, is_fixture, snapshot_dir=N
173
173
 
174
174
 
175
175
  def keepwarm_reload_value(facade, record):
176
- model = facade._keepwarm_model_norm(record.get('model'))
177
176
  prefix = max(0, int(record.get('prefix_proxy') or 0))
177
+ if record.get('auto_warm') and record.get('ttl_kind') == '1h':
178
+ from .keepwarm_auto import avoided_reload
179
+ return max(0.0, avoided_reload(facade, prefix, record.get('model')))
180
+ model = facade._keepwarm_model_norm(record.get('model'))
178
181
  ttl = record.get('ttl_kind') or 'unknown'
179
182
  write = facade._KEEPWARM_INPUT_USD_PER_TOKEN[model] * facade._KEEPWARM_WRITE_PREMIUM.get(ttl, facade._KEEPWARM_WRITE_PREMIUM['unknown'])
180
183
  return prefix * max(0.0, write - facade._KEEPWARM_CACHE_READ_USD_PER_TOKEN[model])
@@ -184,8 +187,12 @@ def keepwarm_pause_net(facade, record, now, rows):
184
187
  """Value a warm resume, net of actual ping costs in this pause."""
185
188
  sid = str(record.get('session_id') or '')
186
189
  start = float(record.get('ts') or 0)
190
+ pause_key = None
191
+ if record.get('auto_warm'):
192
+ pause_key = record.get('pause_key') or facade._keepwarm_pause_key(sid, start)
187
193
  outcomes = [row for row in rows if str(row.get('session_id') or '') == sid
188
194
  and row.get('status') in ('ok', 'error', 'timeout')
195
+ and (pause_key is None or row.get('pause_key') == pause_key)
189
196
  and start <= float(row.get('ts') or 0) <= now]
190
197
  if len(outcomes) < len(record.get('pings_fired') or []):
191
198
  return None