@alexgreensh/token-optimizer 5.13.74 → 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 +80 -82
  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
@@ -39,8 +39,13 @@ def _snapshot(facade, event, sid):
39
39
  usage, model, last = facade._keepwarm_last_usage(path)
40
40
  if not usage or not model or not facade._is_priced_model(model):
41
41
  raise ValueError('model unpriced')
42
+ ttl = facade._keepwarm_ttl_kind(usage)
43
+ if ttl == 'unknown' and event.get('auto'):
44
+ _, measured, last_model = facade._status_bar_transcript_state(path)
45
+ if measured and last_model == model:
46
+ ttl = measured
42
47
  return {'path': str(path), 'byte_size': size, 'mtime': mtime, 'device': current.st_dev,
43
- 'inode': current.st_ino, 'model': model, 'ttl': facade._keepwarm_ttl_kind(usage),
48
+ 'inode': current.st_ino, 'model': model, 'ttl': ttl,
44
49
  'prefix': facade._keepwarm_prefix_proxy(usage), 'last_turn': facade._keepwarm_iso_to_epoch(last)}
45
50
 
46
51
 
@@ -64,16 +69,37 @@ def _prepare(facade, event, sid, ident, when):
64
69
  with _lock(facade) as acquired:
65
70
  if not acquired:
66
71
  return {'ok': False, 'reason': 'ledger-locked'}
67
- existing = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
72
+ rows = facade._keepwarm_load_ledger_rows()
73
+ existing = [r for r in rows if r.get('action_id') == ident]
68
74
  if existing:
69
75
  return {'ok': False, 'reason': 'attempt-already-reserved' if _compatible(existing, sid) else 'identity-conflict'}
76
+ from . import keepwarm_auto, keepwarm_safety
77
+ if keepwarm_safety._pending_attempt(rows, sid, when):
78
+ return {'ok': False, 'reason': 'attempt-in-progress'}
79
+ flags = {key: event[key] for key in ('auto', 'proof') if key in event}
80
+ if flags.get('auto'):
81
+ last_turn = snapshot['last_turn']
82
+ context = event.get('context_tokens')
83
+ if type(context) is not int or not last_turn or not _snapshot_still_usable(snapshot):
84
+ return {'ok': False, 'reason': 'snapshot-unavailable'}
85
+ now = facade.time.time()
86
+ if abs(now - when) > 15 or abs(context - snapshot['prefix']) > context * .1:
87
+ return {'ok': False, 'reason': 'stale-decision'}
88
+ decision = keepwarm_auto.decide(
89
+ facade, sid, min(context, snapshot['prefix']), now - last_turn, snapshot['model'],
90
+ 3600 if snapshot['ttl'] == '1h' else 0,
91
+ event.get('five_hour_pct'), event.get('week_pct'), now, rows=rows)
92
+ if decision['action'] != 'ping':
93
+ return {'ok': False, 'reason': decision['reason']}
94
+ snapshot['proof_context'] = context
95
+ estimate = max(estimate, decision['ping_cost_usd'])
70
96
  _append(facade._keepwarm_ledger_path(), {'status': 'firing', 'source': 'claude-code-mod',
71
97
  'action': 'warm', 'action_id': ident, 'attempt_key': ident, 'session_id': sid,
72
- 'ts': when, 'est_cost_usd': estimate, 'snapshot': snapshot})
98
+ 'ts': when, 'est_cost_usd': estimate, 'snapshot': snapshot, **flags})
73
99
  return {'ok': True, 'duplicate': False}
74
100
 
75
101
 
76
- def _cancel(facade, sid, ident, when):
102
+ def _cancel(facade, event, sid, ident, when):
77
103
  with _lock(facade) as acquired:
78
104
  if not acquired:
79
105
  return {'ok': False, 'reason': 'ledger-locked'}
@@ -82,7 +108,22 @@ def _cancel(facade, sid, ident, when):
82
108
  return {'ok': False, 'reason': 'reservation-unavailable'}
83
109
  if not any(r.get('status') == 'cancelled' for r in rows):
84
110
  _append(facade._keepwarm_ledger_path(), {'status': 'cancelled', 'source': 'claude-code-mod',
85
- 'action': 'warm', 'action_id': ident, 'session_id': sid, 'ts': when})
111
+ 'action': 'warm', 'action_id': ident, 'session_id': sid, 'ts': when,
112
+ **{key: event[key] for key in ('auto', 'proof') if key in event}})
113
+ return {'ok': True}
114
+
115
+
116
+ def _unproved(facade, sid, ident, when):
117
+ with _lock(facade) as acquired:
118
+ if not acquired:
119
+ return {'ok': False, 'reason': 'ledger-locked'}
120
+ rows = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
121
+ if not _compatible(rows, sid) or not any(r.get('status') == 'firing' and r.get('auto') is True for r in rows):
122
+ return {'ok': False, 'reason': 'reservation-unavailable'}
123
+ if not any(r.get('proof') is False for r in rows):
124
+ _append(facade._keepwarm_ledger_path(), {'status': 'unproved', 'source': 'claude-code-mod',
125
+ 'action': 'warm', 'session_id': sid, 'action_id': ident, 'ts': when,
126
+ 'auto': True, 'proof': False})
86
127
  return {'ok': True}
87
128
 
88
129
 
@@ -107,13 +148,17 @@ def record(facade, event):
107
148
  if isinstance(event, dict) and event.get('action') in ('clean', 'clean-first'):
108
149
  from . import mod_compaction_booking
109
150
  return mod_compaction_booking.record(facade, event)
110
- if not isinstance(event, dict) or event.get('action') not in ('warm', 'warm-prepare', 'warm-cancel'):
151
+ if not isinstance(event, dict) or event.get('action') not in ('warm', 'warm-prepare', 'warm-cancel', 'warm-unproved'):
111
152
  return {'ok': False, 'reason': 'unsupported-action'}
153
+ if any(key in event and type(event[key]) is not bool for key in ('auto', 'proof')):
154
+ return {'ok': False, 'reason': 'invalid-auto-proof'}
112
155
  sid, ident, when = _identity(event)
156
+ if event['action'] == 'warm-unproved':
157
+ return _unproved(facade, sid, ident, when)
113
158
  if event['action'] == 'warm-prepare':
114
159
  return _prepare(facade, event, sid, ident, when)
115
160
  if event['action'] == 'warm-cancel':
116
- return _cancel(facade, sid, ident, when)
161
+ return _cancel(facade, event, sid, ident, when)
117
162
  usage = event['usage']
118
163
  if not isinstance(usage, dict) or any(type(usage.get(key)) is not int or usage[key] < 0 for key in _USAGE):
119
164
  return {'ok': False, 'reason': 'invalid-usage'}
@@ -131,6 +176,13 @@ def record(facade, event):
131
176
  snapshot = reservation.get('snapshot') if reservation else _snapshot(facade, event, sid)
132
177
  if not isinstance(snapshot, dict):
133
178
  return {'ok': False, 'reason': 'snapshot-unavailable'}
179
+ flags = {key: event[key] for key in ('auto', 'proof') if key in event}
180
+ if flags.get('auto') or (reservation and reservation.get('auto') is True):
181
+ from .keepwarm_auto import proof_ok
182
+ if reservation is None or reservation.get('auto') is not True:
183
+ return {'ok': False, 'reason': 'reservation-unavailable'}
184
+ flags = {'auto': True, 'proof': flags.get('proof') is True and proof_ok(
185
+ usage, snapshot.get('proof_context')) and not any(r.get('proof') is False for r in existing)}
134
186
  model, ttl = snapshot['model'], snapshot['ttl']
135
187
  creation = usage['cache_creation_input_tokens']
136
188
  cost = facade._get_model_cost(model, usage['input_tokens'], usage['output_tokens'],
@@ -148,18 +200,23 @@ def record(facade, event):
148
200
  if same_pause is not None:
149
201
  pause_key = facade._keepwarm_pause_key(sid, same_pause['ts'])
150
202
  row = {'status': 'ok', 'source': 'claude-code-mod', 'action': 'warm', 'action_id': ident,
151
- 'attempt_key': ident, 'session_id': sid, 'pause_key': pause_key, 'ts': when,
203
+ 'attempt_key': ident, 'session_id': sid, 'pause_key': pause_key, 'ts': when, **flags,
152
204
  'model': model, 'cost_usd': cost, 'cost_basis': 'conservative-1h-write' if creation else 'reported-usage', 'usage': dict(usage)}
153
205
  finished = [r for r in existing if r.get('status') == 'ok']
154
206
  if not finished:
155
207
  _append(facade._keepwarm_ledger_path(), row)
156
208
  usable = _snapshot_still_usable(snapshot)
157
- if event.get('answered', True) is True and usable and same_pause is None and not any(r.get('manual_action_id') == ident for r in arms):
158
- _append(facade._keepwarm_sidecar_path(), {'session_id': sid, 'transcript_path': snapshot['path'],
159
- 'transcript_mtime': snapshot['mtime'], 'byte_size': snapshot['byte_size'], 'model': model,
160
- 'prefix_proxy': snapshot['prefix'], 'ttl_kind': ttl, 'last_turn_ts': snapshot['last_turn'] or when,
161
- 'ts': when, 'state': 'armed', 'owner': None, 'pings_fired': [when],
162
- 'pause_key': pause_key, 'manual_action_id': ident})
209
+ if event.get('answered', True) is True and usable and flags.get('proof') is not False:
210
+ if same_pause is None and not any(r.get('manual_action_id') == ident for r in arms):
211
+ _append(facade._keepwarm_sidecar_path(), {'session_id': sid, 'transcript_path': snapshot['path'],
212
+ 'transcript_mtime': snapshot['mtime'], 'byte_size': snapshot['byte_size'], 'model': model,
213
+ 'prefix_proxy': snapshot['prefix'], 'ttl_kind': ttl, 'last_turn_ts': snapshot['last_turn'] or when,
214
+ 'ts': when, 'state': 'armed', 'owner': None, 'pings_fired': [when],
215
+ 'pause_key': pause_key, 'manual_action_id': ident, 'auto_warm': flags.get('auto', False)})
216
+ elif same_pause is not None and not finished and flags.get('auto'):
217
+ latest = [r for r in arms if r.get('session_id') == sid and r.get('ts') == same_pause['ts']][-1]
218
+ _append(facade._keepwarm_sidecar_path(), dict(latest, auto_warm=True,
219
+ pings_fired=[*latest['pings_fired'], when]))
163
220
  return {'ok': True, 'pause_key': pause_key, 'cost_usd': cost, 'duplicate': bool(finished), 'resume_trackable': usable}
164
221
  except Exception as exc:
165
222
  return {'ok': False, 'reason': 'receipt-unavailable', 'exception_class': type(exc).__name__}
@@ -0,0 +1,420 @@
1
+ """Read-only next steps, grounded in the user's own recent savings data."""
2
+ import importlib
3
+ import json
4
+ import math
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import time
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+
13
+ from hook_provenance import _acquire, _exclusive
14
+ from process_identity import process_start
15
+ from spawn_utils import spawn_detached
16
+
17
+ IDS = ('apply_safe', 'cold_fresh', 'skill_list', 'writes', 'stale_reads', 'routing')
18
+ REPORT_NAME = 'next_report.json'
19
+ LOCK_NAME = 'next_refresh.lock'
20
+ WINDOWS_PID_MARKER = 'next_refresh_pid.json'
21
+ WINDOWS_HANDOFF_SECONDS = 30
22
+ PLAN_NAME = 'next_apply_plan.json'
23
+ MAX_SUMMARY_BYTES = 4 * 1024 * 1024
24
+ # A filesystem timestamp can lead the wall clock by a tick on Windows.
25
+ FILE_MTIME_SKEW_SECONDS = 1
26
+
27
+
28
+ def _now():
29
+ return datetime.now(timezone.utc)
30
+
31
+
32
+ def _read(path):
33
+ try:
34
+ value = json.loads(path.read_text(encoding='utf-8'))
35
+ return value if isinstance(value, dict) else {}
36
+ except (OSError, ValueError, UnicodeError):
37
+ return {}
38
+
39
+
40
+ def _write(path, value):
41
+ path.parent.mkdir(parents=True, exist_ok=True)
42
+ fd, name = tempfile.mkstemp(prefix='.' + path.name, dir=str(path.parent))
43
+ try:
44
+ if hasattr(os, 'fchmod'):
45
+ os.fchmod(fd, 0o600)
46
+ with os.fdopen(fd, 'w', encoding='utf-8') as stream:
47
+ json.dump(value, stream)
48
+ if not hasattr(os, 'fchmod'):
49
+ os.chmod(name, 0o600)
50
+ os.replace(name, path)
51
+ finally:
52
+ if os.path.exists(name):
53
+ os.unlink(name)
54
+
55
+
56
+ def _call(module, function, *args):
57
+ try:
58
+ return getattr(importlib.import_module('.' + module, __package__), function)(*args)
59
+ except Exception:
60
+ return None
61
+
62
+
63
+ def _cached_summary(facade):
64
+ # Only a complete 30-day summary can substitute for the report calculation.
65
+ candidates = []
66
+ try:
67
+ directory = facade._status_bar_dir()
68
+ candidates.append(Path(directory) / 'global.json')
69
+ except Exception:
70
+ pass
71
+ for name in ('dashboard.json', 'dashboard_data.json', 'savings_summary.json'):
72
+ candidates.append(Path(facade.SNAPSHOT_DIR) / name)
73
+ fresh = []
74
+ try:
75
+ path = Path(facade.DASHBOARD_PATH)
76
+ info = path.stat()
77
+ stamp = info.st_mtime
78
+ if (info.st_size <= MAX_SUMMARY_BYTES
79
+ and -FILE_MTIME_SKEW_SECONDS <= time.time() - stamp < 86400):
80
+ html = path.read_text(encoding='utf-8')
81
+ marker = 'window.__TOKEN_DATA__ = '
82
+ start = html.index(marker) + len(marker)
83
+ data, _ = json.JSONDecoder().raw_decode(html[start:])
84
+ summary = data.get('savings') if isinstance(data, dict) else None
85
+ if isinstance(summary, dict) and summary.get('period_days') == 30:
86
+ fresh.append((stamp, summary))
87
+ except (AttributeError, OSError, ValueError, TypeError, UnicodeError):
88
+ pass
89
+ for path in candidates:
90
+ try:
91
+ info = path.stat()
92
+ if info.st_size > MAX_SUMMARY_BYTES:
93
+ continue
94
+ data = _read(path)
95
+ stamp = data.get('computed_at', info.st_mtime)
96
+ skew = 0 if 'computed_at' in data else FILE_MTIME_SKEW_SECONDS
97
+ if isinstance(stamp, str):
98
+ stamp = datetime.fromisoformat(stamp.replace('Z', '+00:00')).timestamp()
99
+ age = time.time() - float(stamp)
100
+ summary = data.get('savings', data)
101
+ if (-skew <= age < 86400 and isinstance(summary, dict)
102
+ and summary.get('period_days') == 30
103
+ and any(k in summary for k in ('output_waste', 'stale_reads_reclaimable', 'model_routing'))):
104
+ fresh.append((float(stamp), summary))
105
+ except (OSError, ValueError, TypeError, OverflowError):
106
+ continue
107
+ if fresh:
108
+ stamp, summary = max(fresh, key=lambda item: item[0])
109
+ return summary, datetime.fromtimestamp(stamp, timezone.utc).isoformat()
110
+ return {}, None
111
+
112
+
113
+ def _compute_summary(facade):
114
+ try:
115
+ summary = facade._get_merged_savings(days=30)
116
+ if not isinstance(summary, dict):
117
+ return None
118
+ except Exception:
119
+ return None
120
+ if 'skill_listing_budget' not in summary:
121
+ listing = None
122
+ try:
123
+ from . import structural_report
124
+ listing = structural_report.skill_listing_budget(days=30, f=facade)
125
+ except Exception:
126
+ pass
127
+ if listing is not None:
128
+ summary = dict(summary, skill_listing_budget=listing)
129
+ return summary
130
+
131
+
132
+ def _number(value):
133
+ try:
134
+ result = float(value)
135
+ return result if math.isfinite(result) else None
136
+ except (TypeError, ValueError):
137
+ return None
138
+
139
+
140
+ def _cached_plan(path, now):
141
+ cached = _read(path)
142
+ try:
143
+ stamp = datetime.fromisoformat(cached['computed_at'])
144
+ age = (now - stamp).total_seconds()
145
+ if 0 <= age < 3600 and isinstance(cached['plan'], dict):
146
+ return cached['plan'], stamp.isoformat()
147
+ except (KeyError, TypeError, ValueError):
148
+ pass
149
+ return None, None
150
+
151
+
152
+ def _report(summary, as_of, plan, pool):
153
+ plan = plan if isinstance(plan, dict) else {}
154
+ items = plan.get('items') if isinstance(plan.get('items'), list) else []
155
+ kinds = {item.get('kind') or str(item.get('id', '')).split(':')[0]
156
+ for item in items if isinstance(item, dict)}
157
+ pool = pool if isinstance(pool, dict) else {}
158
+ listing = summary.get('skill_listing_budget') or {}
159
+ listing = listing if isinstance(listing, dict) else {}
160
+ def part(key):
161
+ value = summary.get(key)
162
+ return value if isinstance(value, dict) else {}
163
+ count = len(items)
164
+ apply_label = 'Apply safe savings ({} {}, one approval)'.format(count, 'change' if count == 1 else 'changes')
165
+ candidates = [
166
+ ('apply_safe', apply_label, plan.get('total_net_usd_month'), 'firm', 'Based on your last 30 days, after each change’s own costs.', 'Run /token-optimizer:apply-safe.'),
167
+ ('skill_list', 'Trim the skill list', listing.get('cost_usd') if listing.get('available') else None, 'firm', 'Based on skill list growth and your calls in the last 30 days.', 'Review the skill list in the dashboard and choose what to archive.'),
168
+ ('cold_fresh', 'Start fresh on cold big sessions', pool.get('cost_saved_usd', pool.get('cost_usd')), 'upper', 'Based on cold sessions in your last 30 days.', 'Start fresh when you return after an hour: /clear, then your message'),
169
+ ('writes', 'Use targeted edits', part('output_waste').get('cost_saved_usd'), 'upper', 'Based on full-file writes in your last 30 days.', 'Use targeted edits instead of rewriting whole files.'),
170
+ ('stale_reads', 'Avoid stale re-reads', part('stale_reads_reclaimable').get('cost_usd'), 'upper', 'Based on stale re-reads in your last 30 days.', 'Avoid re-reading unchanged files or use .contextignore.'),
171
+ ('routing', 'Review model routing', part('model_routing').get('potential_cost_usd'), 'upper', 'Based on your model usage in the last 30 days.', 'Open the routing section of the dashboard.'),
172
+ ]
173
+ overlap = []
174
+ if kinds.intersection(('cold_guard', 'keepwarm_auto')):
175
+ overlap.append('cold_fresh')
176
+ if kinds.intersection(('unused_skill', 'duplicate_skill')):
177
+ overlap.append('skill_list')
178
+ return {'schema': 1, 'as_of': as_of, 'candidates': candidates,
179
+ 'overlap': overlap, 'has_plan_items': bool(items)}
180
+
181
+
182
+ def _result(facade, report, show_all):
183
+ counted = _call('counted_headline', 'build_overall', facade)
184
+ declined = _read(Path(facade.SNAPSHOT_DIR) / 'next_declined.json')
185
+ disabled = _call('routing_default', 'routing_disabled_at', facade) is not None
186
+ try:
187
+ from . import routing_default
188
+ disabled = disabled or routing_default._env_disabled(os.environ)
189
+ except Exception:
190
+ pass
191
+ actions, hidden = [], []
192
+ for ident, label, value, bound, basis, how in report['candidates']:
193
+ number = _number(value)
194
+ unpriced_plan = ident == 'apply_safe' and report['has_plan_items']
195
+ reason = ('routing-off' if ident == 'routing' and disabled else
196
+ 'declined' if ident in declined else
197
+ 'overlap' if ident in report['overlap'] else
198
+ 'not-positive' if (number is None or number <= 0) and not unpriced_plan else None)
199
+ if reason:
200
+ hidden.append({'id': ident, 'why': reason})
201
+ else:
202
+ actions.append({'id': ident, 'label': label, 'net_usd_month': number if number and number > 0 else None,
203
+ 'bound': bound, 'basis': basis, 'how': how})
204
+ actions.sort(key=lambda action: (action['bound'] != 'firm', -(action['net_usd_month'] or 0)))
205
+ return {'schema': 1, 'as_of': report['as_of'], 'counted': counted,
206
+ 'actions': actions if show_all else actions[:5], 'hidden': hidden}
207
+
208
+
209
+ def _build(facade, summary, as_of, show_all, plan=None):
210
+ if plan is None:
211
+ plan = _call('apply_safe', 'build_plan', facade)
212
+ report = _report(summary, as_of, plan, _call('cold_guard', 'pool', facade))
213
+ return _result(facade, report, show_all)
214
+
215
+
216
+ def build(facade, show_all=False):
217
+ summary, cached = _cached_summary(facade)
218
+ if not cached:
219
+ summary = _compute_summary(facade) or {}
220
+ result = _build(facade, summary, cached or _now().isoformat(), show_all)
221
+ if cached:
222
+ result['cached'] = True
223
+ return result
224
+
225
+
226
+ def _start_refresh(facade):
227
+ try:
228
+ argv = [sys.executable, str(Path(facade.__file__).resolve()), 'next', '--refresh-cache']
229
+ directory = Path(facade.SNAPSHOT_DIR)
230
+ directory.mkdir(parents=True, exist_ok=True)
231
+ except (AttributeError, OSError):
232
+ return
233
+ lock = directory / LOCK_NAME
234
+ stdio = dict(stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
235
+ if os.name == 'nt':
236
+ # The process identity covers the handoff until the child takes the lock.
237
+ with _exclusive(lock, timeout=0) as held:
238
+ if held:
239
+ marker = directory / WINDOWS_PID_MARKER
240
+ pending = _read(marker)
241
+ pid = pending.get('pid')
242
+ spawned_at = _number(pending.get('spawned_at'))
243
+ now = time.time()
244
+ # A worker that dies before taking the lock can leave a marker behind.
245
+ start = pending.get('start')
246
+ in_handoff = (spawned_at is not None and 0 <= now - spawned_at < WINDOWS_HANDOFF_SECONDS
247
+ and pid and start and facade._pid_is_running(pid)
248
+ and process_start(pid) == start)
249
+ if not in_handoff:
250
+ child = spawn_detached(argv, **stdio)
251
+ if child is not None:
252
+ _write(marker, {'pid': child.pid, 'start': process_start(child.pid), 'spawned_at': now})
253
+ return
254
+ fd = _acquire(lock, timeout=0)
255
+ if fd is not None:
256
+ try:
257
+ spawn_detached(argv + [str(fd)], pass_fds=(fd,), **stdio)
258
+ finally:
259
+ # Closing only our copy keeps the lock held by the worker.
260
+ os.close(fd)
261
+
262
+
263
+ def _refresh(facade):
264
+ summary = _compute_summary(facade)
265
+ if summary is None:
266
+ return 1
267
+ # An upgraded install has no stored total until a dashboard refresh, so seed it here.
268
+ if _call('counted_headline', 'build_overall', facade) is None:
269
+ since_install = summary.get('since_install') or _call('savings', '_savings_since_install')
270
+ all_in = (since_install or {}).get('all_in') or {}
271
+ if not (all_in.get('routing_pending') or all_in.get('remeasuring')):
272
+ summary['since_install'] = since_install
273
+ _call('counted_closes', 'on_savings_refresh', facade, summary)
274
+ plan = _call('apply_safe', 'build_plan', facade)
275
+ if not isinstance(plan, dict):
276
+ return 1
277
+ pool = _call('cold_guard', 'pool', facade)
278
+ if not isinstance(pool, dict):
279
+ return 1
280
+ report = _report(summary, _now().isoformat(), plan, pool)
281
+ _write(Path(facade.SNAPSHOT_DIR) / REPORT_NAME, report)
282
+ return 0
283
+
284
+
285
+ def _refresh_worker(facade, args):
286
+ lock = Path(facade.SNAPSHOT_DIR) / LOCK_NAME
287
+ if len(args) == 2 and os.name != 'nt':
288
+ import fcntl
289
+
290
+ fd = int(args[1])
291
+ if not os.path.samestat(os.fstat(fd), lock.stat()):
292
+ return 1
293
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
294
+ os.set_inheritable(fd, False)
295
+ return _refresh(facade)
296
+ with _exclusive(lock) as held:
297
+ if not held:
298
+ return 0
299
+ if os.name == 'nt':
300
+ marker = lock.with_name(WINDOWS_PID_MARKER)
301
+ if _read(marker).get('pid') == os.getpid():
302
+ try:
303
+ marker.unlink(missing_ok=True)
304
+ except OSError:
305
+ pass
306
+ return _refresh(facade)
307
+
308
+
309
+ def _foreground_result(facade, show_all):
310
+ directory = Path(facade.SNAPSHOT_DIR)
311
+ report = _read(directory / REPORT_NAME)
312
+ complete = report.get('schema') == 1 and isinstance(report.get('candidates'), list)
313
+ if not complete:
314
+ summary, as_of = _cached_summary(facade)
315
+ plan, plan_as_of = _cached_plan(directory / PLAN_NAME, _now())
316
+ if plan is None:
317
+ # Skill and cold recommendations can overlap a plan still being built.
318
+ summary.pop('skill_listing_budget', None)
319
+ summary.pop('cache_drop', None)
320
+ stamps = [stamp for stamp in (as_of, plan_as_of) if stamp]
321
+ report = _report(summary, min(stamps, default=None), plan, summary.get('cache_drop'))
322
+ result = _result(facade, report, show_all)
323
+ result['preparing'] = not complete
324
+ if result['as_of']:
325
+ result['cached'] = True
326
+ try:
327
+ _start_refresh(facade)
328
+ except OSError:
329
+ pass
330
+ return result
331
+
332
+
333
+ def main(facade, args):
334
+ if args and args[0] == '--refresh-cache':
335
+ return _refresh_worker(facade, args)
336
+ if args and args[0] in ('decline', 'restore'):
337
+ if len(args) != 2 or args[1] not in IDS:
338
+ print('Unknown action. Run measure.py next --all.')
339
+ return 2
340
+ path = Path(facade.SNAPSHOT_DIR) / 'next_declined.json'
341
+ declined = _read(path)
342
+ if args[0] == 'decline':
343
+ declined[args[1]] = _now().date().isoformat()
344
+ else:
345
+ declined.pop(args[1], None)
346
+ _write(path, declined)
347
+ print('{} {}.'.format('Hidden' if args[0] == 'decline' else 'Restored', args[1]))
348
+ return 0
349
+ if any(arg not in ('--json', '--all') for arg in args):
350
+ print('Usage: measure.py next [--json] [--all]')
351
+ return 2
352
+ result = _foreground_result(facade, '--all' in args)
353
+ if '--json' in args:
354
+ print(json.dumps(result, indent=2))
355
+ return 0
356
+ display = (result.get('counted') or {}).get('display') or {}
357
+ print(display.get('short') or ('Your saved total is being calculated.' if result['preparing'] else 'Saved since install is unavailable.'))
358
+ if result.get('cached'):
359
+ print('as of {}'.format(result['as_of']))
360
+ if result['preparing']:
361
+ print('The full list is being prepared. Run /token-optimizer:next again shortly.')
362
+ if not result['actions'] and not result['preparing']:
363
+ print('Nothing to do right now. You are set.')
364
+ elif result['actions']:
365
+ print("Do next. Worth per month on your own last 30 days, after each action's own costs:")
366
+ for n, action in enumerate(result['actions'], 1):
367
+ value = action['net_usd_month']
368
+ amount = (('${:,.2f}/mo' if value < 10 and value % 1 else '${:,.0f}/mo').format(value)
369
+ if value is not None else 'unpriced')
370
+ print(' {}. {} {}{} {}'.format(n, action['label'], 'up to ' if action['bound'] == 'upper' else '', amount, action['how']))
371
+ if any(item['id'] == 'routing' and item['why'] == 'routing-off' for item in result['hidden']):
372
+ print('Hidden: model routing (you turned it off). Everything: measure.py next --all')
373
+ return 0
374
+
375
+
376
+ def on_savings_refresh(facade, summary):
377
+ if not isinstance(summary, dict) or summary.get('period_days', 30) != 30:
378
+ return
379
+ now = _now()
380
+ cache_path = Path(facade.SNAPSHOT_DIR) / PLAN_NAME
381
+ plan, _ = _cached_plan(cache_path, now)
382
+ if plan is None:
383
+ plan = _call('apply_safe', 'build_plan', facade)
384
+ if isinstance(plan, dict):
385
+ _write(cache_path, {'computed_at': now.isoformat(), 'plan': plan})
386
+ else:
387
+ plan = {}
388
+ result = _build(facade, summary, now.isoformat(), True, plan=plan)
389
+ action = next((item for item in result['actions'] if item['bound'] == 'firm' and item['net_usd_month'] is not None), None)
390
+ directory = Path(facade.SNAPSHOT_DIR)
391
+ history_path = directory / 'next_action_history.json'
392
+ history = _read(history_path)
393
+ output = {}
394
+ if action and action['net_usd_month'] >= 5:
395
+ ident, amount = action['id'], action['net_usd_month']
396
+ record = history.get(ident, {})
397
+ try:
398
+ first = datetime.fromisoformat(record['first_seen'])
399
+ age = (now - first).total_seconds() / 86400
400
+ old_amount = float(record['net_usd_month'])
401
+ except (KeyError, ValueError, TypeError):
402
+ age, old_amount = 0, amount
403
+ record = {'first_seen': now.isoformat(), 'net_usd_month': amount}
404
+ if amount >= 2 * old_amount or age >= 37:
405
+ record = {'first_seen': now.isoformat(), 'net_usd_month': amount}
406
+ age = 0
407
+ history[ident] = record
408
+ if age < 7:
409
+ short = '+${:,.0f}/mo ready: /token-optimizer:next'.format(amount)
410
+ output = {'id': ident, 'short': short[:40], 'net_usd_month': amount,
411
+ 'first_seen': record['first_seen'], 'computed_at': now.isoformat()}
412
+ _write(history_path, history)
413
+ _write(directory / 'next_action.json', output)
414
+
415
+
416
+ def status_action(facade, session_id):
417
+ data = _read(Path(facade.SNAPSHOT_DIR) / 'next_action.json')
418
+ if data.get('id') in IDS and isinstance(data.get('short'), str):
419
+ return {'id': data['id'], 'short': data['short'][:40]}
420
+ return None
@@ -0,0 +1,44 @@
1
+ """Dispatch for the POC savings commands. One lazy import per command."""
2
+ import importlib
3
+
4
+ COMMANDS = {
5
+ "counted-total": "counted_headline",
6
+ "apply-safe": "apply_safe",
7
+ "autocompact-advice": "autocompact_advice",
8
+ "cold-guard": "cold_guard",
9
+ "keepwarm-decide": "keepwarm_auto",
10
+ "next": "next_actions",
11
+ }
12
+
13
+ def run(facade, args):
14
+ """Run args[0]. Returns an exit code. Never raises."""
15
+ try:
16
+ module = importlib.import_module("." + COMMANDS[args[0]], __package__)
17
+ return int(module.main(facade, list(args[1:])) or 0)
18
+ except Exception as err:
19
+ print("Token Optimizer: {} failed ({}).".format(args[0], type(err).__name__))
20
+ return 1
21
+
22
+ REFRESH_MODULES = ("counted_closes", "cold_guard", "keepwarm_auto", "next_actions")
23
+
24
+ def on_savings_refresh(facade, summary):
25
+ """Give each lane one isolated call after a full savings summary was computed. Never raises."""
26
+ for name in REFRESH_MODULES:
27
+ try:
28
+ hook = getattr(importlib.import_module("." + name, __package__), "on_savings_refresh", None)
29
+ if hook is not None:
30
+ hook(facade, summary)
31
+ except Exception:
32
+ pass
33
+
34
+ STATUS_KEYS = (("counted_headline", "counted_headline", "cache_value"), ("next_action", "next_actions", "status_action"))
35
+
36
+ def status_extras(facade, session_id):
37
+ """Top-level keys for the status-bar cache. A missing function or any error gives None for that key."""
38
+ out = {}
39
+ for key, name, attr in STATUS_KEYS:
40
+ try:
41
+ out[key] = getattr(importlib.import_module("." + name, __package__), attr)(facade, session_id)
42
+ except Exception:
43
+ out[key] = None
44
+ return out