@alexgreensh/token-optimizer 5.13.77 → 5.13.79

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.
@@ -1,12 +1,12 @@
1
1
  """Fail-closed liveness checks for paused Claude sessions."""
2
2
  import hashlib
3
3
  import json
4
+ import math
4
5
  import os
5
6
  from pathlib import Path
6
7
  import re
7
8
  import shlex
8
9
  import shutil
9
- import stat
10
10
  import subprocess
11
11
  import sys
12
12
  import time
@@ -148,20 +148,7 @@ _NO_OWNER_TTL = 300.0
148
148
 
149
149
  def _owner_cache_path(directory, session_id):
150
150
  name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
151
- return Path(directory) / ('keepwarm-owner-' + name)
152
-
153
-
154
- def _pid_exists(pid):
155
- """Check whether a process may still be running."""
156
- if os.name != 'posix':
157
- return False
158
- try:
159
- os.kill(int(pid), 0)
160
- except PermissionError:
161
- return True
162
- except (OSError, ValueError, TypeError):
163
- return False
164
- return True
151
+ return Path(directory) / ('kw2-owner-' + name)
165
152
 
166
153
 
167
154
  def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_start=None):
@@ -197,10 +184,10 @@ def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_st
197
184
  eligible = owner_eligible(process['pid'])
198
185
  if path is not None:
199
186
  try:
200
- Path(directory).mkdir(parents=True, exist_ok=True)
201
- fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0), 0o600)
202
- with os.fdopen(fd, 'w', encoding='utf-8') as stream:
203
- json.dump({'process': process, 'eligible': eligible, 'ts': now}, stream)
187
+ from codex_io import atomic_write_json
188
+ with keepwarm_rearm.state_lock(path.parent, 0) as held:
189
+ if held:
190
+ atomic_write_json(path, {'process': process, 'eligible': eligible, 'ts': now}, replace_symlink=True)
204
191
  except OSError:
205
192
  pass
206
193
  return process if eligible else None
@@ -215,36 +202,72 @@ def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
215
202
 
216
203
  def _end_path(directory, session_id):
217
204
  name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
218
- return Path(directory) / ('keepwarm-ended-' + name)
205
+ return Path(directory) / ('kw2-ended-' + name)
219
206
 
220
207
 
221
208
  def mark_ended(directory, session_id):
222
209
  if not session_id:
223
210
  return False
224
211
  try:
225
- Path(directory).mkdir(parents=True, exist_ok=True)
212
+ from codex_io import atomic_write
226
213
  path = _end_path(directory, session_id)
227
- flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)
228
- fd = os.open(str(path), flags, 0o600)
229
- with os.fdopen(fd, 'w', encoding='utf-8') as stream:
230
- if hasattr(os, 'fchmod'):
231
- os.fchmod(stream.fileno(), 0o600)
232
- stream.write(str(time.time()))
214
+ stamp = time.time()
215
+ with keepwarm_rearm.state_lock(path.parent, 0) as held:
216
+ if held:
217
+ atomic_write(path, str(stamp), replace_symlink=True)
218
+ else:
219
+ # Immutable input, like a staged Stop. A busy writer cannot lose SessionEnd.
220
+ event = path.parent / 'kw2-ends' / (path.name + '.' + os.urandom(8).hex())
221
+ atomic_write(event, str(stamp), replace_symlink=True)
233
222
  return True
234
223
  except OSError:
235
224
  return False
236
225
 
237
226
 
238
- def ended_since(directory, session_id, armed_at):
227
+ def session_ended(directory, session_id, armed_at):
228
+ path = _end_path(directory, session_id)
229
+ # Imported pauses can still receive SessionEnd from the old hooks.
230
+ pending = path.parent / 'kw2-ends'
239
231
  try:
240
- path = _end_path(directory, session_id)
241
- if path.is_symlink():
242
- return True
243
- return float(path.read_text(encoding='utf-8')) >= float(armed_at)
232
+ events = [pending / name for name in os.listdir(pending) if name.startswith(path.name + '.')]
244
233
  except FileNotFoundError:
245
- return False
246
- except (OSError, ValueError, TypeError):
247
- return True
234
+ events = []
235
+ except OSError:
236
+ return None
237
+ for marker in (path, path.with_name(path.name.replace('kw2-ended-', 'keepwarm-ended-')), *events):
238
+ try:
239
+ if marker.is_symlink():
240
+ return None
241
+ stamp = float(marker.read_text(encoding='utf-8'))
242
+ if not math.isfinite(stamp):
243
+ return None
244
+ if stamp >= float(armed_at):
245
+ return True
246
+ except FileNotFoundError:
247
+ continue
248
+ except (OSError, ValueError, TypeError):
249
+ return None
250
+ return False
251
+
252
+
253
+ def ended_since(directory, session_id, armed_at):
254
+ return session_ended(directory, session_id, armed_at) is not False
255
+
256
+
257
+ def usage_lines(facade, path):
258
+ """Read farther only if the byte suffix cannot answer the usage lookup."""
259
+ try:
260
+ with open(path, 'rb') as stream:
261
+ start = max(0, stream.seek(0, os.SEEK_END) - 65536)
262
+ stream.seek(start)
263
+ lines = stream.read(65536).splitlines()[bool(start):]
264
+ except (OSError, ValueError):
265
+ return
266
+ limit = facade._KEEPWARM_TAIL_LINES
267
+ for line in reversed(lines[-limit:]):
268
+ yield line.decode('utf-8', errors='replace')
269
+ if start and len(lines) < limit:
270
+ yield from reversed(facade._keepwarm_read_tail(path))
248
271
 
249
272
 
250
273
  def terminal_turn(path):
@@ -342,22 +365,27 @@ def _headless_preference_disabled(facade, env):
342
365
 
343
366
 
344
367
  def _headless_latch_reason(facade):
368
+ from .keepwarm_auto import accounting_error, retry_accounting_read
369
+ from .lease_candidate_cleanup import owner_is_gone
345
370
  try:
346
371
  path = _headless_latch(facade)
347
372
  if path.is_symlink():
348
373
  return 'headless-proof'
349
- with path.open(encoding='utf-8') as stream:
350
- state = stream.read(128).split()
374
+ def read():
375
+ with path.open(encoding='utf-8') as stream:
376
+ return stream.read(128).split()
377
+ state = retry_accounting_read(read)
351
378
  if state and state[0] == 'pending':
352
- if len(state) == 3 and state[2].isdecimal() and int(state[2]) > 1 and _pid_exists(state[2]):
379
+ pid = int(state[2]) if len(state) == 3 and state[2].isdecimal() else 0
380
+ if os.name == 'posix' and 1 < pid < 2**31 and not owner_is_gone(pid):
353
381
  return 'headless-busy'
354
382
  if 0 <= facade.time.time() - path.stat().st_mtime < 200:
355
383
  return 'headless-busy'
356
384
  return 'headless-proof'
357
385
  except FileNotFoundError:
358
386
  return None
359
- except OSError:
360
- return 'accounting-unavailable'
387
+ except OSError as exc:
388
+ return 'headless-busy' if accounting_error(exc) == 'ledger-locked' else 'accounting-unavailable'
361
389
  except UnicodeError:
362
390
  return 'headless-proof'
363
391
 
@@ -452,7 +480,7 @@ def _pending_attempt(rows, sid, now, timeout=600):
452
480
  def fire_headless(facade, record, *, now, env=None, runner=None, live=None, meters=None):
453
481
  """Reserve once under the shared lock, then run one bounded fork and prove it."""
454
482
  from .mod_action_booking import _append, _lock
455
- from .keepwarm_auto import read_ledger
483
+ from .keepwarm_auto import accounting_error, read_ledger
456
484
 
457
485
  sid, model = record['session_id'], record['model']
458
486
  context = record['prefix_proxy']
@@ -474,9 +502,10 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
474
502
  if meters is None:
475
503
  meters = _headless_meters(facade, now)
476
504
  try:
505
+ # Stale 5.13.76 readers can exceed the daily cap by multiple pings during upgrade overlap.
477
506
  rows = read_ledger(facade._keepwarm_ledger_path())
478
- except (OSError, ValueError):
479
- return {'fired': False, 'reason': 'accounting-unavailable'}
507
+ except (OSError, ValueError) as exc:
508
+ return {'fired': False, 'reason': accounting_error(exc)}
480
509
  decision = _headless_decision(facade, record, now, env, meters, rows)
481
510
  if decision['action'] != 'ping':
482
511
  return {'fired': False, 'reason': decision['reason']}
@@ -509,6 +538,7 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
509
538
  try:
510
539
  _append(facade._keepwarm_ledger_path(), {**common, 'status': 'firing',
511
540
  'ts': now, 'est_cost_usd': fallback})
541
+ keepwarm_rearm.verify_spend(held)
512
542
  reason = _headless_preference_disabled(facade, env) if live() else 'session-changed'
513
543
  if reason:
514
544
  _append(facade._keepwarm_ledger_path(), {**common, 'status': 'cancelled', 'ts': now})
@@ -531,9 +561,9 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
531
561
  continue
532
562
  _append(facade._keepwarm_ledger_path(), {**common, **outcome, 'ts': max(now, facade.time.time())})
533
563
  recorded = True
534
- if outcome['proof']:
535
- _track_proven_ping(facade, record, now)
536
564
  break
565
+ if recorded and outcome['proof']:
566
+ _track_proven_ping(facade, record, now)
537
567
  finally:
538
568
  # The pending marker excludes other headless pings until we settle it.
539
569
  # If the ledger stays locked, the reservation still counts at fallback cost.
@@ -552,13 +582,12 @@ def _track_proven_ping(facade, record, now):
552
582
  """Append a replacement arm under the shared lock, only after proven usage."""
553
583
  from .mod_action_booking import _append
554
584
 
555
- found = next((rec for rec in reversed(facade.load_keepwarm_records())
556
- if rec.get('session_id') == record['session_id']
557
- and rec.get('byte_size') == record['byte_size']
558
- and rec.get('transcript_mtime') == record['transcript_mtime']), None)
559
- latest = found or record
560
- updated = dict(latest, auto_warm=True, pings_fired=[*(latest.get('pings_fired') or []), now])
561
- _append(facade._keepwarm_sidecar_path(), updated)
585
+ with facade._keepwarm_lock() as held:
586
+ if held:
587
+ found = next((r for r in reversed(facade.load_keepwarm_records()) if same_pause(r, record)
588
+ and r['session_id'] == record['session_id']), record)
589
+ _append(facade._keepwarm_sidecar_path(), dict(found, auto_warm=True,
590
+ pings_fired=[*(found.get('pings_fired') or []), now]))
562
591
 
563
592
 
564
593
  def _headless_meters(facade, now):
@@ -709,26 +738,13 @@ def stop_flush_args(facade, args, hook_input):
709
738
  or 'agent_id' in hook_input or 'agent_type' in hook_input
710
739
  or str(hook_input.get('hook_event_name', 'Stop')).lower() != 'stop'
711
740
  or not facade._keepwarm_valid_arg(sid)
712
- or '--transcript-path' not in args
713
- or headless_disabled(facade) not in (None, 'headless-busy')):
741
+ or '--transcript-path' not in args or 'subagents' in Path(transcript).parts):
714
742
  return args
715
743
  parent_pid = int(os.environ.get(HOOK_PARENT_PID_ENV, '0'))
716
- path = Path(transcript)
717
- snapshot = path.stat()
718
- if parent_pid <= 1 or 'subagents' in path.parts or not stat.S_ISREG(snapshot.st_mode):
719
- return args
720
- from .cold_guard import _bounded_last_usage, _TAIL_BYTES
721
- from .keepwarm_auto import MIN_CONTEXT
722
-
723
- usage, _, _ = _bounded_last_usage(path)
724
- # A large tool result can hide the usage row from this bounded read.
725
- # The existing worker checks the full turn before writing an arm.
726
- incomplete = usage is None and snapshot.st_size > _TAIL_BYTES
727
- if incomplete or (usage and facade._keepwarm_prefix_proxy(usage) >= MIN_CONTEXT):
728
- parent_pid, parent_start = _stop_parent(facade, parent_pid, os.environ.get('TOKEN_OPTIMIZER_HOOK_PARENT_START'))
729
- if parent_start:
730
- args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
731
- '--keepwarm-stop-at', str(now)]
744
+ parent_pid, parent_start = _stop_parent(facade, parent_pid, os.environ.get('TOKEN_OPTIMIZER_HOOK_PARENT_START'))
745
+ if parent_pid > 1 and parent_start:
746
+ args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
747
+ '--keepwarm-stop-at', str(now)]
732
748
  except Exception:
733
749
  pass
734
750
  return args
@@ -749,6 +765,7 @@ def flush_hook_args(facade, args):
749
765
  def run_flush_worker(facade, args):
750
766
  """Arm before the refresh throttle and watch after releasing the flush lock."""
751
767
  record = None
768
+ retry = []
752
769
  try:
753
770
  def value(flag):
754
771
  return next(v for k, v in reversed(list(zip(args, args[1:]))) if k == flag)
@@ -760,11 +777,16 @@ def run_flush_worker(facade, args):
760
777
  if parent_pid > 1 and parent_start:
761
778
  record = facade.write_keepwarm_arm_record(
762
779
  value('--session-id'), value('--transcript-path'),
763
- now=float(value('--keepwarm-stop-at')), parent_pid=parent_pid, parent_start=parent_start,
780
+ now=float(value('--keepwarm-stop-at')), parent_pid=parent_pid, parent_start=parent_start, retry=retry,
764
781
  )
765
782
  except Exception:
766
783
  pass
767
784
  facade._run_session_end_flush_worker(args)
785
+ if retry:
786
+ try:
787
+ record = keepwarm_rearm.retry_due_stop(facade, *retry[0])
788
+ except (OSError, ValueError):
789
+ pass # The scheduler still owns the staged copy.
768
790
  if (record and not facade._daemon_snapshot_sandboxed() and record['ttl_kind'] == '1h'
769
791
  and headless_disabled(facade) in (None, 'headless-busy') and facade._is_priced_model(record['model'])):
770
792
  try:
@@ -777,11 +799,10 @@ def watch_armed_terminal(facade, sid):
777
799
  """Reuse the flush process, with one watcher per terminal session."""
778
800
  import fcntl
779
801
  filename = hashlib.sha256(sid.encode('utf-8')).hexdigest()
780
- path = facade.SNAPSHOT_DIR / ('keepwarm-owner-watch-' + filename)
802
+ path = facade.SNAPSHOT_DIR / ('kw2-watch-' + filename)
781
803
  fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | getattr(os, 'O_NOFOLLOW', 0), 0o600)
782
804
  try:
783
805
  fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
784
- os.utime(fd)
785
806
  except BaseException:
786
807
  os.close(fd)
787
808
  raise
@@ -796,7 +817,8 @@ def _watch_delay(facade, record, fd):
796
817
  disabled = headless_disabled(facade)
797
818
  if disabled not in (None, 'headless-busy') or not record:
798
819
  return None
799
- if not owner_alive(record['owner']) or ended_since(facade.SNAPSHOT_DIR, record['session_id'], record['ts']):
820
+ ended = session_ended(facade.SNAPSHOT_DIR, record['session_id'], record['ts'])
821
+ if ended or not owner_alive(record['owner']):
800
822
  return None
801
823
  rows = facade._keepwarm_load_ledger_rows()
802
824
  if (now - record['last_turn_ts'] > policy.CACHE_LIFETIME * policy.MAX_PER_PAUSE
@@ -804,9 +826,7 @@ def _watch_delay(facade, record, fd):
804
826
  if _pending_attempt(rows, record['session_id'], now, facade._KEEPWARM_PING_TIMEOUT_SECONDS):
805
827
  return 5
806
828
  return None
807
- if now - os.fstat(fd).st_mtime > policy.DAY:
808
- os.utime(fd)
809
- if facade.classify_keepwarm_record(record, now=now) != 'still_paused':
829
+ if ended is None or facade.classify_keepwarm_record(record, now=now) != 'still_paused':
810
830
  return 30
811
831
  if disabled == 'headless-busy':
812
832
  return 5
@@ -69,7 +69,10 @@ def _prepare(facade, event, sid, ident, when):
69
69
  if not acquired:
70
70
  return {'ok': False, 'reason': 'ledger-locked'}
71
71
  from . import keepwarm_auto, keepwarm_safety
72
- rows = keepwarm_auto.read_ledger(facade._keepwarm_ledger_path())
72
+ try:
73
+ rows = keepwarm_auto.read_ledger(facade._keepwarm_ledger_path())
74
+ except (ValueError, OSError) as exc:
75
+ return {'ok': False, 'reason': keepwarm_auto.accounting_error(exc)}
73
76
  existing = [r for r in rows if r.get('action_id') == ident]
74
77
  if existing:
75
78
  return {'ok': False, 'reason': 'attempt-already-reserved' if _compatible(existing, sid) else 'identity-conflict'}
@@ -96,6 +99,8 @@ def _prepare(facade, event, sid, ident, when):
96
99
  _append(facade._keepwarm_ledger_path(), {'status': 'firing', 'source': 'claude-code-mod',
97
100
  'action': 'warm', 'action_id': ident, 'attempt_key': ident, 'session_id': sid,
98
101
  'ts': when, 'est_cost_usd': estimate, 'snapshot': snapshot, **flags})
102
+ from .keepwarm_rearm import verify_spend
103
+ verify_spend(acquired)
99
104
  return {'ok': True, 'duplicate': False}
100
105
 
101
106
 
@@ -165,8 +170,8 @@ def record(facade, event):
165
170
  return {'ok': False, 'reason': 'invalid-usage'}
166
171
  # Old callers can submit an already answered attempt; new mod calls reserve first.
167
172
  facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
168
- with _lock(facade) as acquired:
169
- if not acquired:
173
+ with _lock(facade) as acquired, facade._keepwarm_lock() as state:
174
+ if not acquired or not state:
170
175
  return {'ok': False, 'reason': 'ledger-locked'}
171
176
  existing = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
172
177
  if existing and not _compatible(existing, sid):
@@ -0,0 +1,108 @@
1
+ """Bound the detached dashboard self-heal so it can never run away.
2
+
3
+ The self-heal child rebuilds the dashboard after a hook-path regen ran out of
4
+ time. On very large histories that rebuild used to run for tens of minutes and
5
+ grow to several GB, pushing the machine into swap. The child now:
6
+ * runs at lower CPU priority,
7
+ * exits itself once it passes a wall-clock or peak-memory ceiling,
8
+ * leaves a backoff marker so hooks stop relaunching it for a day.
9
+ A user-opened dashboard is not affected: only the background heal is bounded.
10
+ """
11
+ import os
12
+ import sys
13
+ import threading
14
+ import time
15
+
16
+ BACKOFF_NAME = "dashboard.heal.backoff"
17
+ _DEFAULT_MAX_SECONDS = 600
18
+ _DEFAULT_MAX_MB = 1536
19
+ _DEFAULT_BACKOFF_SECONDS = 24 * 3600
20
+ _POLL_SECONDS = 2.0
21
+
22
+
23
+ def _env_number(name, default):
24
+ try:
25
+ value = float(os.environ.get(name, ""))
26
+ except ValueError:
27
+ return default
28
+ return value if value > 0 else default
29
+
30
+
31
+ def max_seconds():
32
+ return _env_number("TOKEN_OPTIMIZER_SELFHEAL_MAX_SECONDS", _DEFAULT_MAX_SECONDS)
33
+
34
+
35
+ def max_mb():
36
+ return _env_number("TOKEN_OPTIMIZER_SELFHEAL_MAX_MB", _DEFAULT_MAX_MB)
37
+
38
+
39
+ def backoff_seconds():
40
+ return _env_number("TOKEN_OPTIMIZER_SELFHEAL_BACKOFF_SECONDS", _DEFAULT_BACKOFF_SECONDS)
41
+
42
+
43
+ def peak_rss_mb():
44
+ """Peak resident memory of this process in MB, or None where unknown."""
45
+ try:
46
+ import resource
47
+ except ImportError: # Windows: the wall-clock cap still applies.
48
+ return None
49
+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
50
+ # macOS reports bytes, Linux reports kilobytes.
51
+ return peak / (1024 * 1024) if sys.platform == "darwin" else peak / 1024
52
+
53
+
54
+ def backoff_active(snapshot_dir, now=None):
55
+ marker = snapshot_dir / BACKOFF_NAME
56
+ try:
57
+ age = (time.time() if now is None else now) - marker.stat().st_mtime
58
+ except OSError:
59
+ return False
60
+ return 0 <= age < backoff_seconds()
61
+
62
+
63
+ def clear_backoff(snapshot_dir):
64
+ try:
65
+ (snapshot_dir / BACKOFF_NAME).unlink()
66
+ except OSError:
67
+ pass
68
+
69
+
70
+ def _write_backoff(snapshot_dir, reason):
71
+ try:
72
+ snapshot_dir.mkdir(parents=True, exist_ok=True)
73
+ (snapshot_dir / BACKOFF_NAME).write_text(reason + "\n", encoding="utf-8")
74
+ except OSError:
75
+ pass
76
+
77
+
78
+ def check(snapshot_dir, started, now=None, rss_mb=None):
79
+ """Return the reason to stop, or None. Split out so tests need no thread."""
80
+ elapsed = (time.monotonic() if now is None else now) - started
81
+ if elapsed > max_seconds():
82
+ return "time %ds > %ds" % (elapsed, max_seconds())
83
+ rss = peak_rss_mb() if rss_mb is None else rss_mb
84
+ if rss is not None and rss > max_mb():
85
+ return "memory %dMB > %dMB" % (rss, max_mb())
86
+ return None
87
+
88
+
89
+ def start(snapshot_dir, exit_fn=os._exit):
90
+ """Arm the ceilings for this process. Call once, in the self-heal child only."""
91
+ try:
92
+ os.nice(10)
93
+ except (AttributeError, OSError):
94
+ pass
95
+ started = time.monotonic()
96
+
97
+ def watch():
98
+ while True:
99
+ time.sleep(_POLL_SECONDS)
100
+ reason = check(snapshot_dir, started)
101
+ if reason:
102
+ _write_backoff(snapshot_dir, reason)
103
+ exit_fn(3)
104
+ return
105
+
106
+ thread = threading.Thread(target=watch, name="to-selfheal-guard", daemon=True)
107
+ thread.start()
108
+ return thread
@@ -483,7 +483,7 @@ def render_run_sh(root: Path, pycache: Path, version: str) -> str:
483
483
  # Required files for a usable install; the extracted package carries the rest.
484
484
  _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
485
485
  "skills/token-optimizer/scripts/measure.py", "skills/token-optimizer/scripts/session_store.py", "skills/token-optimizer/scripts/session_store_guard.py") + tuple(
486
- "skills/token-optimizer/scripts/_measure/" + name for name in ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py')
486
+ "skills/token-optimizer/scripts/_measure/" + name for name in ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'savings_headline.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py', 'selfheal_guard.py', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'keepwarm_rearm.py', 'next_actions.py')
487
487
  )
488
488
 
489
489
  # Written into the cache dir on install. Uninstall only removes the shared
@@ -64,7 +64,7 @@ SKILL_INSTALL_FILES = (
64
64
 
65
65
 
66
66
  # Completeness is separate from the legacy healthy-output counts.
67
- _MEASURE_PACKAGE_FILES = ('_measure/__init__.py', '_measure/_compat.py', '_measure/runtime.py', '_measure/pricing.py', '_measure/audit.py', '_measure/dashboard.py', '_measure/lifecycle.py', '_measure/sessions.py', '_measure/trends.py', '_measure/cache_policy.py', '_measure/daemon.py', '_measure/quality_archive.py', '_measure/continuity.py', '_measure/savings.py', '_measure/cli.py', '_measure/dashboard_history.py', '_measure/weekly_activity.py', '_measure/headline.py', '_measure/counted_position.py', '_measure/counted_pricing_v5.py', '_measure/transcript_backfill.py', '_measure/counted_subagents.py', '_measure/lean_resume_threshold.py', '_measure/output_reread.py', '_measure/session_effect.py', '_measure/structural_ledger.py', '_measure/structural_archives.py', '_measure/structural_listing.py', '_measure/structural_report.py', '_measure/structural_seed.py', '_measure/structural_value.py', '_measure/rework_metrics.py', '_measure/session_best.py', '_measure/savings_story.py', '_measure/savings_headline.py', '_measure/counted_orphans.py', '_measure/counted_cap.py', '_measure/archive_void_evidence.py', '_measure/cost_per_message_trend.py', '_measure/lean_resume_receivers.py', '_measure/routing_period.py', '_measure/fixture_context.py', '_measure/transcript_product.py', '_measure/periphery_exposure.py', '_measure/structure_funnel.py', '_measure/setup_attachment_counter.py', '_measure/first_read_outcomes.py', '_measure/setup_budget_monitor.py', '_measure/setup_connector_ledger.py', '_measure/first_call_context.py', '_measure/timestamp_cache.py', '_measure/token_type_split.py', '_measure/evidence_parallel.py', '_measure/ttl_period.py', '_measure/first_read_revive.py', '_measure/mcp_archive_tripwire.py', '_measure/compaction_survival.py', '_measure/archive_void_codex.py', '_measure/compression_fixture_void.py', '_measure/feature_health.py', '_measure/archive_health.py', '_measure/coverage_report.py', '_measure/file_refetch.py', '_measure/holdout_report.py', '_measure/structural_dedupe.py', '_measure/setup_step.py', '_measure/baseline_provenance.py', '_measure/own_price_card.py', '_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py', '_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_action_diagnostics.py', '_measure/mod_action_selftest.py', '_measure/install_baseline.py', '_measure/routing_credit.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py', '_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py', '_measure/routing_default.py', '_measure/pilot_report.py', '_measure/nudge_followthrough.py', '_measure/runway_all_in.py', '_measure/session_activity.py', '_measure/routing_savings.py', '_measure/pt_resume_cues.py', '_measure/subscription_audits.py', '_measure/limit_units.py', '_measure/local_adapt.py', '_measure/prefix_cost.py', '_measure/poc_commands.py', '_measure/counted_closes.py', '_measure/counted_headline.py', '_measure/apply_safe.py', '_measure/autocompact_advice.py', '_measure/cold_guard.py', '_measure/keepwarm_auto.py', '_measure/keepwarm_rearm.py', '_measure/next_actions.py')
67
+ _MEASURE_PACKAGE_FILES = ('_measure/__init__.py', '_measure/_compat.py', '_measure/runtime.py', '_measure/pricing.py', '_measure/audit.py', '_measure/dashboard.py', '_measure/lifecycle.py', '_measure/sessions.py', '_measure/trends.py', '_measure/cache_policy.py', '_measure/daemon.py', '_measure/quality_archive.py', '_measure/continuity.py', '_measure/savings.py', '_measure/cli.py', '_measure/dashboard_history.py', '_measure/weekly_activity.py', '_measure/headline.py', '_measure/counted_position.py', '_measure/counted_pricing_v5.py', '_measure/transcript_backfill.py', '_measure/counted_subagents.py', '_measure/lean_resume_threshold.py', '_measure/output_reread.py', '_measure/session_effect.py', '_measure/structural_ledger.py', '_measure/structural_archives.py', '_measure/structural_listing.py', '_measure/structural_report.py', '_measure/structural_seed.py', '_measure/structural_value.py', '_measure/rework_metrics.py', '_measure/session_best.py', '_measure/savings_story.py', '_measure/savings_headline.py', '_measure/counted_orphans.py', '_measure/counted_cap.py', '_measure/archive_void_evidence.py', '_measure/cost_per_message_trend.py', '_measure/lean_resume_receivers.py', '_measure/routing_period.py', '_measure/fixture_context.py', '_measure/transcript_product.py', '_measure/periphery_exposure.py', '_measure/structure_funnel.py', '_measure/setup_attachment_counter.py', '_measure/first_read_outcomes.py', '_measure/setup_budget_monitor.py', '_measure/setup_connector_ledger.py', '_measure/first_call_context.py', '_measure/timestamp_cache.py', '_measure/token_type_split.py', '_measure/evidence_parallel.py', '_measure/ttl_period.py', '_measure/first_read_revive.py', '_measure/mcp_archive_tripwire.py', '_measure/compaction_survival.py', '_measure/archive_void_codex.py', '_measure/compression_fixture_void.py', '_measure/feature_health.py', '_measure/archive_health.py', '_measure/coverage_report.py', '_measure/file_refetch.py', '_measure/holdout_report.py', '_measure/structural_dedupe.py', '_measure/setup_step.py', '_measure/baseline_provenance.py', '_measure/own_price_card.py', '_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py', '_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_action_diagnostics.py', '_measure/mod_action_selftest.py', '_measure/install_baseline.py', '_measure/routing_credit.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py', '_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/selfheal_guard.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py', '_measure/routing_default.py', '_measure/pilot_report.py', '_measure/nudge_followthrough.py', '_measure/runway_all_in.py', '_measure/session_activity.py', '_measure/routing_savings.py', '_measure/pt_resume_cues.py', '_measure/subscription_audits.py', '_measure/limit_units.py', '_measure/local_adapt.py', '_measure/prefix_cost.py', '_measure/poc_commands.py', '_measure/counted_closes.py', '_measure/counted_headline.py', '_measure/apply_safe.py', '_measure/autocompact_advice.py', '_measure/cold_guard.py', '_measure/keepwarm_auto.py', '_measure/keepwarm_rearm.py', '_measure/next_actions.py')
68
68
 
69
69
 
70
70
  def _repo_root() -> Path:
@@ -357,7 +357,7 @@ def _registration_checks() -> list[dict[str, str]]:
357
357
 
358
358
 
359
359
  # Completeness is separate from the legacy healthy-output counts.
360
- _MEASURE_PACKAGE_FILES = ('_measure/__init__.py', '_measure/_compat.py', '_measure/runtime.py', '_measure/pricing.py', '_measure/audit.py', '_measure/dashboard.py', '_measure/lifecycle.py', '_measure/sessions.py', '_measure/trends.py', '_measure/cache_policy.py', '_measure/daemon.py', '_measure/quality_archive.py', '_measure/continuity.py', '_measure/savings.py', '_measure/cli.py', '_measure/dashboard_history.py', '_measure/weekly_activity.py', '_measure/headline.py', '_measure/counted_position.py', '_measure/counted_pricing_v5.py', '_measure/transcript_backfill.py', '_measure/counted_subagents.py', '_measure/lean_resume_threshold.py', '_measure/output_reread.py', '_measure/session_effect.py', '_measure/structural_ledger.py', '_measure/structural_archives.py', '_measure/structural_listing.py', '_measure/structural_report.py', '_measure/structural_seed.py', '_measure/structural_value.py', '_measure/rework_metrics.py', '_measure/session_best.py', '_measure/savings_story.py', '_measure/savings_headline.py', '_measure/counted_orphans.py', '_measure/counted_cap.py', '_measure/archive_void_evidence.py', '_measure/cost_per_message_trend.py', '_measure/lean_resume_receivers.py', '_measure/routing_period.py', '_measure/fixture_context.py', '_measure/transcript_product.py', '_measure/periphery_exposure.py', '_measure/structure_funnel.py', '_measure/setup_attachment_counter.py', '_measure/first_read_outcomes.py', '_measure/setup_budget_monitor.py', '_measure/setup_connector_ledger.py', '_measure/first_call_context.py', '_measure/timestamp_cache.py', '_measure/token_type_split.py', '_measure/evidence_parallel.py', '_measure/ttl_period.py', '_measure/first_read_revive.py', '_measure/mcp_archive_tripwire.py', '_measure/compaction_survival.py', '_measure/archive_void_codex.py', '_measure/compression_fixture_void.py', '_measure/feature_health.py', '_measure/archive_health.py', '_measure/coverage_report.py', '_measure/file_refetch.py', '_measure/holdout_report.py', '_measure/structural_dedupe.py', '_measure/setup_step.py', '_measure/baseline_provenance.py', '_measure/own_price_card.py', '_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py', '_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_action_diagnostics.py', '_measure/mod_action_selftest.py', '_measure/install_baseline.py', '_measure/routing_credit.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py', '_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py', '_measure/routing_default.py', '_measure/pilot_report.py', '_measure/nudge_followthrough.py', '_measure/runway_all_in.py', '_measure/session_activity.py', '_measure/routing_savings.py', '_measure/pt_resume_cues.py', '_measure/subscription_audits.py', '_measure/limit_units.py', '_measure/local_adapt.py', '_measure/prefix_cost.py', '_measure/poc_commands.py', '_measure/counted_closes.py', '_measure/counted_headline.py', '_measure/apply_safe.py', '_measure/autocompact_advice.py', '_measure/cold_guard.py', '_measure/keepwarm_auto.py', '_measure/keepwarm_rearm.py', '_measure/next_actions.py')
360
+ _MEASURE_PACKAGE_FILES = ('_measure/__init__.py', '_measure/_compat.py', '_measure/runtime.py', '_measure/pricing.py', '_measure/audit.py', '_measure/dashboard.py', '_measure/lifecycle.py', '_measure/sessions.py', '_measure/trends.py', '_measure/cache_policy.py', '_measure/daemon.py', '_measure/quality_archive.py', '_measure/continuity.py', '_measure/savings.py', '_measure/cli.py', '_measure/dashboard_history.py', '_measure/weekly_activity.py', '_measure/headline.py', '_measure/counted_position.py', '_measure/counted_pricing_v5.py', '_measure/transcript_backfill.py', '_measure/counted_subagents.py', '_measure/lean_resume_threshold.py', '_measure/output_reread.py', '_measure/session_effect.py', '_measure/structural_ledger.py', '_measure/structural_archives.py', '_measure/structural_listing.py', '_measure/structural_report.py', '_measure/structural_seed.py', '_measure/structural_value.py', '_measure/rework_metrics.py', '_measure/session_best.py', '_measure/savings_story.py', '_measure/savings_headline.py', '_measure/counted_orphans.py', '_measure/counted_cap.py', '_measure/archive_void_evidence.py', '_measure/cost_per_message_trend.py', '_measure/lean_resume_receivers.py', '_measure/routing_period.py', '_measure/fixture_context.py', '_measure/transcript_product.py', '_measure/periphery_exposure.py', '_measure/structure_funnel.py', '_measure/setup_attachment_counter.py', '_measure/first_read_outcomes.py', '_measure/setup_budget_monitor.py', '_measure/setup_connector_ledger.py', '_measure/first_call_context.py', '_measure/timestamp_cache.py', '_measure/token_type_split.py', '_measure/evidence_parallel.py', '_measure/ttl_period.py', '_measure/first_read_revive.py', '_measure/mcp_archive_tripwire.py', '_measure/compaction_survival.py', '_measure/archive_void_codex.py', '_measure/compression_fixture_void.py', '_measure/feature_health.py', '_measure/archive_health.py', '_measure/coverage_report.py', '_measure/file_refetch.py', '_measure/holdout_report.py', '_measure/structural_dedupe.py', '_measure/setup_step.py', '_measure/baseline_provenance.py', '_measure/own_price_card.py', '_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py', '_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_action_diagnostics.py', '_measure/mod_action_selftest.py', '_measure/install_baseline.py', '_measure/routing_credit.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py', '_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/selfheal_guard.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py', '_measure/routing_default.py', '_measure/pilot_report.py', '_measure/nudge_followthrough.py', '_measure/runway_all_in.py', '_measure/session_activity.py', '_measure/routing_savings.py', '_measure/pt_resume_cues.py', '_measure/subscription_audits.py', '_measure/limit_units.py', '_measure/local_adapt.py', '_measure/prefix_cost.py', '_measure/poc_commands.py', '_measure/counted_closes.py', '_measure/counted_headline.py', '_measure/apply_safe.py', '_measure/autocompact_advice.py', '_measure/cold_guard.py', '_measure/keepwarm_auto.py', '_measure/keepwarm_rearm.py', '_measure/next_actions.py')
361
361
 
362
362
 
363
363
  def _engine_checks() -> list[dict[str, str]]:
@@ -106,7 +106,7 @@ _ENABLE_SNIPPET = "plugins:\n enabled:\n - token-optimizer\n"
106
106
 
107
107
 
108
108
  # Completeness is separate from the legacy healthy-output counts.
109
- _MEASURE_PACKAGE_FILES = ('_measure/__init__.py', '_measure/_compat.py', '_measure/runtime.py', '_measure/pricing.py', '_measure/audit.py', '_measure/dashboard.py', '_measure/lifecycle.py', '_measure/sessions.py', '_measure/trends.py', '_measure/cache_policy.py', '_measure/daemon.py', '_measure/quality_archive.py', '_measure/continuity.py', '_measure/savings.py', '_measure/cli.py', '_measure/dashboard_history.py', '_measure/weekly_activity.py', '_measure/headline.py', '_measure/counted_position.py', '_measure/counted_pricing_v5.py', '_measure/transcript_backfill.py', '_measure/counted_subagents.py', '_measure/lean_resume_threshold.py', '_measure/output_reread.py', '_measure/session_effect.py', '_measure/structural_ledger.py', '_measure/structural_archives.py', '_measure/structural_listing.py', '_measure/structural_report.py', '_measure/structural_seed.py', '_measure/structural_value.py', '_measure/rework_metrics.py', '_measure/session_best.py', '_measure/savings_story.py', '_measure/savings_headline.py', '_measure/counted_orphans.py', '_measure/counted_cap.py', '_measure/archive_void_evidence.py', '_measure/cost_per_message_trend.py', '_measure/lean_resume_receivers.py', '_measure/routing_period.py', '_measure/fixture_context.py', '_measure/transcript_product.py', '_measure/periphery_exposure.py', '_measure/structure_funnel.py', '_measure/setup_attachment_counter.py', '_measure/first_read_outcomes.py', '_measure/setup_budget_monitor.py', '_measure/setup_connector_ledger.py', '_measure/first_call_context.py', '_measure/timestamp_cache.py', '_measure/token_type_split.py', '_measure/evidence_parallel.py', '_measure/ttl_period.py', '_measure/first_read_revive.py', '_measure/mcp_archive_tripwire.py', '_measure/compaction_survival.py', '_measure/archive_void_codex.py', '_measure/compression_fixture_void.py', '_measure/feature_health.py', '_measure/archive_health.py', '_measure/coverage_report.py', '_measure/file_refetch.py', '_measure/holdout_report.py', '_measure/structural_dedupe.py', '_measure/setup_step.py', '_measure/baseline_provenance.py', '_measure/own_price_card.py', '_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py', '_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_action_diagnostics.py', '_measure/mod_action_selftest.py', '_measure/install_baseline.py', '_measure/routing_credit.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py', '_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py', '_measure/routing_default.py', '_measure/pilot_report.py', '_measure/nudge_followthrough.py', '_measure/runway_all_in.py', '_measure/session_activity.py', '_measure/routing_savings.py', '_measure/pt_resume_cues.py', '_measure/subscription_audits.py', '_measure/limit_units.py', '_measure/local_adapt.py', '_measure/prefix_cost.py', '_measure/poc_commands.py', '_measure/counted_closes.py', '_measure/counted_headline.py', '_measure/apply_safe.py', '_measure/autocompact_advice.py', '_measure/cold_guard.py', '_measure/keepwarm_auto.py', '_measure/keepwarm_rearm.py', '_measure/next_actions.py')
109
+ _MEASURE_PACKAGE_FILES = ('_measure/__init__.py', '_measure/_compat.py', '_measure/runtime.py', '_measure/pricing.py', '_measure/audit.py', '_measure/dashboard.py', '_measure/lifecycle.py', '_measure/sessions.py', '_measure/trends.py', '_measure/cache_policy.py', '_measure/daemon.py', '_measure/quality_archive.py', '_measure/continuity.py', '_measure/savings.py', '_measure/cli.py', '_measure/dashboard_history.py', '_measure/weekly_activity.py', '_measure/headline.py', '_measure/counted_position.py', '_measure/counted_pricing_v5.py', '_measure/transcript_backfill.py', '_measure/counted_subagents.py', '_measure/lean_resume_threshold.py', '_measure/output_reread.py', '_measure/session_effect.py', '_measure/structural_ledger.py', '_measure/structural_archives.py', '_measure/structural_listing.py', '_measure/structural_report.py', '_measure/structural_seed.py', '_measure/structural_value.py', '_measure/rework_metrics.py', '_measure/session_best.py', '_measure/savings_story.py', '_measure/savings_headline.py', '_measure/counted_orphans.py', '_measure/counted_cap.py', '_measure/archive_void_evidence.py', '_measure/cost_per_message_trend.py', '_measure/lean_resume_receivers.py', '_measure/routing_period.py', '_measure/fixture_context.py', '_measure/transcript_product.py', '_measure/periphery_exposure.py', '_measure/structure_funnel.py', '_measure/setup_attachment_counter.py', '_measure/first_read_outcomes.py', '_measure/setup_budget_monitor.py', '_measure/setup_connector_ledger.py', '_measure/first_call_context.py', '_measure/timestamp_cache.py', '_measure/token_type_split.py', '_measure/evidence_parallel.py', '_measure/ttl_period.py', '_measure/first_read_revive.py', '_measure/mcp_archive_tripwire.py', '_measure/compaction_survival.py', '_measure/archive_void_codex.py', '_measure/compression_fixture_void.py', '_measure/feature_health.py', '_measure/archive_health.py', '_measure/coverage_report.py', '_measure/file_refetch.py', '_measure/holdout_report.py', '_measure/structural_dedupe.py', '_measure/setup_step.py', '_measure/baseline_provenance.py', '_measure/own_price_card.py', '_measure/transcript_stream.py', '_measure/checkpoint_direction.py', '_measure/checkpoint_retention.py', '_measure/keepwarm_safety.py', '_measure/keepwarm_economics.py', '_measure/keepwarm_linux.py', '_measure/mod_action_booking.py', '_measure/mod_action_diagnostics.py', '_measure/mod_action_selftest.py', '_measure/install_baseline.py', '_measure/routing_credit.py', '_measure/mod_compaction_booking.py', '_measure/mod_fresh_booking.py', '_measure/quality_continuity.py', '_measure/quality_checkpoint.py', '_measure/codex_quality.py', '_measure/lease_candidate_cleanup.py', '_measure/session_store_spool.py', '_measure/upgrade_drain_control.py', '_measure/compression_scan_checkpoint.py', '_measure/status_bar_lock.py', '_measure/session_flush_lock.py', '_measure/context_reset_marker.py', '_measure/holdout_fallback.py', '_measure/dashboard_heal_claim.py', '_measure/selfheal_guard.py', '_measure/config_cache.py', '_measure/setup_observation_cache.py', '_measure/status_bar_refresh.py', '_measure/routing_default.py', '_measure/pilot_report.py', '_measure/nudge_followthrough.py', '_measure/runway_all_in.py', '_measure/session_activity.py', '_measure/routing_savings.py', '_measure/pt_resume_cues.py', '_measure/subscription_audits.py', '_measure/limit_units.py', '_measure/local_adapt.py', '_measure/prefix_cost.py', '_measure/poc_commands.py', '_measure/counted_closes.py', '_measure/counted_headline.py', '_measure/apply_safe.py', '_measure/autocompact_advice.py', '_measure/cold_guard.py', '_measure/keepwarm_auto.py', '_measure/keepwarm_rearm.py', '_measure/next_actions.py')
110
110
 
111
111
 
112
112
  def _scripts_dir() -> Path:
@@ -349,16 +349,17 @@ def _exclusive(lock_path, timeout=2.0):
349
349
  os.close(fd)
350
350
 
351
351
 
352
- def _acquire(lock_path, timeout):
353
- """A descriptor holding the lock on ``lock_path``, or None."""
352
+ def _acquire(lock_path, timeout, *, busy=None, nofollow=False):
353
+ """Return a locked fd, busy on contention, or None for unusable storage."""
354
354
  flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
355
355
  try:
356
356
  if os.path.lexists(str(lock_path)) and not stat.S_ISREG(os.stat(str(lock_path)).st_mode):
357
357
  return None
358
- fd = os.open(str(lock_path), flags, 0o600)
358
+ fd = os.open(str(lock_path), flags | (getattr(os, "O_NOFOLLOW", 0) if nofollow else 0), 0o600)
359
359
  except OSError:
360
360
  return None
361
361
  try:
362
+ failure = None
362
363
  usable = stat.S_ISREG(os.fstat(fd).st_mode) and (fcntl is not None or msvcrt is not None)
363
364
  deadline = time.monotonic() + timeout
364
365
  while usable:
@@ -366,15 +367,16 @@ def _acquire(lock_path, timeout):
366
367
  if got:
367
368
  return fd
368
369
  if got is None or time.monotonic() >= deadline:
370
+ failure = busy if got is False else None
369
371
  break
370
372
  time.sleep(0.01)
371
373
  except OSError:
372
- pass
374
+ failure = None
373
375
  except BaseException:
374
376
  os.close(fd)
375
377
  raise
376
378
  os.close(fd)
377
- return None
379
+ return failure
378
380
 
379
381
 
380
382
  def _update(path, mutate):
@@ -2447,7 +2447,7 @@ _cache_ttl_waste_cached = _measure_compat.bind(_measure_providers['cache_policy'
2447
2447
  # cache_health.json / cohort_tripwire.json sites above. NOT compression_log.py
2448
2448
  # (that is a SQLite writer despite its name).
2449
2449
 
2450
- _KEEPWARM_SIDECAR_NAME = "keepwarm_state.jsonl"
2450
+ _KEEPWARM_SIDECAR_NAME = "keepwarm_pauses_v2.jsonl"
2451
2451
  _KEEPWARM_LOCK_NAME = ".keepwarm_state.lock"
2452
2452
  # Records older than this (by their arm ts) are dropped on compaction regardless of
2453
2453
  # state: an arm that never resumed and never got pinged is dead weight after 14d.
@@ -2746,7 +2746,7 @@ _KEEPWARM_IDLE_RECHECK_SECONDS = 120
2746
2746
  # Per-session ping lock filename prefix in SNAPSHOT_DIR.
2747
2747
  _KEEPWARM_PING_LOCK_PREFIX = ".keepwarm_ping."
2748
2748
  # Whole-tick single-instance lock filename.
2749
- _KEEPWARM_TICK_LOCK_NAME = ".keepwarm_tick.lock"
2749
+ _KEEPWARM_TICK_LOCK_NAME = ".keepwarm-tick-v2.lock"
2750
2750
  # Ping-spend / outcome ledger sidecar (operational accounting only; realized
2751
2751
  # savings live in the SQLite path, NOT here).
2752
2752
  _KEEPWARM_LEDGER_NAME = "keepwarm_ledger.jsonl"