@alexgreensh/token-optimizer 5.13.73 → 5.13.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -8
  4. package/hooks/sessionstart_runner.py +25 -0
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/assets/dashboard.html +20 -7
  7. package/skills/token-optimizer/assets/savings_story.js +10 -6
  8. package/skills/token-optimizer/references/cli-reference.md +9 -0
  9. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -2
  10. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +3 -1
  11. package/skills/token-optimizer/scripts/_measure/cache_policy.py +2 -79
  12. package/skills/token-optimizer/scripts/_measure/cli.py +24 -0
  13. package/skills/token-optimizer/scripts/_measure/daemon.py +77 -15
  14. package/skills/token-optimizer/scripts/_measure/install_baseline.py +157 -0
  15. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +16 -3
  16. package/skills/token-optimizer/scripts/_measure/mod_action_diagnostics.py +24 -0
  17. package/skills/token-optimizer/scripts/_measure/mod_action_selftest.py +33 -0
  18. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +4 -4
  19. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +2 -2
  20. package/skills/token-optimizer/scripts/_measure/nudge_followthrough.py +334 -0
  21. package/skills/token-optimizer/scripts/_measure/own_price_card.py +3 -0
  22. package/skills/token-optimizer/scripts/_measure/pilot_report.py +349 -0
  23. package/skills/token-optimizer/scripts/_measure/pricing.py +15 -414
  24. package/skills/token-optimizer/scripts/_measure/quality_archive.py +5 -10
  25. package/skills/token-optimizer/scripts/_measure/routing_credit.py +60 -0
  26. package/skills/token-optimizer/scripts/_measure/routing_default.py +374 -0
  27. package/skills/token-optimizer/scripts/_measure/routing_savings.py +368 -0
  28. package/skills/token-optimizer/scripts/_measure/runway_all_in.py +42 -0
  29. package/skills/token-optimizer/scripts/_measure/savings.py +29 -247
  30. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  31. package/skills/token-optimizer/scripts/_measure/session_activity.py +128 -0
  32. package/skills/token-optimizer/scripts/_measure/ttl_period.py +59 -0
  33. package/skills/token-optimizer/scripts/cloud_kit.py +1 -4
  34. package/skills/token-optimizer/scripts/codex_doctor.py +1 -10
  35. package/skills/token-optimizer/scripts/hermes_doctor.py +1 -10
  36. package/skills/token-optimizer/scripts/hermes_install.py +1 -10
  37. package/skills/token-optimizer/scripts/injection.py +5 -2
  38. package/skills/token-optimizer/scripts/measure.py +4 -4
@@ -0,0 +1,374 @@
1
+ """Model-routing guidance on by default: SessionStart injection + install markers.
2
+
3
+ Routing advice used to be manual-only (``measure.py inject-routing``), so most
4
+ installs never had it and the savings report could not attribute routing
5
+ behavior to Token Optimizer. This module makes it default:
6
+
7
+ * On SessionStart (Claude Code and Codex only) the MODEL_ROUTING managed
8
+ block is injected into the user's GLOBAL instruction file
9
+ (``~/.claude/CLAUDE.md`` / ``$CODEX_HOME/AGENTS.md``) through the existing
10
+ ``inject_managed_block``. The check is cheap: no history scans, one small
11
+ file read, and the block is regenerated without the volatile "last 30
12
+ days" stats line so its bytes are stable across days (prompt-cache
13
+ stability). ``inject_managed_block`` reports "unchanged" and writes
14
+ nothing when the block already matches, so repeat sessions are no-ops.
15
+ * ``routing_injected_at`` (ISO date) is written to the data dir ONCE, the
16
+ first time the block lands. ``routing_enabled_since()`` / the credit
17
+ window helpers expose it so the savings code only credits routing from
18
+ the date the guidance actually existed.
19
+ * Opt-out: ``TOKEN_OPTIMIZER_ROUTING=0`` skips injection.
20
+ ``measure.py inject-routing --uninstall`` removes the block everywhere
21
+ and records ``routing_removed_at``; SessionStart never re-adds it after
22
+ that (a later manual ``inject-routing`` re-enables and clears the mark).
23
+ * First-run audit offer: once per install, one short line suggests
24
+ ``/token-optimizer`` to apply setup trims, only while the trim ledger
25
+ (``structural_ledger``) has no recorded trims.
26
+
27
+ Everything fails open: any error means "do nothing this session", never a
28
+ broken hook.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import os
33
+ import json
34
+ from datetime import datetime, timezone
35
+ from pathlib import Path
36
+
37
+ from . import _compat
38
+
39
+ ENV_FLAG = "TOKEN_OPTIMIZER_ROUTING"
40
+ SECTION = "MODEL_ROUTING"
41
+ INJECTED_MARKER = "routing_injected_at"
42
+ REMOVED_MARKER = "routing_removed_at"
43
+ AUDIT_OFFER_MARKER = "once-audit-offer.json"
44
+ FAILURE_MARKER = "routing_injection_failure"
45
+
46
+ # Runtimes whose instruction file this feature knows how to write.
47
+ _ROUTING_RUNTIMES = ("claude", "codex")
48
+
49
+ AUDIT_OFFER_TEXT = (
50
+ "[Token Optimizer] Run /token-optimizer to find and apply setup trims."
51
+ )
52
+
53
+ _INJECT_NOTICE = (
54
+ "[Token Optimizer] Added model-routing guidance to {name}. "
55
+ "Opt out: TOKEN_OPTIMIZER_ROUTING=0."
56
+ )
57
+
58
+
59
+ def _facade(f=None):
60
+ return f if f is not None else _compat.facade()
61
+
62
+
63
+ def _data_dir(f=None):
64
+ return Path(_facade(f).SNAPSHOT_DIR)
65
+
66
+
67
+ def _marker_path(f, name):
68
+ return _data_dir(f) / name
69
+
70
+
71
+ def _read_marker(f, name):
72
+ """Marker contents (stripped) or None. Never raises."""
73
+ try:
74
+ text = _marker_path(f, name).read_text(encoding="utf-8").strip()
75
+ return text or None
76
+ except (OSError, UnicodeDecodeError):
77
+ return None
78
+
79
+
80
+ def _write_marker(f, name, value):
81
+ """Overwrite a marker. Returns True on write, False on any error."""
82
+ try:
83
+ path = _marker_path(f, name)
84
+ path.parent.mkdir(parents=True, exist_ok=True)
85
+ path.write_text(value, encoding="utf-8")
86
+ return True
87
+ except OSError:
88
+ return False
89
+
90
+
91
+ def _write_marker_once(f, name, value):
92
+ """Create a marker only when absent (O_EXCL). True when this call wrote it."""
93
+ try:
94
+ path = _marker_path(f, name)
95
+ path.parent.mkdir(parents=True, exist_ok=True)
96
+ fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
97
+ except FileExistsError:
98
+ return False
99
+ except OSError:
100
+ return False
101
+ try:
102
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
103
+ fh.write(value)
104
+ except OSError:
105
+ pass
106
+ return True
107
+
108
+
109
+ def _utc_today():
110
+ """ISO date (UTC) used for markers and the pinned block timestamp."""
111
+ return datetime.now(timezone.utc).date().isoformat()
112
+
113
+
114
+ # ------------------------------------------------------------------ markers
115
+
116
+
117
+ def routing_injected_at(f=None, data_dir=None):
118
+ """ISO date Token Optimizer's routing block first landed, or None."""
119
+ if data_dir is not None:
120
+ f = _compat.namespace({"SNAPSHOT_DIR": data_dir})
121
+ return _read_marker(f, INJECTED_MARKER)
122
+
123
+
124
+ def routing_removed_at(f=None, data_dir=None):
125
+ """ISO date the routing block was uninstalled, or None."""
126
+ if data_dir is not None:
127
+ f = _compat.namespace({"SNAPSHOT_DIR": data_dir})
128
+ return _read_marker(f, REMOVED_MARKER)
129
+
130
+
131
+ def routing_enabled_since(f=None, data_dir=None):
132
+ """Start of the routing-enabled window (``routing_injected_at``), or None.
133
+
134
+ This is the date the savings code credits realized routing from. It stays
135
+ set after an uninstall: pair it with :func:`routing_disabled_at` for the
136
+ end of the window, or use :func:`routing_credit_window` for both.
137
+ """
138
+ return routing_injected_at(f, data_dir)
139
+
140
+
141
+ def routing_disabled_at(f=None, data_dir=None):
142
+ """End of the routing-enabled window (``routing_removed_at``), or None."""
143
+ return routing_removed_at(f, data_dir)
144
+
145
+
146
+ def routing_credit_window(f=None, data_dir=None):
147
+ """``(enabled_since, disabled_at)`` ISO dates; either side may be None."""
148
+ return routing_enabled_since(f, data_dir), routing_disabled_at(f, data_dir)
149
+
150
+
151
+ HISTORY = 'routing_intervals.jsonl'
152
+
153
+
154
+ def _intervals(directory, injected=None, removed=None):
155
+ path = Path(directory) / HISTORY
156
+ try:
157
+ events = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines() if line]
158
+ except FileNotFoundError:
159
+ return [(injected, removed)] if injected else []
160
+ result = []
161
+ for event in events:
162
+ if event.get('injected_at') and (not result or result[-1][1]):
163
+ result.append((event['injected_at'], None))
164
+ elif event.get('removed_at') and result and result[-1][1] is None:
165
+ result[-1] = (result[-1][0], event['removed_at'])
166
+ return result
167
+
168
+
169
+ def _append_interval(directory, event, injected=None, removed=None):
170
+ path = Path(directory) / HISTORY
171
+ path.parent.mkdir(parents=True, exist_ok=True)
172
+ if not path.exists() and injected:
173
+ with path.open('a', encoding='utf-8') as stream:
174
+ stream.write(json.dumps({'injected_at': injected}) + '\n')
175
+ if removed:
176
+ stream.write(json.dumps({'removed_at': removed}) + '\n')
177
+ with path.open('a', encoding='utf-8') as stream:
178
+ stream.write(json.dumps(event) + '\n')
179
+
180
+
181
+ def routing_credit_intervals(f=None, data_dir=None):
182
+ if data_dir is not None:
183
+ f = _compat.namespace({'SNAPSHOT_DIR': data_dir})
184
+ return _intervals(_data_dir(f), routing_injected_at(f), routing_removed_at(f))
185
+
186
+
187
+ # ------------------------------------------------------- instruction files
188
+
189
+
190
+ def managed_instruction_candidates(f):
191
+ """Same candidate list the ``inject-routing`` CLI resolves against.
192
+
193
+ Claude Code: project CLAUDE.md files then the global ``~/.claude/CLAUDE.md``.
194
+ Codex: project AGENTS.md files then the global ``$CODEX_HOME/AGENTS.md``.
195
+ """
196
+ f = _facade(f)
197
+ cwd = Path.cwd()
198
+ if f.detect_runtime() == "codex":
199
+ return [cwd / "AGENTS.md", cwd / "AGENTS.override.md",
200
+ Path(f.runtime_home()) / "AGENTS.md"]
201
+ return [cwd / "CLAUDE.md", cwd / ".claude" / "CLAUDE.md",
202
+ Path(f.CLAUDE_DIR) / "CLAUDE.md"]
203
+
204
+
205
+ def global_instruction_file(f):
206
+ """The user's GLOBAL instruction file (last candidate), never a project one."""
207
+ candidates = managed_instruction_candidates(f)
208
+ return candidates[-1] if candidates else None
209
+
210
+
211
+ # ----------------------------------------------------------------- opt-out
212
+
213
+
214
+ def _env_disabled(environ):
215
+ raw = (environ.get(ENV_FLAG) or "").strip().lower()
216
+ return raw in ("0", "false", "no", "off")
217
+
218
+
219
+ # --------------------------------------------------------------- injection
220
+
221
+
222
+ def _routing_block(f):
223
+ """The MODEL_ROUTING block WITHOUT the volatile stats line and WITHOUT a
224
+ history scan (``trends={}`` skips ``_collect_trends_data``)."""
225
+ return _facade(f).generate_model_routing_block(trends={})
226
+
227
+
228
+ def _inject_once(f, notices):
229
+ """Inject the routing block into the global instruction file. Idempotent."""
230
+ f = _facade(f)
231
+ if routing_removed_at(f):
232
+ return # uninstalled on purpose; never re-add
233
+ block = _routing_block(f)
234
+ if not block:
235
+ return
236
+ target = global_instruction_file(f)
237
+ if target is None:
238
+ return
239
+ injected = routing_injected_at(f)
240
+ # Pin the block's "updated" stamp to the first-injection date so the bytes
241
+ # are identical on every later day (cache stability, no daily rewrite).
242
+ stamp = f"{injected or _utc_today()}T00:00"
243
+ try:
244
+ target.parent.mkdir(parents=True, exist_ok=True)
245
+ import injection
246
+ result = injection.inject_managed_block(
247
+ str(target), SECTION, block, timestamp=stamp)
248
+ except Exception as exc:
249
+ _write_marker(f, FAILURE_MARKER, type(exc).__name__)
250
+ return
251
+ action = result.get("action")
252
+ if action in ("inserted", "replaced", "unchanged"):
253
+ try:
254
+ _marker_path(f, FAILURE_MARKER).unlink(missing_ok=True)
255
+ except OSError:
256
+ pass
257
+ else:
258
+ _write_marker(f, FAILURE_MARKER, "injection failed")
259
+ if action in ("inserted", "replaced", "unchanged") and not injected:
260
+ # The block is present (fresh write or already there): stamp the
261
+ # credit-window start once. "unchanged" still counts -- a missing
262
+ # marker with a live block means the date was lost, not the guidance.
263
+ record_injection(f)
264
+ if action in ("inserted", "replaced"):
265
+ notices.append(_INJECT_NOTICE.format(name=target.name))
266
+
267
+
268
+ def record_injection(f=None):
269
+ """Stamp ``routing_injected_at`` and clear ``routing_removed_at``.
270
+
271
+ Called by ``measure.py inject-routing`` after a real (non-dry-run)
272
+ injection so manual installs feed the same credit window as the
273
+ SessionStart path. A re-enable after ``--uninstall`` restarts the window
274
+ at today; a first injection keeps the earliest date (write-once).
275
+ """
276
+ f = _facade(f)
277
+ injected, removed = routing_credit_window(f)
278
+ if not injected or removed:
279
+ _append_interval(_data_dir(f), {'injected_at': _utc_today()}, injected, removed)
280
+ if _read_marker(f, REMOVED_MARKER) is not None:
281
+ _write_marker(f, INJECTED_MARKER, _utc_today())
282
+ else:
283
+ _write_marker_once(f, INJECTED_MARKER, _utc_today())
284
+ try:
285
+ _marker_path(f, REMOVED_MARKER).unlink(missing_ok=True)
286
+ except OSError:
287
+ pass
288
+
289
+
290
+ def uninstall_routing(f=None):
291
+ """Remove MODEL_ROUTING blocks from every instruction candidate and record
292
+ ``routing_removed_at``. Returns {"files": [paths removed]}."""
293
+ f = _facade(f)
294
+ removed = []
295
+ try:
296
+ import injection
297
+ for candidate in managed_instruction_candidates(f):
298
+ if not candidate.exists():
299
+ continue
300
+ result = injection.remove_managed_block(str(candidate), SECTION)
301
+ if result.get("action") == "removed":
302
+ removed.append(str(candidate))
303
+ except Exception:
304
+ pass
305
+ injected, prior_removed = routing_credit_window(f)
306
+ if injected and not prior_removed:
307
+ _append_interval(_data_dir(f), {'removed_at': _utc_today()}, injected, prior_removed)
308
+ _write_marker(f, REMOVED_MARKER, _utc_today())
309
+ return {"files": removed}
310
+
311
+
312
+ # ------------------------------------------------------------ audit offer
313
+
314
+
315
+ def _trims_recorded(f):
316
+ """True when the setup-trim ledger holds any trim. Fails closed (True)
317
+ when the ledger cannot be read, so a broken read never nags."""
318
+ try:
319
+ from . import structural_ledger
320
+ return bool(structural_ledger.load_trims(_data_dir(f)))
321
+ except Exception:
322
+ return True
323
+
324
+
325
+ def _maybe_offer_audit(f, notices):
326
+ """Once per install: one line suggesting /token-optimizer for setup trims,
327
+ only while no setup trims are recorded. Marker written before the notice
328
+ so a failed print cannot re-nag every session."""
329
+ f = _facade(f)
330
+ if _read_marker(f, AUDIT_OFFER_MARKER) is not None:
331
+ return
332
+ if _trims_recorded(f):
333
+ _write_marker_once(f, AUDIT_OFFER_MARKER, _utc_today())
334
+ return
335
+ _write_marker_once(f, AUDIT_OFFER_MARKER, _utc_today())
336
+ notices.append(AUDIT_OFFER_TEXT)
337
+
338
+
339
+ # ------------------------------------------------------------- entry point
340
+
341
+
342
+ def session_start(f=None, environ=None):
343
+ """SessionStart body. Returns user-facing notice strings (possibly empty).
344
+
345
+ Cheap by contract: env checks, two marker stats, one instruction-file
346
+ read, one small ledger read. No history or transcript scans.
347
+
348
+ Under pytest this is a no-op: every write target (instruction file,
349
+ SNAPSHOT_DIR markers, trim ledger) resolves to the developer's real home
350
+ unless a test redirects it, and the suite drives hooks in-process. Same
351
+ guard as sessions.py / cache_policy.py. Tests that want the real path
352
+ delete PYTEST_CURRENT_TEST and point every env override at tmp dirs.
353
+ """
354
+ f = _facade(f)
355
+ environ = os.environ if environ is None else environ
356
+ if os.environ.get("PYTEST_CURRENT_TEST"):
357
+ return []
358
+ notices = []
359
+ try:
360
+ runtime = f.detect_runtime()
361
+ except Exception:
362
+ return notices
363
+ if runtime not in _ROUTING_RUNTIMES:
364
+ return notices
365
+ if not _env_disabled(environ):
366
+ try:
367
+ _inject_once(f, notices)
368
+ except Exception:
369
+ pass
370
+ try:
371
+ _maybe_offer_audit(f, notices)
372
+ except Exception:
373
+ pass
374
+ return notices