@alexgreensh/token-optimizer 5.13.68 → 5.13.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,178 @@
1
+ """Durable, idempotent receipts for actions taken in the Claude Code mod."""
2
+ import json
3
+ import math
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+ import stat
8
+
9
+ _ID = re.compile(r'^[A-Za-z0-9._-]{1,128}$')
10
+ _USAGE = ('input_tokens', 'output_tokens', 'cache_read_input_tokens', 'cache_creation_input_tokens')
11
+
12
+
13
+ def _append(path, row):
14
+ flags = os.O_APPEND | os.O_CREAT | os.O_WRONLY | getattr(os, 'O_NOFOLLOW', 0)
15
+ fd = os.open(str(path), flags, 0o600)
16
+ with os.fdopen(fd, 'a', encoding='utf-8') as stream:
17
+ stream.write(json.dumps(row, separators=(',', ':'), allow_nan=False) + '\n')
18
+
19
+
20
+ def _identity(event):
21
+ sid, ident = event.get('session_id'), event.get('action_id')
22
+ if not isinstance(sid, str) or not _ID.fullmatch(sid) or not isinstance(ident, str) or not _ID.fullmatch(ident):
23
+ raise ValueError('invalid identity')
24
+ when = float(event['timestamp'])
25
+ if not math.isfinite(when) or when <= 0:
26
+ raise ValueError('invalid timestamp')
27
+ return sid, ident, when
28
+
29
+
30
+ def _snapshot(facade, event, sid):
31
+ path = Path(event['transcript_path'])
32
+ size, mtime = event['byte_size'], float(event['transcript_mtime'])
33
+ if (path.name != sid + '.jsonl' or path.is_symlink() or type(size) is not int or size <= 0 or
34
+ not math.isfinite(mtime)):
35
+ raise ValueError('invalid snapshot')
36
+ current = path.stat()
37
+ if not stat.S_ISREG(current.st_mode) or current.st_size != size or abs(current.st_mtime - mtime) > 0.001:
38
+ raise ValueError('transcript changed')
39
+ usage, model, last = facade._keepwarm_last_usage(path)
40
+ if not usage or not model or not facade._is_priced_model(model):
41
+ raise ValueError('model unpriced')
42
+ return {'path': str(path), 'byte_size': size, 'mtime': mtime, 'device': current.st_dev,
43
+ 'inode': current.st_ino, 'model': model, 'ttl': facade._keepwarm_ttl_kind(usage),
44
+ 'prefix': facade._keepwarm_prefix_proxy(usage), 'last_turn': facade._keepwarm_iso_to_epoch(last)}
45
+
46
+
47
+ def _lock(facade):
48
+ facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
49
+ path = facade.SNAPSHOT_DIR / (facade._KEEPWARM_LOCK_NAME + '.lease')
50
+ return facade.lease_lock(path, acquire_timeout=2.0, cohort_throttle=False, reclaim_released=True)
51
+
52
+
53
+ def _compatible(rows, sid):
54
+ return all(row.get('session_id') == sid and row.get('action') == 'warm' for row in rows)
55
+
56
+
57
+ def _prepare(facade, event, sid, ident, when):
58
+ snapshot = _snapshot(facade, event, sid)
59
+ estimate = facade._keepwarm_ping_cost_est(snapshot['prefix'], snapshot['model'])
60
+ if not math.isfinite(estimate) or estimate <= 0:
61
+ raise ValueError('estimate unavailable')
62
+ db = facade._init_trends_db()
63
+ db.close()
64
+ with _lock(facade) as acquired:
65
+ if not acquired:
66
+ return {'ok': False, 'reason': 'ledger-locked'}
67
+ existing = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
68
+ if existing:
69
+ return {'ok': False, 'reason': 'attempt-already-reserved' if _compatible(existing, sid) else 'identity-conflict'}
70
+ _append(facade._keepwarm_ledger_path(), {'status': 'firing', 'source': 'claude-code-mod',
71
+ 'action': 'warm', 'action_id': ident, 'attempt_key': ident, 'session_id': sid,
72
+ 'ts': when, 'est_cost_usd': estimate, 'snapshot': snapshot})
73
+ return {'ok': True, 'duplicate': False}
74
+
75
+
76
+ def _cancel(facade, sid, ident, when):
77
+ with _lock(facade) as acquired:
78
+ if not acquired:
79
+ return {'ok': False, 'reason': 'ledger-locked'}
80
+ rows = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
81
+ if not rows or not _compatible(rows, sid) or any(r.get('status') == 'ok' for r in rows):
82
+ return {'ok': False, 'reason': 'reservation-unavailable'}
83
+ if not any(r.get('status') == 'cancelled' for r in rows):
84
+ _append(facade._keepwarm_ledger_path(), {'status': 'cancelled', 'source': 'claude-code-mod',
85
+ 'action': 'warm', 'action_id': ident, 'session_id': sid, 'ts': when})
86
+ return {'ok': True}
87
+
88
+
89
+ def _snapshot_still_usable(snapshot):
90
+ try:
91
+ path = Path(snapshot['path'])
92
+ current = path.stat()
93
+ return (not path.is_symlink() and stat.S_ISREG(current.st_mode) and
94
+ (current.st_dev, current.st_ino) == (snapshot['device'], snapshot['inode']) and
95
+ current.st_size >= snapshot['byte_size'] and
96
+ (current.st_size > snapshot['byte_size'] or abs(current.st_mtime - snapshot['mtime']) <= 0.001))
97
+ except (KeyError, TypeError, OSError):
98
+ return False
99
+
100
+
101
+ def record(facade, event):
102
+ """Reserve then book usage once; credit only a subsequently proven warm return."""
103
+ try:
104
+ if isinstance(event, dict) and event.get('action') == 'fresh':
105
+ from . import mod_fresh_booking
106
+ return mod_fresh_booking.record(facade, event)
107
+ if isinstance(event, dict) and event.get('action') in ('clean', 'clean-first'):
108
+ from . import mod_compaction_booking
109
+ return mod_compaction_booking.record(facade, event)
110
+ if not isinstance(event, dict) or event.get('action') not in ('warm', 'warm-prepare', 'warm-cancel'):
111
+ return {'ok': False, 'reason': 'unsupported-action'}
112
+ sid, ident, when = _identity(event)
113
+ if event['action'] == 'warm-prepare':
114
+ return _prepare(facade, event, sid, ident, when)
115
+ if event['action'] == 'warm-cancel':
116
+ return _cancel(facade, sid, ident, when)
117
+ usage = event['usage']
118
+ if not isinstance(usage, dict) or any(type(usage.get(key)) is not int or usage[key] < 0 for key in _USAGE):
119
+ return {'ok': False, 'reason': 'invalid-usage'}
120
+ # Old callers can submit an already answered attempt; new mod calls reserve first.
121
+ facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
122
+ with _lock(facade) as acquired:
123
+ if not acquired:
124
+ return {'ok': False, 'reason': 'ledger-locked'}
125
+ existing = [r for r in facade._keepwarm_load_ledger_rows() if r.get('action_id') == ident]
126
+ if existing and not _compatible(existing, sid):
127
+ return {'ok': False, 'reason': 'identity-conflict'}
128
+ if any(r.get('status') == 'cancelled' for r in existing):
129
+ return {'ok': False, 'reason': 'reservation-cancelled'}
130
+ reservation = next((r for r in existing if r.get('status') == 'firing'), None)
131
+ snapshot = reservation.get('snapshot') if reservation else _snapshot(facade, event, sid)
132
+ if not isinstance(snapshot, dict):
133
+ return {'ok': False, 'reason': 'snapshot-unavailable'}
134
+ model, ttl = snapshot['model'], snapshot['ttl']
135
+ creation = usage['cache_creation_input_tokens']
136
+ cost = facade._get_model_cost(model, usage['input_tokens'], usage['output_tokens'],
137
+ usage['cache_read_input_tokens'], creation, cache_create_1h=creation,
138
+ cache_create_5m=0, per_request=True)
139
+ if not math.isfinite(cost) or cost <= 0:
140
+ return {'ok': False, 'reason': 'cost-unavailable'}
141
+ db = facade._init_trends_db()
142
+ db.close()
143
+ pause_key = facade._keepwarm_pause_key(sid, when)
144
+ arms = facade.load_keepwarm_records()
145
+ same_pause = next((r for r in arms if r.get('session_id') == sid and
146
+ r.get('byte_size') == snapshot['byte_size'] and
147
+ r.get('transcript_mtime') == snapshot['mtime'] and r.get('pings_fired')), None)
148
+ if same_pause is not None:
149
+ pause_key = facade._keepwarm_pause_key(sid, same_pause['ts'])
150
+ row = {'status': 'ok', 'source': 'claude-code-mod', 'action': 'warm', 'action_id': ident,
151
+ 'attempt_key': ident, 'session_id': sid, 'pause_key': pause_key, 'ts': when,
152
+ 'model': model, 'cost_usd': cost, 'cost_basis': 'conservative-1h-write' if creation else 'reported-usage', 'usage': dict(usage)}
153
+ finished = [r for r in existing if r.get('status') == 'ok']
154
+ if not finished:
155
+ _append(facade._keepwarm_ledger_path(), row)
156
+ usable = _snapshot_still_usable(snapshot)
157
+ if event.get('answered', True) is True and usable and same_pause is None and not any(r.get('manual_action_id') == ident for r in arms):
158
+ _append(facade._keepwarm_sidecar_path(), {'session_id': sid, 'transcript_path': snapshot['path'],
159
+ 'transcript_mtime': snapshot['mtime'], 'byte_size': snapshot['byte_size'], 'model': model,
160
+ 'prefix_proxy': snapshot['prefix'], 'ttl_kind': ttl, 'last_turn_ts': snapshot['last_turn'] or when,
161
+ 'ts': when, 'state': 'armed', 'owner': None, 'pings_fired': [when],
162
+ 'pause_key': pause_key, 'manual_action_id': ident})
163
+ return {'ok': True, 'pause_key': pause_key, 'cost_usd': cost, 'duplicate': bool(finished), 'resume_trackable': usable}
164
+ except Exception:
165
+ return {'ok': False, 'reason': 'receipt-unavailable'}
166
+
167
+
168
+ def main(facade):
169
+ """Read a single bounded action receipt from standard input."""
170
+ try:
171
+ raw = facade.sys.stdin.read(65537)
172
+ if len(raw) > 65536:
173
+ raise ValueError('receipt too large')
174
+ result = record(facade, json.loads(raw))
175
+ except (ValueError, TypeError):
176
+ result = {'ok': False, 'reason': 'invalid-receipt'}
177
+ print(json.dumps(result, separators=(',', ':')))
178
+ return 0 if result['ok'] else 1
@@ -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