@alexgreensh/token-optimizer 5.13.81 → 5.13.83

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 (39) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/token-optimizer/assets/savings_story.js +6 -4
  6. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  7. package/skills/token-optimizer/scripts/_measure/continuity.py +30 -3
  8. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +32 -15
  9. package/skills/token-optimizer/scripts/_measure/daemon.py +25 -2
  10. package/skills/token-optimizer/scripts/_measure/dashboard.py +2 -1
  11. package/skills/token-optimizer/scripts/_measure/feature_health.py +14 -5
  12. package/skills/token-optimizer/scripts/_measure/install_baseline.py +2 -1
  13. package/skills/token-optimizer/scripts/_measure/like_for_like.py +329 -0
  14. package/skills/token-optimizer/scripts/_measure/limit_units.py +39 -0
  15. package/skills/token-optimizer/scripts/_measure/model_families.py +133 -0
  16. package/skills/token-optimizer/scripts/_measure/own_price_card.py +38 -14
  17. package/skills/token-optimizer/scripts/_measure/pilot_report.py +197 -48
  18. package/skills/token-optimizer/scripts/_measure/pricing.py +7 -2
  19. package/skills/token-optimizer/scripts/_measure/quality_archive.py +41 -19
  20. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +2 -0
  21. package/skills/token-optimizer/scripts/_measure/savings.py +155 -80
  22. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -2
  23. package/skills/token-optimizer/scripts/_measure/trends.py +20 -2
  24. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +37 -4
  25. package/skills/token-optimizer/scripts/antigravity_doctor.py +42 -6
  26. package/skills/token-optimizer/scripts/antigravity_install.py +18 -9
  27. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  28. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  29. package/skills/token-optimizer/scripts/cursor_coach.py +5 -4
  30. package/skills/token-optimizer/scripts/cursor_install.py +1 -0
  31. package/skills/token-optimizer/scripts/delta_serve.py +174 -0
  32. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  33. package/skills/token-optimizer/scripts/hermes_doctor.py +2 -1
  34. package/skills/token-optimizer/scripts/hermes_install.py +2 -1
  35. package/skills/token-optimizer/scripts/measure.py +14 -21
  36. package/skills/token-optimizer/scripts/read_cache.py +19 -76
  37. package/skills/token-optimizer/scripts/reset_epoch.py +5 -3
  38. package/skills/token-optimizer/scripts/session_activity.py +1 -1
  39. package/skills/token-optimizer/scripts/session_store.py +5 -6
@@ -3582,13 +3582,13 @@ _session_model_reprice = _measure_compat.bind(_measure_providers['pricing']._ses
3582
3582
  # * verbosity_* -- output reductions are estimated, not counted removals.
3583
3583
  _COUNTED_SE_EVENT_TYPES = (
3584
3584
  "tool_archive", "tool_archive_reexpand", "tool_archive_refetch_block",
3585
- "structure_map", "delta_read", "codemap_outline", "builtin_grep", "builtin_glob", "big_read_preview",
3585
+ "structure_map", "delta_read", "delta_read_reread", "codemap_outline", "builtin_grep", "builtin_glob", "big_read_preview",
3586
3586
  )
3587
3587
  # compression_events features that are bookkeeping, not removals.
3588
3588
  _COUNTED_CE_EXCLUDED_FEATURES = (
3589
3589
  "quality_nudge", "loop_detection", "cohort_demoted", "fresh_session_nudge",
3590
3590
  "cache_drop_warning", "first_read_edit_followup",
3591
- "delta_read", # read_cache emits both ledgers; savings_events owns this key
3591
+ "delta_read", "delta_read_reread", # read_cache emits both ledgers; savings_events owns this key and its debit
3592
3592
  "structure_map", "big_read_preview", # same: logged to both ledgers, savings_events owns it
3593
3593
  )
3594
3594
  # Ledger events count from here; earlier months use transcript markers instead
@@ -3721,7 +3721,6 @@ _counted_cumulative_summary = _measure_compat.bind(_measure_providers['savings']
3721
3721
  _dashboard_savings_data = _measure_compat.bind(_measure_providers['savings']._dashboard_savings_data, __name__, defaults=(30, False, False,))
3722
3722
 
3723
3723
 
3724
-
3725
3724
  _net_realized_savings = _measure_compat.bind(_measure_providers['savings']._net_realized_savings, __name__)
3726
3725
 
3727
3726
 
@@ -4682,7 +4681,6 @@ _unlink_if_exists = _measure_compat.bind(_measure_providers['daemon']._unlink_if
4682
4681
  _unlink_reporting = _measure_compat.bind(_measure_providers['daemon']._unlink_reporting, __name__)
4683
4682
 
4684
4683
 
4685
-
4686
4684
  _get_or_create_daemon_token = _measure_compat.bind(_measure_providers['daemon']._get_or_create_daemon_token, __name__)
4687
4685
 
4688
4686
 
@@ -4810,7 +4808,6 @@ _clear_daemon_install_failed_marker = _measure_compat.bind(_measure_providers['d
4810
4808
  _uninstall_launchd_daemon = _measure_compat.bind(_measure_providers['daemon']._uninstall_launchd_daemon, __name__, defaults=(False, False,))
4811
4809
 
4812
4810
 
4813
-
4814
4811
  WINDOWS_TASK_NAME = (
4815
4812
  "TokenOptimizerCodexDashboard" if _DAEMON_RUNTIME == "codex"
4816
4813
  else ("TokenOptimizerHermesDashboard" if _DAEMON_RUNTIME == "hermes"
@@ -4850,7 +4847,6 @@ _install_task_scheduler_daemon = _measure_compat.bind(_measure_providers['daemon
4850
4847
  _uninstall_task_scheduler_daemon = _measure_compat.bind(_measure_providers['daemon']._uninstall_task_scheduler_daemon, __name__, defaults=(False, False,))
4851
4848
 
4852
4849
 
4853
-
4854
4850
  # Runtime-suffix-derived (not a codex-vs-else ternary) so hermes/copilot get
4855
4851
  # their own unit + launcher names instead of colliding on the Claude ones, the
4856
4852
  # same way DAEMON_LABEL / WINDOWS_TASK_NAME already distinguish every runtime.
@@ -4887,7 +4883,6 @@ _install_systemd_user_daemon = _measure_compat.bind(_measure_providers['daemon']
4887
4883
  _uninstall_systemd_user_daemon = _measure_compat.bind(_measure_providers['daemon']._uninstall_systemd_user_daemon, __name__, defaults=(False, False,))
4888
4884
 
4889
4885
 
4890
-
4891
4886
  _normalized_platform = _measure_compat.bind(_measure_providers['daemon']._normalized_platform, __name__)
4892
4887
 
4893
4888
 
@@ -6321,7 +6316,7 @@ _checkpoint_cooldown_remaining = _measure_compat.bind(_measure_providers['qualit
6321
6316
  _record_checkpoint_metadata = _measure_compat.bind(_measure_providers['quality_archive']._record_checkpoint_metadata, __name__, kwdefaults={'fill_pct': None, 'quality_score': None})
6322
6317
 
6323
6318
 
6324
- _append_checkpoint_event = _measure_compat.bind(_measure_providers['quality_archive']._append_checkpoint_event, __name__, kwdefaults={'fill_pct': None, 'quality_score': None})
6319
+ _append_checkpoint_event = _measure_compat.bind(_measure_providers['quality_archive']._append_checkpoint_event, __name__, kwdefaults={'fill_pct': None, 'quality_score': None, 'placeholder': False, 'quality_unmeasured': False})
6325
6320
 
6326
6321
 
6327
6322
  checkpoint_stats = _measure_compat.bind(_measure_providers['quality_archive'].checkpoint_stats, __name__, defaults=(7, False,))
@@ -6860,7 +6855,7 @@ _V5_COMPRESSION_LABELS = {
6860
6855
  # continuation value lives only in _estimate_behavioral_savings (estimated).
6861
6856
  _NON_SAVINGS_COMPRESSION_FEATURES = frozenset({
6862
6857
  "fresh_session_nudge", "cohort_demoted", "first_read_edit_followup",
6863
- "cache_drop_warning", "agent_result_skeleton", "unknown", "loop_detection", "cold_guard",
6858
+ "cache_drop_warning", "agent_result_skeleton", "unknown", "loop_detection", "cold_guard", "delta_read_reread",
6864
6859
  "context_advisory_shadow", "context_size_advisory", "post_run_classify_shadow",
6865
6860
  })
6866
6861
 
@@ -7023,6 +7018,8 @@ _NUDGE_HEEDED_SQL = _counted_sql(
7023
7018
  _estimate_contamination_exit_savings = _measure_compat.bind(_measure_providers['savings']._estimate_contamination_exit_savings, __name__, defaults=(30,))
7024
7019
 
7025
7020
 
7021
+ # Zero-credit restores remain in the restored/served cohorts because the serve
7022
+ # happened; tokens_saved sizes the separate credit, not cohort membership.
7026
7023
  _CHECKPOINT_RESTORED_SQL = _counted_sql(
7027
7024
  "savings_events",
7028
7025
  "SELECT DISTINCT session_id FROM {table} "
@@ -7074,7 +7071,6 @@ _ROUTING_BILLABLE_CLASSES = ("fresh_input", "cache_create_5m", "cache_create_1h"
7074
7071
  "output", "unsplit")
7075
7072
 
7076
7073
 
7077
-
7078
7074
  _foreign_savings_card_exact = _measure_compat.bind(_measure_providers['pricing']._foreign_savings_card_exact, __name__)
7079
7075
 
7080
7076
 
@@ -7145,7 +7141,6 @@ _sum_tool_calls = _measure_compat.bind(_measure_providers['savings']._sum_tool_c
7145
7141
  _estimate_output_waste = _measure_compat.bind(_measure_providers['savings']._estimate_output_waste, __name__, defaults=(30,))
7146
7142
 
7147
7143
 
7148
-
7149
7144
  _estimate_cache_drop_savings = _measure_compat.bind(_measure_providers['savings']._estimate_cache_drop_savings, __name__, defaults=(30,))
7150
7145
 
7151
7146
 
@@ -7356,16 +7351,14 @@ _SESSION_WEIGHT_MIN_ANCHOR_SESSIONS = _int_env(
7356
7351
  "TOKEN_OPTIMIZER_WEIGHT_MIN_ANCHOR_SESSIONS", 100)
7357
7352
 
7358
7353
 
7359
- # Constant measuring-stick rate card ($/MTok: fresh input / output / cache-read /
7360
- # cache-write) for the session-weight pool's HEADLINE arm. Both eras are priced at
7361
- # these SAME rates so model-mix and vendor price drift (Sonnet 4.6 -> Sonnet 5
7362
- # $3->$2-class generational moves, Fable 5 entering the mix) cannot leak into the
7363
- # transformation claim -- only billed-volume behaviour (tokens per unit of work and
7364
- # the fresh/cache class split) moves it. On this ledger that drift is ~$1.2K/mo of
7365
- # the engine-priced per-call delta (37%); claiming it as "your transformation" would
7366
- # be crediting Token Optimizer for Anthropic's price cuts. The engine-priced variant
7367
- # is still computed and disclosed separately. Cache-write is deliberately priced at
7368
- # the flat 5m rate for ALL writes so TTL-mix drift between eras cannot count either.
7354
+ # Fallback measuring-stick rate card ($/MTok: fresh input / output / cache-read /
7355
+ # cache-write) for the session-weight pool's HEADLINE arm when detailed per-model
7356
+ # class evidence is unavailable. The preferred basis is like-for-like current
7357
+ # reference pricing per model family: both eras use the same newest family card,
7358
+ # so generation/vendor drift cannot leak into the transformation while real
7359
+ # routing between families still counts. The engine-priced variant is still
7360
+ # computed and disclosed separately. Cache-write is deliberately priced at the
7361
+ # flat 5m rate for ALL writes in this fallback so TTL-mix drift cannot count.
7369
7362
  _WEIGHT_POOL_FLAT_RATES = {"input": 5.0, "output": 25.0, "cache_read": 0.50,
7370
7363
  "cache_write": 6.25}
7371
7364
 
@@ -31,6 +31,7 @@ from fnmatch import fnmatch
31
31
  from pathlib import Path
32
32
  from typing import Any, Optional
33
33
 
34
+ import delta_serve
34
35
  from hook_io import read_stdin_hook_input
35
36
  from plugin_env import is_v5_flag_enabled, resolve_snapshot_dir
36
37
  from runtime_env import project_config_value, run_origin, runtime_home
@@ -52,7 +53,6 @@ except ImportError:
52
53
  _redact_creds = None
53
54
  _pop_redaction_warning = None
54
55
 
55
-
56
56
  def _redact_for_storage(text: str) -> Optional[str]:
57
57
  """Credential-redacted copy of ``text`` for persistence, or None.
58
58
 
@@ -80,7 +80,6 @@ def _marker_key(kind: str, file_path: str) -> Optional[str]:
80
80
  safe = _redact_for_storage(file_path)
81
81
  return None if safe is None else f"{kind}:{safe}"
82
82
 
83
-
84
83
  from structure_map import (
85
84
  StructureMapResult,
86
85
  detect_structure_language,
@@ -1642,7 +1641,8 @@ def _handle_read_impl(hook_input: dict[str, Any], mode: str, quiet: bool, funnel
1642
1641
  break
1643
1642
 
1644
1643
  funnel.metadata(mtime_match, size_match, range_covered)
1645
- if not (mtime_match and size_match and range_covered):
1644
+ # #361: the read after a delta deny must reach the host, which has no successful read of the file yet.
1645
+ if not (mtime_match and size_match and range_covered) or delta_serve.post_delta_full_read_required(entry, mtime_match, size_match):
1646
1646
  funnel.row["exit_reason"] = "metadata_or_range"
1647
1647
  # v5.0: Delta mode -- return diff instead of allowing full re-read
1648
1648
  delta_enabled = _is_v5_delta_enabled()
@@ -1700,76 +1700,16 @@ def _handle_read_impl(hook_input: dict[str, Any], mode: str, quiet: bool, funnel
1700
1700
  if delta_tokens >= old_tokens or delta_bytes >= new_bytes:
1701
1701
  delta_text = None # diff too large, fall through
1702
1702
  if delta_text is not None:
1703
- entry["mtime_ns"] = current_stat.st_mtime_ns
1704
- entry["size_bytes"] = current_stat.st_size
1705
- entry["content_hash"] = new_hash
1706
- entry["read_count"] = int(entry.get("read_count", 0) or 0) + 1
1707
- entry["last_access"] = time.time()
1708
- _reset_replacement_state(entry)
1709
- if len(safe_new_content.encode("utf-8", errors="replace")) <= MAX_CONTENT_CACHE_BYTES:
1710
- store.upsert_cached_content(file_path, safe_new_content, new_hash)
1711
- cached = store.get_cached_content(file_path)
1712
- if not cached or cached.get("content_hash") != new_hash:
1713
- entry["content_hash"] = None
1714
- store.delete_cached_content(file_path)
1715
- else:
1716
- entry["content_hash"] = None
1717
- store.delete_cached_content(file_path)
1718
- store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1719
-
1720
- net_saved = max(0, old_tokens - delta_tokens)
1721
-
1722
- _log_decision(
1723
- "block",
1724
- file_path,
1725
- f"delta_read_{entry['read_count']}",
1726
- session_id,
1727
- mode=mode,
1728
- actual_substitution=True,
1729
- eligible=True,
1730
- language=language,
1731
- reason_code="delta_diff",
1732
- offset=offset,
1733
- limit=limit,
1734
- replacement_type="delta",
1735
- file_tokens_est=old_tokens,
1736
- replacement_tokens_est=delta_tokens,
1737
- net_saved_tokens_est=net_saved,
1738
- replacement_fingerprint=new_hash[:16],
1739
- repeat_replacement_count=0,
1740
- save_hook_additional_context_enabled=save_hook_context_enabled,
1703
+ delta_serve.serve_delta(
1704
+ file_path=file_path, entry=entry, store=store, reset_epoch=reset_epoch,
1705
+ session_id=session_id, mode=mode, language=language, offset=offset, limit=limit,
1706
+ quiet=quiet, save_hook_context_enabled=save_hook_context_enabled,
1707
+ current_stat=current_stat, new_hash=new_hash, safe_new_content=safe_new_content,
1708
+ delta_text=delta_text, delta_stats=delta_stats, old_tokens=old_tokens,
1709
+ delta_tokens=delta_tokens, max_cache_bytes=MAX_CONTENT_CACHE_BYTES,
1710
+ emit_fn=_emit_pretool_response, log_decision_fn=_log_decision,
1711
+ log_savings_fn=_log_savings_event, reset_fn=_reset_replacement_state,
1741
1712
  )
1742
- _log_savings_event("delta_read", net_saved, session_id,
1743
- f"{Path(file_path).name}:+{delta_stats['added']}/-{delta_stats['removed']}")
1744
- # Log to compression_events for v5 telemetry
1745
- try:
1746
- sys.path.insert(0, str(Path(__file__).resolve().parent))
1747
- from measure import _log_compression_event
1748
- _log_compression_event(
1749
- feature="delta_read",
1750
- original_text=" " * (old_tokens * 4), # proxy
1751
- compressed_text=delta_text,
1752
- session_id=session_id,
1753
- command_pattern=f"Read:{Path(file_path).name}",
1754
- quality_preserved=True,
1755
- verified=True,
1756
- tier="measured", # realized: reaches headline explicitly
1757
- detail=f"+{delta_stats['added']}/-{delta_stats['removed']}",
1758
- )
1759
- except Exception:
1760
- pass
1761
- if not quiet:
1762
- print(
1763
- f"[Read Cache] Delta mode: {file_path} "
1764
- f"(+{delta_stats['added']}/-{delta_stats['removed']}, saved~{net_saved:,})",
1765
- file=sys.stderr,
1766
- )
1767
- reason = (
1768
- f"{Path(file_path).name} was edited; showing diff "
1769
- f"(+{delta_stats['added']}/-{delta_stats['removed']} lines) "
1770
- f"instead of full re-read."
1771
- )
1772
- _emit_pretool_response("deny", reason, delta_text)
1773
1713
  return # EXIT: delta handled, do NOT evaluate structure map
1774
1714
  else:
1775
1715
  # Hash unchanged despite mtime change (e.g., touch). Allow normal read.
@@ -1778,13 +1718,14 @@ def _handle_read_impl(hook_input: dict[str, Any], mode: str, quiet: bool, funnel
1778
1718
  pass # Fail open: fall through to normal allow
1779
1719
 
1780
1720
  file_changed = not (mtime_match and size_match)
1781
- reason_code_allow = "file_modified" if file_changed else "new_range"
1721
+ reason_code_allow = "file_modified" if file_changed else (
1722
+ "post_delta_reread" if delta_serve.post_delta_full_read_required(entry, mtime_match, size_match) else "new_range")
1782
1723
  entry["mtime_ns"] = current_stat.st_mtime_ns
1783
1724
  entry["size_bytes"] = current_stat.st_size
1784
1725
  if file_changed:
1785
1726
  entry["ranges_seen"] = [[offset, limit]]
1786
1727
  else:
1787
- ranges_seen.append([offset, limit])
1728
+ if [offset, limit] not in ranges_seen: ranges_seen.append([offset, limit])
1788
1729
  if len(ranges_seen) > 20:
1789
1730
  ranges_seen = ranges_seen[-20:]
1790
1731
  entry["ranges_seen"] = ranges_seen
@@ -1810,7 +1751,7 @@ def _handle_read_impl(hook_input: dict[str, Any], mode: str, quiet: bool, funnel
1810
1751
  elif delta_enabled and offset == 0 and limit == 0 and cache_needs_clear_after_read:
1811
1752
  entry["content_hash"] = None
1812
1753
  store.delete_cached_content(file_path)
1813
- elif delta_enabled and offset == 0 and limit == 0 and not entry.get("cached_content"):
1754
+ elif delta_enabled and offset == 0 and limit == 0 and not entry.get("cached_content") and not (cached and cached.get("content_hash") == entry.get("content_hash")):
1814
1755
  try:
1815
1756
  from delta_diff import is_delta_eligible, content_hash, MAX_CONTENT_CACHE_BYTES
1816
1757
  if is_delta_eligible(file_path):
@@ -1824,6 +1765,8 @@ def _handle_read_impl(hook_input: dict[str, Any], mode: str, quiet: bool, funnel
1824
1765
  store.upsert_cached_content(file_path, safe_fc, safe_hash)
1825
1766
  except Exception:
1826
1767
  pass
1768
+ if reason_code_allow == "post_delta_reread" and offset == 0 and limit == 0:
1769
+ delta_serve.emit_reread_debit(entry=entry, file_path=file_path, session_id=session_id, log_savings_fn=_log_savings_event)
1827
1770
  _reset_replacement_state(entry)
1828
1771
  store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1829
1772
  _log_decision(
@@ -2289,6 +2232,7 @@ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
2289
2232
  existing["ranges_seen"] = [] # content changed; old ranges are stale
2290
2233
  existing["last_access"] = time.time()
2291
2234
  _reset_replacement_state(existing)
2235
+ existing["delta_debit_tokens"] = 0
2292
2236
 
2293
2237
  if new_fc is not None and new_hash is not None:
2294
2238
  existing["content_hash"] = new_hash
@@ -2314,7 +2258,6 @@ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
2314
2258
  except Exception:
2315
2259
  pass
2316
2260
 
2317
-
2318
2261
  def handle_stats(session_id: str) -> None:
2319
2262
  """Print cache stats for a session."""
2320
2263
 
@@ -127,8 +127,8 @@ class ResetEpochMixin:
127
127
  read_count, content_hash, last_access,
128
128
  last_replacement_fingerprint, last_replacement_type,
129
129
  repeat_replacement_count, last_structure_reason,
130
- last_structure_confidence, last_tool_use_id)
131
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
130
+ last_structure_confidence, last_tool_use_id, delta_debit_tokens)
131
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
132
132
  ON CONFLICT(file_path) DO UPDATE SET
133
133
  mtime_ns=excluded.mtime_ns,
134
134
  size_bytes=excluded.size_bytes,
@@ -142,7 +142,8 @@ class ResetEpochMixin:
142
142
  repeat_replacement_count=excluded.repeat_replacement_count,
143
143
  last_structure_reason=excluded.last_structure_reason,
144
144
  last_structure_confidence=excluded.last_structure_confidence,
145
- last_tool_use_id=excluded.last_tool_use_id
145
+ last_tool_use_id=excluded.last_tool_use_id,
146
+ delta_debit_tokens=excluded.delta_debit_tokens
146
147
  """,
147
148
  (
148
149
  file_path,
@@ -159,6 +160,7 @@ class ResetEpochMixin:
159
160
  entry.get("last_structure_reason", ""),
160
161
  float(entry.get("last_structure_confidence", 0.0)),
161
162
  entry.get("last_tool_use_id", ""),
163
+ int(entry.get("delta_debit_tokens", 0) or 0),
162
164
  ),
163
165
  )
164
166
 
@@ -93,7 +93,7 @@ def ensure_activity_view(conn):
93
93
  overrides[name] = f"COALESCE(json_extract({source('daily_metrics_json')}, '$.\"' || d.key || '\".{key}'), {overrides[name]})"
94
94
  # Optional ingestion/provenance columns are deliberately not dependencies of
95
95
  # this view. Their migrations can fail or be retried independently.
96
- for name in ("id", "jsonl_path", "project", "is_sidechain", "session_uuid", "slug", "topic", "collected_at", "version"):
96
+ for name in ("id", "jsonl_path", "project", "is_sidechain", "session_uuid", "slug", "topic", "collected_at", "version", "usage_parser_version"):
97
97
  overrides[name] = source(name, "s.rowid" if name == "id" else "NULL")
98
98
  # Metadata-only activity days (user/tool activity with no billed usage that
99
99
  # day) still belong to the projection: they carry message/tool/skill counts
@@ -70,7 +70,7 @@ CREATE TABLE IF NOT EXISTS file_reads (
70
70
  repeat_replacement_count INTEGER DEFAULT 0,
71
71
  last_structure_reason TEXT DEFAULT '',
72
72
  last_structure_confidence REAL DEFAULT 0.0,
73
- last_tool_use_id TEXT DEFAULT ''
73
+ last_tool_use_id TEXT DEFAULT '', delta_debit_tokens INTEGER NOT NULL DEFAULT 0
74
74
  );
75
75
  CREATE INDEX IF NOT EXISTS idx_file_reads_last_access ON file_reads(last_access DESC);
76
76
  CREATE TABLE IF NOT EXISTS tool_outputs (
@@ -327,11 +327,10 @@ class SessionStore(ResetEpochMixin):
327
327
  cols = {r[1] for r in conn.execute("PRAGMA table_info(file_reads)").fetchall()}
328
328
  except sqlite3.DatabaseError:
329
329
  return
330
- if "last_tool_use_id" not in cols:
331
- try:
332
- conn.execute("ALTER TABLE file_reads ADD COLUMN last_tool_use_id TEXT DEFAULT ''")
333
- except sqlite3.OperationalError:
334
- pass
330
+ for col, decl in (("last_tool_use_id", "TEXT DEFAULT ''"), ("delta_debit_tokens", "INTEGER NOT NULL DEFAULT 0")):
331
+ if col not in cols:
332
+ try: conn.execute(f"ALTER TABLE file_reads ADD COLUMN {col} {decl}")
333
+ except sqlite3.OperationalError: pass
335
334
 
336
335
  def _ensure_command_outputs_columns(self, conn: sqlite3.Connection) -> None:
337
336
  """Add last_tool_use_id to command_outputs if absent, so cross-turn