@alexgreensh/token-optimizer 5.13.68 → 5.13.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -1,7 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat
4
-
3
+ from . import _compat, dashboard_history, session_store_spool
5
4
 
6
5
  def _settings_lock(user_initiated=None):
7
6
  """Bounded portable lease for settings.json writes.
@@ -25,40 +24,13 @@ def _settings_lock(user_initiated=None):
25
24
  ) as acquired:
26
25
  yield acquired
27
26
 
28
-
29
27
  def _acquire_session_end_flush_lock(max_age_seconds=None):
30
- """Return a lock directory path, or None if another worker is active."""
31
- _measure_facade = _compat.facade()
32
- lock_dir = _measure_facade.SNAPSHOT_DIR / ".session-end-flush.lock"
33
- try:
34
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
35
- lock_dir.mkdir(mode=0o700)
36
- return lock_dir
37
- except FileExistsError:
38
- try:
39
- age = _measure_facade.time.time() - lock_dir.stat().st_mtime
40
- if age > max_age_seconds:
41
- lock_dir.rmdir()
42
- try:
43
- lock_dir.mkdir(mode=0o700)
44
- except FileExistsError:
45
- return None
46
- return lock_dir
47
- except OSError:
48
- pass
49
- return None
50
- except OSError:
51
- return None
52
-
28
+ from . import session_flush_lock
29
+ return session_flush_lock.acquire(_compat.facade(), max_age_seconds)
53
30
 
54
31
  def _release_session_end_flush_lock(lock_dir):
55
- _measure_facade = _compat.facade()
56
- if not lock_dir:
57
- return
58
- try:
59
- lock_dir.rmdir()
60
- except OSError:
61
- pass
32
+ from . import session_flush_lock
33
+ session_flush_lock.release(lock_dir)
62
34
 
63
35
 
64
36
  def _session_refresh_due(min_interval_seconds=None):
@@ -259,7 +231,7 @@ def _run_session_end_flush_worker(args, budget_seconds=None):
259
231
  # No browser in a cloud VM: the 4 MB dashboard rebuild is skipped
260
232
  # there (an explicit /token-dashboard still builds it on demand).
261
233
  if not _lean and not (_measure_facade._dashboard_hook_backoff_active() or _measure_facade._dashboard_selfheal_inflight()):
262
- _measure_facade.generate_standalone_dashboard(days=30, quiet=True)
234
+ _measure_facade.generate_standalone_dashboard(quiet=True)
263
235
  except _measure_facade._HookTimeout:
264
236
  # Gap 4: the bounded SessionEnd regen was killed by the 20s budget
265
237
  # (a large history's 4 MB build does not fit), so it may have left
@@ -268,7 +240,7 @@ def _run_session_end_flush_worker(args, budget_seconds=None):
268
240
  # file catches up off the hot path instead of waiting for the user
269
241
  # to re-open. Re-raised so the outer handler still runs cleanup.
270
242
  try:
271
- _measure_facade._spawn_detached_dashboard_selfheal(days=30)
243
+ _measure_facade._spawn_detached_dashboard_selfheal()
272
244
  except Exception:
273
245
  pass
274
246
  raise
@@ -610,21 +582,17 @@ def _dispatch_collect(args):
610
582
  _measure_facade._install_hook_budget(20) if (_measure_facade._running_under_hook() and not rebuild) else None
611
583
  )
612
584
  try:
613
- _measure_facade.collect_sessions(days=days, quiet=quiet, rebuild=rebuild)
585
+ session_store_spool.drain_collect(_measure_facade.SNAPSHOT_DIR); _measure_facade.collect_sessions(days=days, quiet=quiet, rebuild=rebuild)
614
586
  except _measure_facade._HookTimeout:
615
587
  pass
588
+ except _measure_facade.sqlite3.OperationalError as exc:
589
+ if "locked" not in str(exc).lower() and "busy" not in str(exc).lower(): raise
590
+ try: _measure_facade._log_spawn_failure("collect deferred after SQLite contention")
591
+ except Exception: pass
616
592
  finally:
617
593
  _measure_facade._clear_hook_budget(deadline)
618
594
 
619
- # Existing-script-install self-heal. An old script
620
- # install has the collect&&dashboard fossil in settings.json and NO
621
- # ensure-health SessionStart hook, so run_ensure_health never reaches it.
622
- # The fossil's OWN hook-path run reconciles settings.json here, removing
623
- # the fossil going forward. Runs AFTER the flush and its 20s budget are
624
- # cleared, so it never delays the flush itself; the self-heal carries its
625
- # OWN short deadline (see the helper) so a stalled settings write can't
626
- # hold the hook pipe open. Throttled to 24h, fail-open. Gated on the hook
627
- # path so an interactive terminal `collect` never triggers it.
595
+ # Repair legacy hook installs after the bounded collect finishes.
628
596
  if _measure_facade._running_under_hook():
629
597
  try:
630
598
  _measure_facade._maybe_self_heal_sessionend_fossils_on_hook()
@@ -667,6 +635,8 @@ def _spawn_detached_dashboard_selfheal(days=None, force=None, *, hook_timeout=No
667
635
  # Detach so the child outlives the killed hook: POSIX new session, or
668
636
  # (on Windows) DETACHED_PROCESS. start_new_session is POSIX-only.
669
637
  popen_kw = {} if _measure_facade.os.name == "nt" else {"start_new_session": True}
638
+ if days is None:
639
+ days = dashboard_history.selected_days(_measure_facade.RUNTIME_DIR, _measure_facade.TRENDS_DB)
670
640
  argv = [_measure_facade.sys.executable, _measure_facade.os.path.abspath(_measure_facade.__file__),
671
641
  "dashboard", "--quiet", "--days", str(int(days))]
672
642
  if force:
@@ -819,71 +789,8 @@ def _dashboard_selfheal_build_lock():
819
789
 
820
790
 
821
791
  def _dashboard_heal_spawn_due():
822
- """Return True iff THIS caller should spawn a dashboard heal.
823
-
824
- Bug (thundering herd): on a version bump every concurrent
825
- SessionStart's ensure-health tick sees the stale sidecar and each spawns a
826
- DETACHED, unbounded, FORCED ~9s rebuild -- N sessions => N simultaneous
827
- builds all racing os.replace on the same dashboard.html (the very lock
828
- contention the api/regenerate retry was calibrated around). This collapses
829
- that to ONE: the first caller atomically claims ``dashboard.heal.lock``
830
- (O_CREAT|O_EXCL, the same pidfile shape as ``_keepwarm_tick_singleton`` and
831
- ``_daemon_install_lock``) and spawns; concurrent callers within the staleness
832
- window see the fresh marker and skip. The marker is deliberately NOT unlinked
833
- on the happy path -- it must OUTLIVE this call to suppress the herd, and it is
834
- reclaimed by the next caller once it ages past the window.
835
-
836
- The child holds a separate OS lock for the full rebuild. Check it here so
837
- even an expired marker cannot launch another child while one is working.
838
- Fail-OPEN on filesystem errors; the child lock still prevents duplicate work.
839
- """
840
- _measure_facade = _compat.facade()
841
- if _measure_facade._dashboard_selfheal_inflight():
842
- return False
843
- marker = _measure_facade.SNAPSHOT_DIR / _measure_facade._DASHBOARD_HEAL_LOCK_NAME
844
- try:
845
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
846
- except OSError:
847
- return True
848
- fd = None
849
- try:
850
- fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
851
- except FileExistsError:
852
- # A recent spawn already claimed the marker. Reclaim ONLY if it is stale;
853
- # a fresh marker means a heal is already in flight, so no-op.
854
- try:
855
- age = _measure_facade.time.time() - marker.stat().st_mtime
856
- except OSError:
857
- return True # unreadable mtime: don't suppress the heal
858
- if age <= _measure_facade._DASHBOARD_HEAL_LOCK_STALE_SECONDS:
859
- return False
860
- # Known bounded residual (same unlink+O_EXCL shape as
861
- # _keepwarm_tick_singleton): the fresh-claim path above is race-free, but
862
- # if TWO ticks both observe the SAME stale marker and both pass the age
863
- # check before either unlinks, both can reclaim and spawn -- at most 2
864
- # rebuilds, only at the 60s staleness edge with concurrent sessions. That
865
- # is consistent with the fail-open contract (an extra rebuild is harmless;
866
- # the detached child is itself idempotent via os.replace + the version
867
- # guard), so it is accepted rather than serialised with a heavier lock.
868
- try:
869
- _measure_facade.os.unlink(str(marker))
870
- fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
871
- except FileExistsError:
872
- return False # lost the reclaim race to another session -- it heals
873
- except OSError:
874
- return True
875
- except OSError:
876
- return True
877
- try:
878
- _measure_facade.os.write(fd, str(_measure_facade.os.getpid()).encode("ascii"))
879
- except OSError:
880
- pass
881
- finally:
882
- try:
883
- _measure_facade.os.close(fd)
884
- except OSError:
885
- pass
886
- return True
792
+ from . import dashboard_heal_claim
793
+ return dashboard_heal_claim.claim(_compat.facade())
887
794
 
888
795
 
889
796
  def _is_plugin_installed():
@@ -3792,8 +3699,8 @@ def _is_v5_feature_enabled(feature_name):
3792
3699
  if r is not None:
3793
3700
  return r
3794
3701
 
3795
- # Config.json (user, then plugin-data, via _read_config_flag).
3796
3702
  config_val = _measure_facade._read_config_flag(feat["config_key"], None)
3703
+ if feature_name == "keepwarm" and config_val is None and _measure_facade._read_config_flag("keepwarm_consent", "unasked") == "declined": return False
3797
3704
  if config_val is not None:
3798
3705
  r = _measure_facade.interpret_flag_value(config_val, env_truthy_value=tv)
3799
3706
  if r is not None:
@@ -3806,8 +3713,8 @@ def _set_v5_feature(feature_name, enabled):
3806
3713
  """Enable or disable a v5 feature via config.json (persistent, dashboard-friendly)."""
3807
3714
  _measure_facade = _compat.facade()
3808
3715
  feat = _measure_facade.V5_FEATURES.get(feature_name)
3809
- if not feat:
3810
- return False
3716
+ if not feat: return False
3717
+ if feature_name == "keepwarm": return False
3811
3718
  _measure_facade._write_config_flag(feat["config_key"], bool(enabled))
3812
3719
  return True
3813
3720
 
@@ -3880,9 +3787,7 @@ def _get_v5_feature_status():
3880
3787
  except OSError:
3881
3788
  codex_hooks_text = ""
3882
3789
  for name, feat in _measure_facade.V5_FEATURES.items():
3883
- # Resolve env from the process AND settings.json so the dashboard sees
3884
- # flags a user "marked" even when this process (e.g. the daemon) did not
3885
- # inherit Claude Code's env injection.
3790
+ if name == "keepwarm" and (_measure_facade.detect_runtime() != "claude" or _measure_facade._normalized_platform() == "Windows"): continue
3886
3791
  env_val = _measure_facade._resolve_feature_env(feat["env_var"])
3887
3792
  config_val = _measure_facade._read_config_flag(feat["config_key"], None)
3888
3793
  enabled = _measure_facade._is_v5_feature_enabled(name)
@@ -3904,9 +3809,9 @@ def _get_v5_feature_status():
3904
3809
  "how": feat["how"],
3905
3810
  "risk": feat["risk"],
3906
3811
  "risk_level": feat.get("risk_level", "none"),
3907
- "recommended": recommended,
3908
- "enabled": enabled,
3909
- "source": source,
3812
+ "recommended": recommended if name != "keepwarm" else False,
3813
+ "enabled": enabled if name != "keepwarm" else False,
3814
+ "source": source if name != "keepwarm" else "paused",
3910
3815
  "env_var": feat["env_var"],
3911
3816
  "config_key": feat["config_key"],
3912
3817
  }
@@ -4376,43 +4281,18 @@ def _settings_read_highwater() -> dict | None:
4376
4281
 
4377
4282
 
4378
4283
  def _settings_update_highwater(data: dict) -> bool:
4379
- """Update the high-water mark if this sighting has MORE top-level keys
4380
- AND has at least one user-authored key. A file with only machine-written
4381
- keys is never a valid high-water candidate (it could be wipe residue
4382
- with more keys than the real highwater). Returns True if updated."""
4284
+ """Snapshot settings.json WITHOUT secrets (settings_backup.scrub) when the
4285
+ file has at least one user-authored key. env, API-key helpers, MCP env and
4286
+ headers and any credential-looking value never reach the snapshot. True if
4287
+ updated."""
4383
4288
  _measure_facade = _compat.facade()
4384
- if not isinstance(data, dict) or not data:
4385
- return False
4386
- # Poisoning guard: only snapshot files that have user-authored keys.
4387
- # A file with only machine-written keys is wipe residue, not a valid
4388
- # high-water candidate.
4389
- if not _measure_facade._settings_has_user_keys(data):
4390
- return False
4289
+ if not isinstance(data, dict) or not _measure_facade._settings_has_user_keys(data):
4290
+ return False # poisoning guard: a machine-only file is wipe residue
4391
4291
  try:
4392
- d = _measure_facade._settings_heal_ensure_dir()
4393
- if d is None:
4394
- return False
4395
- existing = _measure_facade._settings_read_highwater()
4396
- if existing is None or len(data) > len(existing):
4397
- if not _measure_facade._settings_write_file_secure(
4398
- d / "highwater.json",
4399
- _measure_facade.json.dumps(data, indent=2, ensure_ascii=False) + "\n",
4400
- ):
4401
- return False
4402
- # Record metadata.
4403
- meta = {
4404
- "key_count": len(data),
4405
- "key_set": sorted(data.keys()),
4406
- "timestamp": _measure_facade.datetime.now().isoformat(),
4407
- }
4408
- _measure_facade._settings_write_file_secure(
4409
- d / "highwater.meta.json",
4410
- _measure_facade.json.dumps(meta, indent=2) + "\n",
4411
- )
4412
- return True
4292
+ import settings_backup
4293
+ return settings_backup.update_highwater(_measure_facade, data) is not None
4413
4294
  except (OSError, TypeError):
4414
- pass
4415
- return False
4295
+ return False
4416
4296
 
4417
4297
 
4418
4298
  def _settings_read_tombstones() -> set:
@@ -4788,25 +4668,34 @@ def _maybe_self_heal_settings() -> None:
4788
4668
  a. Read the high-water mark. If none, fail open (nothing to restore).
4789
4669
  b. Compute absent keys = high-water keys - live keys - tombstoned.
4790
4670
  c. If no absent keys, fail open.
4791
- d. Backup the live file via _backup_settings_file. If backup fails,
4671
+ d. Back up the live file minus secrets (settings_backup). If it fails,
4792
4672
  ABORT (no restore without a backup).
4793
4673
  e. Re-read settings.json under the settings lock to avoid value race.
4794
4674
  f. Additive merge: add only absent keys from the high-water mark.
4795
4675
  g. Write via _settings_write_atomic_silent (suppresses guard stderr).
4796
4676
  h. Log the restoration.
4797
4677
 
4798
- SILENT: no stdout, no stderr to the user. All diagnostics go to the heal
4799
- log. FAIL OPEN: any error returns without touching the file.
4678
+ The snapshot and the pre-restore backup never hold secrets
4679
+ (settings_backup.scrub); a scrubbed value stays absent on restore. stdout
4680
+ stays silent; a restore prints one stderr line, names the keys it could not
4681
+ restore, and is recorded in the heal log. TOKEN_OPTIMIZER_SETTINGS_HEAL=0
4682
+ skips snapshot and restore. FAIL OPEN: any error returns without touching
4683
+ the file.
4800
4684
  """
4801
4685
  _measure_facade = _compat.facade()
4802
4686
  try:
4803
- data, _path, ok = _measure_facade._read_settings_json_checked()
4804
- if not ok or not isinstance(data, dict):
4805
- return # unreadable or malformed: fail open
4806
-
4687
+ import settings_backup
4807
4688
  heal_dir = _measure_facade._settings_heal_ensure_dir()
4808
4689
  if heal_dir is None:
4809
4690
  return # can't create heal dir: fail open
4691
+ # Shrink older full copies to owned keys even when the heal is off:
4692
+ # it only removes data. TOKEN_OPTIMIZER_SETTINGS_HEAL=0 skips the rest.
4693
+ settings_backup.migrate_to_secret_free(_measure_facade)
4694
+ if settings_backup.heal_disabled():
4695
+ return
4696
+ data, _path, ok = _measure_facade._read_settings_json_checked()
4697
+ if not ok or not isinstance(data, dict):
4698
+ return # unreadable or malformed: fail open
4810
4699
 
4811
4700
  # --- Healthy sighting: check tombstones + snapshot ---
4812
4701
  if _measure_facade._settings_has_user_keys(data):
@@ -4815,11 +4704,10 @@ def _maybe_self_heal_settings() -> None:
4815
4704
  _measure_facade._settings_check_tombstones(data, previously_restored)
4816
4705
  # Snapshot: update high-water mark if richer.
4817
4706
  if _measure_facade._settings_update_highwater(data):
4707
+ _kept = settings_backup.read_meta(_measure_facade)
4818
4708
  _measure_facade._settings_heal_log(
4819
- "snapshot",
4820
- key_count=len(data),
4821
- key_set=sorted(data.keys()),
4822
- )
4709
+ "snapshot", key_count=_kept.get("key_count"), key_set=_kept.get("key_set"),
4710
+ withheld_keys=_kept.get("withheld_keys"))
4823
4711
  # Time-proximity signal: record last healthy sighting timestamp.
4824
4712
  _measure_facade._settings_write_file_secure(
4825
4713
  heal_dir / "last_healthy.json",
@@ -4832,7 +4720,7 @@ def _maybe_self_heal_settings() -> None:
4832
4720
  if not _measure_facade._settings_is_wipe_residue(data):
4833
4721
  return # has unknown keys that aren't machine-written: fail open
4834
4722
 
4835
- highwater = _measure_facade._settings_read_highwater()
4723
+ highwater = settings_backup.read_highwater(_measure_facade)
4836
4724
  if not highwater:
4837
4725
  return # no high-water mark: nothing to restore from
4838
4726
 
@@ -4844,10 +4732,10 @@ def _maybe_self_heal_settings() -> None:
4844
4732
  if not absent_keys:
4845
4733
  return # nothing to restore (all missing keys are tombstoned)
4846
4734
 
4847
- # Pre-restore backup (reuses the existing _backup_settings_file helper).
4735
+ # Pre-restore backup of the live file, secret-free (settings_backup.backup_scrubbed).
4848
4736
  # If the backup fails, ABORT: no restore without a reversible backup.
4849
4737
  backup_dir = heal_dir / "backups"
4850
- backup_path = _measure_facade._backup_settings_file(backup_dir)
4738
+ backup_path = settings_backup.backup_scrubbed(_measure_facade, backup_dir)
4851
4739
  if backup_path is None:
4852
4740
  _measure_facade._settings_heal_log(
4853
4741
  "restore_aborted",
@@ -4901,6 +4789,7 @@ def _maybe_self_heal_settings() -> None:
4901
4789
  # Write via the silent atomic writer (suppresses guard stderr).
4902
4790
  # The guard will verify we're not dropping any keys.
4903
4791
  if _measure_facade._settings_write_atomic_silent(merged):
4792
+ _notice = settings_backup.restore_notice(restored, settings_backup.read_meta(_measure_facade))
4904
4793
  _measure_facade._settings_heal_log(
4905
4794
  "restore",
4906
4795
  restored_keys=restored,
@@ -4909,7 +4798,9 @@ def _maybe_self_heal_settings() -> None:
4909
4798
  backup_path=str(backup_path),
4910
4799
  live_key_count=len(data),
4911
4800
  healed_key_count=len(merged),
4801
+ notice=_notice,
4912
4802
  )
4803
+ settings_backup.announce_restore(_notice)
4913
4804
  except Exception:
4914
4805
  # Fail open, always. A heal that breaks a session is a worse bug
4915
4806
  # than the one it heals.
@@ -5092,7 +4983,7 @@ def run_ensure_health():
5092
4983
  # already uses; _dashboard_heal_spawn_due() fails OPEN so a lock
5093
4984
  # glitch never skips the heal.
5094
4985
  try:
5095
- _measure_facade._spawn_detached_dashboard_selfheal(days=30, force=True, hook_timeout=False)
4986
+ _measure_facade._spawn_detached_dashboard_selfheal(force=True, hook_timeout=False)
5096
4987
  print(f" [Token Optimizer] Refreshing dashboard to v{_measure_facade.TOKEN_OPTIMIZER_VERSION} (background)", file=_measure_facade.sys.stderr)
5097
4988
  except Exception as _e:
5098
4989
  print(f" [Token Optimizer] dashboard refresh failed: {_e}", file=_measure_facade.sys.stderr)
@@ -0,0 +1,120 @@
1
+ """Helpers for evaluating MCP archive re-expansion and building previews."""
2
+
3
+ import re
4
+ import math
5
+ import sqlite3
6
+ import time
7
+ from datetime import datetime
8
+
9
+ SAMPLE_SIZE = 20
10
+ WINDOW = 300
11
+
12
+
13
+ def _connect(db):
14
+ conn = sqlite3.connect(str(db), timeout=0.05)
15
+ conn.execute('CREATE TABLE IF NOT EXISTS mcp_archive_net_observations '
16
+ '(tool TEXT NOT NULL, session TEXT NOT NULL, archive_id TEXT NOT NULL, '
17
+ 'created REAL NOT NULL, saved INTEGER NOT NULL, PRIMARY KEY(session, archive_id))')
18
+ conn.execute('CREATE INDEX IF NOT EXISTS mcp_archive_net_observations_tool_time '
19
+ 'ON mcp_archive_net_observations(tool, created DESC)')
20
+ conn.execute('CREATE TABLE IF NOT EXISTS mcp_archive_expand_calls '
21
+ '(session TEXT NOT NULL, archive_id TEXT NOT NULL, created REAL NOT NULL)')
22
+ conn.execute('CREATE INDEX IF NOT EXISTS mcp_archive_expand_calls_lookup '
23
+ 'ON mcp_archive_expand_calls(session, archive_id, created)')
24
+ conn.execute('CREATE TABLE IF NOT EXISTS mcp_archive_net_demotions '
25
+ '(tool TEXT PRIMARY KEY, created REAL NOT NULL, samples INTEGER NOT NULL, '
26
+ 'archived INTEGER NOT NULL, reexpanded INTEGER NOT NULL, overhead INTEGER NOT NULL)')
27
+ return conn
28
+
29
+
30
+ def record(db, tool, session, archive_id, saved, now=None):
31
+ """Record a replacement, never an archive that served the full result."""
32
+ try:
33
+ with _connect(db) as conn:
34
+ conn.execute('INSERT OR IGNORE INTO mcp_archive_net_observations VALUES (?,?,?,?,?)',
35
+ (tool, session, archive_id, time.time() if now is None else now, saved))
36
+ except sqlite3.Error:
37
+ pass
38
+
39
+
40
+ def expand_call_overhead(archive_id):
41
+ """Conservative proxy: command characters plus 16 framing tokens."""
42
+ return 16 + math.ceil(len('python3 measure.py expand ' + archive_id) / 3.3)
43
+
44
+
45
+ def record_expand(db, session, archive_id, now=None):
46
+ """Count every expand call, including repeats without a fresh debit."""
47
+ try:
48
+ with _connect(db) as conn:
49
+ conn.execute('INSERT INTO mcp_archive_expand_calls SELECT ?,?,? WHERE EXISTS '
50
+ '(SELECT 1 FROM mcp_archive_net_observations WHERE session=? AND archive_id=?)',
51
+ (session, archive_id, time.time() if now is None else now, session, archive_id))
52
+ except Exception:
53
+ pass
54
+
55
+
56
+ def decide(db, tool, active=False, now=None):
57
+ """Recompute a sticky demotion on mature samples; shadow never blocks."""
58
+ now = time.time() if now is None else now
59
+ try:
60
+ with _connect(db) as conn:
61
+ conn.execute('BEGIN IMMEDIATE')
62
+ demoted = conn.execute('SELECT 1 FROM mcp_archive_net_demotions WHERE tool=?', (tool,)).fetchone()
63
+ if not demoted:
64
+ rows = conn.execute('SELECT session, archive_id, created, saved FROM mcp_archive_net_observations '
65
+ 'WHERE tool=? AND created<=? ORDER BY created DESC, rowid DESC LIMIT ?',
66
+ (tool, now - WINDOW, SAMPLE_SIZE)).fetchall()
67
+ expanded = overhead = 0
68
+ for session, archive_id, created, saved in rows:
69
+ start = datetime.fromtimestamp(created).isoformat()
70
+ end = datetime.fromtimestamp(now).isoformat()
71
+ matches = conn.execute("SELECT detail,tokens_saved FROM savings_events WHERE event_type='tool_archive_reexpand' "
72
+ 'AND session_id=? AND timestamp>=? AND timestamp<=?',
73
+ (session, start, end)).fetchall()
74
+ expanded += sum(tokens or 0 for detail, tokens in matches if (detail or '').split(' ', 1)[0] == archive_id)
75
+ calls = conn.execute('SELECT COUNT(*) FROM mcp_archive_expand_calls WHERE session=? AND archive_id=? AND created>=? AND created<=?',
76
+ (session, archive_id, created, now)).fetchone()[0]
77
+ overhead += calls * expand_call_overhead(archive_id)
78
+ archived = sum(row[3] for row in rows)
79
+ if len(rows) == SAMPLE_SIZE and expanded + overhead >= archived:
80
+ conn.execute('INSERT OR IGNORE INTO mcp_archive_net_demotions VALUES (?,?,?,?,?,?)',
81
+ (tool, now, len(rows), archived, expanded, overhead))
82
+ demoted = True
83
+ return bool(active and demoted)
84
+ except (sqlite3.Error, OSError, ValueError):
85
+ return False
86
+
87
+
88
+ def evaluate(events, sample_size=20):
89
+ """Demote a complete sample when its signed net is not positive."""
90
+ recent = list(events)[-sample_size:]
91
+ return len(recent) == sample_size and sum(reexpanded + overhead for _, reexpanded, overhead in recent) >= sum(saved for saved, _, _ in recent)
92
+
93
+
94
+ def structured_preview(text, limit=3500, breaks_cluster=None):
95
+ """Show both ends and a bounded outline of recognizable headings."""
96
+ if len(text) <= limit:
97
+ return text
98
+ headings = []
99
+ for line in text[:131072].splitlines():
100
+ line = line.strip()
101
+ if re.match(r'^#{1,6}\s+\S', line):
102
+ headings.append(line[:120])
103
+ else:
104
+ key = re.match(r'^"([^"\\]{1,80})"\s*:', line)
105
+ if key and key.group(1) not in headings:
106
+ headings.append(key.group(1))
107
+ outline = '\n'.join(headings)
108
+ outline = outline[:min(1000, limit // 3)]
109
+ prefix = '\n\n[Outline]\n' + outline if outline else ''
110
+ separator = '\n\n[... middle omitted ...]\n\n'
111
+ remaining = max(0, limit - len(prefix) - len(separator))
112
+ head = remaining * 2 // 3
113
+ tail = remaining - head
114
+ tail_start = len(text) - tail
115
+ if breaks_cluster:
116
+ while head > 0 and breaks_cluster(text, head):
117
+ head -= 1
118
+ while tail_start < len(text) and breaks_cluster(text, tail_start):
119
+ tail_start += 1
120
+ return text[:head] + prefix + separator + text[tail_start:]