@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
@@ -0,0 +1,36 @@
1
+ """Serialize dashboard self-heal launch-marker transitions."""
2
+ from hook_provenance import _exclusive
3
+
4
+
5
+ def claim(facade):
6
+ try:
7
+ facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
8
+ guard = facade.SNAPSHOT_DIR / "dashboard.heal.claim.guard"
9
+ with _exclusive(guard, timeout=0.05) as held:
10
+ if not held:
11
+ try:
12
+ fd = facade.os.open(str(guard), facade.os.O_RDWR)
13
+ facade.os.close(fd)
14
+ except OSError:
15
+ return True
16
+ return False
17
+ if facade._dashboard_selfheal_inflight():
18
+ return False
19
+ marker = facade.SNAPSHOT_DIR / facade._DASHBOARD_HEAL_LOCK_NAME
20
+ try:
21
+ fd = facade.os.open(str(marker), facade.os.O_CREAT | facade.os.O_EXCL | facade.os.O_WRONLY, 0o600)
22
+ except FileExistsError:
23
+ try:
24
+ if facade.time.time() - marker.stat().st_mtime <= facade._DASHBOARD_HEAL_LOCK_STALE_SECONDS:
25
+ return False
26
+ facade.os.unlink(str(marker))
27
+ fd = facade.os.open(str(marker), facade.os.O_CREAT | facade.os.O_EXCL | facade.os.O_WRONLY, 0o600)
28
+ except OSError:
29
+ return False
30
+ try:
31
+ facade.os.write(fd, str(facade.os.getpid()).encode("ascii"))
32
+ finally:
33
+ facade.os.close(fd)
34
+ return True
35
+ except OSError:
36
+ return True
@@ -0,0 +1,79 @@
1
+ """Persist the dashboard's embedded history window across rebuilds."""
2
+ import json
3
+ import os
4
+ import sqlite3
5
+ import tempfile
6
+ from datetime import date
7
+ from pathlib import Path
8
+
9
+ DEFAULT_DAYS = 30
10
+
11
+
12
+ def valid(value):
13
+ return value == 'all' or (type(value) is int and 1 <= value <= 365000)
14
+
15
+
16
+ def load(runtime_dir):
17
+ try:
18
+ path = Path(runtime_dir) / 'token-optimizer' / 'dashboard-history.json'
19
+ if path.is_symlink() or path.stat().st_size > 1024:
20
+ return DEFAULT_DAYS
21
+ value = json.loads(path.read_text(encoding='utf-8')).get('days')
22
+ return value if valid(value) else DEFAULT_DAYS
23
+ except (OSError, ValueError, AttributeError):
24
+ return DEFAULT_DAYS
25
+
26
+
27
+ def save(runtime_dir, value):
28
+ if not valid(value):
29
+ raise ValueError('invalid dashboard history window')
30
+ path = Path(runtime_dir) / 'token-optimizer' / 'dashboard-history.json'
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ fd, name = tempfile.mkstemp(prefix='.history-', dir=str(path.parent))
33
+ try:
34
+ with os.fdopen(fd, 'w', encoding='utf-8') as handle:
35
+ json.dump({'days': value}, handle)
36
+ os.replace(name, path)
37
+ finally:
38
+ if os.path.exists(name):
39
+ os.unlink(name)
40
+
41
+
42
+ def resolve_days(value, db_path, today=None):
43
+ if value != 'all':
44
+ return value if valid(value) else DEFAULT_DAYS
45
+ today = today or date.today()
46
+ earliest = None
47
+ try:
48
+ # URI mode=ro prevents an absent DB from being created as a side effect.
49
+ uri = Path(db_path).resolve().as_uri() + '?mode=ro'
50
+ with sqlite3.connect(uri, uri=True) as conn:
51
+ columns = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
52
+ for column in ('date', 'first_activity_day'):
53
+ if column in columns:
54
+ value = conn.execute('SELECT MIN(' + column + ') FROM session_log').fetchone()[0]
55
+ if value:
56
+ day = date.fromisoformat(value[:10])
57
+ earliest = day if earliest is None else min(earliest, day)
58
+ # Older databases may not yet have activity bounds. Inspect their
59
+ # daily maps so an older day is not hidden by the session date.
60
+ for column in ('daily_usage_json', 'parent_daily_usage_json', 'daily_calls_json'):
61
+ if column not in columns:
62
+ continue
63
+ condition = ' WHERE first_activity_day IS NULL' if 'first_activity_day' in columns else ''
64
+ for (raw,) in conn.execute('SELECT ' + column + ' FROM session_log' + condition):
65
+ try:
66
+ for key in json.loads(raw or '{}'):
67
+ day = date.fromisoformat(key)
68
+ earliest = day if earliest is None else min(earliest, day)
69
+ except (ValueError, TypeError):
70
+ continue
71
+ except (OSError, sqlite3.Error, ValueError, TypeError):
72
+ pass
73
+ # A missing or old DB falls back to a broad window for JSONL discovery.
74
+ earliest = earliest or date(1900, 1, 1)
75
+ return max(DEFAULT_DAYS, (today - earliest).days + 1)
76
+
77
+
78
+ def selected_days(runtime_dir, db_path):
79
+ return resolve_days(load(runtime_dir), db_path)
@@ -0,0 +1,95 @@
1
+ """Bounded parallel transcript scanning without sharing database handles."""
2
+ import os
3
+ import time
4
+ import multiprocessing
5
+ import sys
6
+ import threading
7
+ from concurrent.futures import ProcessPoolExecutor
8
+ from pathlib import Path
9
+
10
+ _POOL_GATE = threading.BoundedSemaphore(1)
11
+
12
+
13
+ def safe_entrypoint():
14
+ """Only spawn from the guarded CLI, never an arbitrary embedding script."""
15
+ main = getattr(sys.modules.get('__main__'), '__file__', '')
16
+ try:
17
+ return bool(main) and Path(main).resolve() == (Path(__file__).resolve().parents[1] / 'measure.py').resolve()
18
+ except (OSError, ValueError):
19
+ return False
20
+
21
+
22
+ def watch_parent():
23
+ """A killed regeneration must not strand idle scanner processes."""
24
+ parent = multiprocessing.parent_process()
25
+ if parent is None:
26
+ return
27
+ def stop_with_parent():
28
+ parent.join()
29
+ os._exit(1)
30
+ threading.Thread(target=stop_with_parent, daemon=True).start()
31
+
32
+
33
+ def _scan(path):
34
+ from .session_effect import scan_transcript
35
+ try:
36
+ return scan_transcript(path)
37
+ except (OSError, ValueError, TypeError):
38
+ return None
39
+
40
+
41
+ def first_call(path):
42
+ from .first_call_context import observe, transcript
43
+ try:
44
+ return observe(transcript(path), lambda value: round(len(value) / 4)), False
45
+ except (OSError, ValueError, TypeError):
46
+ return None, True
47
+
48
+
49
+ def _scan_chunk(worker, paths):
50
+ return [worker(path) for path in paths]
51
+
52
+
53
+ def batches(items, deadline, max_bytes, worker=_scan):
54
+ """Yield in order while workers scan ahead of the parent's large-file work."""
55
+ workers = min(8, os.cpu_count() or 1)
56
+ position = 0
57
+ pool, futures, next_submit = None, {}, 0
58
+ acquired = not multiprocessing.current_process().daemon and _POOL_GATE.acquire(blocking=False)
59
+ try:
60
+ if acquired:
61
+ pool = ProcessPoolExecutor(max_workers=workers, mp_context=multiprocessing.get_context('spawn'), initializer=watch_parent)
62
+ while position < len(items) and (deadline is None or time.monotonic() <= deadline):
63
+ while next_submit < len(items) and len(futures) < 128:
64
+ indexes = []
65
+ while next_submit < len(items) and len(indexes) < 4 and len(futures) + len(indexes) < 128:
66
+ if items[next_submit][1].st_size <= max_bytes:
67
+ indexes.append(next_submit)
68
+ next_submit += 1
69
+ if indexes:
70
+ future = pool.submit(_scan_chunk, worker, [items[index][0] for index in indexes])
71
+ futures.update({index: (future, offset) for offset, index in enumerate(indexes)})
72
+ path, stat = items[position]
73
+ if stat.st_size <= max_bytes:
74
+ future, offset = futures.pop(position)
75
+ result = future.result()[offset]
76
+ else:
77
+ result = worker(path)
78
+ yield [((path, stat), result)]
79
+ position += 1
80
+ except (OSError, RuntimeError, AssertionError):
81
+ pass
82
+ finally:
83
+ for future, _ in futures.values():
84
+ future.cancel()
85
+ try:
86
+ if pool is not None:
87
+ pool.shutdown(wait=True, cancel_futures=True)
88
+ finally:
89
+ if acquired:
90
+ _POOL_GATE.release()
91
+ if position < len(items):
92
+ while position < len(items) and (deadline is None or time.monotonic() <= deadline):
93
+ batch = items[position:position + 64]
94
+ yield [(item, worker(item[0])) for item in batch]
95
+ position += len(batch)
@@ -0,0 +1,256 @@
1
+ """Feature health: tell any user when a savings feature has gone quiet.
2
+
3
+ For each savings feature this compares how often it fired in the last 30 days
4
+ with how often it fired before, scaled by how active the user was in each
5
+ period (distinct active days). A feature that used to fire on a share of the
6
+ user's active days and now fires far less than that share predicts is flagged.
7
+
8
+ Universal by design: no fixed dates, no absolute event thresholds. The only
9
+ constants are statistical: a warning needs an expected count of at least
10
+ MIN_EXPECTED events (under a Poisson model, seeing zero by chance when about
11
+ six are expected is under a 0.3% event), so light users are never warned on
12
+ noise and heavy users are warned early.
13
+
14
+ Read-only. An unavailable database or missing table never reads as zero: the
15
+ result says ``available: False`` (or ``status: "unknown"`` per feature).
16
+ Pure stdlib; never imported by measure.py itself, only by the dashboard.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import sqlite3
21
+ from bisect import bisect_left
22
+ from datetime import datetime, timedelta
23
+ from pathlib import Path
24
+
25
+ RECENT_DAYS = 30
26
+ HISTORY_DAYS = 180 # earlier rate looks back at most this far
27
+ MIN_EXPECTED = 6.0 # expected events needed before "quiet" can fire
28
+ QUIET_RATIO = 0.15 # observed/expected at or below this = went quiet
29
+ FADING_RATIO = 0.4 # below this (with enough volume) = fading
30
+ MIN_EXPECTED_FADING = 12.0
31
+ ZERO_EFFECT_MIN = 8 # recent events needed to judge "fires, saves nothing"
32
+ ZERO_EFFECT_SHARE = 0.9
33
+
34
+ # (key, label, table, column, names, prefix_match)
35
+ # delta_read and structure_map also write a mirror row to compression_events;
36
+ # only the savings_events row is counted so nothing is double counted.
37
+ FEATURES = (
38
+ ("structure_map", "Structure map", "savings_events", "event_type", ("structure_map",), False),
39
+ ("delta_read", "Delta re-reads", "savings_events", "event_type", ("delta_read",), False),
40
+ ("crossturn_dedup", "Cross-turn dedup", "compression_events", "feature", ("crossturn_dedup",), False),
41
+ ("hint_followed", "Followed hints", "savings_events", "event_type", ("hint_followed",), False),
42
+ ("first_read_skeleton", "First-read skeleton", "compression_events", "feature", ("first_read_skeleton",), False),
43
+ ("tool_archive", "Tool output archive", "savings_events", "event_type", ("tool_archive",), False),
44
+ # Per-command bash categories were folded into one pipeline over time;
45
+ # grouping them keeps that rename from reading as an outage.
46
+ ("bash_compression", "Bash compression", "compression_events", "feature", ("bash_compress_", "bash_generic"), True),
47
+ ("build_output_compress", "Build output compression", "compression_events", "feature", ("build_output_compress",), False),
48
+ ("checkpoint_restore", "Checkpoint restore", "savings_events", "event_type", ("checkpoint_restore",), False),
49
+ ("resume_lean", "Lean resume", "savings_events", "event_type", ("resume_lean",), False),
50
+ )
51
+
52
+ # Known false positives, excluded from the user's own "earlier rate" so a history
53
+ # padded with them cannot make a healthy feature read as "went quiet".
54
+ # feature key -> (twin feature in the same table, seconds). An event counts as a
55
+ # false positive when the twin feature logged the SAME command within that many
56
+ # seconds: two installs saw one call, one compressed it and the other claimed it
57
+ # was a repeat (the duplicate-install pattern).
58
+ FALSE_POSITIVE_TWINS = {"crossturn_dedup": ("bash_compress_pipeline", 3.0)}
59
+
60
+ _SAVED_EXPR = {
61
+ "savings_events": "COALESCE(tokens_saved, 0)",
62
+ "compression_events": "COALESCE(original_tokens, 0) - COALESCE(compressed_tokens, 0)",
63
+ }
64
+
65
+
66
+ def _connect_ro(db_path):
67
+ if db_path is None:
68
+ return None
69
+ path = Path(db_path)
70
+ if not path.is_file():
71
+ return None
72
+ try:
73
+ conn = sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.5)
74
+ conn.execute("SELECT 1").fetchone()
75
+ return conn
76
+ except sqlite3.Error:
77
+ return None
78
+
79
+
80
+ def _tables(conn):
81
+ try:
82
+ return {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
83
+ except sqlite3.Error:
84
+ return set()
85
+
86
+
87
+ def _where(column, names, prefix):
88
+ if prefix:
89
+ parts, params = [], []
90
+ for n in names:
91
+ if n.endswith("_"):
92
+ parts.append(f"{column} LIKE ? ESCAPE '!'")
93
+ params.append(n.replace("_", "!_") + "%")
94
+ else:
95
+ parts.append(f"{column} = ?")
96
+ params.append(n)
97
+ return "(" + " OR ".join(parts) + ")", params
98
+ marks = ",".join("?" for _ in names)
99
+ return f"{column} IN ({marks})", list(names)
100
+
101
+
102
+ def _epoch(ts):
103
+ try:
104
+ return (datetime.fromisoformat(str(ts)[:26]).replace(tzinfo=None) - datetime(1970, 1, 1)).total_seconds()
105
+ except (ValueError, TypeError):
106
+ return None
107
+
108
+
109
+ def _without_twins(conn, table, column, names, twin, since, recent_start):
110
+ """Recount a feature with twin-confirmed false positives removed.
111
+
112
+ Returns (recent, zero_recent, earlier, first_earlier, last), or None when the
113
+ table cannot tell commands apart (then the plain counts stand).
114
+ """
115
+ twin_name, seconds = twin
116
+ try:
117
+ if "command_pattern" not in {r[1] for r in conn.execute(f"PRAGMA table_info({table})")}:
118
+ return None
119
+ where, params = _where(column, names, False)
120
+ events = conn.execute(
121
+ f"SELECT timestamp, {_SAVED_EXPR[table]}, command_pattern FROM {table} "
122
+ f"WHERE {where} AND timestamp >= ?", params + [since]).fetchall()
123
+ twins = {}
124
+ for ts, cmd in conn.execute(
125
+ f"SELECT timestamp, command_pattern FROM {table} "
126
+ f"WHERE {column} = ? AND command_pattern IS NOT NULL AND timestamp >= ?", (twin_name, since)):
127
+ t = _epoch(ts)
128
+ if t is not None:
129
+ twins.setdefault(cmd, []).append(t)
130
+ except sqlite3.Error:
131
+ return None
132
+ for times in twins.values():
133
+ times.sort()
134
+ recent = zero_recent = earlier = 0
135
+ first_earlier = last = None
136
+ for ts, saved, cmd in events:
137
+ t = _epoch(ts)
138
+ times = twins.get(cmd) if (cmd and t is not None) else None
139
+ if times:
140
+ i = bisect_left(times, t - seconds)
141
+ if i < len(times) and times[i] <= t + seconds:
142
+ continue
143
+ last = ts if last is None or ts > last else last
144
+ if ts >= recent_start:
145
+ recent += 1
146
+ zero_recent += 1 if saved <= 0 else 0
147
+ else:
148
+ earlier += 1
149
+ first_earlier = ts if first_earlier is None or ts < first_earlier else first_earlier
150
+ return recent, zero_recent, earlier, first_earlier, last
151
+
152
+
153
+ def _active_days(conn, tables, start, end):
154
+ """Distinct days with any recorded activity in [start, end)."""
155
+ days = set()
156
+ queries = []
157
+ if "session_log" in tables:
158
+ queries.append("SELECT DISTINCT substr(date, 1, 10) FROM session_log WHERE date >= ? AND date < ?")
159
+ for t in ("savings_events", "compression_events"):
160
+ if t in tables:
161
+ queries.append(f"SELECT DISTINCT substr(timestamp, 1, 10) FROM {t} WHERE timestamp >= ? AND timestamp < ?")
162
+ for q in queries:
163
+ try:
164
+ days.update(r[0] for r in conn.execute(q, (start, end)) if r[0])
165
+ except sqlite3.Error:
166
+ continue
167
+ return days
168
+
169
+
170
+ def _status(recent, expected, earlier, zero_recent):
171
+ if recent >= ZERO_EFFECT_MIN and zero_recent >= ZERO_EFFECT_SHARE * recent:
172
+ return "no_effect"
173
+ if expected is None:
174
+ return "new" if recent else ("never" if not earlier else "idle")
175
+ if expected >= MIN_EXPECTED and recent <= QUIET_RATIO * expected:
176
+ return "quiet"
177
+ if expected >= MIN_EXPECTED_FADING and recent < FADING_RATIO * expected:
178
+ return "fading"
179
+ if recent == 0:
180
+ return "rare"
181
+ return "ok"
182
+
183
+
184
+ _MESSAGES = {
185
+ "quiet": "Used to fire on your sessions and has gone quiet. It may be broken or switched off.",
186
+ "fading": "Firing far less than your own earlier rate.",
187
+ "no_effect": "Fires, but recorded no saving. The hook may report a replacement that never took effect.",
188
+ }
189
+
190
+
191
+ def collect(db_path, now=None, recent_days=RECENT_DAYS):
192
+ """Return the feature-health payload. Never writes; never raises."""
193
+ try:
194
+ return _collect(db_path, now, recent_days)
195
+ except Exception: # fail-open: the dashboard must always render
196
+ return {"available": False, "features": [], "warnings": 0}
197
+
198
+
199
+ def _collect(db_path, now, recent_days):
200
+ now = now or datetime.now()
201
+ if getattr(now, "tzinfo", None) is not None:
202
+ now = now.replace(tzinfo=None)
203
+ conn = _connect_ro(db_path)
204
+ if conn is None:
205
+ return {"available": False, "features": [], "warnings": 0}
206
+ try:
207
+ tables = _tables(conn)
208
+ if not tables & {"savings_events", "compression_events"}:
209
+ return {"available": False, "features": [], "warnings": 0}
210
+ recent_start = (now - timedelta(days=recent_days)).isoformat()
211
+ history_start = (now - timedelta(days=recent_days + HISTORY_DAYS)).isoformat()
212
+ end = (now + timedelta(days=1)).isoformat()
213
+ recent_active = len(_active_days(conn, tables, recent_start, end))
214
+ rows = []
215
+ for key, label, table, column, names, prefix in FEATURES:
216
+ row = {"feature": key, "label": label, "events": None, "earlier_events": None,
217
+ "expected": None, "last_event": None, "status": "unknown", "warning": False}
218
+ if table not in tables:
219
+ rows.append(row)
220
+ continue
221
+ where, params = _where(column, names, prefix)
222
+ try:
223
+ recent, zero_recent = conn.execute(
224
+ f"SELECT COUNT(*), COALESCE(SUM({_SAVED_EXPR[table]} <= 0), 0) FROM {table} "
225
+ f"WHERE {where} AND timestamp >= ?", params + [recent_start]).fetchone()
226
+ earlier, first_earlier = conn.execute(
227
+ f"SELECT COUNT(*), MIN(timestamp) FROM {table} WHERE {where} "
228
+ f"AND timestamp >= ? AND timestamp < ?", params + [history_start, recent_start]).fetchone()
229
+ last = conn.execute(f"SELECT MAX(timestamp) FROM {table} WHERE {where}", params).fetchone()[0]
230
+ except sqlite3.Error:
231
+ rows.append(row)
232
+ continue
233
+ if key in FALSE_POSITIVE_TWINS:
234
+ kept = _without_twins(conn, table, column, names, FALSE_POSITIVE_TWINS[key], history_start, recent_start)
235
+ if kept is not None:
236
+ recent, zero_recent, earlier, first_earlier, last = kept
237
+ expected = None
238
+ if earlier and first_earlier:
239
+ # Earlier rate = events per active day since the feature first fired
240
+ # in the lookback, so a feature added mid-history is not diluted.
241
+ earlier_active = len(_active_days(conn, tables, str(first_earlier)[:10], recent_start))
242
+ if earlier_active:
243
+ expected = round(earlier / earlier_active * recent_active, 1)
244
+ status = _status(recent, expected, earlier, zero_recent)
245
+ row.update(events=recent, earlier_events=earlier, expected=expected,
246
+ last_event=str(last)[:10] if last else None, status=status,
247
+ warning=status in ("quiet", "no_effect"))
248
+ if status in _MESSAGES:
249
+ row["message"] = _MESSAGES[status]
250
+ rows.append(row)
251
+ return {"available": True, "window_days": recent_days, "active_days": recent_active,
252
+ "features": rows, "warnings": sum(1 for r in rows if r["warning"])}
253
+ except sqlite3.Error:
254
+ return {"available": False, "features": [], "warnings": 0}
255
+ finally:
256
+ conn.close()