@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,65 @@
1
+ """Recognize transcripts made by Token Optimizer's benchmark harness."""
2
+ import fnmatch
3
+ import json
4
+ import os
5
+ from functools import lru_cache
6
+
7
+ # The harness runs each benchmark session in tempfile.mkdtemp(prefix="to-bench-M<n>-"),
8
+ # so its project key is the temp dir path with separators turned into dashes:
9
+ # macOS /private/var/folders/xx/yy/T/to-bench-M1-abc -> -private-var-folders-xx-yy-T-to-bench-M1-abc
10
+ # Linux /tmp/to-bench-M1-abc (or $TMPDIR) -> -tmp-to-bench-M1-abc
11
+ # Windows C:\Users\u\AppData\Local\Temp\to-bench-M1-abc -> C--Users-u-AppData-Local-Temp-to-bench-M1-abc
12
+ _PATTERNS = (
13
+ '*/-private-var-folders-*-T-to-bench-M[0-9]-*/*.jsonl',
14
+ '*/-var-folders-*-T-to-bench-M[0-9]-*/*.jsonl',
15
+ '*/*-tmp-to-bench-M[0-9]-*/*.jsonl',
16
+ '*/*-temp-to-bench-M[0-9]-*/*.jsonl',
17
+ '*/*-Temp-to-bench-M[0-9]-*/*.jsonl',
18
+ '*/*-TEMP-to-bench-M[0-9]-*/*.jsonl',
19
+ )
20
+ _PATTERN = _PATTERNS[0] # kept for callers that import the macOS pattern
21
+
22
+
23
+ def benchmark_path(path):
24
+ text = str(path or '').replace('\\', '/')
25
+ return bool(text) and any(fnmatch.fnmatchcase(text, pattern) for pattern in _PATTERNS)
26
+
27
+
28
+ @lru_cache(maxsize=4096)
29
+ def _usage_in_file(path, size, mtime):
30
+ try:
31
+ with open(path, encoding='utf-8', errors='replace') as stream:
32
+ for line in stream:
33
+ if '"usage"' not in line or '"assistant"' not in line:
34
+ continue
35
+ try:
36
+ obj = json.loads(line)
37
+ except ValueError:
38
+ continue
39
+ if not isinstance(obj, dict) or not isinstance(obj.get('message'), dict):
40
+ continue
41
+ usage = obj['message'].get('usage')
42
+ if obj.get('type') == 'assistant' and isinstance(usage, dict) and any(isinstance(v, (int, float)) and not isinstance(v, bool) and v > 0 for v in usage.values()):
43
+ return True
44
+ except (OSError, AttributeError):
45
+ pass
46
+ return False
47
+
48
+
49
+ def has_usage(path):
50
+ try:
51
+ stat = os.stat(path)
52
+ return _usage_in_file(str(path), stat.st_size, stat.st_mtime_ns)
53
+ except (OSError, TypeError, ValueError):
54
+ return False
55
+
56
+
57
+ def allowed_path(path):
58
+ return not benchmark_path(path) or has_usage(path)
59
+
60
+
61
+ def excluded_session_sql(alias):
62
+ glob = " OR ".join("replace(s.jsonl_path, char(92), '/') GLOB '" + p + "'" for p in _PATTERNS)
63
+ return ("COALESCE((SELECT CASE WHEN " + glob + " "
64
+ "THEN to_transcript_has_usage(s.jsonl_path) ELSE 1 END FROM session_log s "
65
+ "WHERE s.session_uuid=COALESCE(NULLIF(" + alias + ".session_uuid,''),NULLIF(" + alias + ".session_id,'')) ORDER BY s.id DESC LIMIT 1), 1)=1")
@@ -0,0 +1,100 @@
1
+ """One token headline shared by dashboard, CLI and runway."""
2
+
3
+
4
+ def _number(value):
5
+ try:
6
+ return int(float(value or 0))
7
+ except (TypeError, ValueError, OverflowError):
8
+ return 0
9
+
10
+
11
+
12
+ def token_headline(summary):
13
+ s = summary or {}
14
+ pools = ('hint_followed', 'resume_lean_verified')
15
+ verbosity = sum(max(0, _number(v.get('tokens_saved'))) for k, v in (s.get('by_category') or {}).items()
16
+ if str(k).startswith('verbosity') and isinstance(v, dict))
17
+ removed = max(0, _number(s.get('total_tokens')) - verbosity)
18
+ parts = {}
19
+ for name in pools:
20
+ pool = s.get(name) or s.get(name + '_estimated') or {}
21
+ if isinstance(pool, dict):
22
+ parts[name] = max(0, _number(pool.get('tokens_saved')))
23
+ removed += parts[name]
24
+ output = 0
25
+ reload_avoided = parts.get('resume_lean_verified', 0)
26
+ counted = s.get('counted_period') or {}
27
+ available = bool(counted.get('available'))
28
+ reread = _number(counted.get('reread_tokens')) if available else 0
29
+ return {
30
+ 'removed_tokens': removed, 'reread_tokens': reread,
31
+ 'context_removed_tokens': max(0, removed - output - reload_avoided),
32
+ 'output_not_generated_tokens': min(output, removed),
33
+ 'reload_avoided_tokens': min(reload_avoided, max(0, removed - output)),
34
+ 'total_tokens': max(0, removed + reread), 'reread_available': available,
35
+ 'removed_priced_tokens': _number(counted.get('removed_tokens')) if available else 0,
36
+ 'removed_usd': counted.get('oneshot_usd') if available else None,
37
+ 'reread_usd': counted.get('reread_usd') if available else None,
38
+ 'oneshot_prices_available': counted.get('oneshot_prices_available', True),
39
+ 'reread_prices_available': counted.get('reread_prices_available', True),
40
+ 'refresh_incomplete_events': _number(counted.get('refresh_incomplete_events')),
41
+ 'unmeasured_events': _number(counted.get('unmeasured_events')),
42
+ 'pricing_note': counted.get('pricing_note', ''),
43
+ 'oneshot_floor_note': counted.get('oneshot_floor_note', ''),
44
+ }
45
+
46
+
47
+ def input_traffic(conn, start, end):
48
+ """Dated parent input and output, including cache, without sidechains."""
49
+ import json
50
+ columns = {row[1] for row in conn.execute('PRAGMA table_info(session_log)')}
51
+ parent = 'parent_daily_usage_json' if 'parent_daily_usage_json' in columns else 'NULL'
52
+ daily = 'daily_usage_json' if 'daily_usage_json' in columns else 'NULL'
53
+ side = 'COALESCE(is_sidechain,0)' if 'is_sidechain' in columns else '0'
54
+ total = missing = combined = 0
55
+ for own, merged in conn.execute('SELECT {}, {} FROM session_log WHERE {}=0'.format(parent, daily, side)):
56
+ try:
57
+ usage = json.loads(own if own is not None else merged or 'null')
58
+ except (TypeError, ValueError):
59
+ usage = None
60
+ if not isinstance(usage, dict):
61
+ missing += 1
62
+ continue
63
+ combined += int(own is None and bool(usage))
64
+ for day, models in usage.items():
65
+ if not isinstance(day, str) or not (start <= day <= end) or not isinstance(models, dict):
66
+ continue
67
+ for bucket in models.values():
68
+ if isinstance(bucket, dict):
69
+ total += sum(max(0, _number(bucket.get(k))) for k in
70
+ ('fresh_input', 'cache_create', 'cache_read', 'output'))
71
+ return {'tokens': total, 'complete': missing == 0 and combined == 0,
72
+ 'basis': 'dated input and output, including cache reads and writes',
73
+ 'missing_rows': missing, 'combined_rows': combined}
74
+
75
+
76
+ def attach(summary, days):
77
+ """Token headline plus the typical-session effect, coverage and fleet share."""
78
+ summary['token_headline'] = token_headline(summary)
79
+ try:
80
+ from . import session_effect
81
+ summary['session_effect'] = session_effect.summary(days)
82
+ except Exception as err: # never break the savings payload
83
+ summary['session_effect'] = {'available': False, 'reason': type(err).__name__}
84
+ return summary
85
+
86
+
87
+ def cli_headline(h, days, effect=None):
88
+ cached = ('~{:,} re-reads avoided'.format(h['reread_tokens']) if h['reread_available']
89
+ else 're-reads unavailable')
90
+ text = ' ~{:,} tokens kept out of context ({} days) · ~{:,} context removed · ~{:,} output not generated · ~{:,} reload avoided · {}'.format(
91
+ h['total_tokens'], days, h.get('context_removed_tokens', h['removed_tokens']),
92
+ h.get('output_not_generated_tokens', 0), h.get('reload_avoided_tokens', 0), cached)
93
+ if effect:
94
+ from . import session_effect
95
+ text += ''.join('\n' + line for line in session_effect.cli_lines(effect))
96
+ if h['refresh_incomplete_events'] or h['unmeasured_events']:
97
+ text += '\n Estimated; some transcript coverage or refreshes are incomplete.'
98
+ if h['pricing_note']:
99
+ text += '\n ' + h['pricing_note']
100
+ return text
@@ -0,0 +1,96 @@
1
+ """Persist a first holdout assignment when the trends database is busy."""
2
+ import json
3
+ import os
4
+ import re
5
+ import sqlite3
6
+ import time
7
+ import uuid
8
+ from datetime import datetime
9
+
10
+ from hook_provenance import _exclusive
11
+ from .lease_candidate_cleanup import owner_is_gone
12
+
13
+ _SESSION = re.compile(r"^[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$")
14
+
15
+
16
+ def read(directory, session_id):
17
+ path = directory / ".holdout-pending" / (session_id + ".json")
18
+ try:
19
+ data = json.loads(path.read_text(encoding="utf-8"))
20
+ if data.get("arm") not in ("control", "treatment"):
21
+ return None
22
+ share = float(data["share"])
23
+ if not 0 < share <= 1:
24
+ return None
25
+ return data["arm"], share, str(data["assigned_at"])
26
+ except (OSError, ValueError, TypeError, KeyError):
27
+ return None
28
+
29
+
30
+ def claim(directory, session_id, arm, share):
31
+ root = directory / ".holdout-pending"
32
+ root.mkdir(parents=True, exist_ok=True, mode=0o700)
33
+ stripe = int(session_id.replace("-", "")[:2], 16) & 15
34
+ with _exclusive(root / (".guard-%x" % stripe), timeout=0.25) as held:
35
+ if not held:
36
+ return read(directory, session_id)
37
+ found = read(directory, session_id)
38
+ if found is not None:
39
+ return found
40
+ assigned_at = datetime.now().isoformat()
41
+ temporary = root / (".candidate-%d-%s.tmp" % (os.getpid(), uuid.uuid4().hex))
42
+ fd = os.open(str(temporary), os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
43
+ try:
44
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
45
+ json.dump({"arm": arm, "share": share, "assigned_at": assigned_at}, handle)
46
+ handle.flush()
47
+ os.fsync(handle.fileno())
48
+ os.replace(temporary, root / (session_id + ".json"))
49
+ finally:
50
+ try:
51
+ temporary.unlink()
52
+ except FileNotFoundError:
53
+ pass
54
+ return arm, share, assigned_at
55
+
56
+
57
+ def sweep(directory, conn):
58
+ """Reclaim only aged candidates already committed to the trends ledger."""
59
+ root = directory / ".holdout-pending"
60
+ if not root.is_dir():
61
+ return
62
+ deadline = time.monotonic() + 0.01
63
+ with _exclusive(root / ".sweep.guard", timeout=0) as held:
64
+ if not held:
65
+ return
66
+ try:
67
+ with os.scandir(root) as entries:
68
+ for entry in entries:
69
+ if time.monotonic() >= deadline:
70
+ return
71
+ try:
72
+ if not entry.is_file(follow_symlinks=False):
73
+ continue
74
+ if entry.name.startswith(".candidate-") and entry.name.endswith(".tmp"):
75
+ parts = entry.name[len(".candidate-"):-4].split("-")
76
+ if (len(parts) == 2 and parts[0].isdigit() and len(parts[1]) == 32
77
+ and all(c in "0123456789abcdef" for c in parts[1])
78
+ and entry.stat(follow_symlinks=False).st_mtime < time.time() - 86400
79
+ and owner_is_gone(int(parts[0]))):
80
+ os.unlink(entry.path)
81
+ continue
82
+ sid = entry.name[:-5] if entry.name.endswith(".json") else ""
83
+ if not _SESSION.match(sid) or entry.stat(follow_symlinks=False).st_mtime >= time.time() - 30 * 86400:
84
+ continue
85
+ stripe = int(sid.replace("-", "")[:2], 16) & 15
86
+ with _exclusive(root / (".guard-%x" % stripe), timeout=0) as locked:
87
+ if not locked:
88
+ continue
89
+ row = conn.execute("SELECT arm FROM holdout_sessions WHERE session_uuid=?", (sid,)).fetchone()
90
+ current = read(directory, sid)
91
+ if row and current and row[0] == current[0]:
92
+ os.unlink(entry.path)
93
+ except (OSError, ValueError, sqlite3.Error):
94
+ continue
95
+ except OSError:
96
+ pass
@@ -0,0 +1,129 @@
1
+ """Control-group comparison for the holdout (see holdout.py). Read-only.
2
+
3
+ Two unpaired arms of sessions: control (hooks ran in shadow) and treatment
4
+ (hooks acted). Nothing is shown until each arm has at least ``MIN_SESSIONS``
5
+ sessions of at least ``MIN_CALLS`` API calls, because anything smaller is noise
6
+ presented as a result. Intervals: a Wilson interval for a share of sessions,
7
+ and a plain percentile bootstrap (fixed seed, resampling sessions within each
8
+ arm independently) for means and for the treatment-minus-control difference.
9
+ The arms are not paired, so a paired bootstrap does not apply.
10
+
11
+ Metrics per arm: API calls per session; input + output tokens per call (a
12
+ dollar figure needs the pricing layer and is a follow-up, labelled as tokens
13
+ here); the share of sessions with at least one archive re-expand. Only counts
14
+ and aggregates leave this module.
15
+ """
16
+ import math
17
+ import random
18
+ import sqlite3
19
+ import statistics
20
+ from pathlib import Path
21
+
22
+ MIN_SESSIONS = 30
23
+ MIN_CALLS = 10
24
+ BOOTSTRAP_RESAMPLES = 2000
25
+ SEED = 1729
26
+ CONFIDENCE = 0.95
27
+
28
+
29
+ def wilson(k, n, confidence=CONFIDENCE):
30
+ """Wilson score interval for k of n: (point, low, high). n must be positive."""
31
+ z = statistics.NormalDist().inv_cdf((1.0 + confidence) / 2.0)
32
+ z2, point = z * z, k / n
33
+ denom = 1.0 + z2 / n
34
+ center = (point + z2 / (2.0 * n)) / denom
35
+ half = (z / denom) * math.sqrt(point * (1.0 - point) / n + z2 / (4.0 * n * n))
36
+ # At k == 0 the lower bound is exactly 0 and at k == n the upper bound is exactly 1; the two
37
+ # terms cancel only up to float rounding, which differs by platform (2.8e-17 on Linux and Windows).
38
+ low = 0.0 if k == 0 else max(0.0, center - half)
39
+ high = 1.0 if k == n else min(1.0, center + half)
40
+ return point, low, high
41
+
42
+
43
+ def _quantile(sorted_values, q):
44
+ pos = q * (len(sorted_values) - 1)
45
+ lo, hi = int(math.floor(pos)), int(math.ceil(pos))
46
+ return sorted_values[lo] + (sorted_values[hi] - sorted_values[lo]) * (pos - lo)
47
+
48
+
49
+ def bootstrap_mean(values, resamples=BOOTSTRAP_RESAMPLES, seed=SEED, confidence=CONFIDENCE):
50
+ rng = random.Random(seed)
51
+ n = len(values)
52
+ means = sorted(sum(values[rng.randrange(n)] for _ in range(n)) / n for _ in range(resamples))
53
+ tail = (1.0 - confidence) / 2.0
54
+ return sum(values) / n, _quantile(means, tail), _quantile(means, 1.0 - tail)
55
+
56
+
57
+ def bootstrap_diff(control, treatment, resamples=BOOTSTRAP_RESAMPLES, seed=SEED, confidence=CONFIDENCE):
58
+ """Mean(treatment) - mean(control) with a percentile interval; arms resampled independently."""
59
+ rng = random.Random(seed)
60
+ nc, nt = len(control), len(treatment)
61
+ diffs = sorted(sum(treatment[rng.randrange(nt)] for _ in range(nt)) / nt
62
+ - sum(control[rng.randrange(nc)] for _ in range(nc)) / nc
63
+ for _ in range(resamples))
64
+ tail = (1.0 - confidence) / 2.0
65
+ return (sum(treatment) / nt - sum(control) / nc), _quantile(diffs, tail), _quantile(diffs, 1.0 - tail)
66
+
67
+
68
+ def _empty(enabled=False, why=None):
69
+ out = {"available": True, "ready": False, "enabled": enabled,
70
+ "arms": {"control": 0, "treatment": 0}, "needed": MIN_SESSIONS, "min_calls": MIN_CALLS}
71
+ if why:
72
+ out["why"] = why
73
+ return out
74
+
75
+
76
+ def _sessions(db_path):
77
+ """[(arm, api_calls, tokens, reexpanded)] for non-sidechain sessions in an arm."""
78
+ path = Path(db_path)
79
+ with sqlite3.connect(path.resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0) as conn:
80
+ tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
81
+ if "holdout_sessions" not in tables:
82
+ return None
83
+ if "session_log" not in tables:
84
+ return []
85
+ reexpanded = set()
86
+ if "savings_events" in tables:
87
+ reexpanded = {r[0] for r in conn.execute(
88
+ "SELECT DISTINCT session_uuid FROM savings_events "
89
+ "WHERE event_type = 'tool_archive_reexpand' AND session_uuid IS NOT NULL")}
90
+ rows = conn.execute(
91
+ "SELECT h.arm, h.session_uuid, MAX(COALESCE(s.api_calls, 0)), "
92
+ "MAX(COALESCE(s.input_tokens, 0) + COALESCE(s.output_tokens, 0)) "
93
+ "FROM holdout_sessions h JOIN session_log s ON s.session_uuid = h.session_uuid "
94
+ "WHERE COALESCE(s.is_sidechain, 0) = 0 AND h.arm IN ('control', 'treatment') "
95
+ "GROUP BY h.arm, h.session_uuid").fetchall()
96
+ return [(arm, int(calls), int(tokens), uuid in reexpanded) for arm, uuid, calls, tokens in rows]
97
+
98
+
99
+ def collect(db_path, min_sessions=MIN_SESSIONS, min_calls=MIN_CALLS, resamples=BOOTSTRAP_RESAMPLES):
100
+ """Arm comparison, or the not-ready state. A missing table means the holdout never ran."""
101
+ if db_path is None or not Path(db_path).is_file():
102
+ return _empty()
103
+ try:
104
+ rows = _sessions(db_path)
105
+ except (sqlite3.Error, OSError, ValueError):
106
+ return {"available": False, "ready": False, "why": "ledger unreadable"}
107
+ if rows is None:
108
+ return _empty()
109
+ arms = {"control": [], "treatment": []}
110
+ for arm, calls, tokens, reexp in rows:
111
+ if calls >= min_calls:
112
+ arms[arm].append((calls, tokens / calls, 1.0 if reexp else 0.0))
113
+ counts = {k: len(v) for k, v in arms.items()}
114
+ out = _empty(enabled=True)
115
+ out.update(arms=counts, needed=min_sessions, min_calls=min_calls)
116
+ if min(counts.values()) < min_sessions:
117
+ return out
118
+ metrics = {}
119
+ for name, idx in (("calls_per_session", 0), ("tokens_per_call", 1), ("reexpand_rate", 2)):
120
+ per_arm = {a: [r[idx] for r in v] for a, v in arms.items()}
121
+ entry = {a: dict(zip(("mean", "low", "high"),
122
+ bootstrap_mean(per_arm[a], resamples) if name != "reexpand_rate"
123
+ else wilson(sum(per_arm[a]), len(per_arm[a]))))
124
+ for a in arms}
125
+ entry["difference"] = dict(zip(("mean", "low", "high"),
126
+ bootstrap_diff(per_arm["control"], per_arm["treatment"], resamples)))
127
+ metrics[name] = entry
128
+ out.update(ready=True, metrics=metrics, interval=CONFIDENCE)
129
+ return out
@@ -0,0 +1,201 @@
1
+ """Conservative return estimates from this installation's session history."""
2
+ from bisect import bisect_right
3
+ import hashlib
4
+ import json
5
+
6
+
7
+ def feature_settings():
8
+ return {'keepwarm': {'env_var': 'TOKEN_OPTIMIZER_KEEPWARM',
9
+ 'config_key': 'v5_keepwarm', 'default': True,
10
+ 'label': 'Keep-warm', 'what': 'Paused while we prove it is safe and saves you money.',
11
+ 'value': 'Automatic warm-ups are paused.', 'impact_pct': 0,
12
+ 'how': 'Automatic warm-ups do not run in this release.',
13
+ 'risk': 'A ping uses plan limits or API credits.', 'risk_level': 'low', 'recommended': False}}
14
+
15
+
16
+ def toggle(facade, enabled):
17
+ """The paused release does not expose an active setting."""
18
+ return False
19
+
20
+
21
+ class GapHistory:
22
+ """Index fully observed windows so replays do not rescan all transcripts."""
23
+
24
+ def __init__(self, sessions):
25
+ self.sessions = sessions
26
+ self.index = {}
27
+
28
+ def counts(self, now, elapsed, horizon):
29
+ key = (elapsed, horizon)
30
+ if key not in self.index:
31
+ at_risk, returned = [], []
32
+ for session in self.sessions:
33
+ times = sorted(t for t in session if isinstance(t, (int, float)))
34
+ for index, start in enumerate(times):
35
+ end = times[index + 1] if index + 1 < len(times) else None
36
+ if end is not None and end <= start + elapsed:
37
+ continue
38
+ cutoff = start + elapsed + horizon
39
+ at_risk.append(cutoff)
40
+ if end is not None and end <= cutoff:
41
+ returned.append(cutoff)
42
+ self.index[key] = (sorted(at_risk), sorted(returned))
43
+ at_risk, returned = self.index[key]
44
+ return bisect_right(at_risk, now), bisect_right(returned, now)
45
+
46
+
47
+ def return_probability(sessions, now, elapsed, horizon, minimum=20, prior=10):
48
+ """Estimate returns in the cover window for pauses surviving to elapsed.
49
+
50
+ Each session is an ordered sequence of turn timestamps. A terminal pause is
51
+ counted as no return once its whole observation window has elapsed. Windows
52
+ not yet fully observed are excluded, avoiding look-ahead and censor bias.
53
+ Ten prior no-return observations shrink small samples; cold starts return 0.
54
+ """
55
+ if elapsed < 0 or horizon <= 0:
56
+ return 0.0
57
+ if isinstance(sessions, GapHistory):
58
+ candidates, successes = sessions.counts(now, elapsed, horizon)
59
+ return successes / (candidates + prior) if candidates >= minimum else 0.0
60
+ candidates = successes = 0
61
+ for session in sessions:
62
+ times = sorted(t for t in session if isinstance(t, (int, float)) and t <= now)
63
+ for index, start in enumerate(times):
64
+ end = times[index + 1] if index + 1 < len(times) else None
65
+ cutoff = start + elapsed + horizon
66
+ if cutoff > now or (end is not None and end <= start + elapsed):
67
+ continue
68
+ candidates += 1
69
+ if end is not None and end <= cutoff:
70
+ successes += 1
71
+ if candidates < minimum:
72
+ return 0.0
73
+ return successes / (candidates + prior)
74
+
75
+
76
+ def decision(history, now, elapsed, ttl_kind, since, reload_value, ping_cost, phase):
77
+ ttl = 3600 if ttl_kind == '1h' else 300
78
+ cover = max(0, ttl - since) + ttl
79
+ probability = return_probability((history or {}).get('gap_sessions', []),
80
+ float(now), elapsed, cover)
81
+ if probability * reload_value <= 10 * ping_cost:
82
+ return {'action': 'stop', 'reason': 'insufficient-return-value', 'phase': phase}
83
+ return {'action': 'ping', 'reason': 'due', 'phase': phase}
84
+
85
+
86
+ def load_history(facade, supplied, records):
87
+ """Read local main-session transcripts only when an active tick needs them."""
88
+ if supplied is not None or not records:
89
+ return supplied
90
+ sessions = []
91
+ try:
92
+ paths = facade._find_all_jsonl_files(30)
93
+ for path, _, _ in paths:
94
+ turns = facade.parse_session_turns(path)
95
+ times = [facade._keepwarm_iso_to_epoch(t.get('timestamp')) for t in turns]
96
+ sessions.append([t for t in times if t is not None])
97
+ except (OSError, ValueError, TypeError, KeyError):
98
+ return {'gap_sessions': []}
99
+ return {'gap_sessions': GapHistory(sessions)}
100
+
101
+
102
+ def with_gaps(stats, sessions):
103
+ return dict(stats, gap_sessions=sessions or [])
104
+
105
+
106
+ def gate_reason(facade):
107
+ try:
108
+ summary = verified_summary(facade, 30, facade.time.time())
109
+ if summary['pings'] and summary['net_usd'] < 0:
110
+ return 'negative-net'
111
+ return 'live-resume-unverified'
112
+ except Exception:
113
+ return 'accounting-unavailable'
114
+
115
+
116
+ def verified_summary(facade, days, now):
117
+ conn = facade._open_trends_db_readonly(timeout=1.0)
118
+ try:
119
+ keys = {row[0] for row in conn.execute(
120
+ "SELECT pause_key FROM savings_events WHERE event_type = 'keepwarm_estimated' AND pause_key IS NOT NULL")}
121
+ finally:
122
+ conn.close()
123
+ rows = [row for row in facade._keepwarm_load_ledger_rows()
124
+ if row.get('status') != 'realized' or row.get('pause_key') in keys]
125
+ return facade.keepwarm_spend_summary(days=days, now=now, rows=rows)
126
+
127
+
128
+ def manual_count(rows, start):
129
+ attempts, cancelled = set(), set()
130
+ for row in rows:
131
+ try:
132
+ if (row.get('source') == 'claude-code-mod' and row.get('action') == 'warm' and
133
+ row.get('status') in ('firing', 'ok', 'cancelled') and float(row.get('ts', 0)) >= start):
134
+ (cancelled if row.get('status') == 'cancelled' else attempts).add(row.get('action_id'))
135
+ except (TypeError, ValueError):
136
+ continue
137
+ attempts.discard(None)
138
+ return len(attempts - cancelled)
139
+
140
+
141
+ def headline_pool(facade, cutoff):
142
+ """Use the spend ledger, including pings that never led to a return."""
143
+ now = facade.time.time()
144
+ start = facade._keepwarm_iso_to_epoch(cutoff)
145
+ if start is None:
146
+ return None
147
+ try:
148
+ if hasattr(facade, "keepwarm_detect_realized"):
149
+ facade.keepwarm_detect_realized(now=now)
150
+ summary = verified_summary(facade, max(0, now - start) / 86400, now)
151
+ except Exception:
152
+ return None
153
+ if not summary['pings'] and not summary['realized_count']:
154
+ return None
155
+ return {'events': summary['pings'] + summary['realized_count'],
156
+ 'tokens_saved': 0, 'cost_saved_usd': summary['net_usd'],
157
+ 'manual_pings': manual_count(facade._keepwarm_load_ledger_rows(), start)}
158
+
159
+
160
+ def claim_outcome(outcomes, firing_time):
161
+ """Match each completed ping to at most one reserved attempt."""
162
+ for index, outcome_time in enumerate(outcomes):
163
+ if outcome_time >= firing_time - 0.001:
164
+ outcomes.pop(index)
165
+ return True
166
+ return False
167
+
168
+
169
+ def attempt_key(record):
170
+ try:
171
+ session, armed = str(record['session_id']), float(record['ts'])
172
+ attempts = record.get('pings_fired') or []
173
+ if not session or armed <= 0 or not isinstance(attempts, list):
174
+ return None
175
+ raw = json.dumps([session, armed, len(attempts)], separators=(',', ':')).encode()
176
+ return hashlib.sha256(raw).hexdigest()
177
+ except (KeyError, TypeError, ValueError, OverflowError):
178
+ return None
179
+
180
+
181
+ def already_attempted(rows, key):
182
+ return not key or any(row.get('status') == 'firing' and row.get('attempt_key') == key
183
+ for row in rows)
184
+
185
+
186
+ def reconcile_while_paused(facade, reason, now, dry_run):
187
+ if reason in ('negative-net', 'kill-switch', 'settings-disabled', 'consent-declined',
188
+ 'tripwire-off', 'live-resume-unverified', 'accounting-unavailable') and not dry_run:
189
+ try:
190
+ facade.keepwarm_detect_realized(now=now)
191
+ except Exception:
192
+ pass
193
+
194
+
195
+ def transcript_changed(record):
196
+ try:
197
+ from pathlib import Path
198
+ stat = Path(record['transcript_path']).stat()
199
+ return stat.st_size != int(record['byte_size']) or stat.st_mtime != float(record['transcript_mtime'])
200
+ except (KeyError, TypeError, ValueError, OSError):
201
+ return False