@alexgreensh/token-optimizer 5.13.80 → 5.13.82

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 (45) 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 +2 -2
  7. package/skills/token-optimizer/scripts/_measure/audit.py +5 -6
  8. package/skills/token-optimizer/scripts/_measure/cache_policy.py +16 -39
  9. package/skills/token-optimizer/scripts/_measure/continuity.py +30 -3
  10. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +32 -15
  11. package/skills/token-optimizer/scripts/_measure/daemon.py +25 -2
  12. package/skills/token-optimizer/scripts/_measure/dashboard.py +2 -1
  13. package/skills/token-optimizer/scripts/_measure/feature_health.py +14 -5
  14. package/skills/token-optimizer/scripts/_measure/install_baseline.py +2 -1
  15. package/skills/token-optimizer/scripts/_measure/like_for_like.py +329 -0
  16. package/skills/token-optimizer/scripts/_measure/limit_units.py +39 -0
  17. package/skills/token-optimizer/scripts/_measure/model_families.py +133 -0
  18. package/skills/token-optimizer/scripts/_measure/own_price_card.py +38 -14
  19. package/skills/token-optimizer/scripts/_measure/pilot_report.py +197 -48
  20. package/skills/token-optimizer/scripts/_measure/pricing.py +7 -2
  21. package/skills/token-optimizer/scripts/_measure/project_md_walk.py +29 -0
  22. package/skills/token-optimizer/scripts/_measure/quality_archive.py +41 -19
  23. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +2 -0
  24. package/skills/token-optimizer/scripts/_measure/savings.py +155 -80
  25. package/skills/token-optimizer/scripts/_measure/sessions.py +7 -2
  26. package/skills/token-optimizer/scripts/_measure/transcript_product.py +113 -58
  27. package/skills/token-optimizer/scripts/_measure/trends.py +20 -2
  28. package/skills/token-optimizer/scripts/_measure/ttl_file_memo.py +109 -0
  29. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +64 -7
  30. package/skills/token-optimizer/scripts/antigravity_doctor.py +62 -17
  31. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +20 -3
  32. package/skills/token-optimizer/scripts/antigravity_install.py +18 -9
  33. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  34. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  35. package/skills/token-optimizer/scripts/cursor_coach.py +5 -4
  36. package/skills/token-optimizer/scripts/cursor_install.py +1 -0
  37. package/skills/token-optimizer/scripts/delta_serve.py +174 -0
  38. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  39. package/skills/token-optimizer/scripts/hermes_doctor.py +2 -1
  40. package/skills/token-optimizer/scripts/hermes_install.py +2 -1
  41. package/skills/token-optimizer/scripts/measure.py +14 -21
  42. package/skills/token-optimizer/scripts/read_cache.py +19 -76
  43. package/skills/token-optimizer/scripts/reset_epoch.py +5 -3
  44. package/skills/token-optimizer/scripts/session_activity.py +1 -1
  45. package/skills/token-optimizer/scripts/session_store.py +5 -6
@@ -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