@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
@@ -1,6 +1,6 @@
1
1
  """Definition-only implementations; mutable state belongs to measure."""
2
2
  from __future__ import annotations
3
- from . import _compat
3
+ from . import _compat, transcript_stream, quality_continuity, upgrade_drain_control
4
4
 
5
5
 
6
6
  def _find_all_jsonl_files(days=None):
@@ -82,15 +82,10 @@ def _extract_skills_and_agents_from_subagent(filepath):
82
82
  skills = {}
83
83
  subagents = {}
84
84
  try:
85
- if _measure_facade.os.stat(filepath).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
86
- return skills, subagents
87
- except OSError:
88
- return skills, subagents
89
- try:
90
- with open(filepath, "r", encoding="utf-8", errors="replace") as f:
85
+ with transcript_stream.open_transcript(filepath) as f:
91
86
  for line in f:
92
87
  if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
93
- continue
88
+ continue # bounded per-line work, same limit as the Codex adapter
94
89
  try:
95
90
  record = _measure_facade.json.loads(line)
96
91
  except _measure_facade.json.JSONDecodeError:
@@ -220,16 +215,10 @@ def _extract_costly_prompts(jsonl_path, tier=None, top_n=None):
220
215
  pending_prompt = None
221
216
 
222
217
  try:
223
- if _measure_facade.os.stat(jsonl_path).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
224
- return prompts
225
- except OSError:
226
- return prompts
227
-
228
- try:
229
- with open(jsonl_path, "r", encoding="utf-8", errors="replace") as f:
218
+ with transcript_stream.open_transcript(jsonl_path) as f:
230
219
  for line in f:
231
220
  if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
232
- continue
221
+ continue # bounded per-line work, same limit as the Codex adapter
233
222
  try:
234
223
  record = _measure_facade.json.loads(line)
235
224
  except _measure_facade.json.JSONDecodeError:
@@ -577,8 +566,8 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
577
566
  _measure_facade = _compat.facade()
578
567
  try:
579
568
  st = _measure_facade.os.stat(filepath)
580
- cache_key = (str(filepath), st.st_mtime_ns, st.st_size, window_start, window_end)
581
- if cache_key in _measure_facade._parse_session_jsonl_cache:
569
+ cache_key = (str(filepath), st.st_mtime_ns, st.st_size, window_start, window_end) if st.st_size <= transcript_stream.LARGE_BYTES else None
570
+ if cache_key in _measure_facade._parse_session_jsonl_cache and not transcript_stream.needs_resume(filepath):
582
571
  return _measure_facade._parse_session_jsonl_cache[cache_key]
583
572
  except OSError:
584
573
  cache_key = None # stat failed — parse without caching
@@ -625,18 +614,11 @@ def _parse_session_jsonl(filepath, window_start=None, window_end=None):
625
614
  is_sidechain = sidechain_reason is not None
626
615
  first_user_record_seen = False
627
616
 
628
- # Bound the work like the Codex adapter's _iter_json_records: a multi-GB
629
- # transcript or one pathological line must not dominate a parse. st is set
630
- # when the initial os.stat above succeeded; skip oversized files outright
631
- # and oversized lines individually.
632
- if cache_key is not None and st.st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
633
- return None
634
-
635
617
  try:
636
- with open(filepath, "r", encoding="utf-8", errors="replace") as f:
618
+ with transcript_stream.open_transcript(filepath) as f:
637
619
  for line in f:
638
620
  if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
639
- continue
621
+ continue # bounded per-line work, same limit as the Codex adapter
640
622
  try:
641
623
  record = _measure_facade.json.loads(line)
642
624
  except _measure_facade.json.JSONDecodeError:
@@ -1034,19 +1016,11 @@ def parse_session_turns(filepath):
1034
1016
  turn_by_key = {}
1035
1017
  parts_by_key = {}
1036
1018
 
1037
- # Bound the work like the Codex adapter's _iter_json_records (see
1038
- # _parse_session_jsonl): skip oversized files and oversized lines.
1039
1019
  try:
1040
- if _measure_facade.os.stat(filepath).st_size > _measure_facade.codex_session.MAX_PARSE_FILE_BYTES:
1041
- return turns
1042
- except OSError:
1043
- return turns
1044
-
1045
- try:
1046
- with open(filepath, "r", encoding="utf-8", errors="replace") as f:
1020
+ with transcript_stream.open_transcript(filepath) as f:
1047
1021
  for line in f:
1048
1022
  if len(line) > _measure_facade.codex_session.MAX_JSONL_LINE_CHARS:
1049
- continue
1023
+ continue # bounded per-line work, same limit as the Codex adapter
1050
1024
  try:
1051
1025
  record = _measure_facade.json.loads(line)
1052
1026
  except _measure_facade.json.JSONDecodeError:
@@ -1126,6 +1100,9 @@ def parse_session_turns(filepath):
1126
1100
  "gap_since_prev_seconds": gap_since_prev_seconds,
1127
1101
  "tools_used": tools,
1128
1102
  "cost_usd": round(cost, 6),
1103
+ # Stable across copies of one transcript: cache health
1104
+ # dedupes a synced or copied session by it.
1105
+ "request_id": req_key,
1129
1106
  }
1130
1107
  ctx_usage = _measure_facade._context_usage(usage)
1131
1108
  if ctx_usage is not usage:
@@ -1182,103 +1159,10 @@ def parse_session_turns(filepath):
1182
1159
 
1183
1160
 
1184
1161
  def score_session_quality(session_data):
1185
- """Score a single session's quality on a 0-100 scale.
1186
-
1187
- Uses a simplified version of the 5-signal quality score:
1188
- - Context fill at session end (25%)
1189
- - Message count risk (25%)
1190
- - Cache hit rate (20%)
1191
- - Output/input ratio (15%)
1192
- - Compaction events (15%)
1193
-
1194
- session_data should include: total_input_tokens, total_output_tokens,
1195
- message_count, cache_hit_rate, api_calls, and optionally total_cache_read.
1196
- """
1197
- _measure_facade = _compat.facade()
1198
- score = 0.0
1199
-
1200
- # Signal 1: Context fill (25%)
1201
- # Lower fill = better (more room for work)
1202
- context_window = _measure_facade.detect_context_window()[0]
1203
- total_input = session_data.get("total_input_tokens", 0)
1204
- fill_ratio = total_input / context_window if context_window > 0 else 0
1205
- if fill_ratio < 0.3:
1206
- fill_score = 100
1207
- elif fill_ratio < 0.5:
1208
- fill_score = 80
1209
- elif fill_ratio < 0.7:
1210
- fill_score = 55
1211
- elif fill_ratio < 0.85:
1212
- fill_score = 30
1213
- else:
1214
- fill_score = 10
1215
- score += fill_score * 0.25
1216
-
1217
- # Signal 2: Message count risk (25%)
1218
- # More messages = higher risk of quality degradation
1219
- msg_count = session_data.get("message_count", 0)
1220
- if msg_count <= 20:
1221
- msg_score = 100
1222
- elif msg_count <= 40:
1223
- msg_score = 80
1224
- elif msg_count <= 60:
1225
- msg_score = 55
1226
- elif msg_count <= 100:
1227
- msg_score = 30
1228
- else:
1229
- msg_score = 10
1230
- score += msg_score * 0.25
1231
-
1232
- # Signal 3: Cache hit rate (20%)
1233
- # Higher cache = better (reusing context efficiently)
1234
- chr_ = session_data.get("cache_hit_rate", 0)
1235
- if chr_ >= 0.8:
1236
- cache_score = 100
1237
- elif chr_ >= 0.6:
1238
- cache_score = 80
1239
- elif chr_ >= 0.4:
1240
- cache_score = 55
1241
- elif chr_ >= 0.2:
1242
- cache_score = 30
1243
- else:
1244
- cache_score = 10
1245
- score += cache_score * 0.20
1246
-
1247
- # Signal 4: Output/input ratio (15%)
1248
- # Very low ratio = wasteful (loading lots of context, producing little)
1249
- total_output = session_data.get("total_output_tokens", 0)
1250
- if total_input > 0:
1251
- oi_ratio = total_output / total_input
1252
- else:
1253
- oi_ratio = 1.0
1254
- if oi_ratio >= 0.05:
1255
- oi_score = 100
1256
- elif oi_ratio >= 0.02:
1257
- oi_score = 70
1258
- elif oi_ratio >= 0.01:
1259
- oi_score = 40
1260
- else:
1261
- oi_score = 15
1262
- score += oi_score * 0.15
1263
-
1264
- # Signal 5: API calls vs messages (15%)
1265
- # Healthy: roughly 1 API call per 2 messages
1266
- api_calls = session_data.get("api_calls", 0)
1267
- if msg_count > 0 and api_calls > 0:
1268
- calls_per_msg = api_calls / msg_count
1269
- if calls_per_msg <= 0.6:
1270
- api_score = 100
1271
- elif calls_per_msg <= 0.8:
1272
- api_score = 75
1273
- else:
1274
- api_score = 50
1275
- else:
1276
- api_score = 50
1277
- score += api_score * 0.15
1278
-
1279
- final = int(round(min(100, max(0, score))))
1280
-
1281
- return {"score": final, "band": _measure_facade.score_to_band(final), "grade": _measure_facade.score_to_grade(final)}
1162
+ """Score observed current occupancy through the common v3 scorer."""
1163
+ return quality_continuity.session_quality(
1164
+ session_data.get("context_tokens"), session_data.get("model_context_window"),
1165
+ session_data.get("model"), session_data.get("compactions", 0))
1282
1166
 
1283
1167
 
1284
1168
  def _record_model(msg):
@@ -1406,8 +1290,12 @@ def _is_file_collected(conn, jsonl_path, check_mtime=None):
1406
1290
  try:
1407
1291
  collected = _measure_facade.datetime.fromisoformat(row[0]).timestamp()
1408
1292
  path = _measure_facade.Path(jsonl_path)
1293
+ if path.stat().st_size > transcript_stream.LARGE_BYTES:
1294
+ observed = conn.execute('SELECT transcript_mtime FROM session_log WHERE jsonl_path=?', (str(path),)).fetchone()
1295
+ if observed and observed[0] != path.stat().st_mtime:
1296
+ return False
1409
1297
  paths = [path, *_measure_facade._find_subagent_jsonl_files(path)]
1410
- return all(path.stat().st_mtime <= collected for path in paths)
1298
+ return all(path.stat().st_mtime <= collected and not transcript_stream.needs_resume(path) for path in paths)
1411
1299
  except (OSError, TypeError, ValueError):
1412
1300
  return False
1413
1301
 
@@ -1463,10 +1351,10 @@ def _store_adapter_activity(conn, dedup_key, parsed):
1463
1351
  "FROM session_log WHERE jsonl_path=?", (dedup_key,)).fetchone()
1464
1352
  if current and tuple(current) == params[:-1]:
1465
1353
  return 0
1466
- conn.execute(
1354
+ changed = upgrade_drain_control.session_write(conn,
1467
1355
  "UPDATE session_log SET first_activity_day=?,last_activity_day=?,date=?,daily_usage_json=?, "
1468
1356
  "parent_daily_usage_json=?,daily_calls_json=? WHERE jsonl_path=?", params)
1469
- return 1
1357
+ return int(changed is not None)
1470
1358
 
1471
1359
 
1472
1360
  def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallback, quiet=None):
@@ -1539,7 +1427,7 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
1539
1427
  if existing is not None and int(existing[0]) == is_incomplete:
1540
1428
  return _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1541
1429
  try:
1542
- conn.execute(
1430
+ changed = upgrade_drain_control.session_write(conn,
1543
1431
  """UPDATE session_log SET
1544
1432
  date=?, project=?, duration_minutes=?, input_tokens=?,
1545
1433
  output_tokens=?, message_count=?, api_calls=?, cache_hit_rate=?,
@@ -1553,6 +1441,8 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
1553
1441
  WHERE jsonl_path=?""",
1554
1442
  values + (dedup_key,),
1555
1443
  )
1444
+ if changed is None:
1445
+ return 0
1556
1446
  _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1557
1447
  return 1
1558
1448
  except _measure_facade.sqlite3.Error as exc:
@@ -1561,7 +1451,7 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
1561
1451
  return 0
1562
1452
 
1563
1453
  try:
1564
- cur = conn.execute(
1454
+ cur = upgrade_drain_control.session_write(conn,
1565
1455
  """INSERT OR IGNORE INTO session_log
1566
1456
  (jsonl_path, date, project, duration_minutes, input_tokens,
1567
1457
  output_tokens, message_count, api_calls, cache_hit_rate,
@@ -1578,7 +1468,7 @@ def _insert_normalized_session(conn, dedup_key, parsed, platform, project_fallba
1578
1468
  if not quiet:
1579
1469
  print(f"[Token Optimizer] skipped a {platform} session: {exc}")
1580
1470
  return 0
1581
- if cur.rowcount == 1:
1471
+ if cur is not None and cur.rowcount == 1:
1582
1472
  _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1583
1473
  return 1
1584
1474
  return 0
@@ -1789,7 +1679,7 @@ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
1789
1679
  old = tuple(int(v or 0) for v in stored)
1790
1680
  if any(n < o for n, o in zip(new, old)) or new == old:
1791
1681
  return False
1792
- conn.execute(
1682
+ changed = upgrade_drain_control.session_write(conn,
1793
1683
  """UPDATE session_log
1794
1684
  SET duration_minutes = ?, input_tokens = ?, output_tokens = ?,
1795
1685
  message_count = ?, api_calls = ?, cache_hit_rate = ?,
@@ -1799,7 +1689,9 @@ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
1799
1689
  model_usage_json = ?, all_model_usage_json = ?,
1800
1690
  model_usage_breakdown_json = ?, version = ?, topic = ?,
1801
1691
  collected_at = ?
1802
- WHERE jsonl_path = ?""",
1692
+ WHERE jsonl_path = ? AND COALESCE(message_count,0)<=? AND COALESCE(input_tokens,0)<=?
1693
+ AND COALESCE(output_tokens,0)<=? AND COALESCE(api_calls,0)<=?
1694
+ AND (COALESCE(message_count,0)<? OR COALESCE(input_tokens,0)<? OR COALESCE(output_tokens,0)<? OR COALESCE(api_calls,0)<?)""",
1803
1695
  (
1804
1696
  parsed["duration_minutes"],
1805
1697
  parsed["total_input_tokens"],
@@ -1821,8 +1713,9 @@ def _hermes_refresh_session_totals(conn, dedup_key, parsed):
1821
1713
  parsed.get("topic"),
1822
1714
  _measure_facade.datetime.now().isoformat(),
1823
1715
  dedup_key,
1824
- ),
1716
+ ) + new + new,
1825
1717
  )
1718
+ if changed is None or changed.rowcount != 1: return False
1826
1719
  _measure_facade._store_adapter_activity(conn, dedup_key, parsed)
1827
1720
  return True
1828
1721
 
@@ -2377,7 +2270,7 @@ def _grok_summary():
2377
2270
  print(f" Cost: ~${total_cost:,.2f} ({cost_known} session(s) with authoritative cost)")
2378
2271
  else:
2379
2272
  print(" Cost: no authoritative billing data recorded (costUsdTicks scrubbed)")
2380
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2273
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2381
2274
  if top_models:
2382
2275
  print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2383
2276
  if incomplete:
@@ -2593,7 +2486,7 @@ def _copilot_summary():
2593
2486
  print(f" Cost: ~${total_cost:,.2f} (premium requests)")
2594
2487
  else:
2595
2488
  print(" Cost: no billing data recorded by Copilot for these sessions")
2596
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2489
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2597
2490
  if top_models:
2598
2491
  print(" Models: " + ", ".join(f"{_measure_facade._strip_ansi(str(m))} ({v:,})" for m, v in top_models))
2599
2492
  if incomplete:
@@ -2819,13 +2712,9 @@ def _write_cursor_restore_context(sessions, quiet=None):
2819
2712
  import tempfile # noqa: PLC0415
2820
2713
 
2821
2714
  from runtime_env import cursor_home as _ch # noqa: PLC0415
2822
-
2823
- # Group the most recent COMPLETE session per workspace root. The key
2824
- # must match what the sessionStart hook looks up: workspace_roots[0]
2825
- # (the repo root Cursor exports) first, then cwd as a fallback. Using
2826
- # cwd alone would key the file by a tool's working_directory (often a
2827
- # subdirectory) while sessionStart looks up the repo root — a silent
2828
- # never-match.
2715
+ from cursor_bridge_checkpoint import normalize_workspace # noqa: PLC0415
2716
+ from datetime import datetime # noqa: PLC0415
2717
+ # Match sessionStart's workspace root and source-session end time.
2829
2718
  by_ws: dict = {}
2830
2719
  for s in sessions:
2831
2720
  if s.get("incomplete"):
@@ -2837,19 +2726,21 @@ def _write_cursor_restore_context(sessions, quiet=None):
2837
2726
  root = str(s.get("cwd") or s.get("slug") or "")
2838
2727
  if not root:
2839
2728
  continue
2840
- by_ws.setdefault(root, []).append(s)
2841
-
2729
+ by_ws.setdefault(normalize_workspace(root), []).append(s)
2842
2730
  def _clean(value):
2843
2731
  _measure_facade = _compat.facade()
2844
2732
  text = str(value or "")
2845
2733
  text = "".join(ch for ch in text if ch == " " or ch.isprintable())
2846
2734
  return text[:200]
2847
-
2848
2735
  base = _ch() / "token-optimizer" / "restore-context"
2849
2736
  base.mkdir(parents=True, exist_ok=True)
2850
2737
  for root, group in by_ws.items():
2851
- latest = max(group, key=lambda s: ((_measure_facade := _compat.facade()), (s.get("first_ts") is not None, s.get("first_ts") or ""))[1])
2852
- lines = [f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2738
+ latest = max(group, key=lambda s: (s.get("last_ts") is not None, s.get("last_ts") or ""))
2739
+ try:
2740
+ end_ts = datetime.fromisoformat(str(latest.get("last_ts") or "").replace("Z", "+00:00")).timestamp()
2741
+ except (ValueError, OverflowError):
2742
+ continue
2743
+ lines = [f"<!-- source-end: {end_ts} -->", f"[Token Optimizer] Continuity from your previous Cursor session in {_clean(root)}:"]
2853
2744
  if latest.get("model"):
2854
2745
  lines.append(
2855
2746
  f"- Model: {_clean(latest['model'])}; "
@@ -2884,8 +2775,34 @@ def _cursor_summary():
2884
2775
  import cursor_state as _cst # noqa: PLC0415
2885
2776
 
2886
2777
  home = _ch() if _ch is not None else _measure_facade.Path.home() / ".cursor"
2887
- tallies = [t for p in _cst.find_tallies(home) if (t := _cst.read_tally(p)) is not None]
2888
- normalized = [s for t in tallies if (s := _measure_facade.cursor_session.normalize_session(t))]
2778
+ tallies = []
2779
+ for p in _cst.find_tallies(home):
2780
+ t = _cst.read_tally(p)
2781
+ if t is not None:
2782
+ tallies.append(_cst.idle_finalise(t))
2783
+
2784
+ # Resolve the same token sources _collect_cursor_sessions uses: raw tally
2785
+ # JSON never carries bubble_tokens/transcript_tokens, so without this the
2786
+ # summary always reports 0 tokens and mislabels every session "estimated".
2787
+ composer_ids = [
2788
+ str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2789
+ ]
2790
+ try:
2791
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
2792
+ except Exception:
2793
+ bubble_tokens = {}
2794
+ normalized = []
2795
+ for t in tallies:
2796
+ t = dict(t)
2797
+ cid = str(t.get("conversation_id") or t.get("session_id") or "")
2798
+ t["bubble_tokens"] = bubble_tokens.get(cid)
2799
+ try:
2800
+ t["transcript_tokens"] = _cst.transcript_estimate(t.get("transcript_path"), home)
2801
+ except Exception:
2802
+ t["transcript_tokens"] = None
2803
+ s = _measure_facade.cursor_session.normalize_session(t)
2804
+ if s is not None:
2805
+ normalized.append(s)
2889
2806
 
2890
2807
  print("Token Optimizer — Cursor summary")
2891
2808
  if not normalized:
@@ -2899,7 +2816,12 @@ def _cursor_summary():
2899
2816
  total_in = sum(s.get("total_input_tokens", 0) for s in normalized)
2900
2817
  total_out = sum(s.get("total_output_tokens", 0) for s in normalized)
2901
2818
  incomplete = sum(1 for s in normalized if s.get("incomplete"))
2902
- estimated = sum(1 for s in normalized if s.get("estimated"))
2819
+ token_sources = {}
2820
+ for s in normalized:
2821
+ src = s.get("token_source") or "unknown"
2822
+ token_sources[src] = token_sources.get(src, 0) + 1
2823
+ estimated = token_sources.get("cursor_transcript_estimate", 0)
2824
+ unknown_tokens = token_sources.get("cursor_tally_only", 0)
2903
2825
  compactions = sum(s.get("compactions", 0) for s in normalized)
2904
2826
  surfaces = {}
2905
2827
  for s in normalized:
@@ -2907,7 +2829,11 @@ def _cursor_summary():
2907
2829
  surfaces[sur] = surfaces.get(sur, 0) + 1
2908
2830
 
2909
2831
  print(f" {len(normalized)} session(s)")
2910
- print(f" Tokens: {total_in:,} in / {total_out:,} out")
2832
+ print(f" Tokens: {total_in:,} in / {total_out:,} out" + (f" (includes {estimated} estimated sessions)" if estimated else ""))
2833
+ if token_sources:
2834
+ print(" Token sources: " + ", ".join(
2835
+ f"{k} ({v})" for k, v in sorted(token_sources.items())
2836
+ ))
2911
2837
  if compactions:
2912
2838
  print(f" Compactions captured: {compactions}")
2913
2839
  if surfaces:
@@ -2917,7 +2843,12 @@ def _cursor_summary():
2917
2843
  if estimated:
2918
2844
  print(
2919
2845
  f" {estimated} session(s) use estimated token counts "
2920
- "(state.vscdb tokenCount is best-effort; transcripts carry no usage)"
2846
+ "(transcript chars-over-four; state.vscdb tokenCount is best-effort)"
2847
+ )
2848
+ if unknown_tokens:
2849
+ print(
2850
+ f" {unknown_tokens} session(s) have no token figures "
2851
+ "(tally only) — unknown, not zero"
2921
2852
  )
2922
2853
  print()
2923
2854
  print(" Cost: Cursor stores no local billing data — no savings headline is")
@@ -2972,7 +2903,7 @@ def _collect_cursor_sessions(days=None, quiet=None, rebuild=None):
2972
2903
  str(t.get("conversation_id") or t.get("session_id") or "") for t in tallies
2973
2904
  ]
2974
2905
  try:
2975
- bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids)
2906
+ bubble_tokens = _cst.read_state_vscdb_tokens(composer_ids, db_path=_cst.state_vscdb_path_for_home(home))
2976
2907
  except Exception:
2977
2908
  bubble_tokens = {}
2978
2909
 
@@ -3683,7 +3614,7 @@ def _stamp_usage_parser_version(conn, filepath):
3683
3614
  re-parsed on every collect."""
3684
3615
  _measure_facade = _compat.facade()
3685
3616
  try:
3686
- conn.execute(
3617
+ upgrade_drain_control.session_write(conn,
3687
3618
  "UPDATE session_log SET usage_parser_version = ? WHERE jsonl_path = ?",
3688
3619
  (_measure_facade._USAGE_PARSER_VERSION, str(filepath)))
3689
3620
  except _measure_facade.sqlite3.Error:
@@ -4024,20 +3955,22 @@ def _upgrade_drain_after_pass(conn, backlog):
4024
3955
  if _measure_facade._upgrade_meta_get(conn, _measure_facade._UPGRADE_DRAIN_META) == key:
4025
3956
  return False
4026
3957
  if not backlog:
4027
- _measure_facade._upgrade_drain_mark_done(conn)
3958
+ with upgrade_drain_control.running(_measure_facade) as held:
3959
+ if held: _measure_facade._upgrade_drain_mark_done(conn)
4028
3960
  return False
4029
3961
  # Under pytest the child would run against the real ~/.claude.
4030
3962
  if _measure_facade.os.environ.get("PYTEST_CURRENT_TEST") and not _measure_facade.os.environ.get(
4031
3963
  "TOKEN_OPTIMIZER_TEST_ALLOW_DRAIN_SPAWN"):
4032
3964
  return False
4033
3965
  raw = _measure_facade._upgrade_meta_get(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META) or ""
4034
- attempts = int(raw.split(":", 1)[1]) if raw.startswith(key + ":") else 0
4035
- if attempts >= _measure_facade._UPGRADE_DRAIN_MAX_ATTEMPTS:
3966
+ ready, attempts = upgrade_drain_control.retry_ready(raw, key, _measure_facade.time.time())
3967
+ if not ready:
4036
3968
  return False
4037
3969
  if not _measure_facade._upgrade_drain_claim_lock():
4038
3970
  return False
4039
- if _measure_facade._spawn_upgrade_drain():
4040
- _measure_facade._upgrade_meta_set(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META, f"{key}:{attempts + 1}")
3971
+ started = _measure_facade._spawn_upgrade_drain()
3972
+ _measure_facade._upgrade_meta_set(conn, _measure_facade._UPGRADE_DRAIN_ATTEMPTS_META, f"{key}:{attempts + 1}:{_measure_facade.time.time()}")
3973
+ if started:
4041
3974
  return True
4042
3975
  _measure_facade._upgrade_drain_release_lock()
4043
3976
  return False
@@ -4048,29 +3981,12 @@ def _upgrade_drain_after_pass(conn, backlog):
4048
3981
  def _upgrade_drain_claim_lock():
4049
3982
  """Claim the drain lock file (O_EXCL); reclaim one left by a dead child."""
4050
3983
  _measure_facade = _compat.facade()
4051
- marker = _measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME
4052
- try:
4053
- _measure_facade.SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
4054
- try:
4055
- fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
4056
- except FileExistsError:
4057
- if _measure_facade.time.time() - marker.stat().st_mtime <= _measure_facade._UPGRADE_DRAIN_LOCK_STALE_SECONDS:
4058
- return False
4059
- _measure_facade.os.unlink(str(marker))
4060
- fd = _measure_facade.os.open(str(marker), _measure_facade.os.O_CREAT | _measure_facade.os.O_EXCL | _measure_facade.os.O_WRONLY, 0o600)
4061
- with _measure_facade.os.fdopen(fd, "w") as handle:
4062
- handle.write(str(_measure_facade.os.getpid()))
4063
- return True
4064
- except OSError:
4065
- return False
3984
+ return upgrade_drain_control.claim(_measure_facade)
4066
3985
 
4067
3986
 
4068
3987
  def _upgrade_drain_release_lock():
4069
3988
  _measure_facade = _compat.facade()
4070
- try:
4071
- (_measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME).unlink()
4072
- except OSError:
4073
- pass
3989
+ upgrade_drain_control.release(_measure_facade)
4074
3990
 
4075
3991
 
4076
3992
  def _spawn_upgrade_drain():
@@ -4093,10 +4009,7 @@ def _spawn_upgrade_drain():
4093
4009
  creationflags=(getattr(_measure_facade.subprocess, "DETACHED_PROCESS", 0) | _measure_facade._NO_WINDOW),
4094
4010
  **popen_kw,
4095
4011
  )
4096
- try:
4097
- (_measure_facade.SNAPSHOT_DIR / _measure_facade._UPGRADE_DRAIN_LOCK_NAME).write_text(str(child.pid))
4098
- except OSError:
4099
- pass
4012
+ upgrade_drain_control.publish_child(_measure_facade, child.pid)
4100
4013
  return True
4101
4014
  except Exception as exc:
4102
4015
  try:
@@ -4126,7 +4039,14 @@ def _run_upgrade_drain(days=None, quiet=None):
4126
4039
  _measure_facade = _compat.facade()
4127
4040
  _measure_facade.os.environ["TOKEN_OPTIMIZER_UPGRADE_DRAIN"] = "1"
4128
4041
  try:
4129
- return _measure_facade.collect_sessions(days=days or _measure_facade._upgrade_drain_days(), quiet=quiet)
4042
+ with upgrade_drain_control.running(_measure_facade) as held:
4043
+ return _measure_facade.collect_sessions(days=days or _measure_facade._upgrade_drain_days(), quiet=quiet) if held else None
4044
+ except _measure_facade.sqlite3.OperationalError as exc:
4045
+ if "locked" not in str(exc).lower() and "busy" not in str(exc).lower():
4046
+ raise
4047
+ try: _measure_facade._log_spawn_failure("upgrade drain deferred after SQLite contention")
4048
+ except Exception: pass
4049
+ return 0
4130
4050
  finally:
4131
4051
  _measure_facade._upgrade_drain_release_lock()
4132
4052
 
@@ -4378,19 +4298,18 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4378
4298
  # This copy changed since last seen and may hold requests the
4379
4299
  # stored copy lacks; its per-day usage (merged across copies) is
4380
4300
  # recomputed by the next backfill.
4381
- conn.execute(
4301
+ changed = upgrade_drain_control.session_write(conn,
4382
4302
  "UPDATE session_log SET daily_usage_json = NULL WHERE session_uuid = ? AND jsonl_path != ?",
4383
4303
  (session_uuid, str(filepath)))
4304
+ if changed is None:
4305
+ conn.rollback(); parse_truncated = True; break
4384
4306
  _measure_facade._stamp_usage_parser_version(conn, filepath)
4385
4307
  continue
4386
4308
  else:
4387
4309
  other = []
4388
4310
 
4389
- # Compute quality score at collection time for persistence
4390
4311
  sq = _measure_facade.score_session_quality(parsed)
4391
- # B1: persist reclaimable stale-read waste (opportunity tier, not realized).
4392
4312
  stale_waste = _measure_facade._session_stale_waste_tokens(filepath)
4393
-
4394
4313
  # Resolve the platform for this session. Codex transcripts carry
4395
4314
  # "runtime": "codex" in their parsed dict; Claude transcripts do not
4396
4315
  # set the key, so detect_runtime() (which returns the active runtime,
@@ -4412,7 +4331,7 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4412
4331
  o_mark += ", ?"
4413
4332
  o_val += (_measure_facade._USAGE_PARSER_VERSION,)
4414
4333
  o_upd += ",\n usage_parser_version=excluded.usage_parser_version"
4415
- cur = conn.execute(
4334
+ cur = upgrade_drain_control.session_write(conn,
4416
4335
  """INSERT INTO session_log
4417
4336
  (jsonl_path, date, project, duration_minutes, input_tokens,
4418
4337
  output_tokens, message_count, api_calls, cache_hit_rate,
@@ -4499,6 +4418,8 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4499
4418
  _measure_facade.json.dumps(daily_usage),
4500
4419
  ) + o_val,
4501
4420
  )
4421
+ if cur is None:
4422
+ conn.rollback(); parse_truncated = True; break
4502
4423
  if cur.rowcount != 1:
4503
4424
  continue
4504
4425
  calls = dict(parsed.get("daily_calls") or {})
@@ -4506,11 +4427,13 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4506
4427
  if not u.get("advisor") and u.get("n", 1) and u.get("day"):
4507
4428
  day = u["day"]
4508
4429
  calls[day] = calls.get(day, 0) + 1
4509
- conn.execute(
4430
+ changed = upgrade_drain_control.session_write(conn,
4510
4431
  "UPDATE session_log SET first_activity_day=?, last_activity_day=?, transcript_mtime=?, "
4511
4432
  "parent_daily_usage_json=?, daily_calls_json=?, daily_metrics_json=? WHERE jsonl_path=?",
4512
4433
  (activity_bounds[0] if activity_bounds else None, activity_bounds[-1] if activity_bounds else None, mtime,
4513
4434
  _measure_facade.json.dumps(parent_daily), _measure_facade.json.dumps(calls), _measure_facade.json.dumps(session_daily_metrics), str(filepath)))
4435
+ if changed is None:
4436
+ conn.rollback(); parse_truncated = True; break
4514
4437
  if merged is not None:
4515
4438
  _measure_facade._claim_requests(conn, owner_id, merged)
4516
4439
  live_owners.add(_measure_facade._stable_hash63(owner_id))
@@ -4527,7 +4450,8 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4527
4450
  conn.executemany(
4528
4451
  "INSERT OR REPLACE INTO session_log_aliases (jsonl_path, session_uuid, collected_at) "
4529
4452
  "VALUES (?, ?, ?)", [(r[0], session_uuid, r[1]) for r in losers])
4530
- conn.executemany("DELETE FROM session_log WHERE id = ?", [(r[0],) for r in other])
4453
+ if upgrade_drain_control.session_write(conn, "DELETE FROM session_log WHERE id = ?", [(r[0],) for r in other], many=True) is None:
4454
+ conn.rollback(); parse_truncated = True; break
4531
4455
  conn.execute("DELETE FROM session_log_aliases WHERE jsonl_path = ?", (str(filepath),))
4532
4456
 
4533
4457
  new_count += 1
@@ -4557,9 +4481,9 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4557
4481
  budget_seconds=budgets["daily_seconds"])
4558
4482
  daily_truncated = _measure_facade.time.monotonic() - _daily_started >= budgets["daily_seconds"]
4559
4483
  except Exception:
4560
- pass
4484
+ daily_truncated = True
4561
4485
  try:
4562
- _measure_facade._pretool_anchor_step(budget_seconds=5.0)
4486
+ _measure_facade._pretool_anchor_step(budget_seconds=3600.0 if drain == "full" else 5.0)
4563
4487
  except Exception:
4564
4488
  pass
4565
4489
 
@@ -4567,31 +4491,38 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4567
4491
  # collect pass (never at dashboard-regen time). Both helpers carry their
4568
4492
  # own per-pass caps + soft deadline and are fail-open, so a slow transcript
4569
4493
  # can never hold the flush; the backlog converges over passes.
4570
- counted_pending = 0
4494
+ counted_pending = 1
4571
4495
  try:
4496
+ # Sessions where Token Optimizer ran elsewhere (cloud) and logged nothing
4497
+ # here: rebuild their events from its own transcript markers first.
4498
+ transcript_stats = _measure_facade._transcript_backfill.collect_pass(conn, _measure_facade, drain, budgets, quiet=quiet)
4572
4499
  if drain == "full":
4573
- counted_pending = int(_measure_facade._counted_backfill_all(conn, quiet=quiet).get("pending_sessions", 0) or 0)
4500
+ counted_stats = _measure_facade._counted_backfill_all(conn, quiet=quiet)
4501
+ counted_pending = int(counted_stats.get("pending_sessions", 0) or 0) + int(not counted_stats.get("marker_backfill_done"))
4574
4502
  else:
4575
4503
  counted_pending = int(_measure_facade._update_counted_cumulative(
4576
4504
  conn, max_sessions=budgets["counted_sessions"],
4577
4505
  deadline_seconds=budgets["counted_seconds"],
4578
4506
  quiet=quiet).get("pending_sessions", 0) or 0)
4579
4507
  if drain == "inline":
4580
- _measure_facade._counted_marker_backfill(conn, max_files=None,
4508
+ marker_stats = _measure_facade._counted_marker_backfill(conn, max_files=None,
4581
4509
  deadline_seconds=budgets["counted_seconds"], quiet=quiet)
4582
4510
  else:
4583
- _measure_facade._counted_marker_backfill(conn, quiet=quiet)
4584
- except Exception:
4585
- pass
4586
- try:
4587
- if drain == "full":
4588
- _measure_facade._upgrade_drain_mark_done(conn)
4589
- elif not rebuild:
4590
- _measure_facade._upgrade_drain_after_pass(
4591
- conn, backlog=bool(parse_truncated or daily_truncated or counted_pending))
4511
+ marker_stats = _measure_facade._counted_marker_backfill(conn, quiet=quiet)
4512
+ counted_pending += int(not marker_stats.get("done"))
4513
+ counted_pending += int(upgrade_drain_control.backfill_pending(transcript_stats))
4592
4514
  except Exception:
4593
- pass
4594
-
4515
+ counted_pending = max(1, counted_pending)
4516
+ # Verbosity nudges against matched un-nudged replies (savings-truth U5).
4517
+ # Read-only on the DB, one derived JSON file, at most daily, and never on
4518
+ # the hook path: it walks every recent transcript.
4519
+ if drain in ("inline", "full"):
4520
+ try:
4521
+ _measure_facade._output_reread.refresh_study(conn, deadline=(
4522
+ None if drain == "full"
4523
+ else _measure_facade.time.monotonic() + budgets["counted_seconds"]))
4524
+ except Exception:
4525
+ pass
4595
4526
  # ATOMICITY INVARIANT: _rebuild_aggregate_tables does DELETE-then-reINSERT and must
4596
4527
  # NOT commit internally. The whole wipe+rebuild is one transaction that commits only on
4597
4528
  # the next line, so a _HookTimeout (BaseException) mid-rebuild rolls back cleanly and the
@@ -4599,6 +4530,13 @@ def collect_sessions(days=None, quiet=None, rebuild=None):
4599
4530
  # re-INSERTs -- a half-applied commit would leave the dashboard reading empty aggregates.
4600
4531
  _measure_facade._rebuild_aggregate_tables(conn)
4601
4532
  conn.commit()
4533
+ try:
4534
+ if drain == "full" and not (parse_truncated or daily_truncated or counted_pending):
4535
+ _measure_facade._upgrade_drain_mark_done(conn)
4536
+ elif drain != "full" and not rebuild:
4537
+ _measure_facade._upgrade_drain_after_pass(conn, backlog=bool(parse_truncated or daily_truncated or counted_pending))
4538
+ except Exception:
4539
+ pass
4602
4540
  # Ensure schema version is set (idempotent, also set in migration and rebuild)
4603
4541
  conn.execute("PRAGMA user_version = 3")
4604
4542
  conn.commit() # PRAGMA write must be committed explicitly