@alexgreensh/token-optimizer 5.13.78 → 5.13.80

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.78",
16
+ "version": "5.13.80",
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.78",
58
+ "version": "5.13.80",
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.78",
10
+ "version": "5.13.80",
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.78",
3
+ "version": "5.13.80",
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:
@@ -466,30 +466,17 @@ def _keepwarm_read_tail(filepath, max_lines=None):
466
466
 
467
467
 
468
468
  def _keepwarm_last_usage(filepath):
469
- """Scan a transcript tail for the most recent assistant turn carrying usage.
470
-
471
- Returns (usage_dict, model, ts_str) for the last record whose
472
- message.usage is non-empty, or (None, None, None) if none found / unreadable.
473
- Read-only. Used by the fast arm-writer to derive prefix_proxy + ttl_kind
474
- without re-parsing the whole session.
475
- """
469
+ """Find the last main-session assistant usage within the existing line limit."""
476
470
  _measure_facade = _compat.facade()
477
- lines = _measure_facade._keepwarm_read_tail(filepath)
478
- for line in reversed(lines):
479
- line = line.strip()
480
- if not line:
481
- continue
471
+ from . import keepwarm_safety
472
+ for line in keepwarm_safety.usage_lines(_measure_facade, filepath):
482
473
  try:
483
474
  record = _measure_facade.json.loads(line)
484
- except (_measure_facade.json.JSONDecodeError, ValueError):
475
+ except ValueError:
485
476
  continue
486
477
  if not isinstance(record, dict):
487
478
  continue
488
- # Parser parity (integration M2): the realized-booking path
489
- # (parse_session_turns) only reads type=="assistant" turns, so the arm
490
- # writer must use the SAME definition of a usage turn. Arming off a
491
- # non-assistant usage record would spend pings on a session whose resume
492
- # turn the booker can never read -- structurally-impossible payback.
479
+ # Booking also requires main-session assistant usage.
493
480
  if record.get("type") != "assistant" or record.get("isSidechain") or record.get("agentId") or record.get("teamName"):
494
481
  continue
495
482
  msg = record.get("message", {})
@@ -497,9 +484,7 @@ def _keepwarm_last_usage(filepath):
497
484
  continue
498
485
  usage = msg.get("usage", {})
499
486
  if isinstance(usage, dict) and usage:
500
- model = msg.get("model") or record.get("model")
501
- ts = record.get("timestamp") or record.get("ts")
502
- return usage, model, ts
487
+ return usage, msg.get("model") or record.get("model"), record.get("timestamp") or record.get("ts")
503
488
  return None, None, None
504
489
 
505
490
 
@@ -532,7 +517,7 @@ def _keepwarm_iso_to_epoch(ts):
532
517
  return None
533
518
 
534
519
 
535
- 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):
536
521
  """Record a paused terminal snapshot from the flush worker."""
537
522
  _measure_facade = _compat.facade()
538
523
  try:
@@ -600,7 +585,7 @@ def write_keepwarm_arm_record(session_id, transcript_path, now=None, *, parent_p
600
585
  }
601
586
  if turn is not None:
602
587
  record["terminal_turn"] = turn
603
- return keepwarm_rearm.publish_arm(_measure_facade, record)
588
+ return keepwarm_rearm.publish_arm(_measure_facade, record, retry)
604
589
  except Exception:
605
590
  # Absolute backstop: nothing in the arm path may propagate to the hook.
606
591
  return None
@@ -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"
@@ -121,11 +121,11 @@ def _commit_arm(facade, record):
121
121
 
122
122
 
123
123
  def _publish_stop(facade, record, path, now):
124
- from .keepwarm_auto import CACHE_LIFETIME
125
124
  from .keepwarm_safety import session_ended, terminal_turn
126
125
 
127
126
  result = None
128
- if now < record['last_turn_ts'] + CACHE_LIFETIME:
127
+ # Spending checks cache expiry against proved pings. Only expire the pause itself here.
128
+ if now - record['ts'] <= facade._KEEPWARM_MAX_AGE_SECONDS:
129
129
  turn = terminal_turn(facade.Path(record['transcript_path']))
130
130
  ended = session_ended(facade.SNAPSHOT_DIR, record['session_id'], record['ts'])
131
131
  if ended is None or (not ended and turn is None):
@@ -139,7 +139,7 @@ def _publish_stop(facade, record, path, now):
139
139
  return result
140
140
 
141
141
 
142
- def publish_arm(facade, record):
142
+ def publish_arm(facade, record, retry=None):
143
143
  facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
144
144
  pending = None
145
145
  if 'terminal_turn' in record:
@@ -152,26 +152,59 @@ def publish_arm(facade, record):
152
152
  if pending is not None:
153
153
  return _publish_stop(facade, record, pending, facade.time.time())
154
154
  return _commit_arm(facade, record)
155
+ if held is False and pending is not None and retry is not None:
156
+ retry.append((record, pending))
157
+
158
+
159
+ def retry_due_stop(facade, record, path):
160
+ from .keepwarm_auto import BUCKETS
161
+
162
+ if facade.time.time() - record['last_turn_ts'] >= BUCKETS[0]:
163
+ # Fresh pauses can wait for the scheduler. A due one may have less
164
+ # than a minute left, so let this worker claim it as the writer exits.
165
+ with state_lock(facade.SNAPSHOT_DIR, 60) as held:
166
+ if held:
167
+ return _publish_stop(facade, record, path, facade.time.time())
168
+
169
+
170
+ def _import_legacy(facade, now):
171
+ from codex_io import atomic_write_json
172
+ from .mod_action_booking import _append
173
+
174
+ directory = facade.SNAPSHOT_DIR
175
+ marker = directory / '.kw2-imported'
176
+ try:
177
+ previous = {} if marker.is_symlink() else json.loads(marker.read_bytes())
178
+ except (FileNotFoundError, ValueError):
179
+ previous = {} # 5.13.78 left an empty marker.
180
+ stamps = {}
181
+ with os.scandir(directory) as entries:
182
+ for entry in entries:
183
+ legacy = entry.name == 'keepwarm_state.jsonl' or entry.name.startswith('keepwarm-pending-stop-')
184
+ if legacy and entry.is_file(follow_symlinks=False):
185
+ st = entry.stat(follow_symlinks=False)
186
+ stamps[entry.name] = [st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns]
187
+ if stamps == previous:
188
+ return
189
+ imported = {(r['session_id'], r['ts']) for r in facade.load_keepwarm_records(strict=True)}
190
+ for name, stamp in stamps.items():
191
+ if not isinstance(previous, dict) or stamp != previous.get(name):
192
+ rows = {(r['session_id'], r['ts']): r for r in facade.load_keepwarm_records(directory / name, strict=True)}
193
+ for key, row in rows.items():
194
+ if key not in imported and now - float(row['ts']) <= facade._KEEPWARM_MAX_AGE_SECONDS:
195
+ _append(facade._keepwarm_sidecar_path(), row)
196
+ imported.add(key)
197
+ atomic_write_json(marker, stamps, replace_symlink=True)
155
198
 
156
199
 
157
200
  def recover_pending(facade, now):
158
201
  with facade._keepwarm_lock() as held:
159
202
  if not held:
160
203
  return
161
- marker = facade.SNAPSHOT_DIR / '.kw2-imported'
162
- if not marker.exists():
163
- legacy = facade.SNAPSHOT_DIR / 'keepwarm_state.jsonl'
164
- from .mod_action_booking import _append
165
- try:
166
- imported = {(r['session_id'], r['ts']) for r in facade.load_keepwarm_records(strict=True)}
167
- paths = [legacy, *(p for p in facade.SNAPSHOT_DIR.glob('keepwarm-pending-stop-*') if not p.is_symlink())]
168
- rows = {(r['session_id'], r['ts']): r for p in paths for r in facade.load_keepwarm_records(p, strict=True)}
169
- for key, row in rows.items():
170
- if key not in imported and now - float(row['ts']) <= facade._KEEPWARM_MAX_AGE_SECONDS:
171
- _append(facade._keepwarm_sidecar_path(), row)
172
- marker.touch(mode=0o600)
173
- except OSError:
174
- pass # Retry migration independently of current Stops.
204
+ try:
205
+ _import_legacy(facade, now)
206
+ except OSError:
207
+ pass # Retry migration independently of current Stops.
175
208
  for path in facade.SNAPSHOT_DIR.glob('kw2-stop-*'):
176
209
  try:
177
210
  if not path.is_symlink():
@@ -254,6 +254,22 @@ def ended_since(directory, session_id, armed_at):
254
254
  return session_ended(directory, session_id, armed_at) is not False
255
255
 
256
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))
271
+
272
+
257
273
  def terminal_turn(path):
258
274
  """Return the last conversation row's identity from a bounded suffix."""
259
275
  try:
@@ -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:
@@ -159,35 +159,73 @@ def classify(rows, emitted, new_rows=None):
159
159
  return 'pending', None, []
160
160
 
161
161
 
162
- def _project_index(directory):
163
- """Read each transcript once before the database write transaction."""
164
- transcripts, failures = {}, []
162
+ def _start(path):
163
+ """First timestamp of an append-only transcript, without reading the rest."""
164
+ with Path(path).open(encoding='utf-8', errors='replace') as stream:
165
+ for line in stream:
166
+ try:
167
+ row = json.loads(line)
168
+ except ValueError:
169
+ continue
170
+ if isinstance(row, dict) and not row.get('isSidechain'):
171
+ stamp = _epoch(row.get('timestamp'))
172
+ if stamp is not None:
173
+ return stamp
174
+ return None
175
+
176
+
177
+ def _project_index(directory, since):
178
+ """Start times of transcripts written after `since`.
179
+
180
+ Only these can follow a nudged session. Reading every transcript in full
181
+ held a whole project history in memory: 17 GB of logs grew past 11 GB.
182
+ """
183
+ starts, failures = {}, []
165
184
  for path in Path(directory).glob('*.jsonl'):
166
185
  if path.is_symlink():
167
186
  continue
168
187
  try:
169
- rows = list(_rows(path))
170
- stamps = [_epoch(row.get('timestamp')) for row in rows]
171
- stamps = [stamp for stamp in stamps if stamp is not None]
172
- if stamps:
173
- transcripts[path] = (min(stamps), max(stamps), rows)
188
+ if path.stat().st_mtime < since:
189
+ continue
190
+ start = _start(path)
191
+ if start is not None:
192
+ starts[path] = start
174
193
  except Exception as exc:
175
194
  failures.append(exc)
176
- return transcripts, failures
195
+ return starts, failures
177
196
 
178
197
 
179
- def _next_session(path, stamp, index):
198
+ def _nudged_rows(path, stamp):
199
+ """Rows from the nudge on, plus the newest row, and the session's last timestamp."""
200
+ kept, end, newest = [], None, None
201
+ for row in _rows(Path(path)):
202
+ ts = _epoch(row.get('timestamp'))
203
+ if ts is None:
204
+ continue
205
+ if end is None or ts > end:
206
+ end, newest = ts, row
207
+ if ts >= stamp:
208
+ kept.append(row)
209
+ if newest is not None and (_epoch(newest.get('timestamp')) or 0) < stamp:
210
+ kept.append(newest)
211
+ return kept, end
212
+
213
+
214
+ def _successor_rows(path):
215
+ """The opening rows of the next session, up to the requests classify prices."""
216
+ rows = []
217
+ for row in _rows(Path(path)):
218
+ rows.append(row)
219
+ if row.get('type') == 'assistant' and len(_requests(rows)) >= 50:
220
+ break
221
+ return rows
222
+
223
+
224
+ def _next_session(path, stamp, end, starts):
180
225
  current = Path(path)
181
- entry = index.get(current)
182
- if not entry:
183
- return None
184
- end = entry[1]
185
- choices = [(start, str(candidate), rows) for candidate, (start, _, rows) in index.items()
226
+ choices = [(start, str(candidate)) for candidate, start in starts.items()
186
227
  if candidate != current and start > end and start > stamp]
187
- if not choices:
188
- return None, None
189
- _, candidate, rows = min(choices)
190
- return candidate, rows
228
+ return str(min(choices)[1]) if choices else None
191
229
 
192
230
 
193
231
  def _session_ended(facade, sid, last_ts):
@@ -216,31 +254,51 @@ def resolve(facade, conn=None):
216
254
  return
217
255
  _schema(conn)
218
256
  conn.commit()
219
- events = conn.execute('SELECT id,session_uuid,ts,context_tokens,transcript_path,savings_event_id FROM nudge_events').fetchall()
220
- projects = {Path(path).parent for _, _, _, _, path, _ in events if path}
257
+ events = conn.execute("SELECT id,session_uuid,ts,context_tokens,transcript_path,savings_event_id FROM nudge_events WHERE status='pending' AND savings_event_id IS NULL").fetchall()
258
+ events = [event for event in events if event[4] and _epoch(event[2]) is not None]
259
+ first_stamp = {}
260
+ for _, _, ts, _, path, _ in events:
261
+ first_stamp[path] = min(first_stamp.get(path, float('inf')), _epoch(ts))
262
+ nudged = {}
263
+ for path, stamp in first_stamp.items():
264
+ try:
265
+ rows, end = _nudged_rows(path, stamp)
266
+ if end is not None:
267
+ nudged[path] = rows, end
268
+ except Exception as exc:
269
+ _diagnostic(facade, exc)
221
270
  indexes = {}
222
- for project in projects:
271
+ for project in {Path(path).parent for path in first_stamp}:
272
+ ends = [end for path, (_, end) in nudged.items() if Path(path).parent == project]
223
273
  try:
224
- transcripts, failures = _project_index(project)
274
+ # A successor is written after the nudged session ends; allow clock skew.
275
+ starts, failures = _project_index(project, min(ends, default=float('inf')) - 300)
225
276
  except Exception as exc:
226
- transcripts, failures = {}, [exc]
277
+ starts, failures = {}, [exc]
227
278
  for failure in failures:
228
279
  _diagnostic(facade, failure)
229
- indexes[project] = transcripts
280
+ indexes[project] = starts
281
+ successors = {}
230
282
  prepared = {}
231
283
  claimed_sessions = set()
232
284
  events.sort(key=lambda event: (_epoch(event[2]) or 0, event[0]), reverse=True)
233
285
  for ident, sid, ts, before, path, event_id in events:
234
- if not path:
235
- continue
236
- entry = indexes[Path(path).parent].get(Path(path))
237
- if not entry:
286
+ if path not in nudged:
238
287
  continue
239
- rows = entry[2]
288
+ rows, end = nudged[path]
240
289
  status, action, requests = classify(rows, ts)
241
290
  if status == 'pending':
242
- next_path, next_rows = _next_session(path, _epoch(ts), indexes[Path(path).parent])
243
- if next_rows and _session_ended(facade, sid, entry[1]):
291
+ next_path = _next_session(path, _epoch(ts), end, indexes[Path(path).parent])
292
+ next_rows = None
293
+ if next_path and _session_ended(facade, sid, end):
294
+ if next_path not in successors:
295
+ try:
296
+ successors[next_path] = _successor_rows(next_path)
297
+ except Exception as exc:
298
+ _diagnostic(facade, exc)
299
+ successors[next_path] = None
300
+ next_rows = successors[next_path]
301
+ if next_rows:
244
302
  status, action, requests = classify(rows, ts, next_rows)
245
303
  if status == 'followed':
246
304
  if next_path in claimed_sessions:
@@ -0,0 +1,109 @@
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
+ # File clocks can run a moment ahead of time.time() (seen on Windows).
61
+ return -60 <= age < backoff_seconds()
62
+
63
+
64
+ def clear_backoff(snapshot_dir):
65
+ try:
66
+ (snapshot_dir / BACKOFF_NAME).unlink()
67
+ except OSError:
68
+ pass
69
+
70
+
71
+ def _write_backoff(snapshot_dir, reason):
72
+ try:
73
+ snapshot_dir.mkdir(parents=True, exist_ok=True)
74
+ (snapshot_dir / BACKOFF_NAME).write_text(reason + "\n", encoding="utf-8")
75
+ except OSError:
76
+ pass
77
+
78
+
79
+ def check(snapshot_dir, started, now=None, rss_mb=None):
80
+ """Return the reason to stop, or None. Split out so tests need no thread."""
81
+ elapsed = (time.monotonic() if now is None else now) - started
82
+ if elapsed > max_seconds():
83
+ return "time %ds > %ds" % (elapsed, max_seconds())
84
+ rss = peak_rss_mb() if rss_mb is None else rss_mb
85
+ if rss is not None and rss > max_mb():
86
+ return "memory %dMB > %dMB" % (rss, max_mb())
87
+ return None
88
+
89
+
90
+ def start(snapshot_dir, exit_fn=os._exit):
91
+ """Arm the ceilings for this process. Call once, in the self-heal child only."""
92
+ try:
93
+ os.nice(10)
94
+ except (AttributeError, OSError):
95
+ pass
96
+ started = time.monotonic()
97
+
98
+ def watch():
99
+ while True:
100
+ time.sleep(_POLL_SECONDS)
101
+ reason = check(snapshot_dir, started)
102
+ if reason:
103
+ _write_backoff(snapshot_dir, reason)
104
+ exit_fn(3)
105
+ return
106
+
107
+ thread = threading.Thread(target=watch, name="to-selfheal-guard", daemon=True)
108
+ thread.start()
109
+ 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: