@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.
@@ -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.77",
16
+ "version": "5.13.79",
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.77",
58
+ "version": "5.13.79",
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.77",
10
+ "version": "5.13.79",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
@@ -134,7 +134,7 @@ _COLD_COMPILE_FAILED = ".token-optimizer-compile.failed"
134
134
  _COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
135
135
 
136
136
  # This closed set matches _measure.RUNTIME_SOURCES. No recursive repo scan.
137
- _MEASURE_PACKAGE_SOURCES = ('__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')
137
+ _MEASURE_PACKAGE_SOURCES = ('__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')
138
138
 
139
139
 
140
140
  def _runtime_sources(measure_src):
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.77",
3
+ "version": "5.13.79",
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)",
@@ -11,7 +11,7 @@ DOMAIN_MODULES = (
11
11
  # uses them (perf attribution, 2026-11-06).
12
12
  DEFERRED_MODULES = ('audit', 'dashboard', 'sessions', 'savings', 'cli')
13
13
  RUNTIME_SOURCES = ('__init__.py', '_compat.py') + tuple(name + '.py' for name in DOMAIN_MODULES) + ('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')
14
- RUNTIME_SOURCES += ('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',)
14
+ RUNTIME_SOURCES += ('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',)
15
15
  RUNTIME_SOURCES += ('nudge_followthrough.py', 'runway_all_in.py',)
16
16
  RUNTIME_SOURCES += ('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',)
17
17
  # Set True by hooks/userpromptsubmit_runner.py right before `import measure`,
@@ -1,7 +1,6 @@
1
1
  """Lane B: compact-window advice."""
2
2
  from collections import Counter
3
3
  from datetime import datetime, timedelta, timezone
4
- import math
5
4
  import os
6
5
  import statistics
7
6
  import json
@@ -297,6 +296,12 @@ def _median_compaction_cost(facade):
297
296
  return statistics.median(costs) if costs else None
298
297
 
299
298
 
299
+ # Token Optimizer's recommended compact window for 1M-context models: past
300
+ # about 300K tokens every turn re-reads a long history for little extra recall.
301
+ RECOMMENDED_WINDOW = 300000
302
+ _SUMMARY_TOKENS = 20000
303
+
304
+
300
305
  def recommend(facade):
301
306
  """Recommend only when observed history and exact pricing support a net gain."""
302
307
  if getattr(facade, '_is_foreign_runtime', lambda: False)():
@@ -320,13 +325,12 @@ def recommend(facade):
320
325
  if (settings.get('env') or {}).get('CLAUDE_AUTOCOMPACT_PCT_OVERRIDE') is not None:
321
326
  return {'blocked': 'env', 'text': 'The existing percentage override changes the effective compact window.'}
322
327
  current, _ = facade.effective_compact_window(model, env=os.environ, settings=settings)
323
- if current <= 500000:
328
+ if current <= RECOMMENDED_WINDOW:
324
329
  return None
325
330
  peaks = [max(t['context'] for t in turns) for turns, _ in sessions]
326
331
  if sum(peak >= 300000 for peak in peaks) < 20:
327
332
  return None
328
- p75 = sorted(peaks)[max(0, math.ceil(len(peaks) * .75) - 1)]
329
- target = 400000 if p75 < 300000 else 500000 if p75 > 450000 else 450000
333
+ target = RECOMMENDED_WINDOW
330
334
  gross = 0.0
331
335
  crossings = 0
332
336
  happened = 0
@@ -353,6 +357,10 @@ def recommend(facade):
353
357
  extra = max(0, crossings - happened)
354
358
  card = limit_units._resolve_card(facade, model, per_request=True, full_input=target)
355
359
  cost = _median_compaction_cost(facade) if extra else 0
360
+ if cost is None and card and card.get('cache_read') is not None and card.get('output') is not None:
361
+ # No measured compactions yet: price one summary call instead of
362
+ # dropping the advice. Reads the context once, writes ~20K tokens.
363
+ cost = (target * card['cache_read'] + _SUMMARY_TOKENS * card['output']) / 1000000
356
364
  write_rate = card.get('cache_write_1h', card.get('input') * 2 if card.get('input') is not None else None) if card else None
357
365
  if write_rate is None or cost is None:
358
366
  return None
@@ -374,7 +382,7 @@ def plan_item(facade, advice=None):
374
382
  if not advice or advice.get('blocked'):
375
383
  return None
376
384
  return dict(advice, id='autocompact_window', kind='autocompact_window',
377
- label='Compact earlier' + (' for ' + advice['model'] if advice['per_model'] else ''),
385
+ label='Compact at 300K (recommended)' + (' for ' + advice['model'] if advice['per_model'] else ''),
378
386
  tokens_per_request=0, basis=advice['text'], default_selected=True,
379
387
  undo='measure.py apply-safe --undo <receipt_id>')
380
388
 
@@ -384,7 +392,7 @@ def apply_item(facade, item, before_write=None):
384
392
  if getattr(facade, '_is_foreign_runtime', lambda: False)():
385
393
  return {'ok': False}
386
394
  target, model = item.get('target'), item.get('model')
387
- if target not in (400000, 450000, 500000) or not isinstance(model, str) or not model:
395
+ if target != RECOMMENDED_WINDOW or not isinstance(model, str) or not model:
388
396
  return {'ok': False}
389
397
  with facade._settings_lock(user_initiated=True) as acquired:
390
398
  if not acquired:
@@ -391,57 +391,29 @@ def _keepwarm_sidecar_path():
391
391
 
392
392
 
393
393
  def _keepwarm_lock():
394
- """Serialize sidecar and ledger mutations until the writer releases its fd."""
394
+ """Serialize pause mutations until the writer releases its fd."""
395
395
  from . import keepwarm_rearm
396
396
  _measure_facade = _compat.facade()
397
397
  deadline = _measure_facade.current_deadline()
398
398
  timeout = min(0.075, deadline.remaining()) if deadline is not None else 0.075
399
- with keepwarm_rearm.writer_lock(_measure_facade, timeout) as acquired:
399
+ with keepwarm_rearm.state_lock(_measure_facade.SNAPSHOT_DIR, timeout) as acquired:
400
400
  yield acquired
401
401
 
402
402
 
403
403
  def _keepwarm_append_line(path, line):
404
- """Append one already-serialized line to `path` under the keep-warm lock.
405
-
406
- The shared sidecar append pattern: take _keepwarm_lock, ensure
407
- SNAPSHOT_DIR exists, create the file 0600 BEFORE the first write (or re-chmod
408
- an existing one) so a group/other-readable sidecar can never exist, then
409
- append. Returns True on success, False on any OSError. Used by the arm-writer
410
- and the ping ledger; both serialize through the same lock so an
411
- append can never tear against a concurrent compaction rewrite.
412
- """
413
- _measure_facade = _compat.facade()
404
+ """Append with the lock that owns this file."""
405
+ from . import mod_action_booking
406
+ facade = _compat.facade()
407
+ lock = mod_action_booking._lock(facade) if path == facade._keepwarm_ledger_path() else facade._keepwarm_lock()
414
408
  try:
415
- with _measure_facade._keepwarm_lock() as acquired:
416
- if not acquired:
417
- return False
418
- try:
419
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
420
- except OSError:
421
- return False
422
- try:
423
- # Open the append target with O_NOFOLLOW so a pre-planted symlink
424
- # at this path (same-UID TOCTOU, security M3) cannot redirect our
425
- # ledger/state JSON into a victim file: ELOOP -> hard skip. Create
426
- # 0600 if absent. The single fd we write to is the file itself, so
427
- # no separate chmod-then-open race remains.
428
- flags = _measure_facade.os.O_APPEND | _measure_facade.os.O_CREAT | _measure_facade.os.O_WRONLY
429
- if hasattr(_measure_facade.os, "O_NOFOLLOW"):
430
- flags |= _measure_facade.os.O_NOFOLLOW
431
- try:
432
- fd = _measure_facade.os.open(str(path), flags, 0o600)
433
- except OSError:
434
- # ELOOP (symlink) or any open failure -> refuse to write.
435
- return False
436
- try:
437
- with _measure_facade.os.fdopen(fd, "a", encoding="utf-8") as fh:
438
- fh.write(line)
439
- except OSError:
440
- return False
441
- except OSError:
409
+ with lock as held:
410
+ if not held:
442
411
  return False
412
+ flags = facade.os.O_APPEND | facade.os.O_CREAT | facade.os.O_WRONLY | getattr(facade.os, 'O_NOFOLLOW', 0)
413
+ with facade.os.fdopen(facade.os.open(path, flags, 0o600), 'a', encoding='utf-8') as stream:
414
+ stream.write(line)
443
415
  return True
444
- except Exception:
416
+ except OSError:
445
417
  return False
446
418
 
447
419
 
@@ -494,30 +466,17 @@ def _keepwarm_read_tail(filepath, max_lines=None):
494
466
 
495
467
 
496
468
  def _keepwarm_last_usage(filepath):
497
- """Scan a transcript tail for the most recent assistant turn carrying usage.
498
-
499
- Returns (usage_dict, model, ts_str) for the last record whose
500
- message.usage is non-empty, or (None, None, None) if none found / unreadable.
501
- Read-only. Used by the fast arm-writer to derive prefix_proxy + ttl_kind
502
- without re-parsing the whole session.
503
- """
469
+ """Find the last main-session assistant usage within the existing line limit."""
504
470
  _measure_facade = _compat.facade()
505
- lines = _measure_facade._keepwarm_read_tail(filepath)
506
- for line in reversed(lines):
507
- line = line.strip()
508
- if not line:
509
- continue
471
+ from . import keepwarm_safety
472
+ for line in keepwarm_safety.usage_lines(_measure_facade, filepath):
510
473
  try:
511
474
  record = _measure_facade.json.loads(line)
512
- except (_measure_facade.json.JSONDecodeError, ValueError):
475
+ except ValueError:
513
476
  continue
514
477
  if not isinstance(record, dict):
515
478
  continue
516
- # Parser parity (integration M2): the realized-booking path
517
- # (parse_session_turns) only reads type=="assistant" turns, so the arm
518
- # writer must use the SAME definition of a usage turn. Arming off a
519
- # non-assistant usage record would spend pings on a session whose resume
520
- # turn the booker can never read -- structurally-impossible payback.
479
+ # Booking also requires main-session assistant usage.
521
480
  if record.get("type") != "assistant" or record.get("isSidechain") or record.get("agentId") or record.get("teamName"):
522
481
  continue
523
482
  msg = record.get("message", {})
@@ -525,9 +484,7 @@ def _keepwarm_last_usage(filepath):
525
484
  continue
526
485
  usage = msg.get("usage", {})
527
486
  if isinstance(usage, dict) and usage:
528
- model = msg.get("model") or record.get("model")
529
- ts = record.get("timestamp") or record.get("ts")
530
- return usage, model, ts
487
+ return usage, msg.get("model") or record.get("model"), record.get("timestamp") or record.get("ts")
531
488
  return None, None, None
532
489
 
533
490
 
@@ -560,7 +517,7 @@ def _keepwarm_iso_to_epoch(ts):
560
517
  return None
561
518
 
562
519
 
563
- def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_pid=None, parent_start=None):
520
+ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_pid=None, parent_start=None, retry=None):
564
521
  """Record a paused terminal snapshot from the flush worker."""
565
522
  _measure_facade = _compat.facade()
566
523
  try:
@@ -578,13 +535,16 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
578
535
  tp = _measure_facade.Path(transcript_path)
579
536
  now = _measure_facade.time.time() if now is None else now
580
537
  snapshot = tp.stat()
538
+ import stat
539
+ if not stat.S_ISREG(snapshot.st_mode):
540
+ return None
581
541
  turn = None
582
542
  if parent_pid is not None:
583
543
  turn = keepwarm_safety.terminal_turn(tp)
584
544
  turn_epoch = _measure_facade._keepwarm_iso_to_epoch(turn["timestamp"]) if turn else None
585
545
  if (turn_epoch is None or turn_epoch > now or not _measure_facade._keepwarm_valid_arg(session_id)
586
- or "subagents" in tp.parts or keepwarm_safety.ended_since(
587
- _measure_facade.SNAPSHOT_DIR, session_id, turn_epoch)):
546
+ or "subagents" in tp.parts or keepwarm_safety.session_ended(
547
+ _measure_facade.SNAPSHOT_DIR, session_id, turn_epoch) is True):
588
548
  return None
589
549
  usage, model, ts = _measure_facade._keepwarm_last_usage(tp)
590
550
  if not usage:
@@ -625,7 +585,7 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
625
585
  }
626
586
  if turn is not None:
627
587
  record["terminal_turn"] = turn
628
- return keepwarm_rearm.publish_arm(_measure_facade, record, tp, turn)
588
+ return keepwarm_rearm.publish_arm(_measure_facade, record, retry)
629
589
  except Exception:
630
590
  # Absolute backstop: nothing in the arm path may propagate to the hook.
631
591
  return None
@@ -639,12 +599,13 @@ def _valid_keepwarm_record(rec):
639
599
  if not isinstance(rec.get("session_id"), str) or not rec["session_id"] or not rec.get("transcript_path"):
640
600
  return False
641
601
  try:
642
- return _measure_facade.math.isfinite(float(rec.get("ts")))
602
+ return "ts" in rec and all(_measure_facade.math.isfinite(float(rec[key])) for key in
603
+ ("ts", "last_turn_ts", "transcript_mtime") if key in rec)
643
604
  except (TypeError, ValueError, OverflowError):
644
605
  return False
645
606
 
646
607
 
647
- def load_keepwarm_records(path=None):
608
+ def load_keepwarm_records(path=None, *, strict=False):
648
609
  """Load valid arm records from the sidecar; corrupt lines are skipped.
649
610
 
650
611
  Returns a list of record dicts (possibly empty). Never raises: a missing file
@@ -656,8 +617,6 @@ def load_keepwarm_records(path=None):
656
617
  path = _measure_facade._keepwarm_sidecar_path()
657
618
  records = []
658
619
  try:
659
- if not _measure_facade.Path(path).exists():
660
- return []
661
620
  with open(path, "r", encoding="utf-8", errors="replace") as fh:
662
621
  for line in fh:
663
622
  line = line.strip()
@@ -669,7 +628,11 @@ def load_keepwarm_records(path=None):
669
628
  continue
670
629
  if _measure_facade._valid_keepwarm_record(rec):
671
630
  records.append(rec)
631
+ except FileNotFoundError:
632
+ return []
672
633
  except OSError:
634
+ if strict:
635
+ raise
673
636
  return []
674
637
  return records
675
638
 
@@ -712,12 +675,14 @@ def classify_keepwarm_record(rec, now=None):
712
675
  from . import keepwarm_safety
713
676
  owner = rec.get("owner")
714
677
  mod_receipt = owner is None and rec.get("pings_fired") and (rec.get("manual_action_id") or rec.get("auto_warm"))
715
- if ((not mod_receipt and not keepwarm_safety.owner_alive(owner)) or keepwarm_safety.ended_since(
716
- _measure_facade.SNAPSHOT_DIR, rec.get("session_id"), arm_ts)):
678
+ ended = keepwarm_safety.session_ended(_measure_facade.SNAPSHOT_DIR, rec.get("session_id"), arm_ts)
679
+ if ended is None:
680
+ return "unavailable"
681
+ if ended or (not mod_receipt and not keepwarm_safety.owner_alive(owner)):
717
682
  return "gone"
718
683
  if "terminal_turn" in rec:
719
684
  turn = keepwarm_safety.terminal_turn(p)
720
- return "still_paused" if turn and turn == rec["terminal_turn"] else "resumed"
685
+ return "unavailable" if turn is None else ("still_paused" if turn == rec["terminal_turn"] else "resumed")
721
686
  try:
722
687
  armed_size = int(rec["byte_size"])
723
688
  except (KeyError, TypeError, ValueError):
@@ -749,7 +714,10 @@ def compact_keepwarm_sidecar(path=None, now=None):
749
714
  with _measure_facade._keepwarm_lock() as acquired:
750
715
  if not acquired:
751
716
  return (0, 0)
752
- records = _measure_facade.load_keepwarm_records(path)
717
+ try:
718
+ records = _measure_facade.load_keepwarm_records(path, strict=True)
719
+ except OSError:
720
+ return 0, 0
753
721
  # Account for corrupt/invalid lines as dropped for the caller's visibility.
754
722
  try:
755
723
  raw_lines = 0
@@ -763,31 +731,17 @@ def compact_keepwarm_sidecar(path=None, now=None):
763
731
  dropped += len(records) - len(latest)
764
732
  for rec in latest.values():
765
733
  verdict = _measure_facade.classify_keepwarm_record(rec, now=now)
766
- if verdict == "still_paused":
734
+ if verdict in ("still_paused", "unavailable"):
767
735
  kept.append(rec)
768
736
  else:
769
737
  dropped += 1
770
738
  if not path.exists() and not kept:
771
739
  return 0, dropped
772
740
  try:
773
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
774
- fd, tmp_name = _measure_facade.tempfile.mkstemp(
775
- prefix=".keepwarm_state.", suffix=".tmp", dir=str(_measure_facade.SNAPSHOT_DIR))
776
- try:
777
- if hasattr(_measure_facade.os, "fchmod"):
778
- _measure_facade.os.fchmod(fd, 0o600)
779
- with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
780
- for rec in kept:
781
- fh.write(_measure_facade.json.dumps(rec) + "\n")
782
- _measure_facade.os.replace(tmp_name, str(path))
783
- except Exception:
784
- try:
785
- _measure_facade.os.unlink(tmp_name)
786
- except OSError:
787
- pass
788
- raise
741
+ from codex_io import atomic_write
742
+ atomic_write(path, ''.join(_measure_facade.json.dumps(r) + "\n" for r in kept), replace_symlink=True)
789
743
  except OSError:
790
- pass
744
+ return 0, 0
791
745
  return len(kept), dropped
792
746
 
793
747
 
@@ -2224,71 +2178,11 @@ def _keepwarm_emit_tick_observability(now, allowed, reason, armed, fired,
2224
2178
 
2225
2179
 
2226
2180
  def _keepwarm_tick_singleton():
2227
- """Yield True iff this process holds the whole-tick single-instance lock.
2228
-
2229
- Pidfile-style (O_CREAT|O_EXCL) so a hung/long tick blocks the next scheduled
2230
- tick rather than overlapping it. Stale locks (dead owner + old mtime) are
2231
- reclaimed. Yields False (caller exits quietly) when another tick is live.
2232
- """
2233
- _measure_facade = _compat.facade()
2234
- held = False
2235
- lock_path = _measure_facade.SNAPSHOT_DIR / _measure_facade._KEEPWARM_TICK_LOCK_NAME
2236
- fd = None
2237
- try:
2238
- try:
2239
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
2240
- except OSError:
2241
- yield False
2242
- return
2243
- try:
2244
- fd = _measure_facade.os.open(str(lock_path), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
2245
- except FileExistsError:
2246
- # Reclaim if stale.
2247
- now = _measure_facade.time.time()
2248
- try:
2249
- st = lock_path.stat()
2250
- owner = None
2251
- try:
2252
- owner = int(lock_path.read_text(encoding="utf-8").strip() or 0)
2253
- except (OSError, ValueError):
2254
- owner = None
2255
- alive = False
2256
- if owner and owner > 0:
2257
- alive = _measure_facade._pid_is_running(owner)
2258
- if not alive and (now - st.st_mtime) > _measure_facade._KEEPWARM_STALE_LOCK_SECONDS:
2259
- try:
2260
- _measure_facade.os.unlink(str(lock_path))
2261
- fd = _measure_facade.os.open(str(lock_path),
2262
- _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
2263
- except OSError:
2264
- yield False
2265
- return
2266
- else:
2267
- yield False
2268
- return
2269
- except OSError:
2270
- yield False
2271
- return
2272
- except OSError:
2273
- yield False
2274
- return
2275
- try:
2276
- _measure_facade.os.write(fd, str(_measure_facade.os.getpid()).encode("ascii"))
2277
- except OSError:
2278
- pass
2279
- held = True
2280
- yield True
2281
- finally:
2282
- if fd is not None:
2283
- try:
2284
- _measure_facade.os.close(fd)
2285
- except OSError:
2286
- pass
2287
- if held:
2288
- try:
2289
- _measure_facade.os.unlink(str(lock_path))
2290
- except OSError:
2291
- pass
2181
+ """Only one scheduler runs per generation. Process exit releases its lock."""
2182
+ from . import keepwarm_rearm
2183
+ facade = _compat.facade()
2184
+ with keepwarm_rearm.os_lock(facade.SNAPSHOT_DIR / facade._KEEPWARM_TICK_LOCK_NAME, 0) as held:
2185
+ yield held
2292
2186
 
2293
2187
 
2294
2188
  def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
@@ -2434,41 +2328,25 @@ def keepwarm_tick(now=None, dry_run=None, env=None, runner=None,
2434
2328
 
2435
2329
 
2436
2330
  def _keepwarm_rewrite_records(records, now=None):
2437
- """Atomically rewrite the whole sidecar with `records` (0600, under flock).
2438
-
2439
- Used by the tick to persist appended pings_fired entries. Mirrors
2440
- compact_keepwarm_sidecar's atomic rewrite. Never raises.
2441
- """
2442
- _measure_facade = _compat.facade()
2443
- if now is None:
2444
- now = _measure_facade.time.time()
2445
- path = _measure_facade._keepwarm_sidecar_path()
2331
+ """Merge replayed ping counters with Stops published after the tick's read."""
2332
+ from codex_io import atomic_write
2333
+ facade = _compat.facade()
2446
2334
  try:
2447
- with _measure_facade._keepwarm_lock() as acquired:
2448
- if not acquired:
2335
+ with facade._keepwarm_lock() as held:
2336
+ if not held:
2449
2337
  return
2450
- try:
2451
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
2452
- fd, tmp_name = _measure_facade.tempfile.mkstemp(
2453
- prefix=".keepwarm_state.", suffix=".tmp", dir=str(_measure_facade.SNAPSHOT_DIR))
2454
- try:
2455
- if hasattr(_measure_facade.os, "fchmod"):
2456
- _measure_facade.os.fchmod(fd, 0o600)
2457
- with _measure_facade.os.fdopen(fd, "w", encoding="utf-8") as fh:
2458
- for rec in records:
2459
- if _measure_facade._valid_keepwarm_record(rec):
2460
- fh.write(_measure_facade.json.dumps(rec) + "\n")
2461
- _measure_facade.os.replace(tmp_name, str(path))
2462
- except Exception:
2463
- try:
2464
- _measure_facade.os.unlink(tmp_name)
2465
- except OSError:
2466
- pass
2467
- raise
2468
- except OSError:
2469
- pass
2470
- except Exception:
2471
- pass
2338
+ current = {(r['session_id'], r['ts']): r for r in facade.load_keepwarm_records(strict=True)}
2339
+ for row in records:
2340
+ latest = current.get((row['session_id'], row['ts']))
2341
+ if latest is None:
2342
+ continue
2343
+ latest['pings_fired'] = sorted(set(latest.get('pings_fired', ())) | set(row.get('pings_fired', ())))
2344
+ if row.get('ping_failed'):
2345
+ latest['ping_failed'] = True
2346
+ atomic_write(facade._keepwarm_sidecar_path(), ''.join(facade.json.dumps(r) + "\n" for r in current.values()),
2347
+ replace_symlink=True)
2348
+ except (OSError, TypeError, ValueError):
2349
+ return
2472
2350
 
2473
2351
 
2474
2352
  def keepwarm_resume_predictor(features):
@@ -3150,35 +3028,18 @@ def _keepwarm_compact_ledger(now=None, retain_days=None):
3150
3028
  if now is None:
3151
3029
  now = _measure_facade.time.time()
3152
3030
  path = _measure_facade._keepwarm_ledger_path()
3031
+ from . import keepwarm_auto, mod_action_booking
3153
3032
  try:
3154
- if not path.exists():
3155
- return (False, 0, 0)
3156
- size = path.stat().st_size
3157
- except OSError:
3158
- return (False, 0, 0)
3159
- rows = _measure_facade._keepwarm_load_ledger_rows(path)
3160
- cutoff = float(now) - float(retain_days) * 86400.0
3161
- kept = []
3162
- dropped = 0
3163
- has_old = False
3164
- for r in rows:
3165
- try:
3166
- ts = float(r.get("ts", 0) or 0)
3167
- except (TypeError, ValueError):
3168
- ts = 0.0
3169
- if ts < cutoff:
3170
- dropped += 1
3171
- has_old = True
3172
- else:
3173
- kept.append(r)
3174
- # Only rewrite when something would actually change (size cap breached OR old
3175
- # rows present). A clean, in-window, small ledger is left untouched.
3176
- if not has_old and size <= _measure_facade._KEEPWARM_LEDGER_MAX_BYTES:
3177
- return (False, len(kept), 0)
3178
- try:
3179
- with _measure_facade._keepwarm_lock() as acquired:
3033
+ with mod_action_booking._lock(_measure_facade) as acquired:
3180
3034
  if not acquired:
3181
3035
  return (False, 0, 0)
3036
+ size = path.stat().st_size
3037
+ rows = keepwarm_auto.read_ledger(path)
3038
+ cutoff = float(now) - float(retain_days) * 86400.0
3039
+ kept = [row for row in rows if float(row.get("ts", 0)) >= cutoff]
3040
+ dropped = len(rows) - len(kept)
3041
+ if not dropped and size <= _measure_facade._KEEPWARM_LEDGER_MAX_BYTES:
3042
+ return False, len(kept), 0
3182
3043
  try:
3183
3044
  _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
3184
3045
  fd, tmp_name = _measure_facade.tempfile.mkstemp(
@@ -3202,7 +3063,7 @@ def _keepwarm_compact_ledger(now=None, retain_days=None):
3202
3063
  except OSError:
3203
3064
  return (False, len(kept), 0)
3204
3065
  except Exception:
3205
- return (False, len(kept), 0)
3066
+ return (False, 0, 0)
3206
3067
  return (True, len(kept), dropped)
3207
3068
 
3208
3069
 
@@ -3361,18 +3222,26 @@ def keepwarm_detect_realized(now=None, records=None, parse_fn=None):
3361
3222
  records = _measure_facade.load_keepwarm_records()
3362
3223
  out = {"realized": 0, "loss": 0, "skipped": 0, "errors": 0, "booked_usd": 0.0}
3363
3224
  try:
3364
- booked = _measure_facade._keepwarm_booked_pause_keys()
3365
- except Exception:
3366
- booked = set()
3225
+ rows = _measure_facade._keepwarm_load_ledger_rows()
3226
+ booked = _measure_facade._keepwarm_booked_pause_keys(rows)
3227
+ proved = {}
3228
+ for row in rows:
3229
+ if row.get('source') == 'keepwarm-headless' and row.get('status') == 'ok' and row.get('proof') is True:
3230
+ proved.setdefault(row.get('pause_key'), []).append(row['ts'])
3231
+ except (TypeError, ValueError, KeyError, OSError):
3232
+ return out
3367
3233
  for rec in {(r.get("session_id"), r.get("ts")): r for r in records}.values():
3368
3234
  try:
3369
- pings = rec.get("pings_fired")
3370
- n_pings = len(pings) if isinstance(pings, list) else 0
3371
- if n_pings < 1 or rec.get("ping_failed"):
3372
- continue
3373
- sid = rec.get("session_id")
3374
- arm_ts = rec.get("ts")
3235
+ sid, arm_ts = rec.get("session_id"), rec.get("ts")
3375
3236
  pause_key = _measure_facade._keepwarm_pause_key(sid, arm_ts)
3237
+ pings = rec.get("pings_fired") or []
3238
+ # A proven outcome is durable even if the pause lock was busy when its receipt arrived.
3239
+ if len(proved.get(pause_key, ())) > len(pings):
3240
+ pings = proved[pause_key]
3241
+ rec = dict(rec, auto_warm=True, pings_fired=pings)
3242
+ n_pings = len(pings)
3243
+ if not n_pings or rec.get("ping_failed"):
3244
+ continue
3376
3245
  if pause_key in booked:
3377
3246
  continue
3378
3247
  try:
@@ -2726,7 +2726,13 @@ def _dispatch_dashboard(args):
2726
2726
  with lock as acquired:
2727
2727
  if not acquired:
2728
2728
  _measure_facade.sys.exit(0)
2729
+ if _measure_facade.os.environ.get("TOKEN_OPTIMIZER_DASHBOARD_SELFHEAL") == "1":
2730
+ from . import selfheal_guard
2731
+ selfheal_guard.start(_measure_facade.SNAPSHOT_DIR)
2729
2732
  out = _measure_facade.generate_standalone_dashboard(days=days, quiet=quiet, force=force)
2733
+ if out and _measure_facade.os.environ.get("TOKEN_OPTIMIZER_DASHBOARD_SELFHEAL") == "1":
2734
+ from . import selfheal_guard
2735
+ selfheal_guard.clear_backoff(_measure_facade.SNAPSHOT_DIR)
2730
2736
  except _measure_facade._HookTimeout:
2731
2737
  out = None
2732
2738
  timed_out = True
@@ -3,6 +3,10 @@ from hook_provenance import _exclusive
3
3
 
4
4
 
5
5
  def claim(facade):
6
+ # Checked before any lock so no fail-open path below can skip it.
7
+ from . import selfheal_guard
8
+ if selfheal_guard.backoff_active(facade.SNAPSHOT_DIR):
9
+ return False
6
10
  try:
7
11
  facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
8
12
  guard = facade.SNAPSHOT_DIR / "dashboard.heal.claim.guard"