@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
@@ -2653,49 +2653,8 @@ def quick_scan(as_json=None):
2653
2653
  offenders.sort(key=lambda x: ((_measure_facade := _compat.facade()), -x[2])[1])
2654
2654
  top_offenders = offenders[:3]
2655
2655
 
2656
- # Quick win: check for unused skills via trends
2657
- quick_win = None
2658
- try:
2659
- trends = _measure_facade._collect_trends_data(days=30)
2660
- if trends and _measure_facade.detect_runtime() != "codex":
2661
- never_used = trends.get("skills", {}).get("never_used", [])
2662
- active_names = set(skills.get("names", []))
2663
- never_used = sorted({n for n in never_used
2664
- if n in active_names and not _measure_facade._is_own_tool_skill(n)})
2665
- if len(never_used) >= 3:
2666
- # Same rule as the coach's unused-skill savings: measured
2667
- # per-skill frontmatter only — never count x inventory average
2668
- # (which reports the inventory bound when most skills are
2669
- # unused) and never count x a flat constant.
2670
- detail_map = components.get("skills_detail", {})
2671
- measured = 0
2672
- unmeasured = 0
2673
- for _n in never_used:
2674
- try:
2675
- _t = int((detail_map.get(_n) or {}).get("frontmatter_tokens") or 0)
2676
- except (TypeError, ValueError, OverflowError):
2677
- _t = 0
2678
- if _t > 0:
2679
- measured += _t
2680
- else:
2681
- unmeasured += 1
2682
- if measured > 0:
2683
- _unm = f" ({unmeasured} of {len(never_used)} lack per-skill measurement)" if unmeasured else ""
2684
- quick_win = {
2685
- "action": f"Review {len(never_used)} skills not invoked in the window",
2686
- "savings": measured,
2687
- "detail": f"save ~{measured:,} measured tokens/session{_unm}",
2688
- "extend": f"Extends peak quality zone by ~{measured:,} tokens",
2689
- }
2690
- else:
2691
- quick_win = {
2692
- "action": f"Review {len(never_used)} skills not invoked in the window",
2693
- "savings": 0,
2694
- "detail": "savings unknown: per-skill measurements unavailable",
2695
- "extend": "Removing unused skills extends the peak quality zone",
2696
- }
2697
- except Exception:
2698
- pass
2656
+ product_check = _measure_facade._transcript_product.from_facade(_measure_facade) if _rt == 'claude' else None
2657
+ quick_win = _measure_facade._transcript_product.quick_win(_measure_facade, components, skills, product_check) if product_check else None
2699
2658
 
2700
2659
  # If no trends-based win, suggest instruction-file trimming
2701
2660
  if not quick_win and _measure_facade.detect_runtime() == "codex":
@@ -2788,6 +2747,7 @@ def quick_scan(as_json=None):
2788
2747
  for o in top_offenders
2789
2748
  ],
2790
2749
  "quick_win": quick_win,
2750
+ "transcript_checks": product_check,
2791
2751
  "coaching": coaching,
2792
2752
  "subagent_cache": _measure_facade.subagent_cache_block(),
2793
2753
  }
@@ -2807,6 +2767,9 @@ def quick_scan(as_json=None):
2807
2767
  print(f" Startup overhead: {overhead:,} tokens ({overhead_pct:.1f}%)")
2808
2768
  print(f" Usable before degradation: ~{usable_before_degradation:,} (50% fill = peak quality zone)")
2809
2769
  print(f" Messages before auto-compact: ~{msgs_before_compact} at typical message size")
2770
+ if product_check:
2771
+ print(" " + _measure_facade._transcript_product.listing_message(product_check))
2772
+ print(" " + _measure_facade._transcript_product.connector_message(product_check))
2810
2773
 
2811
2774
  print("\n DEGRADATION RISK")
2812
2775
  print(f" Current startup fill: {fill_pct * 100:.0f}% ({overhead:,}) -- {band_name}")
@@ -3003,6 +2966,13 @@ def doctor(as_json=None):
3003
2966
  checks.append(("!!", "Trends DB", "exists but unreadable"))
3004
2967
  else:
3005
2968
  checks.append(("!!", "Trends DB", _measure_facade._hint("not found (fix: python3 measure.py collect)")))
2969
+ from . import archive_health
2970
+ _arc = archive_health.replacement_check(_measure_facade)
2971
+ if _arc.get("status") in ("ok", "warning"):
2972
+ total += 1
2973
+ score += _arc["status"] == "ok"
2974
+ checks.append(("OK", "Tool archive", "replacements confirmed in transcripts") if _arc["status"] == "ok"
2975
+ else ("!!", "Tool archive", _arc.get("message", "replacements not applied")))
3006
2976
 
3007
2977
  # 8. Dashboard freshness
3008
2978
  total += 1
@@ -3585,6 +3555,7 @@ def _auto_capture_pristine_baseline():
3585
3555
  snapshot_before.json exists) and never raises. Returns True on capture.
3586
3556
  """
3587
3557
  _measure_facade = _compat.facade()
3558
+ from . import structural_ledger; structural_ledger.session_start_tick(_measure_facade) # per-component history, throttled
3588
3559
  try:
3589
3560
  filepath = _measure_facade.SNAPSHOT_DIR / "snapshot_before.json"
3590
3561
  if filepath.exists():
@@ -4308,15 +4279,14 @@ def _is_own_tool_skill(name) -> bool:
4308
4279
 
4309
4280
  def _skill_slim_clause(avg_tokens, runtime):
4310
4281
  """Softer-than-archive options for an unused skill, inserted ABOVE the archive
4311
- step. Keeps the skill installed while dropping its per-turn description cost.
4282
+ step. Keeps the skill installed while changing its listing visibility.
4312
4283
 
4313
4284
  Returns a block that STARTS and ends with a newline so it drops cleanly
4314
4285
  between the skill list and the archive step (each call site therefore does
4315
4286
  NOT add its own leading newline). Claude gets the two REAL, distinct Claude
4316
4287
  Code levers -- do not conflate them:
4317
4288
  - skillOverrides "name-only": NAME stays visible to the model (still
4318
- invocable by name), description dropped -> stops auto-triggering, saves
4319
- the description tokens. The true "name-only" middle mode.
4289
+ invocable by name), description dropped -> stops auto-triggering.
4320
4290
  - disable-model-invocation: true (frontmatter): removes the skill from the
4321
4291
  model's context ENTIRELY (name too); only the user invokes it via /name.
4322
4292
  Foreign runtimes have no per-skill toggle, so they get an honest note.
@@ -4324,9 +4294,8 @@ def _skill_slim_clause(avg_tokens, runtime):
4324
4294
  _measure_facade = _compat.facade()
4325
4295
  if runtime == "claude":
4326
4296
  return (
4327
- f"\n Softer than archiving -- two Claude Code levers keep the skill installed and recover "
4328
- f"~{avg_tokens} tokens/skill per turn (Claude may already have dropped some descriptions past "
4329
- f"its listing budget, so treat this as an upper bound):"
4297
+ f"\n Softer than archiving -- two Claude Code levers keep the skill installed. "
4298
+ f"The token change depends on the observed listing and its budget:"
4330
4299
  f"\n - Name-only (keep it discoverable): in the `/skills` menu press Space to cycle a skill to "
4331
4300
  f"`name-only` (writes `skillOverrides` in .claude/settings.local.json). The model still sees the "
4332
4301
  f"NAME so it can invoke it, but the description drops from context and it stops auto-triggering. "
@@ -4447,68 +4416,11 @@ def generate_auto_recommendations(components, trends=None, days=None):
4447
4416
  f"Focus on content that's only relevant for specific workflows."
4448
4417
  )
4449
4418
 
4450
- # --- Rule 3: Unused skills (requires trends data) ---
4451
- # Use actual measured avg if available, else fallback to constant
4452
- _si = components.get("skills", {})
4453
- _actual_avg = _si.get("tokens", 0) // max(_si.get("count", 1), 1) if _si.get("count", 0) > 0 else _measure_facade.TOKENS_PER_SKILL_APPROX
4454
- # Harness-aware "slim it, don't delete it" clause inserted ABOVE the archive
4455
- # step (see _skill_slim_clause). Codex is dispatched to
4456
- # _generate_codex_auto_recommendations and never reaches here, so this only
4457
- # shapes Claude / other-foreign-runtime advice.
4458
4419
  _runtime = _measure_facade.detect_runtime()
4459
- if trends:
4460
- # Never recommend cutting our own measurement skills.
4461
- never_used = [
4462
- s for s in trends.get("skills", {}).get("never_used", [])
4463
- if not _measure_facade._is_own_tool_skill(s)
4464
- ]
4465
- installed_count = trends.get("skills", {}).get("installed_count", 0)
4466
- if len(never_used) >= 5:
4467
- overhead = len(never_used) * _actual_avg
4468
- show_count = min(len(never_used), 8)
4469
- skill_list = ", ".join(_measure_facade._strip_ansi(str(s)) for s in sorted(never_used)[:show_count])
4470
- remaining = len(never_used) - show_count
4471
- quick.append(
4472
- f"**Review {show_count} skills not invoked in {days} days ({len(never_used)} of {installed_count}, counting Skill calls and slash commands)**: "
4473
- f"Each installed skill costs ~{_actual_avg} tokens in the startup menu, every session, whether you use it or not.\n"
4474
- f" Start with these: {skill_list}"
4475
- + (f"\n ({remaining} more will surface after you archive these and re-run.)" if remaining > 0 else "") +
4476
- f"\n For each skill, ask: do I use this? Is it seasonal? Does anything depend on it? "
4477
- f"(`grep -r \"[skill-name]\" ~/.claude/CLAUDE.md ~/.claude/rules/ ~/.claude/skills/`)"
4478
- + _measure_facade._skill_slim_clause(_actual_avg, _runtime) +
4479
- f" Archive (harder step, for truly-dead skills) by moving to ~/.claude/_backups/skills-archived-$(date +%Y%m%d)/ (NOT inside skills/). "
4480
- f"Restore any skill by moving it back. "
4481
- f"~{overhead:,} tokens recoverable across all {len(never_used)}."
4482
- )
4483
- elif len(never_used) >= 2:
4484
- overhead = len(never_used) * _actual_avg
4485
- skill_list = ", ".join(_measure_facade._strip_ansi(str(s)) for s in sorted(never_used))
4486
- medium.append(
4487
- f"**Review {len(never_used)} skills not invoked in {days} days**: "
4488
- f"No Skill call or slash command for these in {days} days: {skill_list}."
4489
- + _measure_facade._skill_slim_clause(_actual_avg, _runtime) +
4490
- f" Or archive truly-dead skills to ~/.claude/_backups/skills-archived-$(date +%Y%m%d)/ (NOT inside skills/). "
4491
- f"~{overhead:,} tokens recoverable."
4492
- )
4493
-
4494
- # --- Rule 3a: Skills audit fallback (no trends data) ---
4495
- skill_info = components.get("skills", {})
4496
- skill_count = skill_info.get("count", 0)
4497
- skill_tokens = skill_info.get("tokens", 0)
4498
- avg_per_skill = skill_tokens // max(skill_count, 1)
4499
- if not trends and skill_count > 10:
4500
- est_archive = skill_count - 10
4501
- est_savings = est_archive * avg_per_skill
4502
- medium.append(
4503
- f"**Review {skill_count} skills ({skill_tokens:,} tokens, no usage data)**: "
4504
- f"You have {skill_count} skills but no session data to determine which are unused. "
4505
- f"Each skill costs ~{avg_per_skill} tokens at startup whether you use it or not.\n"
4506
- f" Install the SessionEnd hook (`{_measure_facade._measure_cli()} setup-hook`) to enable usage-based "
4507
- f"recommendations. Meanwhile, manually review: do you use all {skill_count} regularly?"
4508
- + _measure_facade._skill_slim_clause(avg_per_skill, _runtime) +
4509
- f" Archiving {est_archive} (harder step, truly-dead skills) would free ~{est_savings:,} tokens/session. "
4510
- f"~{est_savings:,} tokens recoverable."
4511
- )
4420
+ if _runtime == 'claude':
4421
+ _product = _measure_facade._transcript_product.from_facade(_measure_facade)
4422
+ quick.extend([_measure_facade._transcript_product.listing_message(_product), _measure_facade._transcript_product.connector_message(_product)])
4423
+ quick.extend(_measure_facade._transcript_product.skill_recommendations(_measure_facade, components, trends, 'counting Skill calls and slash commands'))
4512
4424
 
4513
4425
  # --- Rule 3b: Removed in v2.3.0 ---
4514
4426
  # Aggregate "skills consume N tokens" was not actionable. Specific rules (Rule 3
@@ -5031,37 +4943,17 @@ def generate_coach_data(focus=None, components=None, trends=None, include_determ
5031
4943
  unused_skills = sorted({name for name in unused_skills
5032
4944
  if name in active_names and not _measure_facade._is_own_tool_skill(name)})
5033
4945
  unused_count = len(unused_skills)
5034
- # Savings come from per-skill measurement only: sum the unused candidates'
5035
- # own measured frontmatter tokens. Unmeasured names are reported as such —
5036
- # never an inventory-wide upper bound and never count x a flat constant.
5037
- skills_detail = components.get("skills_detail", {})
5038
- unused_measured_tokens = 0
5039
- unused_unmeasured = 0
5040
- for _name in unused_skills:
5041
- _raw_toks = (skills_detail.get(_name) or {}).get("frontmatter_tokens")
5042
- try:
5043
- _toks = int(_raw_toks)
5044
- except (TypeError, ValueError, OverflowError):
5045
- # NaN/inf/non-numeric entries are unmeasured, not a coach crash.
5046
- _toks = 0
5047
- if _toks > 0:
5048
- unused_measured_tokens += _toks
5049
- else:
5050
- unused_unmeasured += 1
5051
- if unused_measured_tokens > 0 and unused_unmeasured == 0:
5052
- unused_savings = f"~{unused_measured_tokens:,} tokens (measured descriptions of the {unused_count} unused skills)"
5053
- elif unused_measured_tokens > 0:
5054
- unused_savings = (f"~{unused_measured_tokens:,} tokens measured for the unused set "
5055
- f"({unused_unmeasured} of {unused_count} lack per-skill measurement)")
5056
- else:
5057
- unused_savings = "Unknown: per-skill token measurements unavailable for the unused set"
4946
+ product_check = _measure_facade._transcript_product.from_facade(_measure_facade) if is_claude else None
4947
+ unused_savings = _measure_facade._transcript_product.unused_savings(components, unused_skills, product_check)
4948
+ if product_check:
4949
+ patterns_bad.extend(_measure_facade._transcript_product.coach_patterns(product_check))
5058
4950
  unused_ratio = unused_count / skill_count if skill_count > 0 else 0
5059
4951
  if unused_count > 20 and skill_pct > 2 and unused_ratio > 0.8:
5060
4952
  skill_fix = (
5061
4953
  "Review unused Codex skills and plugins. Disable truly stale user skills with "
5062
4954
  "`measure.py codex-skill disable --path ...`; do not edit plugin cache directories directly."
5063
4955
  if is_codex
5064
- else "Review unused skills. Some may be seasonal, but archiving truly abandoned ones saves tokens. Move to ~/.claude/skills/_archived/"
4956
+ else "Review unused skills; use transcript evidence before estimating archive savings."
5065
4957
  )
5066
4958
  # Truly excessive: >80% of skills unused AND significant token overhead
5067
4959
  patterns_bad.append({
@@ -0,0 +1,339 @@
1
+ """Where each "before" baseline came from, and whether Token Optimizer was
2
+ already running inside it.
3
+
4
+ The transformation card and the routing estimate both compare today against an
5
+ earlier window of the user's own history. That window is only a true "before"
6
+ when it ends before the install. A fresh install with no older transcripts, a
7
+ rebuilt ledger, or a lost baseline file all leave an earliest window in which
8
+ the tool was already working, so the comparison understates the result. This
9
+ module finds the install date from the evidence on disk, classifies each
10
+ baseline window against it, and writes the sentence every surface shows.
11
+
12
+ Pure reads. Never raises.
13
+ """
14
+ import json
15
+ import re
16
+ import sqlite3
17
+ from datetime import datetime, timedelta
18
+
19
+ ROUTING_HISTORY_DAYS = 14
20
+ # Days of a baseline window that may fall after install before the window stops
21
+ # counting as pre-install (the install day itself, plus a short tail).
22
+ _TAIL_SHARE = 0.10
23
+ _INSTALL_PROOF = ("snapshot", "first_event")
24
+
25
+
26
+ def _day(value):
27
+ try:
28
+ return datetime.strptime(str(value)[:10], "%Y-%m-%d")
29
+ except (TypeError, ValueError):
30
+ return None
31
+
32
+
33
+ def _iso(day):
34
+ return day.strftime("%Y-%m-%d") if day else None
35
+
36
+
37
+ def _read_json(path):
38
+ try:
39
+ data = json.loads(path.read_text(encoding="utf-8"))
40
+ return data if isinstance(data, dict) else None
41
+ except (OSError, ValueError, TypeError, AttributeError):
42
+ return None
43
+
44
+
45
+ def _first_event_day(facade):
46
+ """Date of the earliest event Token Optimizer logged, or None."""
47
+ try:
48
+ if not facade.TRENDS_DB.exists():
49
+ return None
50
+ conn = facade._open_trends_db_readonly(timeout=1.0)
51
+ except Exception:
52
+ return None
53
+ found = []
54
+ try:
55
+ for table in ("savings_events", "compression_events"):
56
+ try:
57
+ row = conn.execute(
58
+ "SELECT MIN(timestamp) FROM " + table + " WHERE timestamp >= '2000'").fetchone()
59
+ except sqlite3.Error:
60
+ continue
61
+ day = _day(row[0]) if row and row[0] else None
62
+ if day:
63
+ found.append(day)
64
+ finally:
65
+ try:
66
+ conn.close()
67
+ except sqlite3.Error:
68
+ pass
69
+ return min(found) if found else None
70
+
71
+
72
+ def _earliest_session_day(facade):
73
+ try:
74
+ if not facade.TRENDS_DB.exists():
75
+ return None
76
+ conn = facade._init_trends_db()
77
+ try:
78
+ facade.ensure_activity_view(conn)
79
+ row = conn.execute("SELECT MIN(date) FROM session_activity WHERE date >= '2000'").fetchone()
80
+ finally:
81
+ conn.close()
82
+ return _day(row[0]) if row and row[0] else None
83
+ except Exception:
84
+ return None
85
+
86
+
87
+ def install_evidence(facade):
88
+ """{"date", "source"}: the earliest dated proof the tool was installed.
89
+
90
+ "snapshot" is the first-run baseline snapshot, "first_event" the earliest
91
+ logged event (it wins when a later audit re-took the snapshot). With
92
+ neither, the earliest session on record stands in as "earliest_session":
93
+ good enough to date a since-install total, but not proof of an install, so
94
+ no baseline window is classified against it.
95
+ """
96
+ proofs = []
97
+ try:
98
+ snap = _read_json(facade.SNAPSHOT_DIR / "snapshot_before.json")
99
+ day = _day((snap or {}).get("timestamp"))
100
+ if day:
101
+ proofs.append((day, "snapshot"))
102
+ except Exception:
103
+ pass
104
+ day = _first_event_day(facade)
105
+ if day:
106
+ proofs.append((day, "first_event"))
107
+ if proofs:
108
+ day, source = min(proofs, key=lambda item: item[0])
109
+ return {"date": _iso(day), "source": source}
110
+ day = _earliest_session_day(facade)
111
+ return {"date": _iso(day), "source": "earliest_session" if day else None}
112
+
113
+
114
+ def window_coverage(start, end, install):
115
+ """Classify the inclusive window [start, end] against the install date.
116
+
117
+ coverage: "pre_install" (a true before), "partial" (installed part-way
118
+ through), "post_install" (the tool ran for the whole window), or "unknown"
119
+ (no window, or no proof of when the tool was installed).
120
+ """
121
+ s, e = _day(start), _day(end)
122
+ install = install or {}
123
+ out = {"start": _iso(s), "end": _iso(e), "coverage": "unknown",
124
+ "install_date": install.get("date"), "install_source": install.get("source"),
125
+ "window_days": None, "post_install_days": None}
126
+ if not s or not e or e < s:
127
+ return out
128
+ days = (e - s).days + 1
129
+ out["window_days"] = days
130
+ d = _day(install.get("date"))
131
+ if not d or install.get("source") not in _INSTALL_PROOF:
132
+ return out
133
+ post = 0 if d > e else (e - max(s, d)).days + 1
134
+ out["post_install_days"] = post
135
+ if post <= max(1, int(days * _TAIL_SHARE)):
136
+ out["coverage"] = "pre_install"
137
+ elif d <= s:
138
+ out["coverage"] = "post_install"
139
+ else:
140
+ out["coverage"] = "partial"
141
+ return out
142
+
143
+
144
+ def _span(cov):
145
+ return "%s to %s" % (cov["start"], cov["end"]) if cov.get("start") and cov.get("end") else ""
146
+
147
+
148
+ def _transformation_copy(cov):
149
+ span = _span(cov)
150
+ where = " (%s)" % span if span else ""
151
+ state = cov["coverage"]
152
+ if state == "pre_install":
153
+ return ("compared with your own baseline from before you installed%s." % where, "")
154
+ lead = "compared with your earliest tracked month%s." % where
155
+ if state == "post_install":
156
+ note = ("Token Optimizer was already running in that month (installed %s), so this is the "
157
+ "change since then. Your usage from before install is not on record, so the full "
158
+ "before-and-after gap cannot be measured and this figure understates it."
159
+ % cov["install_date"])
160
+ elif state == "partial":
161
+ note = ("Token Optimizer was installed on %s, inside that month (%d of its %d days came "
162
+ "after install), so the true gap is larger and this figure understates it."
163
+ % (cov["install_date"], cov["post_install_days"], cov["window_days"]))
164
+ else:
165
+ note = ("The install date is not on record, so it is not known whether Token Optimizer "
166
+ "was already running in that month.")
167
+ if cov.get("pending_anchor") == "building":
168
+ note += (" A closer baseline is still being built from your older transcripts; "
169
+ "this figure will update when it is ready.")
170
+ return lead, note
171
+
172
+
173
+ def transformation(facade, baseline, weight_pool):
174
+ """Provenance of the transformation card's "before" arm.
175
+
176
+ anchor: "pinned_window" (the frozen early window, priced from transcripts),
177
+ "calendar_month" (earliest complete month still in the ledger) or
178
+ "frozen_session" (the frozen typical session, no work-unit pool).
179
+ """
180
+ try:
181
+ baseline = baseline or {}
182
+ window = baseline.get("window") or {}
183
+ anchor, start, end, pending = "frozen_session", window.get("start"), window.get("end"), None
184
+ if weight_pool:
185
+ label = str(weight_pool.get("anchor_month") or "")
186
+ month = re.fullmatch(r"(\d{4})-(\d{2})", label)
187
+ if month:
188
+ anchor = "calendar_month"
189
+ first = datetime(int(month.group(1)), int(month.group(2)), 1)
190
+ start = _iso(first)
191
+ end = _iso((first + timedelta(days=32)).replace(day=1) - timedelta(days=1))
192
+ state = _read_json(facade.SNAPSHOT_DIR / facade._PRETOOL_ANCHOR_FILE) or {}
193
+ if state.get("status") == "building":
194
+ pending = "building"
195
+ else:
196
+ anchor = "pinned_window"
197
+ dates = re.findall(r"\d{4}-\d{2}-\d{2}", label)
198
+ if len(dates) == 2:
199
+ start, end = dates
200
+ cov = window_coverage(start, end, install_evidence(facade))
201
+ try:
202
+ stated = baseline.get("opus_share_source") == "pretool_baseline"
203
+ share = float(baseline.get("opus_share") or 0)
204
+ except (TypeError, ValueError):
205
+ stated, share = False, 0.0
206
+ cov.update(anchor=anchor, pending_anchor=pending,
207
+ mix_source="stated" if stated else ("measured" if share > 0 else "current_mix"))
208
+ cov["lead"], cov["note"] = _transformation_copy(cov)
209
+ if cov["coverage"] in ("post_install", "partial"):
210
+ # The tool ran in the baseline month, so the comparison is with that
211
+ # month, never with a time before Token Optimizer.
212
+ unit = "request" if weight_pool else "session"
213
+ span = _span(cov)
214
+ cov["versus"] = "at your earliest month's cost per " + unit
215
+ cov["versus_label"] = "At your earliest month's cost per " + unit
216
+ cov["claim"] = ("At the cost per %s of your earliest tracked month%s, this period would "
217
+ "cost you this much more." % (unit, " (%s)" % span if span else ""))
218
+ cov["mix_note"] = {
219
+ "stated": "stated by you (set-baseline)",
220
+ "measured": "measured in your earliest tracked month",
221
+ "current_mix": "not measured, so your current mix is used on both sides",
222
+ }[cov["mix_source"]]
223
+ return cov
224
+ except Exception:
225
+ return None
226
+
227
+
228
+ def weight_pool_caveat(anchor_label, provenance):
229
+ """The method paragraph under a work-normalized transformation."""
230
+ text = (
231
+ "Work-normalized counterfactual: every API call you dispatched this "
232
+ "period, priced at the baseline's cost per call ("
233
+ + str(anchor_label) + "), at ONE constant rate card both eras -- so only how much "
234
+ "context each call carries (and how often the cache serves it) moves "
235
+ "the number; model-price and mix changes between eras are excluded and "
236
+ "disclosed separately, not claimed. Sessions are not used as the unit "
237
+ "because the lighter workflow itself splits the same work into more, "
238
+ "smaller sessions, which would count capacity gained as money saved. "
239
+ "The delta includes every volume mechanism at once (context "
240
+ "compression, lean output, loop prevention, continuity handovers), so "
241
+ "the metered and estimated pools are not added on top -- they would "
242
+ "double-count; the directly-metered floor still shows in its own card. "
243
+ "Delegated (subagent) work is excluded from this figure. The per-call delta "
244
+ "cannot separate Token Optimizer's effect from your own behaviour "
245
+ "drift -- the metered floor is the part we can prove action by action."
246
+ )
247
+ note = (provenance or {}).get("note")
248
+ return text + (" " + note if note else "")
249
+
250
+
251
+ def routing_baseline(facade):
252
+ """(shares, source, stated, early_mix) for realized routing when the user
253
+ has no stated baseline file: the mix captured at install, else the frozen
254
+ baseline (stable, and the same one the transformation card uses), else the
255
+ earliest days still in the ledger, which move if the ledger is rebuilt.
256
+ """
257
+ try:
258
+ snap = _read_json(facade.SNAPSHOT_DIR / "snapshot_before.json") or {}
259
+ mix = snap.get("model_mix") or {}
260
+ shares = (mix.get("shares") or {}) if mix.get("activity_basis") == 1 else {}
261
+ if shares:
262
+ return shares, "snapshot", False, None
263
+ except Exception:
264
+ pass
265
+ try:
266
+ frozen = _read_json(facade.SNAPSHOT_DIR / "baseline_state.json") or {}
267
+ shares = frozen.get("model_shares")
268
+ if (frozen.get("activity_basis") == 1 and isinstance(shares, dict)
269
+ and any(isinstance(v, (int, float)) and v > 0 for v in shares.values())):
270
+ return (dict(shares), "frozen_baseline",
271
+ frozen.get("opus_share_source") == "pretool_baseline", None)
272
+ except Exception:
273
+ pass
274
+ early = facade._earliest_model_mix()
275
+ if early:
276
+ return early["shares"], "history", False, early
277
+ return None, None, False, None
278
+
279
+
280
+ def _routing_window(facade, source):
281
+ if source == "snapshot":
282
+ snap = _read_json(facade.SNAPSHOT_DIR / "snapshot_before.json") or {}
283
+ end = _day(snap.get("timestamp"))
284
+ return (_iso(end - timedelta(days=ROUTING_HISTORY_DAYS)), _iso(end)) if end else (None, None)
285
+ if source == "frozen_baseline":
286
+ window = (_read_json(facade.SNAPSHOT_DIR / "baseline_state.json") or {}).get("window") or {}
287
+ return window.get("start"), window.get("end")
288
+ if source == "history":
289
+ first = _day((facade._earliest_model_mix() or {}).get("first_date"))
290
+ return (_iso(first), _iso(first + timedelta(days=ROUTING_HISTORY_DAYS))) if first else (None, None)
291
+ return None, None
292
+
293
+
294
+ def routing(facade, result):
295
+ """Provenance of the routing estimate's baseline mix, with display copy."""
296
+ try:
297
+ result = result or {}
298
+ source = result.get("baseline_source")
299
+ if not source:
300
+ return None
301
+ try:
302
+ pct = "%d%%" % round(float(result.get("baseline_opus_share") or 0) * 100)
303
+ except (TypeError, ValueError):
304
+ pct = ""
305
+ if source == "pretool_baseline" or result.get("baseline_stated"):
306
+ return {"source": source, "kind": "stated", "coverage": "stated",
307
+ "lead": "At your stated %s Opus baseline." % pct,
308
+ "short": "assuming %s Opus before Token Optimizer" % pct,
309
+ "ledger": "Estimated routing, at your stated %s Opus baseline" % pct}
310
+ install = install_evidence(facade)
311
+ if source == "snapshot" and install.get("source") == "snapshot":
312
+ # The mix was read from the days before the first-run snapshot.
313
+ start, end = _routing_window(facade, source)
314
+ cov = window_coverage(start, end, {"date": None, "source": None})
315
+ cov.update(coverage="pre_install", install_date=install["date"], install_source="snapshot")
316
+ else:
317
+ cov = window_coverage(*_routing_window(facade, source), install)
318
+ span = _span(cov)
319
+ when = " from %s" % span if span else ""
320
+ state = cov["coverage"]
321
+ if state == "pre_install":
322
+ lead = "Compared with your measured model mix before install (%s Opus%s)." % (pct, when)
323
+ short = "against your measured %s Opus mix before install" % pct
324
+ elif state in ("post_install", "partial"):
325
+ lead = ("Compared with your earliest measured model mix (%s Opus%s). Token Optimizer was "
326
+ "already running then (installed %s), so this is the shift since that period and "
327
+ "understates the shift since install." % (pct, when, cov["install_date"]))
328
+ short = ("against your earliest measured mix, %s Opus%s, with Token Optimizer already "
329
+ "running" % (pct, when))
330
+ else:
331
+ lead = ("Compared with your earliest measured model mix (%s Opus%s). The install date is "
332
+ "not on record, so it is not known whether Token Optimizer was already running "
333
+ "then." % (pct, when))
334
+ short = "against your earliest measured mix, %s Opus%s" % (pct, when)
335
+ cov.update(source=source, kind="measured", lead=lead, short=short,
336
+ ledger="Estimated routing, " + short)
337
+ return cov
338
+ except Exception:
339
+ return None