@alexgreensh/token-optimizer 5.13.64 → 5.13.66

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 (26) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +62 -13
  4. package/hooks/userpromptsubmit_runner.py +13 -1
  5. package/package.json +1 -1
  6. package/skills/token-optimizer/scripts/_measure/__init__.py +16 -0
  7. package/skills/token-optimizer/scripts/_measure/_compat.py +200 -0
  8. package/skills/token-optimizer/scripts/_measure/audit.py +6949 -0
  9. package/skills/token-optimizer/scripts/_measure/cache_policy.py +6997 -0
  10. package/skills/token-optimizer/scripts/_measure/cli.py +2722 -0
  11. package/skills/token-optimizer/scripts/_measure/continuity.py +4630 -0
  12. package/skills/token-optimizer/scripts/_measure/daemon.py +6773 -0
  13. package/skills/token-optimizer/scripts/_measure/dashboard.py +4358 -0
  14. package/skills/token-optimizer/scripts/_measure/lifecycle.py +5952 -0
  15. package/skills/token-optimizer/scripts/_measure/pricing.py +2101 -0
  16. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7138 -0
  17. package/skills/token-optimizer/scripts/_measure/runtime.py +1231 -0
  18. package/skills/token-optimizer/scripts/_measure/savings.py +7702 -0
  19. package/skills/token-optimizer/scripts/_measure/sessions.py +4784 -0
  20. package/skills/token-optimizer/scripts/_measure/trends.py +2432 -0
  21. package/skills/token-optimizer/scripts/cloud_kit.py +7 -8
  22. package/skills/token-optimizer/scripts/codex_doctor.py +14 -0
  23. package/skills/token-optimizer/scripts/devin_source.py +1 -0
  24. package/skills/token-optimizer/scripts/hermes_doctor.py +13 -0
  25. package/skills/token-optimizer/scripts/hermes_install.py +11 -0
  26. package/skills/token-optimizer/scripts/measure.py +2428 -60928
@@ -13,7 +13,7 @@
13
13
  "name": "token-optimizer",
14
14
  "source": "./",
15
15
  "description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
16
- "version": "5.13.64",
16
+ "version": "5.13.66",
17
17
  "author": {
18
18
  "name": "Alex Greenshpun",
19
19
  "url": "https://linkedin.com/in/alexgreensh"
@@ -55,7 +55,7 @@
55
55
  "name": "token-optimizer-cowork",
56
56
  "source": "./cowork/token-optimizer",
57
57
  "description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
58
- "version": "5.13.64",
58
+ "version": "5.13.66",
59
59
  "author": {
60
60
  "name": "Alex Greenshpun",
61
61
  "url": "https://linkedin.com/in/alexgreensh"
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/alexgreensh/token-optimizer",
9
9
  "repository": "https://github.com/alexgreensh/token-optimizer",
10
- "version": "5.13.64",
10
+ "version": "5.13.66",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
@@ -133,18 +133,57 @@ _COLD_COMPILE_LOCK = ".token-optimizer-compile.lock"
133
133
  _COLD_COMPILE_FAILED = ".token-optimizer-compile.failed"
134
134
  _COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
135
135
 
136
- # The detached compiler, run as `python -c`. It compiles measure.py first and
137
- # drops the lock as soon as that one is written (the hooks only wait for it),
138
- # then warms the consolidated runners and the plugin's other scripts. A
139
- # failure on measure.py leaves a marker keyed to the source's mtime and size,
136
+ # This closed set matches _measure.RUNTIME_SOURCES. No recursive repo scan.
137
+ _MEASURE_PACKAGE_SOURCES = (
138
+ '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
139
+ 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
140
+ 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py',
141
+ )
142
+
143
+
144
+ def _runtime_sources(measure_src):
145
+ package = os.path.join(os.path.dirname(measure_src), '_measure')
146
+ sources = (measure_src,)
147
+ required = os.path.isdir(package)
148
+ if not required:
149
+ # Old unsplit fixture trees have no package. A damaged split install
150
+ # must still include its missing providers in readiness/failure keys.
151
+ try:
152
+ with open(measure_src, 'rb') as stream:
153
+ required = b'from _measure import _compat' in stream.read()
154
+ except OSError:
155
+ pass
156
+ if required:
157
+ sources += tuple(os.path.join(package, name) for name in _MEASURE_PACKAGE_SOURCES)
158
+ return sources
159
+
160
+
161
+ def _source_set_key(measure_src):
162
+ import hashlib
163
+ records = []
164
+ for source in _runtime_sources(measure_src):
165
+ try:
166
+ st = os.stat(source)
167
+ records.append(f'{source}:{st.st_mtime_ns}:{st.st_size}')
168
+ except OSError:
169
+ records.append(f'{source}:missing')
170
+ if len(records) == 1:
171
+ st = os.stat(measure_src)
172
+ return f'{st.st_mtime_ns}:{st.st_size}'
173
+ return hashlib.sha256('\n'.join(records).encode('utf-8')).hexdigest()
174
+
175
+ # The detached compiler warms the entire eager runtime before dropping its
176
+ # lock, then warms the consolidated runners and the other flat scripts. A
177
+ # failure leaves a marker keyed to every required source's mtime and size,
140
178
  # so hooks stop deferring to a compile that cannot succeed and compile inline
141
179
  # as before.
142
180
  _COMPILER_SOURCE = r'''
143
181
  import sys
144
182
  sys.path[:] = [p for p in sys.path if p not in ("", ".")]
145
183
  sys.dont_write_bytecode = False
146
- import os, importlib.util, py_compile
184
+ import os, importlib.util, py_compile, json
147
185
  _tag, lock, failed, prefix, opt, measure_src, hooks_dir, scripts_dir = sys.argv[1:9]
186
+ sources, source_key = json.loads(sys.argv[9]), sys.argv[10]
148
187
  sys.pycache_prefix = prefix or None
149
188
  opt = int(opt)
150
189
  mode = py_compile.PycInvalidationMode.TIMESTAMP
@@ -169,12 +208,12 @@ def _compile(src):
169
208
  py_compile.compile(src, cfile=cfile, doraise=True, optimize=opt, invalidation_mode=mode)
170
209
 
171
210
  try:
172
- _compile(measure_src)
211
+ for source in sources:
212
+ _compile(source)
173
213
  except BaseException:
174
214
  try:
175
- st = os.stat(measure_src)
176
215
  with open(failed, "w", encoding="utf-8") as fh:
177
- fh.write("%d:%d" % (st.st_mtime_ns, st.st_size))
216
+ fh.write(source_key)
178
217
  except OSError:
179
218
  pass
180
219
  finally:
@@ -232,9 +271,8 @@ def _bytecode_fresh(source: str, cache: str) -> bool:
232
271
  def _compile_failed_for(marker: str, source: str) -> bool:
233
272
  """The background compile already failed on this exact source."""
234
273
  try:
235
- st = os.stat(source)
236
274
  with open(marker, encoding="utf-8") as fh:
237
- return fh.read(64).strip() == f"{st.st_mtime_ns}:{st.st_size}"
275
+ return fh.read(128).strip() == _source_set_key(source)
238
276
  except (OSError, ValueError):
239
277
  return False
240
278
 
@@ -277,11 +315,13 @@ def _start_background_compile(lock, failed, measure_src, plugin_scripts):
277
315
  """Start the one detached compiler. Returns its Popen, or None (the lock is
278
316
  then released again and the caller compiles inline)."""
279
317
  import subprocess
318
+ import json
280
319
 
281
320
  hooks_dir = os.path.dirname(os.path.abspath(__file__))
282
321
  argv = [sys.executable, "-c", _COMPILER_SOURCE, _COLD_COMPILE_TAG, lock, failed,
283
322
  getattr(sys, "pycache_prefix", None) or "", str(sys.flags.optimize),
284
- measure_src, hooks_dir, plugin_scripts]
323
+ measure_src, hooks_dir, plugin_scripts,
324
+ json.dumps(_runtime_sources(measure_src)), _source_set_key(measure_src)]
285
325
  proc = None
286
326
  try:
287
327
  from spawn_utils import spawn_detached
@@ -315,7 +355,11 @@ def _measure_bytecode_ready(plugin_scripts: str, wait_s: float) -> bool:
315
355
  cache = _bytecode_path(measure_src)
316
356
  except Exception:
317
357
  return True
318
- if _bytecode_fresh(measure_src, cache):
358
+ def ready():
359
+ return all(_bytecode_fresh(source, _bytecode_path(source))
360
+ for source in _runtime_sources(measure_src))
361
+
362
+ if ready():
319
363
  return True
320
364
  if not os.path.isfile(measure_src):
321
365
  return True
@@ -329,7 +373,7 @@ def _measure_bytecode_ready(plugin_scripts: str, wait_s: float) -> bool:
329
373
  end = time.monotonic() + max(0.0, wait_s)
330
374
  child = None
331
375
  while True:
332
- if _bytecode_fresh(measure_src, cache):
376
+ if ready():
333
377
  return True
334
378
  if _compile_failed_for(failed, measure_src):
335
379
  return True
@@ -452,9 +496,14 @@ def main() -> int:
452
496
  deadline = HookDeadline(110).start()
453
497
  except Exception:
454
498
  deadline = None
499
+ previous_measure = sys.modules.get('measure')
455
500
  try:
456
501
  runpy.run_module(module_name, run_name="__main__", alter_sys=True)
457
502
  finally:
503
+ if previous_measure is None and module_name == 'measure':
504
+ sys.modules.pop('measure', None)
505
+ elif previous_measure is not None:
506
+ sys.modules['measure'] = previous_measure
458
507
  if deadline is not None:
459
508
  try:
460
509
  deadline.cancel()
@@ -92,7 +92,19 @@ _MEASURE_DIR = _resolve_measure_dir()
92
92
  if _MEASURE_DIR and _MEASURE_DIR not in sys.path:
93
93
  sys.path.insert(0, _MEASURE_DIR)
94
94
 
95
- import measure # noqa: E402 (path bootstrapped above)
95
+ # This process only calls the facade, so it may defer the providers no
96
+ # UserPromptSubmit handler runs (_measure.HOOK_IMPORT, consumed by the import).
97
+ try:
98
+ import _measure as _measure_package # noqa: E402
99
+ if "measure" not in sys.modules:
100
+ _measure_package.HOOK_IMPORT = True
101
+ except Exception:
102
+ _measure_package = None
103
+ try:
104
+ import measure # noqa: E402 (path bootstrapped above)
105
+ finally:
106
+ if _measure_package is not None:
107
+ _measure_package.HOOK_IMPORT = False
96
108
 
97
109
 
98
110
  # --------------------------------------------------------------------------- #
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.64",
3
+ "version": "5.13.66",
4
4
  "description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
@@ -0,0 +1,16 @@
1
+ """Definition-only providers for the measure compatibility facade."""
2
+
3
+ # Shared by the facade and the bounded hook warmer. No filesystem discovery.
4
+ DOMAIN_MODULES = (
5
+ 'runtime', 'pricing', 'audit', 'dashboard', 'lifecycle', 'sessions',
6
+ 'trends', 'cache_policy', 'daemon', 'quality_archive', 'continuity',
7
+ 'savings', 'cli',
8
+ )
9
+ # Loaded on first use instead of at facade import, only when the importer sets
10
+ # HOOK_IMPORT. No module-level facade code and no UserPromptSubmit handler
11
+ # uses them (perf attribution, 2026-11-06).
12
+ DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
13
+ RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES)
14
+ # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
15
+ # which consumes it. That process never patches or enumerates the facade.
16
+ HOOK_IMPORT = False
@@ -0,0 +1,200 @@
1
+ """Keep old global lookups and definition-time binding on the active facade."""
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ import importlib.machinery
6
+ import sys
7
+ import threading
8
+ from types import ModuleType
9
+
10
+ _LOCK = threading.RLock()
11
+ _UNSWEPT = [] # deferred bindings a facade statement assigned; the next bind() sweeps them
12
+
13
+
14
+ def facade():
15
+ """Resolve once per invocation, never once per global reference."""
16
+ return sys.modules['measure']
17
+
18
+
19
+ def read_global(module, name):
20
+ """Exception targets retain Python's global/builtin lookup after cleanup."""
21
+ values = vars(module)
22
+ if name in values:
23
+ return values[name]
24
+ builtins = values.get('__builtins__', __builtins__)
25
+ if not isinstance(builtins, dict):
26
+ builtins = vars(builtins)
27
+ try:
28
+ return builtins[name]
29
+ except KeyError:
30
+ raise NameError(f"name '{name}' is not defined", name=name) from None
31
+
32
+
33
+ def prepare(module):
34
+ """Select the active facade and give this initialization fresh definitions.
35
+
36
+ Ordinary reload creates fresh functions without changing functions already
37
+ exported by a previous facade. Providers carry no business state. Only an
38
+ initialization the UserPromptSubmit runner flags (HOOK_IMPORT, consumed
39
+ here) loads DEFERRED_MODULES on first use; every other one is eager.
40
+ """
41
+ from . import DEFERRED_MODULES, DOMAIN_MODULES
42
+ package = sys.modules[__package__]
43
+ hook, package.HOOK_IMPORT = getattr(package, 'HOOK_IMPORT', False) is True, False
44
+ sys.modules['measure'] = module
45
+ values = vars(module)
46
+ for key in [k for k in ('__getattr__', '__dir__') if getattr(values.get(k), '_measure_lazy', False)]:
47
+ del values[key] # a previous lazy initialization's lookups
48
+ providers = Providers(n for n in DOMAIN_MODULES if hook and n in DEFERRED_MODULES)
49
+ for name in DOMAIN_MODULES:
50
+ if name in providers.deferred:
51
+ _require(name)
52
+ else:
53
+ providers[name] = _fresh(name)
54
+ return providers
55
+
56
+
57
+ def _fresh(name):
58
+ qualified = __package__ + '.' + name
59
+ return importlib.reload(sys.modules[qualified]) if qualified in sys.modules else importlib.import_module(qualified)
60
+
61
+
62
+ def _require(name):
63
+ """A missing deferred provider fails the facade import, cached or not."""
64
+ qualified = __package__ + '.' + name
65
+ if importlib.machinery.PathFinder.find_spec(qualified, sys.modules[__package__].__path__) is None:
66
+ raise ModuleNotFoundError(f'No module named {qualified!r}', name=qualified)
67
+
68
+
69
+ class Providers(dict):
70
+ """Provider modules by domain; a deferred one loads and binds all its names on first use."""
71
+ def __init__(self, deferred):
72
+ super().__init__()
73
+ self.deferred = frozenset(deferred)
74
+ self.pending, self.namespace = {}, None
75
+
76
+ def __missing__(self, name):
77
+ if name in self.deferred:
78
+ return _Domain(self, name)
79
+ raise KeyError(name)
80
+
81
+ def load(self, name):
82
+ with _LOCK:
83
+ if dict.__contains__(self, name):
84
+ return dict.__getitem__(self, name)
85
+ provider = self[name] = _fresh(name)
86
+ for key, binding in list(self.pending.items()):
87
+ if binding.domain == name:
88
+ value = binding.resolve()
89
+ if key not in self.namespace: # a caller's assignment wins
90
+ self.namespace[key] = value
91
+ del self.pending[key]
92
+ return provider
93
+
94
+
95
+ class _Domain:
96
+ """A deferred domain not loaded yet: attributes name its definitions."""
97
+ def __init__(self, providers, domain):
98
+ self.providers, self.domain = providers, domain
99
+
100
+ def __getattr__(self, attr):
101
+ return _Binding(self.providers, self.domain, attr)
102
+
103
+
104
+ class _Binding:
105
+ """One definition of a deferred domain, resolved on first use."""
106
+ __slots__ = ('providers', 'domain', 'attr', 'options', 'value', 'namespace')
107
+
108
+ def __init__(self, providers, domain, attr):
109
+ self.providers, self.domain, self.attr, self.options, self.value, self.namespace = providers, domain, attr, None, None, None
110
+
111
+ def resolve(self):
112
+ if self.value is None:
113
+ module_name, options = self.options
114
+ self.value = bind(getattr(self.providers.load(self.domain), self.attr), module_name, **options)
115
+ return self.value
116
+
117
+ def __call__(self, *args, **kwargs): # only before its sweep; adds a traceback frame
118
+ if self.options is None: # a direct provider call, e.g. the facade's __main__ guard
119
+ return getattr(self.providers.load(self.domain), self.attr)(*args, **kwargs)
120
+ return self.resolve()(*args, **kwargs)
121
+
122
+
123
+ def _sweep():
124
+ """Move assigned deferred bindings out of the namespace; __getattr__ (PEP 562) loads them."""
125
+ with _LOCK:
126
+ waiting = [] # bindings whose statement has not assigned them yet
127
+ while _UNSWEPT:
128
+ binding = _UNSWEPT.pop()
129
+ namespace, providers = binding.namespace, binding.providers
130
+ if namespace.get(binding.attr) is not binding:
131
+ waiting.append(binding)
132
+ elif binding.value is not None or dict.__contains__(providers, binding.domain):
133
+ namespace[binding.attr] = binding.resolve()
134
+ else:
135
+ del namespace[binding.attr]
136
+ providers.pending[binding.attr] = binding
137
+ if providers.namespace is None:
138
+ providers.namespace = namespace
139
+ namespace['__getattr__'], namespace['__dir__'] = _lookups(namespace, providers)
140
+ _UNSWEPT[:] = waiting
141
+
142
+
143
+ def _lookups(namespace, providers):
144
+ def __getattr__(name):
145
+ binding = providers.pending.get(name)
146
+ if binding is not None:
147
+ providers.load(binding.domain)
148
+ if name in namespace:
149
+ return namespace[name]
150
+ raise AttributeError(f"module {namespace.get('__name__')!r} has no attribute {name!r}", name=name)
151
+
152
+ def __dir__():
153
+ return sorted(set(namespace) | set(providers.pending))
154
+ __getattr__._measure_lazy = __dir__._measure_lazy = True
155
+ return __getattr__, __dir__
156
+
157
+
158
+ def bind(value, module_name, *, defaults=None, kwdefaults=None, decorators=()):
159
+ """Bind captured defaults, identity and decorators at the old source site;
160
+ a deferred definition is recorded for its facade (the caller's globals)."""
161
+ if _UNSWEPT:
162
+ _sweep()
163
+ if isinstance(value, _Binding):
164
+ value.options = (module_name, {'defaults': defaults, 'kwdefaults': kwdefaults, 'decorators': decorators})
165
+ value.namespace = sys._getframe(1).f_globals
166
+ _UNSWEPT.append(value)
167
+ return value
168
+ value.__module__ = module_name
169
+ if defaults is not None:
170
+ value.__defaults__ = defaults
171
+ if kwdefaults is not None:
172
+ value.__kwdefaults__ = kwdefaults
173
+ for decorator in reversed(decorators):
174
+ value = decorator(value)
175
+ return value
176
+
177
+
178
+ class Namespace:
179
+ """The source-extraction seam uses the test's supplied fake globals."""
180
+ def __init__(self, values):
181
+ object.__setattr__(self, '_values', values)
182
+
183
+ def __getattribute__(self, name):
184
+ values = object.__getattribute__(self, '_values')
185
+ if name == '__dict__':
186
+ return values
187
+ try:
188
+ return values[name]
189
+ except KeyError as exc:
190
+ raise AttributeError(name) from exc
191
+
192
+ def __setattr__(self, name, value):
193
+ object.__getattribute__(self, '_values')[name] = value
194
+
195
+ def __delattr__(self, name):
196
+ del object.__getattribute__(self, '_values')[name]
197
+
198
+
199
+ def namespace(values):
200
+ return Namespace(values)