@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
@@ -750,7 +750,9 @@ def generate_dashboard(coord_path):
750
750
  # predictor transparency). Fail-open so it never blocks dashboard regen.
751
751
  try:
752
752
  if isinstance(cache_health, dict):
753
+ from . import keepwarm_auto
753
754
  cache_health["keepwarm"] = _measure_facade.keepwarm_cache_health_block(days=30)
755
+ cache_health["keepwarm_auto"] = keepwarm_auto.health_block(_measure_facade)
754
756
  except Exception:
755
757
  pass
756
758
 
@@ -1881,7 +1883,7 @@ def _collect_management_data(components=None, trends=None):
1881
1883
  }
1882
1884
 
1883
1885
 
1884
- def plugin_cleanup(dry_run=None, quiet=None):
1886
+ def plugin_cleanup(dry_run=None, quiet=None, *, selected_items=None, plan_token=None, selected_ids=None):
1885
1887
  """Report stale plugin cache dirs and archive local/plugin skill overlaps.
1886
1888
 
1887
1889
  Two actions:
@@ -1896,6 +1898,9 @@ def plugin_cleanup(dry_run=None, quiet=None):
1896
1898
  import shutil
1897
1899
 
1898
1900
  actions_taken = []
1901
+ if selected_items is not None:
1902
+ from . import apply_safe
1903
+ if not apply_safe.validate_token(_measure_facade, selected_ids, plan_token) or set(selected_items) != {s.split(':', 1)[1] for s in selected_ids if s.startswith('duplicate_skill:')}: return actions_taken
1899
1904
 
1900
1905
  # Defense-in-depth: under a foreign runtime (OpenCode, Copilot),
1901
1906
  # do not touch ~/.claude.
@@ -1904,7 +1909,6 @@ def plugin_cleanup(dry_run=None, quiet=None):
1904
1909
  print(f" Skipped: {_measure_facade.runtime_name_for_humans()} runtime detected; not modifying ~/.claude.")
1905
1910
  return actions_taken
1906
1911
 
1907
- # --- Report 1: Stale cache version dirs (report only, never delete) ---
1908
1912
  registry = _measure_facade.CLAUDE_DIR / "plugins" / "installed_plugins.json"
1909
1913
  cache_dir = _measure_facade.CLAUDE_DIR / "plugins" / "cache"
1910
1914
 
@@ -1952,7 +1956,6 @@ def plugin_cleanup(dry_run=None, quiet=None):
1952
1956
  elif not quiet:
1953
1957
  print("\n Stale plugin cache: clean")
1954
1958
 
1955
- # --- Local skills that duplicate plugin skills ---
1956
1959
  # Scan plugin skills to get the set of skill directory names
1957
1960
  plugin_skill_names = set()
1958
1961
  if registry.exists():
@@ -1989,7 +1992,6 @@ def plugin_cleanup(dry_run=None, quiet=None):
1989
1992
  except (_measure_facade.json.JSONDecodeError, OSError):
1990
1993
  pass
1991
1994
 
1992
- # Check ~/.claude/skills/ for overlaps
1993
1995
  # Only archive if local skill is a plain symlink OR has no extra files beyond SKILL.md.
1994
1996
  # Local skills with custom reference files (loaded on-demand) have content the plugin
1995
1997
  # version lacks, so archiving them would lose functionality.
@@ -2018,6 +2020,7 @@ def plugin_cleanup(dry_run=None, quiet=None):
2018
2020
  today = _measure_facade.time.strftime("%Y%m%d")
2019
2021
  archive_dir = backups_dir / f"skills-deduped-{today}"
2020
2022
  for item in overlaps:
2023
+ if selected_items is not None and item.name not in selected_items: continue
2021
2024
  if dry_run:
2022
2025
  if not quiet:
2023
2026
  print(f" [dry-run] would archive: {item.name} (exists as plugin + local)")
@@ -2087,7 +2090,6 @@ def _manage_skill_locked(action, name):
2087
2090
  print(f" [!] Refusing to modify ~/.claude skills under the {_measure_facade.runtime_name_for_humans()} runtime.")
2088
2091
  return False
2089
2092
 
2090
- # Validate name: prevent path traversal
2091
2093
  if not isinstance(name, str) or not name or "/" in name or "\\" in name or name in (".", "..") or "\0" in name:
2092
2094
  print(f" [!] Invalid skill name: {name}")
2093
2095
  return False
@@ -2507,7 +2509,9 @@ def generate_standalone_dashboard(days=None, quiet=None, force=None):
2507
2509
  # predictor transparency). Fail-open so it never blocks dashboard regen.
2508
2510
  try:
2509
2511
  if isinstance(cache_health, dict):
2512
+ from . import keepwarm_auto
2510
2513
  cache_health["keepwarm"] = _measure_facade.keepwarm_cache_health_block(days=30)
2514
+ cache_health["keepwarm_auto"] = keepwarm_auto.health_block(_measure_facade)
2511
2515
  except Exception:
2512
2516
  pass
2513
2517
 
@@ -3711,6 +3715,9 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3711
3715
  headline["token_headline"] = headline_module.token_headline(headline)
3712
3716
  _measure_facade._apply_counted_oneshot_pricing(headline, counted)
3713
3717
  headline["action_savings"] = _measure_facade._action_savings_components(headline, counted)
3718
+ from . import keepwarm_auto
3719
+ status_headline = savings_headline_module.build(headline)
3720
+ keepwarm_note = keepwarm_auto.status_headline(_measure_facade, status_headline, headline.get("keepwarm_estimated"))
3714
3721
  shown, measured = _measure_facade._dashboard_saved_tokens(headline)
3715
3722
  if measured == 0 and int(window.get("tokens", 0)) > 0:
3716
3723
  return None, "savings database busy"
@@ -3724,7 +3731,7 @@ def _status_bar_savings_or_reason(session_id, _retried=None):
3724
3731
  "total_30d_tokens": shown,
3725
3732
  "total_30d_measured_tokens": measured,
3726
3733
  # The shared headline the band, status line and dashboard hero quote.
3727
- "savings_headline": savings_headline_module.build(headline),
3734
+ "savings_headline": status_headline, "keepwarm_note": keepwarm_note,
3728
3735
  "computed_at": _measure_facade.time.time(),
3729
3736
  }, None
3730
3737
 
@@ -4138,6 +4145,7 @@ def status_bar_payload(session_id, transcript=None, sync=None):
4138
4145
  if path is not None:
4139
4146
  out["last_request_epoch"], out["cache_lifetime"], session_model = (
4140
4147
  _measure_facade._status_bar_transcript_state(path))
4148
+ out["cache_model"] = session_model
4141
4149
  out["compactions"] = _measure_facade._status_bar_compactions(path, sid)
4142
4150
  # The native prompt_cache object (v2.1.251+) is authoritative for the
4143
4151
  # cache countdown/cold state when statusline.js bridged it recently;
@@ -37,14 +37,20 @@ ZERO_EFFECT_SHARE = 0.9
37
37
  FEATURES = (
38
38
  ("structure_map", "Structure map", "savings_events", "event_type", ("structure_map",), False),
39
39
  ("delta_read", "Delta re-reads", "savings_events", "event_type", ("delta_read",), False),
40
+ ("big_read_preview", "Big non-code read previews", "savings_events", "event_type", ("big_read_preview",), False),
40
41
  ("crossturn_dedup", "Cross-turn dedup", "compression_events", "feature", ("crossturn_dedup",), False),
41
42
  ("hint_followed", "Followed hints", "savings_events", "event_type", ("hint_followed",), False),
42
43
  ("first_read_skeleton", "First-read skeleton", "compression_events", "feature", ("first_read_skeleton",), False),
43
44
  ("tool_archive", "Tool output archive", "savings_events", "event_type", ("tool_archive",), False),
45
+ ("builtin_grep", "Built-in Grep compression", "savings_events", "event_type", ("builtin_grep",), False),
46
+ ("builtin_glob", "Built-in Glob compression", "savings_events", "event_type", ("builtin_glob",), False),
44
47
  # Per-command bash categories were folded into one pipeline over time;
45
48
  # grouping them keeps that rename from reading as an outage.
46
49
  ("bash_compression", "Bash compression", "compression_events", "feature", ("bash_compress_", "bash_generic"), True),
47
50
  ("build_output_compress", "Build output compression", "compression_events", "feature", ("build_output_compress",), False),
51
+ ("pipe_compress", "Bash pipelines", "compression_events", "feature", ("pipe_compress",), False),
52
+ ("bash_reread_unchanged", "Bash unchanged file re-reads", "compression_events", "feature", ("bash_reread_unchanged",), False),
53
+ ("large_output_policy", "Large Bash output policy", "compression_events", "feature", ("large_output_policy",), False),
48
54
  ("checkpoint_restore", "Checkpoint restore", "savings_events", "event_type", ("checkpoint_restore",), False),
49
55
  ("resume_lean", "Lean resume", "savings_events", "event_type", ("resume_lean",), False),
50
56
  )
@@ -0,0 +1,452 @@
1
+ """Shared policy for the in-session and headless automatic warm-ups."""
2
+ import argparse
3
+ from collections import defaultdict, deque
4
+ from datetime import datetime, timezone
5
+ import json
6
+ import math
7
+ import os
8
+ from pathlib import Path
9
+ import stat
10
+ import tempfile
11
+
12
+ from . import keepwarm_economics
13
+
14
+ MAX_PER_PAUSE = 2
15
+ MAX_PER_SESSION_DAY = 4
16
+ MAX_PER_DAY = 8
17
+ MARGIN = 3
18
+ DAY = 86400
19
+ BUCKETS = (3300, 6900, 10500)
20
+ CACHE_LIFETIME = 3600
21
+ MIN_CONTEXT = 100_000
22
+ OFF = ('0', 'false', 'off', 'no')
23
+ AUTO_SOURCES = ('claude-code-mod', 'keepwarm-headless')
24
+ PROOF_STOP = 'Automatic keep-warm stopped for this session: the warm-up did not read the cache.'
25
+ HEADLESS_STOP = 'Headless keep-warm stopped for this installation: a warm-up failed the cache proof.'
26
+
27
+
28
+ def _enabled(facade, env=None):
29
+ env = facade.os.environ if env is None else env
30
+ return (facade._read_config_flag('keepwarm_auto', False) is True
31
+ and not facade._keepwarm_llm_ping_disabled(env))
32
+
33
+
34
+ def _history_path(facade):
35
+ return facade.SNAPSHOT_DIR / 'keepwarm_return_history.json'
36
+
37
+
38
+ def _read_history(facade):
39
+ try:
40
+ return json.loads(_history_path(facade).read_text(encoding='utf-8'))
41
+ except (OSError, ValueError):
42
+ return {}
43
+
44
+
45
+ def refresh_history(facade, now):
46
+ path = _history_path(facade)
47
+ source = keepwarm_economics.load_history(facade, None, True)['gap_sessions']
48
+ sessions = source.sessions if isinstance(source, keepwarm_economics.GapHistory) else source
49
+ last_month = keepwarm_economics.GapHistory(
50
+ [[t for t in session if now - 30 * DAY <= t <= now] for session in sessions])
51
+ buckets = {}
52
+ for elapsed in BUCKETS:
53
+ at_risk, returned = last_month.counts(now, elapsed, CACHE_LIFETIME)
54
+ buckets[str(elapsed)] = {'at_risk': at_risk, 'returned': returned}
55
+ output = {'built_at': now, 'buckets': buckets}
56
+ path.parent.mkdir(parents=True, exist_ok=True)
57
+ fd, tmp = tempfile.mkstemp(prefix='.keepwarm-history-', dir=path.parent)
58
+ try:
59
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
60
+ json.dump(output, stream, allow_nan=False)
61
+ os.replace(tmp, path)
62
+ finally:
63
+ Path(tmp).unlink(missing_ok=True)
64
+ return output
65
+
66
+
67
+ def prune_markers(facade, now):
68
+ removed = 0
69
+ if not facade.SNAPSHOT_DIR.is_dir():
70
+ return removed
71
+ for path in facade.SNAPSHOT_DIR.iterdir():
72
+ if not path.name.startswith(('keepwarm-ended-', 'keepwarm-owner-')):
73
+ continue
74
+ try:
75
+ info = path.lstat()
76
+ if stat.S_ISREG(info.st_mode) and info.st_mtime < now - 14 * DAY:
77
+ path.unlink()
78
+ removed += 1
79
+ if removed == 200:
80
+ break
81
+ except OSError:
82
+ continue
83
+ return removed
84
+
85
+
86
+ def on_savings_refresh(facade, summary):
87
+ now = facade.time.time()
88
+ if 0 <= now - _read_history(facade).get('built_at', 0) < DAY:
89
+ return
90
+ facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
91
+ lock = facade.SNAPSHOT_DIR / '.keepwarm-history.lease'
92
+ with facade.lease_lock(lock, acquire_timeout=0, cohort_throttle=False, reclaim_released=True) as held:
93
+ if held and not 0 <= now - _read_history(facade).get('built_at', 0) < DAY:
94
+ refresh_history(facade, now)
95
+ prune_markers(facade, now)
96
+
97
+
98
+ def _caps(pause=0, session=0, day=0):
99
+ return {'pause_left': max(0, MAX_PER_PAUSE - pause),
100
+ 'session_day_left': max(0, MAX_PER_SESSION_DAY - session),
101
+ 'day_left': max(0, MAX_PER_DAY - day)}
102
+
103
+
104
+ def _auto_rows(rows):
105
+ return [row for row in rows if row.get('source') in AUTO_SOURCES
106
+ and row.get('action') == 'warm' and row.get('auto') is True]
107
+
108
+
109
+ def _attempt_id(row):
110
+ return row.get('action_id') or row.get('attempt_key') or (row.get('session_id'), row.get('ts'))
111
+
112
+
113
+ def _cap_counts(rows, session_id, pause_start, now):
114
+ cancelled = {_attempt_id(row) for row in rows if row.get('status') == 'cancelled'}
115
+ attempts = {}
116
+ for row in _auto_rows(rows):
117
+ ident = _attempt_id(row)
118
+ if ident in cancelled or row.get('status') not in ('firing', 'ok', 'error', 'timeout'):
119
+ continue
120
+ ts = float(row['ts'])
121
+ if ident not in attempts or ts < attempts[ident][1]:
122
+ attempts[ident] = (row.get('session_id'), ts)
123
+ return _caps(
124
+ sum(sid == session_id and pause_start <= ts <= now for sid, ts in attempts.values()),
125
+ sum(sid == session_id and now - DAY <= ts <= now for sid, ts in attempts.values()),
126
+ sum(now - DAY <= ts <= now for _, ts in attempts.values()),
127
+ )
128
+
129
+
130
+ def _failed_attempts(rows, now, days, session_id=None):
131
+ return {_attempt_id(row) for row in _auto_rows(rows) if row.get('proof') is False
132
+ and now - days * DAY <= float(row['ts']) <= now
133
+ and (session_id is None or row.get('session_id') == session_id)}
134
+
135
+
136
+ def _trip_reason(facade, now, summary=None):
137
+ if facade.keepwarm_tripwire_mode() == 'off':
138
+ return 'tripwire'
139
+ if summary is None:
140
+ summary = keepwarm_economics.verified_summary(facade, 7, now)
141
+ if summary['pings'] >= 5 and summary['net_usd'] < 0:
142
+ return 'tripwire'
143
+ return None
144
+
145
+
146
+ def avoided_reload(facade, tokens, model):
147
+ read = facade._get_model_cost(model, 0, 0, tokens, 0, per_request=True)
148
+ write = facade._get_model_cost(model, 0, 0, 0, tokens, cache_create_1h=tokens,
149
+ cache_create_5m=0, per_request=True)
150
+ return write - read
151
+
152
+
153
+ def _priced_value(facade, tokens, model):
154
+ ping = facade._keepwarm_ping_cost_est(tokens, model)
155
+ # Use the higher quote when a per-request long-context rate applies.
156
+ full_read = facade._get_model_cost(model, 1000, 0, tokens, 0, per_request=True)
157
+ return max(ping, full_read), avoided_reload(facade, tokens, model)
158
+
159
+
160
+ def _probability(at_risk, returned):
161
+ if type(at_risk) is not int or type(returned) is not int or at_risk < 20 or not 0 <= returned <= at_risk:
162
+ return None
163
+ return returned / (at_risk + 10)
164
+
165
+
166
+ def _bucket(elapsed):
167
+ return min(BUCKETS, key=lambda bucket: abs(bucket - elapsed))
168
+
169
+
170
+ def decide(facade, session_id, context_tokens, idle_seconds, model, lifetime,
171
+ five_hour_pct=None, week_pct=None, now=None, *, headless=False, env=None, rows=None):
172
+ """Read only local policy snapshots and the spend ledger. Fail closed."""
173
+ out = {'action': 'stop', 'reason': 'error', 'p_return': 0.0, 'ping_cost_usd': 0.0,
174
+ 'avoided_usd': 0.0, 'caps': _caps()}
175
+
176
+ def stop(reason):
177
+ out['reason'] = reason
178
+ return out
179
+
180
+ try:
181
+ now = facade.time.time() if now is None else now
182
+ if headless:
183
+ from . import keepwarm_safety
184
+ reason = keepwarm_safety.headless_disabled(facade, env)
185
+ if reason:
186
+ return stop(reason)
187
+ elif not _enabled(facade, env):
188
+ return stop('off')
189
+ trip = _trip_reason(facade, now)
190
+ if trip:
191
+ return stop(trip)
192
+ if lifetime != CACHE_LIFETIME:
193
+ return stop('lifetime')
194
+ if context_tokens < MIN_CONTEXT:
195
+ return stop('small')
196
+ if not facade._is_priced_model(model):
197
+ return stop('unpriced')
198
+ for pct in (five_hour_pct, week_pct):
199
+ if pct is not None and (type(pct) not in (int, float) or not math.isfinite(pct) or pct < 0):
200
+ return stop('meters-unknown')
201
+ if ((five_hour_pct is not None and five_hour_pct >= 80)
202
+ or (week_pct is not None and week_pct >= 90)):
203
+ return stop('limits')
204
+ if (five_hour_pct is None or week_pct is None) and facade.keepwarm_billing_mode(env=env) != 'api':
205
+ return stop('meters-unknown')
206
+ if not math.isfinite(idle_seconds) or idle_seconds < 0:
207
+ return out
208
+ rows = facade._keepwarm_load_ledger_rows() if rows is None else rows
209
+ out['caps'] = _cap_counts(rows, session_id, now - idle_seconds, now)
210
+ for key, reason in zip(out['caps'], ('cap-pause', 'cap-session', 'cap-day')):
211
+ if not out['caps'][key]:
212
+ return stop(reason)
213
+ if _failed_attempts(rows, now, 1, session_id):
214
+ return stop('failed-proof')
215
+ history = _read_history(facade)
216
+ if not 0 <= now - history.get('built_at', 0) <= 7 * DAY:
217
+ return stop('no-history')
218
+ counts = history.get('buckets', {}).get(str(_bucket(idle_seconds)), {})
219
+ probability = _probability(counts.get('at_risk'), counts.get('returned'))
220
+ if probability is None:
221
+ return stop('no-history')
222
+ ping, avoided = _priced_value(facade, context_tokens, model)
223
+ if not all(math.isfinite(cost) and cost > 0 for cost in (ping, avoided)):
224
+ return out
225
+ out.update(p_return=probability, ping_cost_usd=ping, avoided_usd=avoided)
226
+ if probability * avoided < MARGIN * ping:
227
+ return stop('not-worth-it')
228
+ out['action'] = 'ping'
229
+ return stop('due')
230
+ except Exception:
231
+ return stop('error')
232
+
233
+
234
+ def proof_ok(usage, context_tokens):
235
+ if not isinstance(usage, dict) or type(context_tokens) is not int or context_tokens <= 0:
236
+ return False
237
+ read = usage.get('cache_read_input_tokens')
238
+ write = usage.get('cache_creation_input_tokens')
239
+ return (type(read) is int and type(write) is int and write >= 0
240
+ and 100 * read >= 90 * context_tokens and 100 * write <= 5 * context_tokens)
241
+
242
+
243
+ def _mod_active(facade, now):
244
+ cutoff = now - 30 * DAY
245
+ if any(row.get('source') == 'claude-code-mod' and float(row['ts']) >= cutoff
246
+ for row in facade._keepwarm_load_ledger_rows()):
247
+ return True
248
+ conn = facade._open_trends_db_readonly(timeout=0.2)
249
+ try:
250
+ date = datetime.fromtimestamp(cutoff, timezone.utc).isoformat()
251
+ return conn.execute('SELECT 1 FROM mod_action_observations WHERE timestamp >= ? LIMIT 1',
252
+ (date,)).fetchone() is not None
253
+ finally:
254
+ conn.close()
255
+
256
+
257
+ def capped_forecast(facade, days, now, files=None, parse_fn=None):
258
+ """Replay the same spacing, economics and rolling caps across all pauses."""
259
+ cutoff = now - days * DAY
260
+ if files is None:
261
+ files = [path for path, _, _ in facade._find_all_jsonl_files(days)]
262
+ parse = parse_fn or facade.parse_session_turns
263
+ pauses, sessions = [], []
264
+ for path in files:
265
+ entries = [(facade._keepwarm_iso_to_epoch(turn.get('timestamp')), turn) for turn in parse(path)]
266
+ ordered = sorted(((ts, turn) for ts, turn in entries if ts is not None and cutoff <= ts <= now),
267
+ key=lambda pair: pair[0])
268
+ sessions.append([ts for ts, _ in ordered])
269
+ ttl = None
270
+ for index, (start, turn) in enumerate(ordered):
271
+ if turn.get('cache_creation_1h') or turn.get('cache_creation_5m'):
272
+ ttl = '1h' if turn.get('cache_creation_1h', 0) > turn.get('cache_creation_5m', 0) else '5m'
273
+ end = ordered[index + 1][0] if index + 1 < len(ordered) else None
274
+ model = turn.get('model')
275
+ tokens = facade._turn_prefix_cached(turn)
276
+ if ttl != '1h' or tokens < MIN_CONTEXT or not facade._is_priced_model(model):
277
+ continue
278
+ for number, elapsed in enumerate(BUCKETS[:MAX_PER_PAUSE]):
279
+ if start + elapsed <= now and (end is None or start + elapsed < end):
280
+ pauses.append((start + elapsed, str(path), start, number, model, tokens, end))
281
+ history = keepwarm_economics.GapHistory(sessions)
282
+ global_pings, session_pings = deque(), defaultdict(deque)
283
+ credited, first = set(), set()
284
+ spend = gross = 0.0
285
+ pings = 0
286
+ for at, sid, start, number, model, tokens, end in sorted(pauses):
287
+ pause = (sid, start)
288
+ if number and pause not in first:
289
+ continue
290
+ for window in (global_pings, session_pings[sid]):
291
+ while window and window[0] < at - DAY:
292
+ window.popleft()
293
+ if len(global_pings) >= MAX_PER_DAY or len(session_pings[sid]) >= MAX_PER_SESSION_DAY:
294
+ continue
295
+ # Differences of cumulative counts limit the sample to the preceding window.
296
+ recent = history.counts(at, _bucket(at - start), CACHE_LIFETIME)
297
+ older = history.counts(at - 30 * DAY, _bucket(at - start), CACHE_LIFETIME)
298
+ probability = _probability(recent[0] - older[0], recent[1] - older[1])
299
+ ping, saved = _priced_value(facade, tokens, model)
300
+ if probability is None or not 0 < MARGIN * ping <= probability * saved:
301
+ continue
302
+ global_pings.append(at)
303
+ session_pings[sid].append(at)
304
+ first.add(pause)
305
+ spend += ping
306
+ pings += 1
307
+ if end is not None and start + CACHE_LIFETIME < end <= at + CACHE_LIFETIME and pause not in credited:
308
+ credited.add(pause)
309
+ gross += saved
310
+ return {'available': True, 'positive': gross > spend, 'net_usd': gross - spend,
311
+ 'ping_cost_usd': spend, 'avoided_writes': len(credited), 'pings': pings}
312
+
313
+
314
+ def plan_item(facade):
315
+ try:
316
+ if facade._read_config_flag('keepwarm_auto', False) is True or not _mod_active(facade, facade.time.time()):
317
+ return None
318
+ estimate = facade.keepwarm_forecast(days=30, automatic=True)
319
+ if not estimate.get('positive') or estimate['net_usd'] <= 0:
320
+ return None
321
+ return {'id': 'keepwarm_auto:on', 'kind': 'keepwarm_auto',
322
+ 'label': 'Keep big sessions warm automatically (at most 2 per pause, 8 per day)',
323
+ 'tokens_per_request': None, 'net_usd_month': estimate['net_usd'],
324
+ 'own_cost_usd_month': estimate['ping_cost_usd'],
325
+ 'basis': f"replay of your last 30 days: {estimate['avoided_writes']} returns within the hour, {estimate['pings']} pings",
326
+ 'undo': 'measure.py keepwarm-decide set off', 'default_selected': True}
327
+ except Exception:
328
+ return None
329
+
330
+
331
+ def _set_flag(facade, enabled):
332
+ previous = facade._read_config_flag('keepwarm_auto', False)
333
+ facade._write_config_flag('keepwarm_auto', enabled)
334
+ if facade._read_config_flag('keepwarm_auto', None) is not enabled:
335
+ raise OSError('Keep-warm preference could not be saved')
336
+ return previous
337
+
338
+
339
+ def apply_item(facade, item):
340
+ if item.get('id') != 'keepwarm_auto:on':
341
+ raise ValueError('Invalid keep-warm approval')
342
+ previous = _set_flag(facade, True)
343
+ return {'ok': True, 'before': previous, 'after': True}
344
+
345
+
346
+ def undo_item(facade, receipt):
347
+ if receipt.get('ok') is not True or facade._read_config_flag('keepwarm_auto', False) is not receipt.get('after'):
348
+ return False
349
+ before = receipt.get('before')
350
+ _set_flag(facade, before if isinstance(before, bool) else False)
351
+ return True
352
+
353
+
354
+ def health_block(facade):
355
+ from . import keepwarm_safety
356
+ cfg = {'state': 'off', 'reason': 'off', 'pings_7d': 0, 'proof_failed_7d': 0,
357
+ 'net_usd_7d': None, 'caps': _caps()}
358
+ try:
359
+ enabled = _enabled(facade)
360
+ headless = keepwarm_safety.headless_disabled(facade)
361
+ cfg.update(state='on' if enabled else 'off', reason='enabled' if enabled else 'off',
362
+ headless_state='on' if headless is None else 'stopped' if headless == 'headless-proof' else 'off',
363
+ headless_reason=headless)
364
+ now = facade.time.time()
365
+ rows = facade._keepwarm_load_ledger_rows()
366
+ summary = keepwarm_economics.verified_summary(facade, 7, now)
367
+ cfg.update(pings_7d=summary['pings'], net_usd_7d=summary['net_usd'],
368
+ proof_failed_7d=len(_failed_attempts(rows, now, 7)),
369
+ caps=_cap_counts(rows, None, now, now))
370
+ reason = _trip_reason(facade, now, summary)
371
+ if reason:
372
+ cfg.update(state='stopped' if enabled else 'off', reason=reason)
373
+ if cfg['headless_state'] == 'on':
374
+ cfg.update(headless_state='stopped', headless_reason=reason)
375
+ except Exception:
376
+ cfg.update(reason='accounting-unavailable', state='stopped' if cfg['state'] == 'on' else cfg['state'])
377
+ if cfg.get('headless_state') == 'on':
378
+ cfg.update(headless_state='stopped', headless_reason='accounting-unavailable')
379
+ return cfg
380
+
381
+
382
+ def status_headline(facade, headline, keepwarm):
383
+ """Preserve the status bar's existing display contract and signed estimate."""
384
+ from . import keepwarm_safety
385
+
386
+ stopped = keepwarm_safety.headless_disabled(facade) == 'headless-proof'
387
+ has_activity = keepwarm and keepwarm.get('events')
388
+ if not (stopped or has_activity):
389
+ return None
390
+ net = float(keepwarm['cost_saved_usd']) if has_activity else None
391
+ short = 'Keep-warm stopped' if stopped else f"Keep-warm {'-' if net < 0 else '+'}${abs(net):.2f} est."
392
+ note = HEADLESS_STOP if stopped else None
393
+ if has_activity and stopped:
394
+ short += f" {'-' if net < 0 else '+'}${abs(net):.2f} est."
395
+ if headline.get('display'):
396
+ headline['display'] = {**headline['display'],
397
+ 'short': headline['display']['short'] + ' · ' + short,
398
+ 'long': headline['display']['long'] + ' · ' + short}
399
+ else:
400
+ headline['display'] = {'kind': None, 'short': short, 'long': short, 'url': None}
401
+ return note
402
+
403
+
404
+ def _parse_args(args):
405
+ parser = argparse.ArgumentParser(prog='measure.py keepwarm-decide')
406
+ parser.add_argument('--session', required=True, dest='session_id')
407
+ parser.add_argument('--context-tokens', type=int, required=True)
408
+ parser.add_argument('--idle-seconds', type=float, required=True)
409
+ parser.add_argument('--model', required=True)
410
+ parser.add_argument('--lifetime', type=int, required=True)
411
+ parser.add_argument('--five-hour-pct', type=float)
412
+ parser.add_argument('--week-pct', type=float)
413
+ parser.add_argument('--json', action='store_true', dest='as_json')
414
+ return parser.parse_args(args)
415
+
416
+
417
+ def main(facade, args):
418
+ if args in (['set', 'on'], ['set', 'off']):
419
+ _set_flag(facade, args[1] == 'on')
420
+ print('In-session automatic keep-warm is on.' if args[1] == 'on'
421
+ else 'Automatic keep-warm is off in session and headless.')
422
+ elif args == ['reset-headless-proof']:
423
+ from . import keepwarm_safety
424
+ reason = keepwarm_safety.reset_headless_proof(facade)
425
+ if reason:
426
+ print(f'Headless keep-warm proof reset failed ({reason}).')
427
+ return 1
428
+ print('Headless keep-warm proof stop cleared.')
429
+ elif args in (['status'], ['status', '--json']):
430
+ result = health_block(facade)
431
+ if '--json' in args:
432
+ print(json.dumps(result))
433
+ else:
434
+ print(f"Automatic keep-warm is {result['state']} in session and {result.get('headless_state', 'unknown')} headless.")
435
+ if result.get('headless_reason') == 'headless-proof':
436
+ print(HEADLESS_STOP)
437
+ print('Run measure.py keepwarm-decide reset-headless-proof to clear the installation stop.')
438
+ print(f"Last 7 days: {result['pings_7d']} pings, {result['proof_failed_7d']} failed proofs.")
439
+ net = result['net_usd_7d']
440
+ print(f"Estimated net at API rates: ${net:.2f}." if net is not None else 'Estimated net is unavailable.')
441
+ elif len(args) == 3 and args[0] == 'watch':
442
+ from . import keepwarm_safety
443
+ return keepwarm_safety.watch_terminal(facade, args[1], int(args[2]))
444
+ elif args and args[0] == 'headless':
445
+ from . import keepwarm_safety
446
+ return keepwarm_safety.desktop_headless_main(facade, args[1:])
447
+ else:
448
+ values = vars(_parse_args(args))
449
+ as_json = values.pop('as_json')
450
+ result = decide(facade, **values)
451
+ print(json.dumps(result) if as_json else f"{result['action']}: {result['reason']}")
452
+ return 0
@@ -114,7 +114,7 @@ def gate_reason(facade):
114
114
 
115
115
 
116
116
  def verified_summary(facade, days, now):
117
- conn = facade._open_trends_db_readonly(timeout=1.0)
117
+ conn = facade._open_trends_db_readonly(timeout=0.15)
118
118
  try:
119
119
  keys = {row[0] for row in conn.execute(
120
120
  "SELECT pause_key FROM savings_events WHERE event_type = 'keepwarm_estimated' AND pause_key IS NOT NULL")}
@@ -129,7 +129,7 @@ def manual_count(rows, start):
129
129
  attempts, cancelled = set(), set()
130
130
  for row in rows:
131
131
  try:
132
- if (row.get('source') == 'claude-code-mod' and row.get('action') == 'warm' and
132
+ if (row.get('source') == 'claude-code-mod' and row.get('action') == 'warm' and row.get('auto') is not True and
133
133
  row.get('status') in ('firing', 'ok', 'cancelled') and float(row.get('ts', 0)) >= start):
134
134
  (cancelled if row.get('status') == 'cancelled' else attempts).add(row.get('action_id'))
135
135
  except (TypeError, ValueError):
@@ -152,7 +152,7 @@ def headline_pool(facade, cutoff):
152
152
  return None
153
153
  if not summary['pings'] and not summary['realized_count']:
154
154
  return None
155
- return {'events': summary['pings'] + summary['realized_count'],
155
+ return {'label': 'Keep-warm net', 'events': summary['pings'] + summary['realized_count'],
156
156
  'tokens_saved': 0, 'cost_saved_usd': summary['net_usd'],
157
157
  'manual_pings': manual_count(facade._keepwarm_load_ledger_rows(), start)}
158
158
 
@@ -195,7 +195,11 @@ def reconcile_while_paused(facade, reason, now, dry_run):
195
195
  def transcript_changed(record):
196
196
  try:
197
197
  from pathlib import Path
198
- stat = Path(record['transcript_path']).stat()
198
+ from . import keepwarm_safety
199
+ path = Path(record['transcript_path'])
200
+ stat = path.stat()
201
+ if 'terminal_turn' in record:
202
+ return keepwarm_safety.terminal_turn(path) != record['terminal_turn']
199
203
  return stat.st_size != int(record['byte_size']) or stat.st_mtime != float(record['transcript_mtime'])
200
204
  except (KeyError, TypeError, ValueError, OSError):
201
205
  return False