@alexgreensh/token-optimizer 5.13.69 → 5.13.71

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 (148) 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/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -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,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()
@@ -0,0 +1,250 @@
1
+ """Re-fetch metric for file content printed through the shell. Measures only.
2
+
3
+ When the generic fallback cuts the middle out of `sed -n`, `cat`, `head`,
4
+ `tail`, `nl` or `git show <rev>:<file>` output, that is file content the model
5
+ asked to see. This module answers one question from the user's own transcripts:
6
+ after such an elided result, did the same session fetch the same file range
7
+ again (a Read, or a shell print of the same file) within the next three tool
8
+ calls? It changes nothing about compression.
9
+
10
+ Decision rule, fixed before any measurement:
11
+ fewer than 200 elided events CANNOT-MEASURE
12
+ re-fetch rate above 15% MAKE-VERBATIM (these commands become lossless)
13
+ re-fetch rate below 5% MAY-WIDEN (fallback may reach prefixed forms, in shadow)
14
+ otherwise NO-CHANGE
15
+
16
+ Privacy: only counts leave this module. No path, command or output text is kept
17
+ past the comparison, and nothing is written anywhere.
18
+ """
19
+ import json
20
+ import os
21
+ import re
22
+ import shlex
23
+
24
+ WINDOW_CALLS = 3
25
+ MIN_EVENTS = 200
26
+ VERBATIM_ABOVE = 0.15
27
+ WIDEN_BELOW = 0.05
28
+
29
+ # TO's own elision line from the generic compressor (bash_compress._compress_generic).
30
+ _ELIDED = re.compile(r"(?m)^\.\.\. \d+ lines omitted(?: \(kept \d+ error/warning lines\))? \.\.\.$")
31
+ _PREFIX = re.compile(r"^\s*cd\s+(\"[^\"]*\"|'[^']*'|[^\s;&|]+)\s*(?:&&|;)\s*")
32
+ _FILE_PRINTERS = {"cat", "head", "tail", "nl", "sed"}
33
+ _NO_RANGE = None # an unknown range overlaps everything (conservative: counts as a re-fetch)
34
+
35
+
36
+ def _text(content):
37
+ if isinstance(content, str):
38
+ return content
39
+ if isinstance(content, list):
40
+ return "\n".join(b.get("text", "") for b in content
41
+ if isinstance(b, dict) and b.get("type") == "text")
42
+ return ""
43
+
44
+
45
+ def calls(path):
46
+ """Ordered tool calls of one transcript: [{name, input, cwd, text, is_error}].
47
+
48
+ ``text`` is kept for Bash results only; other tools never need it here.
49
+ """
50
+ order, by_id = [], {}
51
+ with open(path, encoding="utf-8", errors="replace") as stream:
52
+ for line in stream:
53
+ if '"tool_use"' not in line and '"tool_result"' not in line:
54
+ continue
55
+ try:
56
+ row = json.loads(line)
57
+ except ValueError:
58
+ continue
59
+ message = row.get("message") if isinstance(row, dict) else None
60
+ content = message.get("content") if isinstance(message, dict) else None
61
+ if not isinstance(content, list):
62
+ continue
63
+ cwd = row.get("cwd") if isinstance(row.get("cwd"), str) else ""
64
+ for block in content:
65
+ if not isinstance(block, dict):
66
+ continue
67
+ kind = block.get("type")
68
+ if kind == "tool_use" and block.get("id"):
69
+ entry = {"name": block.get("name"), "input": block.get("input") or {},
70
+ "cwd": cwd, "text": "", "is_error": False, "has_result": False}
71
+ order.append(entry)
72
+ by_id[block["id"]] = entry
73
+ elif kind == "tool_result":
74
+ entry = by_id.get(block.get("tool_use_id"))
75
+ if entry is not None:
76
+ entry["has_result"] = True
77
+ entry["is_error"] = bool(block.get("is_error"))
78
+ if entry["name"] == "Bash":
79
+ entry["text"] = _text(block.get("content"))
80
+ return order
81
+
82
+
83
+ def _abs(path, cwd, base):
84
+ p = os.path.expanduser(path)
85
+ if not os.path.isabs(p):
86
+ p = os.path.join(base or cwd or "", p)
87
+ return os.path.normpath(p)
88
+
89
+
90
+ def print_targets(command, cwd=""):
91
+ """For a single-stage file print, return [(key, (start, end) or None)], else [].
92
+
93
+ key is a normalized absolute path, or ``rev:path`` for `git show`. Pipelines,
94
+ redirections, substitutions and multi-statement commands return [] because
95
+ TO is not the only thing shaping their output.
96
+ """
97
+ if not isinstance(command, str):
98
+ return []
99
+ base = cwd
100
+ m = _PREFIX.match(command)
101
+ if m:
102
+ d = m.group(1).strip("'\"")
103
+ base = _abs(d, cwd, cwd)
104
+ command = command[m.end():]
105
+ if any(c in command for c in "|&;<>`$\n"):
106
+ return []
107
+ try:
108
+ tokens = shlex.split(command)
109
+ except ValueError:
110
+ return []
111
+ if not tokens:
112
+ return []
113
+ head = tokens[0]
114
+ if head == "git":
115
+ if len(tokens) == 3 and tokens[1] == "show" and ":" in tokens[2] and not tokens[2].startswith("-"):
116
+ rev, _, rel = tokens[2].partition(":")
117
+ return [(f"git:{rev}:{_abs(rel, cwd, base)}", _NO_RANGE)] if rev and rel else []
118
+ return []
119
+ if head not in _FILE_PRINTERS:
120
+ return []
121
+ rest = tokens[1:]
122
+ rng, files, i = _NO_RANGE, [], 0
123
+ if head == "sed":
124
+ script, i = None, 0
125
+ for a in rest:
126
+ if a == "-n":
127
+ continue
128
+ if a.startswith("-") and a != "-":
129
+ return [] # -i, -e, -E ... not the plain print form
130
+ if script is None:
131
+ script = a
132
+ else:
133
+ files.append(a)
134
+ mm = re.fullmatch(r"(\d+)(?:,(\d+))?p", script or "")
135
+ if not mm or not files:
136
+ return []
137
+ start = int(mm.group(1))
138
+ rng = (start, int(mm.group(2) or start))
139
+ else:
140
+ count = None
141
+ while i < len(rest):
142
+ a = rest[i]
143
+ if head in ("head", "tail") and a in ("-n", "-c", "--lines") and i + 1 < len(rest):
144
+ count = rest[i + 1] if a != "-c" else None
145
+ i += 2
146
+ elif head in ("head", "tail") and re.fullmatch(r"-\d+", a):
147
+ count = a[1:]
148
+ i += 1
149
+ elif a.startswith("-") and a != "-":
150
+ i += 1
151
+ else:
152
+ files.append(a)
153
+ i += 1
154
+ if head == "head" and not files:
155
+ return []
156
+ if head == "head":
157
+ n = int(count) if count and count.lstrip("+").isdigit() else 10
158
+ rng = (1, n)
159
+ if head in ("cat", "nl"):
160
+ rng = _NO_RANGE
161
+ if not files:
162
+ return []
163
+ return [(_abs(f, cwd, base), rng) for f in files]
164
+
165
+
166
+ def read_target(entry):
167
+ path = (entry.get("input") or {}).get("file_path")
168
+ if not isinstance(path, str) or not path:
169
+ return None
170
+ inp = entry["input"]
171
+ offset, limit = inp.get("offset"), inp.get("limit")
172
+ rng = _NO_RANGE
173
+ if isinstance(offset, int) and offset >= 1:
174
+ rng = (offset, offset + limit - 1 if isinstance(limit, int) and limit >= 1 else 10 ** 9)
175
+ elif isinstance(limit, int) and limit >= 1:
176
+ rng = (1, limit)
177
+ return _abs(path, entry.get("cwd", ""), entry.get("cwd", "")), rng
178
+
179
+
180
+ def _overlap(a, b):
181
+ if a is _NO_RANGE or b is _NO_RANGE:
182
+ return True
183
+ return a[0] <= b[1] and b[0] <= a[1]
184
+
185
+
186
+ def _follow_up_targets(entry):
187
+ if entry["name"] == "Read":
188
+ t = read_target(entry)
189
+ return [t] if t else []
190
+ if entry["name"] == "Bash":
191
+ cmd = entry["input"].get("command")
192
+ return print_targets(cmd, entry.get("cwd", ""))
193
+ return []
194
+
195
+
196
+ def scan(sequence, acc=None):
197
+ """Count elided file prints and re-fetches in one transcript's call order."""
198
+ acc = acc if acc is not None else new_counts()
199
+ for i, entry in enumerate(sequence):
200
+ if entry["name"] != "Bash" or entry["is_error"] or not _ELIDED.search(entry["text"]):
201
+ continue
202
+ targets = print_targets(entry["input"].get("command"), entry.get("cwd", ""))
203
+ if not targets:
204
+ continue
205
+ acc["events"] += 1
206
+ same_file = same_range = False
207
+ for later in sequence[i + 1:i + 1 + WINDOW_CALLS]:
208
+ for key, rng in _follow_up_targets(later):
209
+ for tkey, trng in targets:
210
+ if key == tkey:
211
+ same_file = True
212
+ if _overlap(rng, trng):
213
+ same_range = True
214
+ acc["refetched_file"] += int(same_file)
215
+ acc["refetched"] += int(same_range)
216
+ return acc
217
+
218
+
219
+ def new_counts():
220
+ return {"events": 0, "refetched": 0, "refetched_file": 0}
221
+
222
+
223
+ def verdict(events, refetched):
224
+ if events < MIN_EVENTS:
225
+ return "CANNOT-MEASURE"
226
+ rate = refetched / events
227
+ if rate > VERBATIM_ABOVE:
228
+ return "MAKE-VERBATIM"
229
+ if rate < WIDEN_BELOW:
230
+ return "MAY-WIDEN"
231
+ return "NO-CHANGE"
232
+
233
+
234
+ def summarize(acc):
235
+ events = acc["events"]
236
+ return {"events": events, "refetched": acc["refetched"], "refetched_any_range": acc["refetched_file"],
237
+ "rate": (acc["refetched"] / events) if events else None,
238
+ "rate_any_range": (acc["refetched_file"] / events) if events else None,
239
+ "window_calls": WINDOW_CALLS, "min_events": MIN_EVENTS,
240
+ "verdict": verdict(events, acc["refetched"])}
241
+
242
+
243
+ def format_lines(summary):
244
+ rate = "n/a" if summary["rate"] is None else f"{summary['rate'] * 100:.1f}%"
245
+ return [f"File content printed through the shell and cut by the generic fallback: "
246
+ f"{summary['events']:,} events.",
247
+ f"Same file range fetched again within {summary['window_calls']} calls: "
248
+ f"{summary['refetched']:,} ({rate}). Same file, any range: {summary['refetched_any_range']:,}.",
249
+ f"Verdict by the written rule (>15% verbatim, <5% may widen, under "
250
+ f"{summary['min_events']} events cannot measure): {summary['verdict']}."]