@alexgreensh/token-optimizer 5.13.69 → 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 (151) 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 +399 -509
  11. package/skills/token-optimizer/assets/savings_story.js +661 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  14. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  15. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  16. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  19. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  20. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  21. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  23. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  24. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  25. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  26. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  28. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  29. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  30. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  31. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  36. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  37. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  38. package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
  39. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  40. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  41. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  42. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  43. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  44. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  46. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  47. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  48. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  50. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  54. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  55. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  56. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  57. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  58. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  59. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  60. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  61. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  62. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  63. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  64. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  65. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  66. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  67. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  68. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  69. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  70. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  71. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  72. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  73. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  74. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  75. package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
  76. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  77. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  78. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  79. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  80. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  81. package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
  82. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  83. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  84. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  85. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  86. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  91. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  92. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  93. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  94. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  95. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  96. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  97. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  98. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  99. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  100. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  101. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  102. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  103. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  104. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  105. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  106. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  107. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  108. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  109. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  110. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  111. package/skills/token-optimizer/scripts/codemap.py +274 -0
  112. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  113. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  114. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  115. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  116. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  117. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  118. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  119. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  120. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  121. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  122. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  123. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  124. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  125. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  126. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  127. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  128. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  129. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  130. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  132. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  133. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  134. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  135. package/skills/token-optimizer/scripts/holdout.py +136 -0
  136. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  137. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  138. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  139. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  140. package/skills/token-optimizer/scripts/measure.py +34 -76
  141. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  142. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  143. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  144. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  145. package/skills/token-optimizer/scripts/session_store.py +49 -99
  146. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  147. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  148. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  149. package/skills/token-optimizer/scripts/statusline.js +1 -1
  150. package/skills/token-optimizer/scripts/structural.py +25 -0
  151. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,276 @@
1
+ """Book a verified manual compaction and its actual model cost atomically."""
2
+ from datetime import datetime
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+ import re
7
+
8
+ _ID = re.compile(r'^[A-Za-z0-9._-]{1,128}$')
9
+ _USAGE = ('input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens')
10
+
11
+
12
+ def _boundary(facade, event, sid, compact_id):
13
+ path = Path(event['transcript_path'])
14
+ if path.name != sid + '.jsonl' or path.is_symlink() or path.stat().st_size > 128 * 1024 * 1024:
15
+ return None
16
+ found, last_model = [], None
17
+ started = float(event.get('started_at', event['timestamp']))
18
+ finished = float(event['timestamp'])
19
+ if not math.isfinite(started) or not math.isfinite(finished) or started > finished:
20
+ return None
21
+ with path.open(encoding='utf-8') as stream:
22
+ for line in stream:
23
+ if 'compact_boundary' not in line and '"assistant"' not in line:
24
+ continue
25
+ try:
26
+ row = json.loads(line)
27
+ except ValueError:
28
+ continue
29
+ if not isinstance(row, dict) or row.get('isSidechain'):
30
+ continue
31
+ if row.get('type') == 'assistant' and isinstance(row.get('message'), dict):
32
+ last_model = row['message'].get('model') or last_model
33
+ if (row.get('type') == 'system' and row.get('subtype') == 'compact_boundary'
34
+ and row.get('sessionId') == sid and (row.get('compactMetadata') or {}).get('trigger') == 'manual'):
35
+ stamp = facade._keepwarm_iso_to_epoch(row.get('timestamp'))
36
+ rid = row.get('uuid')
37
+ if (isinstance(rid, str) and _ID.fullmatch(rid) and (not compact_id or rid == compact_id)
38
+ and stamp is not None and started - 1 <= stamp <= finished + 120):
39
+ found.append((rid, stamp, last_model))
40
+ return found[0] if len(found) == 1 else None
41
+
42
+
43
+ def _record_verified(facade, event):
44
+ """Write one counted removal and its cost only after matching a manual boundary."""
45
+ try:
46
+ if not isinstance(event, dict) or event.get('action') not in ('clean', 'clean-first'):
47
+ return {'ok': False, 'reason': 'unsupported-action'}
48
+ sid, ident, compact_id = (event.get(key) for key in ('session_id', 'action_id', 'compaction_id'))
49
+ if any(not isinstance(v, str) or not _ID.fullmatch(v) for v in (sid, ident)) or (compact_id is not None and (not isinstance(compact_id, str) or not _ID.fullmatch(compact_id))):
50
+ return {'ok': False, 'reason': 'invalid-identity'}
51
+ uuid, unjoinable = facade._extract_session_uuid(sid)
52
+ if not uuid or unjoinable:
53
+ return {'ok': False, 'reason': 'session-unjoinable'}
54
+ before, after = event['before_tokens'], event['after_tokens']
55
+ if type(before) is not int or type(after) is not int or not 0 <= after < before:
56
+ return {'ok': False, 'reason': 'invalid-token-delta'}
57
+ usage = event['usage']
58
+ if not isinstance(usage, dict) or any(type(usage.get(k)) is not int or usage[k] < 0 for k in _USAGE):
59
+ return {'ok': False, 'reason': 'usage-unavailable'}
60
+ ttl, creation = event.get('ttl_kind'), usage['cache_creation_input_tokens']
61
+ if (creation or event['action'] == 'clean-first') and ttl not in ('1h', '5m'):
62
+ return {'ok': False, 'reason': 'cache-write-class-unavailable'}
63
+ boundary = _boundary(facade, event, sid, compact_id)
64
+ if boundary is None:
65
+ return {'ok': False, 'reason': 'manual-boundary-unverified'}
66
+ compact_id, timestamp, preceding_model = boundary
67
+ model = event.get('model') or preceding_model
68
+ if not facade._is_priced_model(model):
69
+ return {'ok': False, 'reason': 'model-unpriced'}
70
+ cost = event.get('cost_usd')
71
+ if (isinstance(cost, bool) or not isinstance(cost, (int, float)) or not math.isfinite(cost) or
72
+ cost < 0 or (cost == 0 and any(usage[k] for k in _USAGE))):
73
+ return {'ok': False, 'reason': 'cost-unavailable'}
74
+ expected = facade._get_model_cost(model, usage['input_tokens'], usage['output_tokens'],
75
+ usage['cache_read_input_tokens'], creation, cache_create_1h=creation if ttl == '1h' else 0,
76
+ cache_create_5m=creation if ttl == '5m' else 0, per_request=True)
77
+ if not math.isfinite(expected) or abs(cost - expected) > max(0.00001, expected * 0.01):
78
+ return {'ok': False, 'reason': 'cost-mismatch'}
79
+ conn = facade._init_trends_db()
80
+ try:
81
+ conn.execute('CREATE TABLE IF NOT EXISTS mod_action_receipts '
82
+ '(action_id TEXT PRIMARY KEY, session_uuid TEXT NOT NULL, compaction_id TEXT NOT NULL, '
83
+ 'compression_event_id INTEGER NOT NULL, cost_event_id INTEGER NOT NULL, action TEXT NOT NULL, ttl_kind TEXT, '
84
+ 'UNIQUE(session_uuid, compaction_id))')
85
+ conn.execute('CREATE TABLE IF NOT EXISTS mod_action_observations '
86
+ '(action_id TEXT PRIMARY KEY, session_uuid TEXT NOT NULL, action TEXT NOT NULL, '
87
+ 'timestamp TEXT NOT NULL, reason TEXT NOT NULL)')
88
+ conn.commit()
89
+ conn.execute('BEGIN IMMEDIATE')
90
+ observed = conn.execute('SELECT session_uuid, action FROM mod_action_observations WHERE action_id=?', (ident,)).fetchone()
91
+ if observed and observed != (uuid, event['action']):
92
+ conn.rollback()
93
+ return {'ok': False, 'reason': 'identity-conflict'}
94
+ old = conn.execute('SELECT action_id, session_uuid, compaction_id, action FROM mod_action_receipts '
95
+ 'WHERE action_id = ? OR (session_uuid = ? AND compaction_id = ?)',
96
+ (ident, uuid, compact_id)).fetchall()
97
+ if old:
98
+ conn.rollback()
99
+ if any(r[0] == ident and r[3] != event['action'] for r in old):
100
+ return {'ok': False, 'reason': 'identity-conflict'}
101
+ if all(r[1:3] == (uuid, compact_id) for r in old):
102
+ return {'ok': True, 'duplicate': True, 'canonical_action_id': old[0][0]}
103
+ return {'ok': False, 'reason': 'identity-conflict'}
104
+ marker = 'compaction_id=' + compact_id
105
+ # Unidentified legacy compaction credit could be this boundary. Suppress
106
+ # our credit for the session, but still book the actual compaction cost.
107
+ existing = conn.execute(
108
+ "SELECT 1 FROM savings_events WHERE (session_uuid=? OR session_id=?) "
109
+ "AND event_type != 'mod_compaction_cost' AND (detail LIKE ? OR "
110
+ "(instr(lower(coalesce(detail,'')), 'compaction_id=')=0 AND "
111
+ "(lower(coalesce(event_type,'')) LIKE '%compact%' OR lower(coalesce(detail,'')) LIKE '%compact%'))) "
112
+ "UNION ALL SELECT 1 FROM compression_events WHERE (session_uuid=? OR session_id=?) "
113
+ "AND feature NOT IN ('mod_clean','mod_clean_first') AND (detail LIKE ? OR "
114
+ "(instr(lower(coalesce(detail,'')), 'compaction_id=')=0 AND "
115
+ "(lower(coalesce(feature,'')) LIKE '%compact%' OR lower(coalesce(detail,'')) LIKE '%compact%'))) LIMIT 1",
116
+ (uuid, sid, '%' + marker + '%', uuid, sid, '%' + marker + '%')).fetchone()
117
+ stamp = datetime.fromtimestamp(timestamp).isoformat()
118
+ feature = 'mod_clean_first' if event['action'] == 'clean-first' else 'mod_clean'
119
+ detail = 'from the Claude Code mod; compaction cost from engine session cost delta; ' + marker
120
+ compression_id = 0 # No compression row when an older credit takes precedence.
121
+ if not existing:
122
+ cur = conn.execute('INSERT INTO compression_events(timestamp,session_id,session_uuid,feature,command_pattern,'
123
+ 'original_tokens,compressed_tokens,compression_ratio,quality_preserved,verified,detail,model,tier) '
124
+ 'VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)', (stamp, sid, uuid, feature, 'manual-compaction', before, after,
125
+ after / before, 0, 1, detail, model, 'measured'))
126
+ if cur.rowcount != 1:
127
+ raise ValueError('removal not written')
128
+ compression_id = cur.lastrowid
129
+ cur = conn.execute('INSERT INTO savings_events(timestamp,event_type,tokens_saved,cost_saved_usd,session_id,'
130
+ 'session_uuid,detail,model,unjoinable) VALUES(?,?,?,?,?,?,?,?,?)',
131
+ (stamp, 'mod_compaction_cost', 0, -cost, sid, uuid, detail, model, 0))
132
+ if cur.rowcount != 1:
133
+ raise ValueError('cost not written')
134
+ cost_id = cur.lastrowid
135
+ cur = conn.execute('INSERT INTO mod_action_receipts(action_id,session_uuid,compaction_id,compression_event_id,cost_event_id,action,ttl_kind) '
136
+ 'VALUES(?,?,?,?,?,?,?)', (ident, uuid, compact_id, compression_id, cost_id, event['action'], ttl))
137
+ if cur.rowcount != 1:
138
+ raise ValueError('receipt not written')
139
+ conn.commit()
140
+ return {'ok': True, 'duplicate': False, 'removed_tokens': 0 if existing else before - after, 'cost_usd': cost, **({'reason': 'existing-compaction-credit'} if existing else {})}
141
+ except Exception:
142
+ conn.rollback()
143
+ raise
144
+ finally:
145
+ conn.close()
146
+ except Exception:
147
+ return {'ok': False, 'reason': 'receipt-unavailable'}
148
+
149
+
150
+
151
+ def _observe(facade, event, reason):
152
+ try:
153
+ sid, ident, action = event.get('session_id'), event.get('action_id'), event.get('action')
154
+ stamp = float(event['timestamp'])
155
+ if (any(not isinstance(v, str) or not _ID.fullmatch(v) for v in (sid, ident)) or
156
+ action not in ('clean', 'clean-first') or not math.isfinite(stamp) or stamp <= 0):
157
+ return False
158
+ uuid, unjoinable = facade._extract_session_uuid(sid)
159
+ if not uuid or unjoinable:
160
+ return False
161
+ conn = facade._init_trends_db()
162
+ try:
163
+ conn.execute('CREATE TABLE IF NOT EXISTS mod_action_observations '
164
+ '(action_id TEXT PRIMARY KEY, session_uuid TEXT NOT NULL, action TEXT NOT NULL, '
165
+ 'timestamp TEXT NOT NULL, reason TEXT NOT NULL)')
166
+ cur = conn.execute('INSERT OR IGNORE INTO mod_action_observations(action_id,session_uuid,action,timestamp,reason) '
167
+ 'VALUES(?,?,?,?,?)', (ident, uuid, action, datetime.fromtimestamp(stamp).isoformat(), reason))
168
+ conn.commit()
169
+ row = conn.execute('SELECT session_uuid,action FROM mod_action_observations WHERE action_id=?', (ident,)).fetchone()
170
+ return cur.rowcount == 1 or row == (uuid, action)
171
+ finally:
172
+ conn.close()
173
+ except Exception:
174
+ return False
175
+
176
+
177
+ def _existing_receipt(facade, event):
178
+ try:
179
+ sid = event['session_id']
180
+ uuid, unjoinable = facade._extract_session_uuid(sid)
181
+ boundary = _boundary(facade, event, sid, event.get('compaction_id'))
182
+ if unjoinable or not uuid or not boundary:
183
+ return None
184
+ conn = facade._open_trends_db_readonly(timeout=1.0)
185
+ try:
186
+ row = conn.execute('SELECT action_id FROM mod_action_receipts WHERE session_uuid=? AND compaction_id=?',
187
+ (uuid, boundary[0])).fetchone()
188
+ return row[0] if row else None
189
+ finally:
190
+ conn.close()
191
+ except Exception:
192
+ return None
193
+
194
+
195
+ def record(facade, event):
196
+ """Record a verified compaction, or retain a confirmed but unpriced action."""
197
+ result = _record_verified(facade, event)
198
+ if result.get('ok') and result.get('duplicate'):
199
+ if result.get('canonical_action_id') == event.get('action_id') and not _observe(facade, event, 'verified'):
200
+ return {'ok': False, 'reason': 'observation-unavailable'}
201
+ return dict(result, priced=True)
202
+ if result.get('ok'):
203
+ return dict(result, priced=True) if _observe(facade, event, 'verified') else {'ok': False, 'reason': 'observation-unavailable'}
204
+ if isinstance(event, dict) and (event.get('observed_manual') is True or event.get('observed_action') is True):
205
+ canonical = _existing_receipt(facade, event)
206
+ if canonical:
207
+ return {'ok': True, 'priced': True, 'duplicate': True, 'canonical_action_id': canonical}
208
+ if (isinstance(event, dict) and (event.get('observed_manual') is True or event.get('observed_action') is True) and result.get('reason') in
209
+ ('invalid-token-delta', 'existing-compaction-credit', 'usage-unavailable', 'cost-unavailable', 'cost-mismatch', 'cache-write-class-unavailable', 'model-unpriced',
210
+ 'manual-boundary-unverified', 'receipt-unavailable')):
211
+ if _observe(facade, event, result.get('reason')):
212
+ return {'ok': True, 'priced': False, 'reason': result.get('reason')}
213
+ return result
214
+
215
+
216
+ def summary(facade, cutoff):
217
+ try:
218
+ conn = facade._open_trends_db_readonly(timeout=1.0)
219
+ try:
220
+ has_receipts = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='mod_action_receipts'").fetchone()
221
+ join = 'LEFT JOIN mod_action_receipts r ON r.action_id=o.action_id' if has_receipts else ''
222
+ unpriced = 'sum(r.action_id IS NULL)' if has_receipts else 'count(*)'
223
+ row = conn.execute('SELECT count(*),' + unpriced + ' FROM mod_action_observations o ' + join +
224
+ ' WHERE o.timestamp >= ?', (cutoff,)).fetchone()
225
+ finally:
226
+ conn.close()
227
+ return {'events': row[0], 'unpriced_events': int(row[1] or 0)} if row[0] else None
228
+ except Exception:
229
+ return None
230
+
231
+ def adjust_score(facade, action, ttl, turns, event_time, tokens, tier_data, original):
232
+ """Put post-compaction reads in the counted stream; add one cold write for clean-first."""
233
+ import bisect
234
+ score = dict(original)
235
+ if action not in ('clean', 'clean-first') or not score.get('observed'):
236
+ return score
237
+ first = bisect.bisect_right([turn[0] for turn in turns], event_time)
238
+ if first >= len(turns):
239
+ return score
240
+ turn = turns[first]
241
+ card = facade._counted_exact_card(turn[1], tier_data, turn[2] if len(turn) > 2 else None)
242
+ for key in ('oneshot_unpriced_credit_tokens', 'oneshot_unpriced_debit_tokens', 'priced_oneshot_events',
243
+ 'oneshot_class_events', 'oneshot_floor_events', 'oneshot_floor_tokens'):
244
+ score[key] = 0
245
+ score['oneshot_usd'] = 0.0
246
+ score['oneshot_class_premium_usd'] = 0.0
247
+ score['reread_tokens'] += tokens
248
+ score['turns_counted'] += 1
249
+ read_rate = card.get('cache_read') if card else None
250
+ if isinstance(read_rate, (int, float)) and math.isfinite(read_rate) and read_rate >= 0:
251
+ score['reread_usd'] += tokens * read_rate / 1e6
252
+ score['priced_reread_turns'] += 1
253
+ else:
254
+ score['reread_unpriced_credit_tokens'] += tokens
255
+ cache_class = turn[3] if len(turn) > 3 else None
256
+ observed_write = isinstance(cache_class, tuple) and len(cache_class) >= 3 and ((ttl == '1h' and cache_class[1] > 0) or (ttl == '5m' and cache_class[2] > 0))
257
+ if action == 'clean-first' and observed_write:
258
+ write_rate = card.get('cache_write_1h' if ttl == '1h' else 'cache_write') if card and ttl in ('1h', '5m') else None
259
+ if isinstance(write_rate, (int, float)) and math.isfinite(write_rate) and write_rate >= 0:
260
+ score['reread_usd'] += tokens * write_rate / 1e6
261
+ else:
262
+ score['reread_unpriced_credit_tokens'] += tokens
263
+ return facade._counted_coverage_totals(score)
264
+
265
+
266
+ def event_features(conn):
267
+ """Find mod removals once per counted pass, including unlinked older rows."""
268
+ try:
269
+ has_receipts = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='mod_action_receipts'").fetchone()
270
+ join = 'LEFT JOIN mod_action_receipts r ON r.compression_event_id=c.id' if has_receipts else ''
271
+ ttl = 'r.ttl_kind' if has_receipts else 'NULL'
272
+ rows = conn.execute('SELECT c.id,c.feature,' + ttl + ' FROM compression_events c ' + join +
273
+ " WHERE c.feature IN ('mod_clean','mod_clean_first')")
274
+ return {'ce:' + str(row[0]): ('clean-first' if row[1] == 'mod_clean_first' else 'clean', row[2]) for row in rows}
275
+ except Exception:
276
+ return {}
@@ -0,0 +1,105 @@
1
+ """Estimated-only receipts for a mod's successful Start fresh action."""
2
+ from datetime import datetime, timedelta, timezone
3
+ import math
4
+ from pathlib import Path
5
+ import re
6
+ import statistics
7
+
8
+ _ID = re.compile(r'^[A-Za-z0-9._-]{1,128}$')
9
+ _MIN_COHORT = 5
10
+ _MAX_TURNS = 10
11
+
12
+
13
+ def record(facade, event):
14
+ """Capture one old session; derive a capped continuation estimate from prior sessions."""
15
+ try:
16
+ if not isinstance(event, dict) or event.get('action') != 'fresh':
17
+ return {'ok': False, 'reason': 'unsupported-action'}
18
+ sid, ident = event.get('session_id'), event.get('action_id')
19
+ if any(not isinstance(v, str) or not _ID.fullmatch(v) for v in (sid, ident)):
20
+ return {'ok': False, 'reason': 'invalid-identity'}
21
+ uuid, unjoinable = facade._extract_session_uuid(sid)
22
+ if not uuid or unjoinable:
23
+ return {'ok': False, 'reason': 'session-unjoinable'}
24
+ stamp, tokens = float(event['timestamp']), event.get('before_tokens')
25
+ handoff = event.get('handoff_tokens_estimate')
26
+ if (not math.isfinite(stamp) or stamp <= 0 or (tokens is not None and (type(tokens) is not int or tokens < 0))
27
+ or (handoff is not None and (type(handoff) is not int or handoff < 0))):
28
+ return {'ok': False, 'reason': 'invalid-evidence'}
29
+ tokens = max(0, tokens - handoff) if tokens is not None and handoff is not None else None
30
+ hint = event.get('transcript_path')
31
+ if not hint:
32
+ candidates = list((facade.CLAUDE_DIR / 'projects').glob('*/' + sid + '.jsonl'))
33
+ hint = candidates[0] if len(candidates) == 1 else None
34
+ path = Path(hint) if hint else None
35
+ usable = bool(path and path.name == sid + '.jsonl' and not path.is_symlink() and path.is_file()
36
+ and path.stat().st_size <= 128 * 1024 * 1024)
37
+ usage, model, _ = facade._keepwarm_last_usage(path) if usable else (None, None, None)
38
+ turns, _, _ = facade._counted_walk_transcript(path) if usable else ([], [], [])
39
+ cutoff = datetime.fromtimestamp(stamp, timezone.utc).replace(tzinfo=None)
40
+ prior_turns = sum(1 for turn in turns if turn[0] <= cutoff) if usable else None
41
+ tier = facade.PRICING_TIERS[facade._load_pricing_tier()]
42
+ card = facade._counted_exact_card(model, tier, tokens) if model and tokens else None
43
+ conn = facade._init_trends_db()
44
+ try:
45
+ conn.execute('CREATE TABLE IF NOT EXISTS mod_fresh_receipts '
46
+ '(action_id TEXT PRIMARY KEY, session_uuid TEXT NOT NULL UNIQUE, timestamp TEXT NOT NULL, '
47
+ 'dropped_tokens INTEGER, prior_turns INTEGER, estimated_turns REAL, '
48
+ 'estimated_usd REAL, cohort_size INTEGER NOT NULL, model TEXT, '
49
+ 'detail TEXT NOT NULL)')
50
+ conn.commit()
51
+ conn.execute('BEGIN IMMEDIATE')
52
+ previous = conn.execute('SELECT action_id, session_uuid FROM mod_fresh_receipts '
53
+ 'WHERE action_id=? OR session_uuid=?', (ident, uuid)).fetchall()
54
+ if previous:
55
+ conn.rollback()
56
+ return {'ok': all(row[1] == uuid for row in previous), 'duplicate': True}
57
+ start = (cutoff - timedelta(days=90)).date().isoformat()
58
+ end = cutoff.date().isoformat()
59
+ calls = [int(row[0]) for row in conn.execute(
60
+ 'SELECT api_calls FROM session_log WHERE date >= ? AND date < ? AND session_uuid != ? '
61
+ 'AND COALESCE(is_sidechain,0)=0 AND api_calls >= ? ORDER BY date DESC LIMIT 1000',
62
+ (start, end, uuid, prior_turns)) if row[0] is not None] if prior_turns else []
63
+ priced = bool(usage and tokens and card and isinstance(card.get('cache_read'), (int, float)))
64
+ estimated_turns = min(_MAX_TURNS, statistics.median(max(0, n - prior_turns) for n in calls)) if priced and len(calls) >= _MIN_COHORT else None
65
+ estimate = tokens * estimated_turns * card['cache_read'] / 1e6 if estimated_turns is not None else None
66
+ cur = conn.execute('INSERT INTO mod_fresh_receipts(action_id,session_uuid,timestamp,dropped_tokens,prior_turns,'
67
+ 'estimated_turns,estimated_usd,cohort_size,model,detail) VALUES(?,?,?,?,?,?,?,?,?,?)',
68
+ (ident, uuid, datetime.fromtimestamp(stamp).isoformat(), tokens, prior_turns, estimated_turns,
69
+ estimate, len(calls), model, 'from the Claude Code mod; estimated old context less handoff; persistent setup may remain; continuation capped at 10 turns'))
70
+ if cur.rowcount != 1:
71
+ raise ValueError('receipt not written')
72
+ conn.commit()
73
+ return {'ok': True, 'duplicate': False, 'estimated_usd': estimate, 'estimated_turns': estimated_turns}
74
+ except Exception:
75
+ conn.rollback()
76
+ raise
77
+ finally:
78
+ conn.close()
79
+ except Exception:
80
+ return {'ok': False, 'reason': 'receipt-unavailable'}
81
+
82
+
83
+ def summary(facade, cutoff):
84
+ """Return an estimated-only pool; missing history is reported as unpriced."""
85
+ try:
86
+ conn = facade._open_trends_db_readonly(timeout=1.0)
87
+ try:
88
+ row = conn.execute('SELECT count(*), sum(estimated_usd), sum(estimated_usd IS NULL) '
89
+ 'FROM mod_fresh_receipts WHERE timestamp >= ?', (cutoff,)).fetchone()
90
+ finally:
91
+ conn.close()
92
+ return {'events': row[0], 'cost_saved_usd': float(row[1] or 0),
93
+ 'unpriced_events': int(row[2] or 0), 'evidence': 'estimated'} if row[0] else None
94
+ except Exception:
95
+ return None
96
+
97
+
98
+ def additive(pool, handover):
99
+ """Do not stack two overlapping counterfactuals when identity is unavailable."""
100
+ try:
101
+ if float((handover or {}).get('cost_saved_usd', 0) or 0) > 0:
102
+ return 0.0
103
+ return max(0.0, float((pool or {}).get('cost_saved_usd', 0) or 0))
104
+ except (TypeError, ValueError):
105
+ return 0.0