@alexgreensh/token-optimizer 5.13.76 → 5.13.78

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,17 +1,18 @@
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
13
13
 
14
- from process_identity import process_start
14
+ from process_identity import process_parent, process_start
15
+ from . import keepwarm_rearm
15
16
 
16
17
 
17
18
  def process_info(pid):
@@ -119,6 +120,7 @@ def owner_eligible(pid):
119
120
  def _find_claude_process(pid=None, lookup=None):
120
121
  pid = os.getppid() if pid is None else pid
121
122
  lookup = process_info if lookup is None else lookup
123
+ children = []
122
124
  for _ in range(16):
123
125
  if pid <= 1:
124
126
  break
@@ -126,7 +128,12 @@ def _find_claude_process(pid=None, lookup=None):
126
128
  if not info:
127
129
  break
128
130
  if is_claude_command(info['command']):
131
+ for child, start, parent in children:
132
+ current = lookup(child)
133
+ if not current or (current['start'], current['ppid']) != (start, parent):
134
+ return None
129
135
  return {'pid': pid, 'start': info['start']}
136
+ children.append((pid, info['start'], info['ppid']))
130
137
  pid = info['ppid']
131
138
  return None
132
139
 
@@ -141,20 +148,7 @@ _NO_OWNER_TTL = 300.0
141
148
 
142
149
  def _owner_cache_path(directory, session_id):
143
150
  name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
144
- return Path(directory) / ('keepwarm-owner-' + name)
145
-
146
-
147
- def _pid_exists(pid):
148
- """Check whether a process may still be running."""
149
- if os.name != 'posix':
150
- return False
151
- try:
152
- os.kill(int(pid), 0)
153
- except PermissionError:
154
- return True
155
- except (OSError, ValueError, TypeError):
156
- return False
157
- return True
151
+ return Path(directory) / ('kw2-owner-' + name)
158
152
 
159
153
 
160
154
  def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_start=None):
@@ -190,10 +184,10 @@ def session_owner(directory, session_id, now=None, *, parent_pid=None, parent_st
190
184
  eligible = owner_eligible(process['pid'])
191
185
  if path is not None:
192
186
  try:
193
- Path(directory).mkdir(parents=True, exist_ok=True)
194
- fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0), 0o600)
195
- with os.fdopen(fd, 'w', encoding='utf-8') as stream:
196
- 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)
197
191
  except OSError:
198
192
  pass
199
193
  return process if eligible else None
@@ -208,36 +202,56 @@ def owner_alive(owner, lookup=process_info, eligibility=owner_eligible):
208
202
 
209
203
  def _end_path(directory, session_id):
210
204
  name = hashlib.sha256(str(session_id).encode('utf-8')).hexdigest()
211
- return Path(directory) / ('keepwarm-ended-' + name)
205
+ return Path(directory) / ('kw2-ended-' + name)
212
206
 
213
207
 
214
208
  def mark_ended(directory, session_id):
215
209
  if not session_id:
216
210
  return False
217
211
  try:
218
- Path(directory).mkdir(parents=True, exist_ok=True)
212
+ from codex_io import atomic_write
219
213
  path = _end_path(directory, session_id)
220
- flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, 'O_NOFOLLOW', 0)
221
- fd = os.open(str(path), flags, 0o600)
222
- with os.fdopen(fd, 'w', encoding='utf-8') as stream:
223
- if hasattr(os, 'fchmod'):
224
- os.fchmod(stream.fileno(), 0o600)
225
- 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)
226
222
  return True
227
223
  except OSError:
228
224
  return False
229
225
 
230
226
 
231
- 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'
232
231
  try:
233
- path = _end_path(directory, session_id)
234
- if path.is_symlink():
235
- return True
236
- 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 + '.')]
237
233
  except FileNotFoundError:
238
- return False
239
- except (OSError, ValueError, TypeError):
240
- 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
241
255
 
242
256
 
243
257
  def terminal_turn(path):
@@ -335,22 +349,27 @@ def _headless_preference_disabled(facade, env):
335
349
 
336
350
 
337
351
  def _headless_latch_reason(facade):
352
+ from .keepwarm_auto import accounting_error, retry_accounting_read
353
+ from .lease_candidate_cleanup import owner_is_gone
338
354
  try:
339
355
  path = _headless_latch(facade)
340
356
  if path.is_symlink():
341
357
  return 'headless-proof'
342
- with path.open(encoding='utf-8') as stream:
343
- state = stream.read(128).split()
358
+ def read():
359
+ with path.open(encoding='utf-8') as stream:
360
+ return stream.read(128).split()
361
+ state = retry_accounting_read(read)
344
362
  if state and state[0] == 'pending':
345
- if len(state) == 3 and state[2].isdecimal() and int(state[2]) > 1 and _pid_exists(state[2]):
363
+ pid = int(state[2]) if len(state) == 3 and state[2].isdecimal() else 0
364
+ if os.name == 'posix' and 1 < pid < 2**31 and not owner_is_gone(pid):
346
365
  return 'headless-busy'
347
366
  if 0 <= facade.time.time() - path.stat().st_mtime < 200:
348
367
  return 'headless-busy'
349
368
  return 'headless-proof'
350
369
  except FileNotFoundError:
351
370
  return None
352
- except OSError:
353
- return 'accounting-unavailable'
371
+ except OSError as exc:
372
+ return 'headless-busy' if accounting_error(exc) == 'ledger-locked' else 'accounting-unavailable'
354
373
  except UnicodeError:
355
374
  return 'headless-proof'
356
375
 
@@ -433,10 +452,10 @@ def _run_ping(facade, runner, command, cwd, env, context, fallback_cost):
433
452
  return row
434
453
 
435
454
 
436
- def _pending_attempt(rows, sid, now):
455
+ def _pending_attempt(rows, sid, now, timeout=600):
437
456
  pending = {r.get('action_id') for r in rows if r.get('session_id') == sid
438
457
  and r.get('action_id') and r.get('status') == 'firing'
439
- and float(r['ts']) > now - 600}
458
+ and now - timeout < float(r['ts']) <= now}
440
459
  finished = {r.get('action_id') for r in rows if r.get('session_id') == sid
441
460
  and r.get('status') in ('ok', 'error', 'timeout', 'cancelled', 'unproved')}
442
461
  return bool(pending - finished)
@@ -445,6 +464,7 @@ def _pending_attempt(rows, sid, now):
445
464
  def fire_headless(facade, record, *, now, env=None, runner=None, live=None, meters=None):
446
465
  """Reserve once under the shared lock, then run one bounded fork and prove it."""
447
466
  from .mod_action_booking import _append, _lock
467
+ from .keepwarm_auto import accounting_error, read_ledger
448
468
 
449
469
  sid, model = record['session_id'], record['model']
450
470
  context = record['prefix_proxy']
@@ -455,20 +475,28 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
455
475
  return {'fired': False, 'reason': 'launch-unavailable'}
456
476
  if live is None:
457
477
  live = lambda: facade.classify_keepwarm_record(record, now=now) == 'still_paused'
458
- if meters is None:
459
- meters = _headless_meters(facade, now)
460
478
  if env is None:
461
479
  env = facade.os.environ
462
480
  latch = _headless_latch(facade)
463
481
  with _lock(facade) as held:
464
482
  if not held:
465
- return {'fired': False, 'reason': 'ledger-locked'}
466
- rows = facade._keepwarm_load_ledger_rows()
483
+ return {'fired': False, 'reason': 'ledger-locked' if held is False else 'accounting-unavailable'}
484
+ # A different session can reserve the last slot while we wait.
485
+ now = facade.time.time()
486
+ if meters is None:
487
+ meters = _headless_meters(facade, now)
488
+ try:
489
+ # Stale 5.13.76 readers can exceed the daily cap by multiple pings during upgrade overlap.
490
+ rows = read_ledger(facade._keepwarm_ledger_path())
491
+ except (OSError, ValueError) as exc:
492
+ return {'fired': False, 'reason': accounting_error(exc)}
467
493
  decision = _headless_decision(facade, record, now, env, meters, rows)
468
494
  if decision['action'] != 'ping':
469
495
  return {'fired': False, 'reason': decision['reason']}
470
- if _pending_attempt(rows, sid, now) or not live():
471
- return {'fired': False, 'reason': 'session-changed-or-busy'}
496
+ if _pending_attempt(rows, sid, now):
497
+ return {'fired': False, 'reason': 'attempt-in-progress'}
498
+ if not live():
499
+ return {'fired': False, 'reason': 'session-changed'}
472
500
  action_id = 'headless-' + os.urandom(16).hex()
473
501
  pause_key = facade._keepwarm_pause_key(sid, record['ts'])
474
502
  fallback = facade._get_model_cost(model, 1000, 0, 0, context,
@@ -486,14 +514,15 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
486
514
  '--permission-prompts', 'none', '--settings', settings,
487
515
  '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}'])
488
516
  try:
489
- fd = os.open(str(latch), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
517
+ keepwarm_rearm.publish_exclusive(latch, f'pending {action_id} {os.getpid()}')
518
+ except FileExistsError:
519
+ return {'fired': False, 'reason': _headless_latch_reason(facade) or 'headless-busy'}
490
520
  except OSError:
491
- return {'fired': False, 'reason': 'headless-proof'}
521
+ return {'fired': False, 'reason': 'accounting-unavailable'}
492
522
  try:
493
- with os.fdopen(fd, 'w') as stream:
494
- stream.write(f'pending {action_id} {os.getpid()}')
495
523
  _append(facade._keepwarm_ledger_path(), {**common, 'status': 'firing',
496
524
  'ts': now, 'est_cost_usd': fallback})
525
+ keepwarm_rearm.verify_spend(held)
497
526
  reason = _headless_preference_disabled(facade, env) if live() else 'session-changed'
498
527
  if reason:
499
528
  _append(facade._keepwarm_ledger_path(), {**common, 'status': 'cancelled', 'ts': now})
@@ -516,9 +545,9 @@ def fire_headless(facade, record, *, now, env=None, runner=None, live=None, mete
516
545
  continue
517
546
  _append(facade._keepwarm_ledger_path(), {**common, **outcome, 'ts': max(now, facade.time.time())})
518
547
  recorded = True
519
- if outcome['proof']:
520
- _track_proven_ping(facade, record, now)
521
548
  break
549
+ if recorded and outcome['proof']:
550
+ _track_proven_ping(facade, record, now)
522
551
  finally:
523
552
  # The pending marker excludes other headless pings until we settle it.
524
553
  # If the ledger stays locked, the reservation still counts at fallback cost.
@@ -537,13 +566,12 @@ def _track_proven_ping(facade, record, now):
537
566
  """Append a replacement arm under the shared lock, only after proven usage."""
538
567
  from .mod_action_booking import _append
539
568
 
540
- found = next((rec for rec in reversed(facade.load_keepwarm_records())
541
- if rec.get('session_id') == record['session_id']
542
- and rec.get('byte_size') == record['byte_size']
543
- and rec.get('transcript_mtime') == record['transcript_mtime']), None)
544
- latest = found or record
545
- updated = dict(latest, auto_warm=True, pings_fired=[*(latest.get('pings_fired') or []), now])
546
- _append(facade._keepwarm_sidecar_path(), updated)
569
+ with facade._keepwarm_lock() as held:
570
+ if held:
571
+ found = next((r for r in reversed(facade.load_keepwarm_records()) if same_pause(r, record)
572
+ and r['session_id'] == record['session_id']), record)
573
+ _append(facade._keepwarm_sidecar_path(), dict(found, auto_warm=True,
574
+ pings_fired=[*(found.get('pings_fired') or []), now]))
547
575
 
548
576
 
549
577
  def _headless_meters(facade, now):
@@ -554,15 +582,19 @@ def _headless_meters(facade, now):
554
582
  return data['five_hour_pct'], data['seven_day_pct']
555
583
 
556
584
 
557
- def _headless_decision(facade, record, now, env, meters, rows):
558
- from . import keepwarm_auto as policy
559
-
560
- since_turn = now - record['last_turn_ts']
585
+ def _cache_age(record, now, rows):
561
586
  last_ping = max((float(r['ts']) for r in rows if r.get('session_id') == record['session_id']
562
587
  and r.get('action') == 'warm' and r.get('status') == 'ok'
563
588
  and r.get('proof') is not False and record['last_turn_ts'] <= float(r['ts']) <= now),
564
589
  default=record['last_turn_ts'])
565
- since_cache = now - last_ping
590
+ return now - last_ping
591
+
592
+
593
+ def _headless_decision(facade, record, now, env, meters, rows):
594
+ from . import keepwarm_auto as policy
595
+
596
+ since_turn = now - record['last_turn_ts']
597
+ since_cache = _cache_age(record, now, rows)
566
598
  if since_cache < policy.BUCKETS[0]:
567
599
  return {'action': 'stop', 'reason': 'not-due', 'due_in_s': policy.BUCKETS[0] - since_cache}
568
600
  if since_cache >= policy.CACHE_LIFETIME - 15:
@@ -580,11 +612,11 @@ def scheduler_tick(facade, now, dry_run, env, runner):
580
612
  if not held:
581
613
  return dict(summary, reason='tick-already-running')
582
614
  if not dry_run:
615
+ keepwarm_rearm.recover_pending(facade, now)
583
616
  booked = facade.keepwarm_detect_realized(now=now)
584
617
  facade.compact_keepwarm_sidecar(now=now)
585
618
  if allowed:
586
- latest = {record['session_id']: record for record in facade.load_keepwarm_records()
587
- if record.get('owner')}
619
+ latest = keepwarm_rearm.latest_terminal_arms(facade)
588
620
  for sid, record in latest.items():
589
621
  try:
590
622
  at = now if dry_run or runner is not None else facade.time.time()
@@ -651,6 +683,31 @@ def desktop_headless_main(facade, args):
651
683
  HOOK_PARENT_PID_ENV = 'TOKEN_OPTIMIZER_HOOK_PARENT_PID'
652
684
 
653
685
 
686
+ def _stop_parent(facade, pid, expected):
687
+ # The host can run the hook under a shell that exits before the detached
688
+ # worker imports measure. Pin the nearest Claude ancestor while it exists.
689
+ original = pid, process_start(pid)
690
+ if not expected or original[1] != expected:
691
+ return pid, None
692
+ chain = {}
693
+ start = original[1]
694
+ while start and pid > 1 and len(chain) < 16:
695
+ executable = facade._posix_exe_path(pid)
696
+ if not executable:
697
+ break
698
+ if is_claude_command(executable):
699
+ if (process_start(pid) == start and all(
700
+ process_parent(child) == parent and process_start(child) == stamp
701
+ for child, (stamp, parent) in chain.items())):
702
+ return pid, start
703
+ return pid, None
704
+ parent = process_parent(pid)
705
+ chain[pid] = start, parent
706
+ pid = parent
707
+ start = process_start(pid) if pid and pid > 1 and pid not in chain else None
708
+ return original
709
+
710
+
654
711
  def stop_flush_args(facade, args, hook_input):
655
712
  """Forward the hook payload and opt the existing worker into eligible arms."""
656
713
  args = list(args)
@@ -665,22 +722,13 @@ def stop_flush_args(facade, args, hook_input):
665
722
  or 'agent_id' in hook_input or 'agent_type' in hook_input
666
723
  or str(hook_input.get('hook_event_name', 'Stop')).lower() != 'stop'
667
724
  or not facade._keepwarm_valid_arg(sid)
668
- or '--transcript-path' not in args
669
- or headless_disabled(facade) not in (None, 'headless-busy')):
725
+ or '--transcript-path' not in args or 'subagents' in Path(transcript).parts):
670
726
  return args
671
727
  parent_pid = int(os.environ.get(HOOK_PARENT_PID_ENV, '0'))
672
- path = Path(transcript)
673
- if parent_pid <= 1 or 'subagents' in path.parts or not stat.S_ISREG(path.stat().st_mode):
674
- return args
675
- from .cold_guard import _bounded_last_usage
676
- from .keepwarm_auto import MIN_CONTEXT
677
-
678
- usage, _, _ = _bounded_last_usage(path)
679
- if usage and facade._keepwarm_prefix_proxy(usage) >= MIN_CONTEXT:
680
- parent_start = process_start(parent_pid)
681
- if parent_start:
682
- args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
683
- '--keepwarm-stop-at', str(now)]
728
+ parent_pid, parent_start = _stop_parent(facade, parent_pid, os.environ.get('TOKEN_OPTIMIZER_HOOK_PARENT_START'))
729
+ if parent_pid > 1 and parent_start:
730
+ args += ['--keepwarm-parent-pid', str(parent_pid), '--keepwarm-parent-start', parent_start,
731
+ '--keepwarm-stop-at', str(now)]
684
732
  except Exception:
685
733
  pass
686
734
  return args
@@ -718,7 +766,7 @@ def run_flush_worker(facade, args):
718
766
  pass
719
767
  facade._run_session_end_flush_worker(args)
720
768
  if (record and not facade._daemon_snapshot_sandboxed() and record['ttl_kind'] == '1h'
721
- and not headless_disabled(facade) and facade._is_priced_model(record['model'])):
769
+ and headless_disabled(facade) in (None, 'headless-busy') and facade._is_priced_model(record['model'])):
722
770
  try:
723
771
  watch_armed_terminal(facade, record['session_id'])
724
772
  except OSError:
@@ -729,56 +777,49 @@ def watch_armed_terminal(facade, sid):
729
777
  """Reuse the flush process, with one watcher per terminal session."""
730
778
  import fcntl
731
779
  filename = hashlib.sha256(sid.encode('utf-8')).hexdigest()
732
- path = facade.SNAPSHOT_DIR / ('keepwarm-owner-watch-' + filename)
780
+ path = facade.SNAPSHOT_DIR / ('kw2-watch-' + filename)
733
781
  fd = os.open(str(path), os.O_CREAT | os.O_WRONLY | getattr(os, 'O_NOFOLLOW', 0), 0o600)
734
782
  try:
735
783
  fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
736
- os.utime(fd)
737
784
  except BaseException:
738
785
  os.close(fd)
739
786
  raise
740
787
  watch_terminal(facade, sid, fd)
741
788
 
742
789
 
743
- def watch_terminal(facade, sid, fd):
744
- """Use current arm and meter evidence at the deadline, then yield at the caps."""
790
+ def _watch_delay(facade, record, fd):
791
+ """Seconds until the next check, or None when this pause is finished."""
745
792
  from . import keepwarm_auto as policy
746
- if not facade._keepwarm_valid_arg(sid):
747
- return 1
748
- try:
749
- os.fstat(fd)
750
- while True:
751
- now = facade.time.time()
752
- disabled = headless_disabled(facade)
753
- if disabled == 'headless-busy':
754
- facade.time.sleep(5)
755
- continue
756
- if disabled:
757
- return 0
758
- records = [r for r in facade.load_keepwarm_records() if r.get('session_id') == sid and r.get('owner')]
759
- if not records:
760
- return 0
761
- record = records[-1]
762
- if not owner_alive(record['owner']) or ended_since(facade.SNAPSHOT_DIR, sid, record['ts']):
763
- return 0
764
- if now - record['last_turn_ts'] > policy.CACHE_LIFETIME * policy.MAX_PER_PAUSE:
765
- return 0
766
- if now - os.fstat(fd).st_mtime > policy.DAY:
767
- os.utime(fd)
768
- state = facade.classify_keepwarm_record(record, now=now)
769
- if state != 'still_paused':
770
- # A new turn is writing its transcript and will arm on Stop.
771
- facade.time.sleep(30)
772
- continue
773
- rows = facade._keepwarm_load_ledger_rows()
774
- decision = _headless_decision(facade, record, now, None, _headless_meters(facade, now), rows)
775
- if decision['reason'] == 'not-due':
776
- facade.time.sleep(min(60, max(1, decision['due_in_s'])))
777
- continue
778
- if decision['action'] != 'ping':
779
- return 0
780
- result = fire_headless(facade, record, now=now)
781
- if not result.get('proof'):
782
- return 0
783
- finally:
784
- os.close(fd)
793
+
794
+ now = facade.time.time()
795
+ disabled = headless_disabled(facade)
796
+ if disabled not in (None, 'headless-busy') or not record:
797
+ return None
798
+ ended = session_ended(facade.SNAPSHOT_DIR, record['session_id'], record['ts'])
799
+ if ended or not owner_alive(record['owner']):
800
+ return None
801
+ rows = facade._keepwarm_load_ledger_rows()
802
+ if (now - record['last_turn_ts'] > policy.CACHE_LIFETIME * policy.MAX_PER_PAUSE
803
+ or _cache_age(record, now, rows) >= policy.CACHE_LIFETIME - 15):
804
+ if _pending_attempt(rows, record['session_id'], now, facade._KEEPWARM_PING_TIMEOUT_SECONDS):
805
+ return 5
806
+ return None
807
+ if ended is None or facade.classify_keepwarm_record(record, now=now) != 'still_paused':
808
+ return 30
809
+ if disabled == 'headless-busy':
810
+ return 5
811
+ decision = _headless_decision(facade, record, now, None, _headless_meters(facade, now), rows)
812
+ if decision['reason'] == 'not-due':
813
+ return min(60, max(1, decision['due_in_s']))
814
+ if decision['action'] == 'ping':
815
+ decision = fire_headless(facade, record, now=now)
816
+ if decision.get('proof'):
817
+ return 0
818
+ retryable = ('headless-busy', 'ledger-locked', 'attempt-in-progress', 'not-due')
819
+ if not decision.get('fired') and decision['reason'] in retryable:
820
+ return 5
821
+ return None
822
+
823
+
824
+ def watch_terminal(facade, sid, fd):
825
+ return keepwarm_rearm.watch_terminal(facade, sid, fd, _watch_delay)
@@ -50,9 +50,8 @@ def _snapshot(facade, event, sid):
50
50
 
51
51
 
52
52
  def _lock(facade):
53
- facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
54
- path = facade.SNAPSHOT_DIR / (facade._KEEPWARM_LOCK_NAME + '.lease')
55
- return facade.lease_lock(path, acquire_timeout=2.0, cohort_throttle=False, reclaim_released=True)
53
+ from .keepwarm_rearm import writer_lock
54
+ return writer_lock(facade, 2.0)
56
55
 
57
56
 
58
57
  def _compatible(rows, sid):
@@ -69,11 +68,14 @@ def _prepare(facade, event, sid, ident, when):
69
68
  with _lock(facade) as acquired:
70
69
  if not acquired:
71
70
  return {'ok': False, 'reason': 'ledger-locked'}
72
- rows = facade._keepwarm_load_ledger_rows()
71
+ from . import keepwarm_auto, keepwarm_safety
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'}
76
- from . import keepwarm_auto, keepwarm_safety
77
79
  if keepwarm_safety._pending_attempt(rows, sid, when):
78
80
  return {'ok': False, 'reason': 'attempt-in-progress'}
79
81
  flags = {key: event[key] for key in ('auto', 'proof') if key in event}
@@ -93,9 +95,12 @@ def _prepare(facade, event, sid, ident, when):
93
95
  return {'ok': False, 'reason': decision['reason']}
94
96
  snapshot['proof_context'] = context
95
97
  estimate = max(estimate, decision['ping_cost_usd'])
98
+ when = now
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
 
@@ -107,6 +112,7 @@ def _cancel(facade, event, sid, ident, when):
107
112
  if not rows or not _compatible(rows, sid) or any(r.get('status') == 'ok' for r in rows):
108
113
  return {'ok': False, 'reason': 'reservation-unavailable'}
109
114
  if not any(r.get('status') == 'cancelled' for r in rows):
115
+ when = max([when] + [r['ts'] for r in rows if r.get('status') == 'firing'])
110
116
  _append(facade._keepwarm_ledger_path(), {'status': 'cancelled', 'source': 'claude-code-mod',
111
117
  'action': 'warm', 'action_id': ident, 'session_id': sid, 'ts': when,
112
118
  **{key: event[key] for key in ('auto', 'proof') if key in event}})
@@ -164,8 +170,8 @@ def record(facade, event):
164
170
  return {'ok': False, 'reason': 'invalid-usage'}
165
171
  # Old callers can submit an already answered attempt; new mod calls reserve first.
166
172
  facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
167
- with _lock(facade) as acquired:
168
- if not acquired:
173
+ with _lock(facade) as acquired, facade._keepwarm_lock() as state:
174
+ if not acquired or not state:
169
175
  return {'ok': False, 'reason': 'ledger-locked'}
170
176
  existing = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
171
177
  if existing and not _compatible(existing, sid):
@@ -181,6 +187,9 @@ def record(facade, event):
181
187
  from .keepwarm_auto import proof_ok
182
188
  if reservation is None or reservation.get('auto') is not True:
183
189
  return {'ok': False, 'reason': 'reservation-unavailable'}
190
+ # Clients can echo the earlier request time. An outcome must
191
+ # settle its reservation or the spend summary charges it twice.
192
+ when = max(when, reservation['ts'])
184
193
  flags = {'auto': True, 'proof': flags.get('proof') is True and proof_ok(
185
194
  usage, snapshot.get('proof_context')) and not any(r.get('proof') is False for r in existing)}
186
195
  model, ttl = snapshot['model'], snapshot['ttl']
@@ -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', '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', '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/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/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: