@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,190 @@
1
+ """Locate unjoined ledger events without assigning ambiguous transcripts."""
2
+ from collections import defaultdict
3
+ from pathlib import Path
4
+ from . import counted_subagents as sub, fixture_context
5
+
6
+
7
+ def _parent(path):
8
+ path = Path(path)
9
+ return path.parent.parent.with_suffix('.jsonl') if path.parent.name == 'subagents' else path
10
+
11
+
12
+ def _event_details(conn, events):
13
+ details = {}
14
+ for key, uuid, *_ in events:
15
+ if uuid or not (key.startswith('ce:') or key.startswith('se:')):
16
+ continue
17
+ table = 'compression_events' if key.startswith('ce:') else 'savings_events'
18
+ row = conn.execute('SELECT session_id FROM ' + table + ' WHERE id=?', (int(key[3:]),)).fetchone()
19
+ details[key] = row[0] if row else None
20
+ return details
21
+
22
+
23
+ def group_events(facade, conn, events, resolve=True):
24
+ """Return session groups and independently proven event transcript paths.
25
+
26
+ Full transcript search is deliberately restricted to an unbounded backfill;
27
+ normal bounded hook collection must not scan the user's entire history.
28
+ """
29
+ groups, direct = {}, {}
30
+ if not resolve:
31
+ for key, uuid, ts, tok, cost, model in events:
32
+ groups.setdefault(uuid, []).append((key, ts, tok, cost, model))
33
+ return groups, direct
34
+ orphan = [event for event in events if not event[1]]
35
+ ids = _event_details(conn, orphan)
36
+ base = facade.CLAUDE_DIR / 'projects'
37
+ agent_index = defaultdict(list)
38
+ if orphan and base.exists():
39
+ for path in base.glob('*/*/subagents/agent-*.jsonl'):
40
+ if _parent(path).is_file() and fixture_context.allowed_path(_parent(path)):
41
+ agent_index[path.stem[6:]].append(path)
42
+ noid = []
43
+ for key, uuid, ts, tok, cost, model in events:
44
+ ev = (key, ts, tok, cost, model)
45
+ if uuid:
46
+ groups.setdefault(uuid, []).append(ev)
47
+ continue
48
+ sid = ids.get(key)
49
+ hits = agent_index.get(sid, []) if sid else []
50
+ if len(hits) == 1:
51
+ path = hits[0]
52
+ direct[key] = path
53
+ groups.setdefault(_parent(path).stem, []).append(ev)
54
+ elif not sid:
55
+ noid.append(ev)
56
+ else:
57
+ groups.setdefault(None, []).append(ev)
58
+ if noid:
59
+ info = sub.event_info(conn, [ev[0] for ev in noid])
60
+ commands = {key: data[1] for key, data in info.items() if key.startswith('ce:') and data[1]}
61
+ hits = defaultdict(list)
62
+ for path in list(base.glob('*/*.jsonl')) + [p for paths in agent_index.values() for p in paths]:
63
+ if not fixture_context.allowed_path(_parent(path)):
64
+ continue
65
+ for dt, tid, name, command, size in sub.index_results(path, path.parent.name == 'subagents'):
66
+ if name == 'Bash' and command:
67
+ stored = sub._stored_command(command)
68
+ if stored in commands.values():
69
+ hits[stored].append((dt, path, tid))
70
+ candidates = {}
71
+ for ev in noid:
72
+ key, ts = ev[:2]
73
+ when = facade._counted_event_utc(ts)
74
+ candidates[key] = [((when - dt).total_seconds(), path, tid) for dt, path, tid in hits.get(commands.get(key), [])
75
+ if when is not None and LAG_MIN <= (when - dt).total_seconds() <= LAG_MAX]
76
+ assigned = assign(candidates)
77
+ for ev in noid:
78
+ path = assigned.get(ev[0])
79
+ if path is not None:
80
+ direct[ev[0]] = path
81
+ groups.setdefault(_parent(path).stem, []).append(ev)
82
+ else:
83
+ groups.setdefault(None, []).append(ev)
84
+ return groups, direct
85
+
86
+
87
+ # The hook logs a bash event right after the tool result it compressed. On
88
+ # located rows the event is 0 to 1 s after the result's (second-truncated)
89
+ # timestamp, occasionally up to 1 s before it; the window allows margin.
90
+ LAG_MIN, LAG_MAX = -3.0, 2.0
91
+ # Results in different transcripts this close in lag are indistinguishable.
92
+ TIE_SECONDS = 1.0
93
+
94
+
95
+ def assign(candidates):
96
+ """One event to one tool result. {event key: transcript path}.
97
+
98
+ ``candidates`` maps an event to [(lag seconds, path, tool_use_id)]. An
99
+ event is placed only when its closest free results all sit in one
100
+ transcript; placing it takes that result, which can settle other events.
101
+ Events still split across transcripts stay unlocated.
102
+ """
103
+ taken, placed = set(), {}
104
+ pending = {key: sorted(values, key=lambda c: (abs(c[0]), str(c[1]), str(c[2])))
105
+ for key, values in candidates.items() if values}
106
+ changed = True
107
+ while changed and pending:
108
+ changed = False
109
+ # Events with the fewest free results first, so a forced pairing is
110
+ # never taken by an event that had other choices.
111
+ order = sorted(pending, key=lambda k: (sum((c[1], c[2]) not in taken for c in pending[k]), k))
112
+ for key in order:
113
+ free = [c for c in pending[key] if (c[1], c[2]) not in taken]
114
+ if not free:
115
+ del pending[key]
116
+ changed = True
117
+ continue
118
+ best = abs(free[0][0])
119
+ rivals = [c for c in free if abs(c[0]) <= best + TIE_SECONDS]
120
+ if len({c[1] for c in rivals}) != 1:
121
+ continue
122
+ _lag, path, tid = rivals[0]
123
+ taken.add((path, tid))
124
+ placed[key] = path
125
+ del pending[key]
126
+ changed = True
127
+ return placed
128
+
129
+
130
+ def apply_scope(scope, direct, parent):
131
+ scope.unresolved = set()
132
+ files = {path.resolve(): index for index, path in enumerate(scope.files)}
133
+ for key, path in direct.items():
134
+ if _parent(path).resolve() != parent.resolve():
135
+ scope.unresolved.add(key)
136
+ elif path == _parent(path):
137
+ scope.location.pop(key, None)
138
+ elif path.resolve() in files:
139
+ scope.location[key] = files[path.resolve()]
140
+ scope.stats["located_subagent"] += 1
141
+ else:
142
+ scope.unresolved.add(key)
143
+ return scope
144
+
145
+
146
+ def can_relocate(old, key, source, ts, tokens, proven):
147
+ return (proven and old and old.get("event_key") == key and old.get("source") == source
148
+ and not old.get("session_uuid") and old.get("event_ts") == ts
149
+ and int(old.get("tokens") or 0) == tokens and old.get("transcript_mtime") is None
150
+ and int(old.get("turns_counted") or 0) == 0 and int(old.get("reread_tokens") or 0) == 0
151
+ and float(old.get("reread_usd") or 0) == 0)
152
+
153
+
154
+ def window_events(facade, conn, events):
155
+ """Reuse stored transcript identity only when its old prefix still matches."""
156
+ import json
157
+ rows = {r[0]: r[1:] for r in conn.execute(
158
+ 'SELECT event_key, session_uuid, event_ts, tokens, pricing_detail FROM counted_reread')}
159
+ out, paths, proofs = [], {}, {}
160
+ for event in events:
161
+ key, uuid, ts, tokens, cost, model = event
162
+ row = rows.get(key)
163
+ if uuid or not row or not row[0] or row[1] != ts or int(row[2] or 0) != int(tokens or 0):
164
+ out.append(event)
165
+ continue
166
+ try:
167
+ detail = json.loads(row[3] or '{}')
168
+ parent = facade._counted_session_path(conn, row[0])
169
+ agent = detail.get('resolved_agent')
170
+ if not parent or not fixture_context.allowed_path(parent) or detail.get('refresh_incomplete') or not detail.get('file_sha256'):
171
+ raise ValueError('no evidence')
172
+ if detail.get("scope") == "subagent" and not agent:
173
+ raise ValueError("missing agent identity")
174
+ if agent:
175
+ if Path(agent).name != agent or not agent.startswith('agent-') or not agent.endswith('.jsonl'):
176
+ raise ValueError('invalid agent name')
177
+ path = parent.with_suffix('') / 'subagents' / agent
178
+ else:
179
+ path = parent
180
+ size = int(detail['file_size'])
181
+ proof_key = (path, size)
182
+ if proof_key not in proofs:
183
+ proofs[proof_key] = facade._counted_file_proof(path, [size])
184
+ if proofs[proof_key]['prefixes'].get(size) != detail['file_sha256']:
185
+ raise ValueError('transcript changed')
186
+ paths[key] = path
187
+ out.append((key, row[0], ts, tokens, cost, model))
188
+ except (OSError, ValueError, TypeError, KeyError):
189
+ out.append(event)
190
+ return out, paths
@@ -0,0 +1,20 @@
1
+ """Recognize cache rebuilds that reach the original removal position."""
2
+
3
+
4
+ def is_rebuild(cache_class, tokens, context, removal_context):
5
+ if not cache_class or len(cache_class) < 4:
6
+ return False
7
+ written, _, _, read = cache_class[:4]
8
+ if not isinstance(written, int) or not isinstance(read, int):
9
+ return False
10
+ try:
11
+ size = abs(int(tokens))
12
+ except (TypeError, ValueError):
13
+ return False
14
+ if written <= 0 or size <= 0 or written < size:
15
+ return False
16
+ if context is None or removal_context is None:
17
+ return read == 0
18
+ return (isinstance(context, int) and isinstance(removal_context, int)
19
+ and removal_context > 0 and context >= removal_context
20
+ and read < removal_context * 0.97)
@@ -0,0 +1,267 @@
1
+ """Counted-ledger pricing, version 5.
2
+
3
+ Three corrections to how already-counted context savings are priced. None of
4
+ them changes a token count; each one prices tokens the ledger already holds at
5
+ the rate the provider actually billed (or would have billed).
6
+
7
+ 1. Write-class premium. An initial removal is logged at the input rate. When
8
+ the next call wrote its context to the cache, the removed tokens would have
9
+ been billed at that write class. The counted pass already measures the
10
+ difference per event (``oneshot_class_premium_usd``); it now joins the action
11
+ total as its own measured part instead of a footnote.
12
+ 2. Cache-miss rereads. A later turn normally re-reads removed context from the
13
+ cache. When a turn read nothing from the cache and wrote at least the removed
14
+ amount, that turn rewrote its whole context, so the removed tokens would have
15
+ been billed at the turn's write class, not the cache-read rate.
16
+ 3. Lean resumes. Older ``resume_lean`` rows were priced on a family card (the
17
+ generic ``opus`` rate). They are repriced on the exact card of the model the
18
+ resumed session recorded.
19
+
20
+ Pure functions only: callers pass rate cards and lookups in, so this module has
21
+ no import-time state and no facade dependency.
22
+ """
23
+
24
+ import json
25
+ import math
26
+ from . import counted_position
27
+
28
+
29
+ def _finite(value):
30
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
31
+
32
+
33
+ # --------------------------------------------------------------------------
34
+ # 1. Write-class premium as an action-savings part
35
+ # --------------------------------------------------------------------------
36
+
37
+ def class_premium_usd(counted):
38
+ """Measured write-class premium for the removal cohort, or 0.0.
39
+
40
+ Only a usable counted ledger contributes; an unavailable one adds nothing.
41
+ """
42
+ counted = counted or {}
43
+ if not counted.get("available"):
44
+ return 0.0
45
+ value = counted.get("oneshot_class_premium_usd", 0.0)
46
+ try:
47
+ value = float(value or 0.0)
48
+ except (TypeError, ValueError):
49
+ return 0.0
50
+ return value if math.isfinite(value) else 0.0
51
+
52
+
53
+ # --------------------------------------------------------------------------
54
+ # 2. Cache-miss reread turns
55
+ # --------------------------------------------------------------------------
56
+
57
+ def is_cache_miss_turn(cache_class, tokens, context=None, removal_context=None):
58
+ """True when a reread turn rewrote its whole context.
59
+
60
+ A partial cache hit counts when its read ends before the context at the
61
+ removal and the later context has not shrunk. Without position evidence,
62
+ only a full miss counts. A missing usage record never counts as a miss.
63
+ """
64
+ return counted_position.is_rebuild(cache_class, tokens, context, removal_context)
65
+
66
+
67
+ def reread_turn_rate(card, cache_class, tokens, oneshot_rate, context=None, removal_context=None):
68
+ """(rate per MTok or None, miss flag) for one reread turn.
69
+
70
+ ``oneshot_rate`` is the counted pass's own write-class resolver
71
+ (``_counted_oneshot_rate``), so a miss turn is priced exactly like the
72
+ first call after a removal: its 1h/5m write class, or the input rate when
73
+ the card has no write premium.
74
+ """
75
+ base = (card or {}).get("cache_read")
76
+ if not _finite(base) or base < 0:
77
+ return base, False
78
+ if not is_cache_miss_turn(cache_class, tokens, context, removal_context):
79
+ return base, False
80
+ rate, basis = oneshot_rate(card, cache_class)
81
+ if basis not in ("class", "exact") or not _finite(rate) or rate < base:
82
+ return base, False
83
+ return rate, True
84
+
85
+
86
+ # --------------------------------------------------------------------------
87
+ # 3. Lean resumes on exact model cards
88
+ # --------------------------------------------------------------------------
89
+
90
+ _RESUME_BASIS = (
91
+ ("cold 1h cache-write", "cache_write_1h"),
92
+ ("warm cache-read", "cache_read"),
93
+ ("working-set fallback", "cache_read"),
94
+ )
95
+
96
+
97
+ def resume_rate_key(detail):
98
+ """Card rate a resume_lean row was priced at, from its own detail text."""
99
+ text = str(detail or "")
100
+ for marker, key in _RESUME_BASIS:
101
+ if marker in text:
102
+ return key
103
+ return None
104
+
105
+
106
+ def resume_exact_model(breakdown_json, family=None):
107
+ """The exact model id a session ran, from session_log.model_usage_breakdown_json.
108
+
109
+ When the row names a family (``opus``), only that family's models are
110
+ candidates. Among candidates the one with the most recorded tokens wins.
111
+ Returns None when nothing usable is recorded.
112
+ """
113
+ try:
114
+ breakdown = json.loads(breakdown_json) if isinstance(breakdown_json, str) else breakdown_json
115
+ except (TypeError, ValueError):
116
+ return None
117
+ if not isinstance(breakdown, dict):
118
+ return None
119
+ sized = []
120
+ for model, parts in breakdown.items():
121
+ if not isinstance(model, str) or not model or model.startswith("<"):
122
+ continue
123
+ total = 0
124
+ if isinstance(parts, dict):
125
+ total = sum(v for v in parts.values() if isinstance(v, int) and not isinstance(v, bool) and v > 0)
126
+ if total > 0:
127
+ sized.append((total, model))
128
+ if family:
129
+ fam = str(family).lower()
130
+ same = [item for item in sized if fam in item[1].lower()]
131
+ if same:
132
+ sized = same
133
+ elif fam in ("opus", "sonnet", "haiku", "fable", "mythos"):
134
+ return None
135
+ if not sized:
136
+ return None
137
+ return max(sized)[1]
138
+
139
+
140
+ def resume_exact_rate(breakdown_json, family, rate_key, exact_card):
141
+ """(per-MTok rate, exact model id) on the session's exact card, or (None, None)."""
142
+ if not rate_key:
143
+ return None, None
144
+ model = resume_exact_model(breakdown_json, family)
145
+ if not model:
146
+ return None, None
147
+ card = exact_card(model) or {}
148
+ rate = card.get(rate_key)
149
+ if rate_key == "cache_write_1h" and not _finite(rate):
150
+ rate = card.get("cache_write")
151
+ if not _finite(rate) or rate < 0:
152
+ return None, None
153
+ return float(rate), model
154
+
155
+
156
+ _RESUME_ROWS_SQL = (
157
+ "SELECT s.tokens_saved, s.cost_saved_usd, s.model, s.detail, "
158
+ " (SELECT l.model_usage_breakdown_json FROM session_log l "
159
+ " WHERE l.session_uuid = s.session_uuid ORDER BY l.id DESC LIMIT 1) "
160
+ "FROM {table} s WHERE s.event_type = 'resume_lean' AND s.timestamp >= ?")
161
+
162
+
163
+ def resume_lean_reprice(conn, table, cutoff, exact_card):
164
+ """Exact-card correction for the resume_lean rows summed in this window.
165
+
166
+ Returns {"delta_usd", "repriced_events", "unresolved_events", "tokens"}.
167
+ The stored rows are never changed: the delta is applied to the estimated
168
+ resume_lean entry at read time. A row whose session or model card cannot be
169
+ resolved keeps its stored price and is counted as unresolved.
170
+ """
171
+ out = {"delta_usd": 0.0, "repriced_events": 0, "unresolved_events": 0, "tokens": 0}
172
+ try:
173
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(session_log)").fetchall()}
174
+ if "model_usage_breakdown_json" not in cols:
175
+ return out
176
+ rows = conn.execute(_RESUME_ROWS_SQL.format(table=table), (cutoff,)).fetchall()
177
+ except Exception:
178
+ return out
179
+ for tokens, cost, family, detail, breakdown in rows:
180
+ try:
181
+ tokens = int(tokens or 0)
182
+ cost = float(cost or 0.0)
183
+ except (TypeError, ValueError):
184
+ continue
185
+ if tokens <= 0:
186
+ continue
187
+ rate, _model = resume_exact_rate(breakdown, family, resume_rate_key(detail), exact_card)
188
+ if rate is None:
189
+ out["unresolved_events"] += 1
190
+ continue
191
+ out["delta_usd"] += tokens * rate / 1e6 - cost
192
+ out["repriced_events"] += 1
193
+ out["tokens"] += tokens
194
+ out["delta_usd"] = round(out["delta_usd"], 6)
195
+ return out
196
+
197
+
198
+ def resume_lean_log_rate(conn, session_uuid, family, rate_key, exact_card):
199
+ """Exact-card rate for a new resume_lean credit, or None to keep the family card."""
200
+ try:
201
+ row = conn.execute(
202
+ "SELECT model_usage_breakdown_json FROM session_log WHERE session_uuid = ? "
203
+ "ORDER BY id DESC LIMIT 1", (session_uuid,)).fetchone()
204
+ except Exception:
205
+ return None
206
+ if not row or not row[0]:
207
+ return None
208
+ rate, _model = resume_exact_rate(row[0], family, rate_key, exact_card)
209
+ return rate
210
+
211
+
212
+ # --------------------------------------------------------------------------
213
+ # Session-mix pricing for rows without per-turn evidence (moved verbatim from
214
+ # savings._counted_session_cache_mix / _counted_rollup_rows, behaviour unchanged)
215
+ # --------------------------------------------------------------------------
216
+
217
+ def session_cache_mix_terms(breakdown, exact_card, rate_key):
218
+ """[(cache_read weight, rate or None)] from a parsed per-model breakdown, or None."""
219
+ terms = []
220
+ for model, parts in breakdown.items():
221
+ weight = parts.get("cache_read") if isinstance(parts, dict) else None
222
+ if not isinstance(weight, int) or isinstance(weight, bool) or weight <= 0:
223
+ continue
224
+ rate = (exact_card(model) or {}).get(rate_key)
225
+ if not (isinstance(rate, (int, float)) and math.isfinite(rate) and rate >= 0):
226
+ rate = None
227
+ terms.append((weight, rate))
228
+ return terms if any(rate is not None for _, rate in terms) else None
229
+
230
+
231
+ def session_mix_price(amount, terms):
232
+ """(usd, priced tokens, unpriced signed remainder) for a signed token amount."""
233
+ total_weight = sum(weight for weight, _ in terms)
234
+ rated = [(weight, rate) for weight, rate in terms if rate is not None]
235
+ rated_weight = sum(weight for weight, _ in rated)
236
+ priced = round(abs(amount) * rated_weight / total_weight)
237
+ usd = (math.copysign(1, amount) * abs(amount)
238
+ * sum(weight * rate for weight, rate in rated) / total_weight / 1e6)
239
+ return usd, priced, int(math.copysign(abs(amount) - priced, amount))
240
+
241
+
242
+ # --------------------------------------------------------------------------
243
+ # Orphaned derived rows
244
+ # --------------------------------------------------------------------------
245
+
246
+ def orphaned_keys(stored_rows, candidate_keys, conn):
247
+ """Stored ledger-event rows whose source event still exists but is no longer
248
+ a counted removal.
249
+
250
+ counted_reread rows are derived from savings/compression events. When an
251
+ event type leaves the counted set (checkpoint_restore moved to the estimated
252
+ tier on 2026-11-05), its old derived rows are never re-scored, so they keep
253
+ their old price forever and, after any pricing-version bump, hold the card in
254
+ "re-measuring" permanently. They are excluded from the counted rollup at read
255
+ time and never deleted. A row whose source event is gone keeps counting (it
256
+ is the durable history). Marker (mk) and media (md) rows have their own
257
+ lifecycles and are left alone.
258
+ """
259
+ present = set()
260
+ try:
261
+ present.update("se:%d" % r[0] for r in conn.execute("SELECT id FROM main.savings_events"))
262
+ present.update("ce:%d" % r[0] for r in conn.execute("SELECT id FROM main.compression_events"))
263
+ except Exception:
264
+ return set()
265
+ return {row["event_key"] for row in stored_rows
266
+ if row.get("source") in ("se", "ce") and row["event_key"] in present
267
+ and row["event_key"] not in candidate_keys}