tokensafe 4.15.0 → 4.15.1

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.15.0",
2
+ "version": "4.15.1",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -70,6 +70,19 @@ def _handle(payload: dict) -> dict:
70
70
  pass
71
71
 
72
72
  tracker = MetricsTracker()
73
+ # One query for every "did this already happen?" check below. The five
74
+ # per-type lookups ran on every invocation and each paid a round trip.
75
+ recent_events: dict = {}
76
+ try:
77
+ recent_events = tracker.get_last_events(conversation_id, (
78
+ "HISTORY_FOLD",
79
+ "GUARD_RAW_CODE_SEARCH",
80
+ "PROTOCOL_REMINDER",
81
+ "BUDGET_WARNING",
82
+ "NOTIFICATION_TURN",
83
+ ))
84
+ except Exception:
85
+ recent_events = {}
73
86
  inject_steps = []
74
87
  workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
75
88
  hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
@@ -164,7 +177,7 @@ def _handle(payload: dict) -> dict:
164
177
  )
165
178
  if folded_text and stats.get("saved_tokens", 0) > 0:
166
179
  # Prevent quadratic double-counting: only record incremental new history mass
167
- prev_event = tracker.get_last_event(session_id=conversation_id, event_type="HISTORY_FOLD")
180
+ prev_event = recent_events.get("HISTORY_FOLD")
168
181
  prev_orig = 0
169
182
  if prev_event and isinstance(prev_event.get("details"), dict):
170
183
  prev_orig = prev_event["details"].get("total_accum_orig", 0) or prev_event.get("original_tokens", 0)
@@ -209,10 +222,10 @@ def _handle(payload: dict) -> dict:
209
222
  history_mass = kernel.measure_transcript(transcript_path)
210
223
 
211
224
  # 4. Adaptive Protocol Enforcement Reminder (Guard-triggered or fresh fold only)
212
- recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
225
+ recent_guard = recent_events.get("GUARD_RAW_CODE_SEARCH")
213
226
  guard_unreminded = False
214
227
  if isinstance(recent_guard, dict):
215
- last_remind = tracker.get_last_event(conversation_id, "PROTOCOL_REMINDER")
228
+ last_remind = recent_events.get("PROTOCOL_REMINDER")
216
229
  is_valid_remind = isinstance(last_remind, dict) and last_remind.get("event_type") == "PROTOCOL_REMINDER"
217
230
  if not is_valid_remind:
218
231
  guard_unreminded = True
@@ -256,7 +269,7 @@ def _handle(payload: dict) -> dict:
256
269
  used_pct = budget.get("used_pct")
257
270
  if (budget.get("measurement") == "measured"
258
271
  and used_pct is not None and used_pct >= 80):
259
- already = tracker.get_last_event(conversation_id, "BUDGET_WARNING")
272
+ already = recent_events.get("BUDGET_WARNING")
260
273
  if not already:
261
274
  if transcript_path:
262
275
  action = (f"Call tokensafe:session_context(action='compact', transcript_path='{transcript_path}') "
@@ -291,7 +304,7 @@ def _handle(payload: dict) -> dict:
291
304
  try:
292
305
  last_input = str(payload.get("lastUserInput") or payload.get("prompt") or "").strip()
293
306
  if invocation_num >= 2 and not last_input:
294
- if not tracker.get_last_event(conversation_id, "NOTIFICATION_TURN"):
307
+ if not recent_events.get("NOTIFICATION_TURN"):
295
308
  inject_steps.append({
296
309
  "systemMessage": {
297
310
  "systemMessage": "",
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.15.0",
3
+ "version": "4.15.1",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "Apache-2.0",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.15.0",
4
+ "version": "4.15.1",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.15.0",
4
+ "version": "4.15.1",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
7
7
  "logo": "assets/logo.png",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.15.0",
6
+ "version": "4.15.1",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.15.0",
26
+ "version": "4.15.1",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.15.0",
42
+ "version": "4.15.1",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -740,13 +740,17 @@ def format_cumulative_banner(tracker: Optional[Any] = None) -> str:
740
740
  saved = int(s.get("total_saved_tokens") or 0)
741
741
  if saved <= 0:
742
742
  return ""
743
- usd = float(s.get("total_usd_saved") or 0.0)
743
+ steps = int(s.get("total_events") or 0)
744
744
  if saved >= 1_000_000:
745
745
  tok_str = f"{saved / 1_000_000:.2f}M"
746
746
  elif saved >= 1_000:
747
747
  tok_str = f"{saved / 1_000:.1f}K"
748
748
  else:
749
749
  tok_str = f"{saved:,}"
750
- return f"[TokenSafe Cumulative: {tok_str} tokens saved (~${usd:.2f} approx)]"
750
+ # Tokens and steps only: no dollar estimate is shown, since a saved
751
+ # token is a counterfactual delta whose price depends on the provider
752
+ # (cache hit vs miss vs output) and is not knowable locally.
753
+ suffix = f" | {steps:,} step" + ("" if steps == 1 else "s") if steps else ""
754
+ return f"[TokenSafe Cumulative: {tok_str} tokens saved{suffix}]"
751
755
  except Exception:
752
756
  return ""
package/src/cli.py CHANGED
@@ -364,8 +364,8 @@ def main(argv: Optional[List[str]] = None):
364
364
  print(f" Data dir: {report['data_dir']}")
365
365
  print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
366
366
  print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
367
- print(f" Saved (pruned+sync): {report['pruned_synced_saved_tokens']:,} tokens")
368
- print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens (≈${report['usd_saved_approx']:.2f})")
367
+ print(f" Synced to cloud: {report['pruned_synced_saved_tokens']:,} tokens (subset of live)")
368
+ print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens")
369
369
  if last:
370
370
  print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
371
371
  print()
package/src/installer.py CHANGED
@@ -60,7 +60,7 @@ UNIFIED_TOKENSAFE_RULE = (
60
60
  "10. **Secret Leak Prevention (Zero Hardcoded Fallbacks)**: Never hardcode real private keys, API secrets, or webhook secrets as fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. Whenever blocked, state:\n"
61
61
  "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
62
62
  "11. **Proof-of-Savings Turn Footer (strictly English)**: Append on tool-using turns:\n"
63
- "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
63
+ "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<steps> steps, <breakdown in English>) | Cumulative Total: <total> tokens`\n"
64
64
  "12. **Universal OUMV Protocol (`oumv`)**: When a workspace profile is OUMV-supported (React+Vite, Vue, Solid, Angular, Go/Gin+Chi, FastAPI/Starlette, Express/Fastify, Next.js, Elysia on Bun, Spring Boot, Laravel/Symfony, ASP.NET Core; Flask/Django mount explicitly as WSGI), "
65
65
  "ALWAYS prefer `tokensafe:oumv(action='status'|'observe'|'understand'|'verify'|'mutate'|'graph', ...)` BEFORE full file crawls, raw curls, or browser checks — "
66
66
  "static OUMV works offline on read/edit tasks too (verify answers a labelled static subset without a runtime), and `tokensafe dev` starts zero-footprint live Vite RPC without touching repo files. "
@@ -375,6 +375,133 @@ class LicenseManager:
375
375
  except Exception:
376
376
  pass
377
377
 
378
+ # --- Quota aggregate cache -------------------------------------------
379
+ # check_quota() runs on every hook invocation and reads a 30-day SQL
380
+ # aggregate plus the sidecar ledger. The aggregate is cached for a few
381
+ # seconds only while usage is in the lower half of the limit, and every
382
+ # recorded measured saving drops the entry, so a cap crossing is never
383
+ # delayed by the TTL.
384
+ _QUOTA_CACHE_KEEP = 4
385
+
386
+ @staticmethod
387
+ def _quota_cache_ttl() -> float:
388
+ try:
389
+ return max(0.0, float(os.environ.get("TOKENSAFE_QUOTA_CACHE_TTL", "60")))
390
+ except (TypeError, ValueError):
391
+ return 60.0
392
+
393
+ @classmethod
394
+ def _quota_cache_path(cls) -> str:
395
+ try:
396
+ return os.path.join(resolve_data_dir(), "quota_state.json")
397
+ except Exception:
398
+ return ""
399
+
400
+ @classmethod
401
+ def _read_quota_cache(cls) -> Dict[str, Any]:
402
+ path = cls._quota_cache_path()
403
+ if not path:
404
+ return {}
405
+ try:
406
+ with open(path, "r", encoding="utf-8") as fh:
407
+ data = json.load(fh)
408
+ entries = data.get("entries") if isinstance(data, dict) else None
409
+ return dict(entries) if isinstance(entries, dict) else {}
410
+ except Exception:
411
+ return {}
412
+
413
+ @classmethod
414
+ def _write_quota_cache(cls, slot: str, payload: Dict[str, Any]) -> None:
415
+ path = cls._quota_cache_path()
416
+ if not path:
417
+ return
418
+ try:
419
+ now = time.time()
420
+ entries = {
421
+ key: value
422
+ for key, value in cls._read_quota_cache().items()
423
+ if isinstance(value, dict) and float(value.get("expires", 0)) > now
424
+ }
425
+ entries[slot] = payload
426
+ trimmed = dict(list(entries.items())[-cls._QUOTA_CACHE_KEEP:])
427
+ tmp = f"{path}.tmp.{os.getpid()}"
428
+ with open(tmp, "w", encoding="utf-8") as fh:
429
+ json.dump({"version": 1, "entries": trimmed}, fh)
430
+ os.replace(tmp, path)
431
+ except Exception:
432
+ pass
433
+
434
+ @classmethod
435
+ def _drop_quota_cache(cls, slot: Optional[str] = None) -> None:
436
+ path = cls._quota_cache_path()
437
+ if not path:
438
+ return
439
+ try:
440
+ if slot is None:
441
+ if os.path.exists(path):
442
+ os.unlink(path)
443
+ return
444
+ entries = cls._read_quota_cache()
445
+ if slot not in entries:
446
+ return
447
+ entries.pop(slot, None)
448
+ if not entries:
449
+ os.unlink(path)
450
+ return
451
+ tmp = f"{path}.tmp.{os.getpid()}"
452
+ with open(tmp, "w", encoding="utf-8") as fh:
453
+ json.dump({"version": 1, "entries": entries}, fh)
454
+ os.replace(tmp, path)
455
+ except Exception:
456
+ pass
457
+
458
+ @classmethod
459
+ def note_quota_activity(cls, delta_saved: int) -> None:
460
+ """Drops the cached aggregate after any recorded measured saving.
461
+
462
+ Measured savings are what the quota counts, so a process that records
463
+ them (the MCP server, where the check gates real optimization) must not
464
+ read a figure from before its own write. Estimated events do not count
465
+ against the quota and leave the cache alone — that is the hook path.
466
+ """
467
+ try:
468
+ if int(delta_saved or 0) <= 0 or not cls._quota_cache_ttl():
469
+ return
470
+ cls._drop_quota_cache(None)
471
+ except Exception:
472
+ pass
473
+
474
+ @classmethod
475
+ def _cached_monthly_saved(cls, tracker, max_tokens: int) -> int:
476
+ """30-day measured savings for quota, cached for a few seconds.
477
+
478
+ Only the lower half of the limit is cached: near the cap the aggregate is
479
+ recomputed on every check, so crossing it is never delayed by the TTL.
480
+ """
481
+ ttl = cls._quota_cache_ttl()
482
+ if ttl <= 0:
483
+ return int(tracker.get_monthly_saved_tokens())
484
+ slot = cls._cache_slot("quota:" + str(getattr(tracker, "db_path", "") or ""))
485
+ try:
486
+ now = time.time()
487
+ entry = cls._read_quota_cache().get(slot)
488
+ if isinstance(entry, dict) and float(entry.get("expires", 0)) > now:
489
+ cached = entry.get("local_saved")
490
+ if isinstance(cached, int) and not isinstance(cached, bool) and 0 <= cached < max_tokens * 0.5:
491
+ return cached
492
+ value = int(tracker.get_monthly_saved_tokens())
493
+ if value < max_tokens * 0.5:
494
+ cls._write_quota_cache(slot, {
495
+ "local_saved": value,
496
+ "expires": now + ttl,
497
+ })
498
+ else:
499
+ cls._drop_quota_cache(slot)
500
+ return value
501
+ except Exception:
502
+ cls._drop_quota_cache(slot)
503
+ return int(tracker.get_monthly_saved_tokens())
504
+
378
505
  @classmethod
379
506
  def validate_license(
380
507
  cls,
@@ -789,7 +916,7 @@ class LicenseManager:
789
916
  except Exception:
790
917
  tracker = None
791
918
 
792
- local_saved = tracker.get_monthly_saved_tokens() if tracker else 0
919
+ local_saved = cls._cached_monthly_saved(tracker, max_tokens) if tracker else 0
793
920
  server_floor = cls._get_server_quota_floor(tracker)
794
921
 
795
922
  # Guest state backup floor (scoped to tracker dir when explicit db_path is provided)
package/src/mcp_server.py CHANGED
@@ -46,7 +46,7 @@ from src.session_context import current_root, current_session_id
46
46
 
47
47
  SERVER_INFO = {
48
48
  "name": "tokensafe-mcp",
49
- "version": "4.15.0"
49
+ "version": "4.15.1"
50
50
  }
51
51
 
52
52
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/metrics.py CHANGED
@@ -65,6 +65,13 @@ _INITIALIZED_METRICS_DBS: set = set()
65
65
  # invocation, so per-instance counters never reached the threshold in production.
66
66
  _AUTOPRUNE_INTERVAL = float(os.environ.get("TOKENSAFE_AUTOPRUNE_INTERVAL", "3600"))
67
67
 
68
+ # Schema notes: there is deliberately no marker file that lets a process skip the
69
+ # `PRAGMA user_version` probe. In WAL mode a write does not bump the main
70
+ # database file's mtime, so an mtime-based marker can silently skip a pending
71
+ # migration (caught by test_legacy_rows_relabelled_on_migration). The probe is
72
+ # not a cost anyway — the cached connection means it runs on the same handle the
73
+ # first real query uses.
74
+
68
75
 
69
76
  class MetricsTracker:
70
77
  """Manages persistent token savings metrics in SQLite with lifetime rollups and retention."""
@@ -79,21 +86,92 @@ class MetricsTracker:
79
86
  self.retention_days = int(os.environ.get("TOKENSAFE_RETENTION_DAYS", "30"))
80
87
  self.max_events = int(os.environ.get("TOKENSAFE_MAX_EVENTS", "5000"))
81
88
  self._event_counter = 0
89
+ # One connection per (tracker, thread). Lifecycle hooks are short-lived
90
+ # processes issuing ~10 short statements per invocation; a connect/pragma/
91
+ # close cycle around each one was pure overhead. Threads never share a
92
+ # handle (sqlite3 connections are not safe to interleave), and the handle
93
+ # is dropped when the database file identity changes (reset, delete and
94
+ # recreate, restored backup).
95
+ self._conn_lock = threading.Lock()
96
+ self._conns: Dict[int, Any] = {}
97
+ self._depth_state = threading.local()
82
98
  self._init_db()
83
99
 
84
- @contextmanager
85
- def _get_connection(self) -> Generator[sqlite3.Connection, None, None]:
86
- conn = sqlite3.connect(self.db_path, timeout=5.0)
100
+ def _connection_identity(self):
101
+ """Identity of the database file, used to notice delete-and-recreate."""
102
+ try:
103
+ stat = os.stat(self.db_path)
104
+ return (stat.st_dev, stat.st_ino)
105
+ except OSError:
106
+ return None
107
+
108
+ def _acquire_connection(self) -> sqlite3.Connection:
109
+ """Returns this thread's cached connection (identity-checked)."""
110
+ thread_id = threading.get_ident()
111
+ identity = self._connection_identity()
112
+ with self._conn_lock:
113
+ entry = self._conns.get(thread_id)
114
+ if entry is not None and entry[1] == identity:
115
+ return entry[0]
116
+ conn = sqlite3.connect(self.db_path, timeout=5.0, check_same_thread=False)
87
117
  conn.row_factory = sqlite3.Row
88
118
  try:
89
119
  conn.execute("PRAGMA busy_timeout=3000;")
90
120
  except sqlite3.Error:
91
121
  pass
122
+ with self._conn_lock:
123
+ previous = self._conns.get(thread_id)
124
+ self._conns[thread_id] = (conn, identity)
125
+ if previous is not None:
126
+ try:
127
+ previous[0].close()
128
+ except Exception:
129
+ pass
130
+ return conn
131
+
132
+ def close(self) -> None:
133
+ """Closes every cached connection (VACUUM needs the file to itself)."""
134
+ with self._conn_lock:
135
+ conns = [entry[0] for entry in self._conns.values()]
136
+ self._conns = {}
137
+ for conn in conns:
138
+ try:
139
+ conn.close()
140
+ except Exception:
141
+ pass
142
+ try:
143
+ self._depth_state.depth = 0
144
+ except Exception:
145
+ pass
146
+
147
+ def __del__(self):
148
+ try:
149
+ self.close()
150
+ except Exception:
151
+ pass
152
+
153
+ @contextmanager
154
+ def _get_connection(self) -> Generator[sqlite3.Connection, None, None]:
155
+ conn = self._acquire_connection()
156
+ depth = int(getattr(self._depth_state, "depth", 0) or 0)
157
+ self._depth_state.depth = depth + 1
92
158
  try:
93
159
  yield conn
94
- conn.commit()
95
- finally:
96
- conn.close()
160
+ except BaseException:
161
+ self._depth_state.depth = depth
162
+ if depth == 0:
163
+ try:
164
+ conn.rollback()
165
+ except sqlite3.Error:
166
+ pass
167
+ raise
168
+ else:
169
+ self._depth_state.depth = depth
170
+ if depth == 0:
171
+ try:
172
+ conn.commit()
173
+ except sqlite3.Error:
174
+ pass
97
175
 
98
176
  @classmethod
99
177
  def _maybe_autoprune(cls, db_path: str):
@@ -484,6 +562,14 @@ class MetricsTracker:
484
562
 
485
563
  if measurement_label == "measured" and saved_tokens > 0:
486
564
  self._sync_quota_mirror(now_iso[:10], saved_tokens)
565
+ # Measured savings are what the quota counts: drop the short-lived
566
+ # aggregate so no quota check can read a figure from before this
567
+ # write (estimated events leave it alone — that is the hook path).
568
+ try:
569
+ from src.license_manager import LicenseManager
570
+ LicenseManager.note_quota_activity(saved_tokens)
571
+ except Exception:
572
+ pass
487
573
 
488
574
  # Wall-clock auto-retention (marker-file gated, cross-process safe)
489
575
  self._maybe_autoprune(self.db_path)
@@ -776,28 +862,46 @@ class MetricsTracker:
776
862
  events.append(ev)
777
863
  return events
778
864
 
865
+ @staticmethod
866
+ def _event_row(row) -> Dict[str, Any]:
867
+ res = dict(row)
868
+ try:
869
+ parsed = json.loads(res["details"]) if res.get("details") else {}
870
+ res["details"] = parsed if isinstance(parsed, dict) else {}
871
+ except Exception:
872
+ res["details"] = {}
873
+ return res
874
+
875
+ def get_last_events(self, session_id: str, event_types: List[str]) -> Dict[str, Dict[str, Any]]:
876
+ """Most recent event per type for a session, in ONE query.
877
+
878
+ The per-turn hook asks for up to five types (history fold, guard, protocol
879
+ reminder, budget warning, notification turn); five round trips cost more
880
+ than the scan itself and the hook is on the keystroke path.
881
+ """
882
+ wanted = [str(event_type) for event_type in (event_types or []) if event_type]
883
+ if not wanted:
884
+ return {}
885
+ placeholders = ",".join("?" for _ in wanted)
886
+ sql = (
887
+ "SELECT id, session_id, timestamp, event_type, original_tokens, optimized_tokens,"
888
+ " saved_tokens, reduction_pct, est_usd_saved, details FROM ("
889
+ " SELECT id, session_id, timestamp, event_type, original_tokens, optimized_tokens,"
890
+ " saved_tokens, reduction_pct, est_usd_saved, details,"
891
+ " ROW_NUMBER() OVER (PARTITION BY event_type ORDER BY id DESC) AS rn"
892
+ " FROM events WHERE session_id = ? AND event_type IN (" + placeholders + ")"
893
+ ") WHERE rn = 1"
894
+ )
895
+ latest: Dict[str, Dict[str, Any]] = {}
896
+ with self._get_connection() as conn:
897
+ for row in conn.execute(sql, (session_id, *wanted)).fetchall():
898
+ res = self._event_row(row)
899
+ latest[str(res.get("event_type"))] = res
900
+ return latest
901
+
779
902
  def get_last_event(self, session_id: str, event_type: str) -> Optional[Dict[str, Any]]:
780
903
  """Returns the most recent event of a given type for a session."""
781
- with self._get_connection() as conn:
782
- cursor = conn.cursor()
783
- cursor.execute("""
784
- SELECT id, session_id, timestamp, event_type, original_tokens,
785
- optimized_tokens, saved_tokens, reduction_pct, est_usd_saved, details
786
- FROM events
787
- WHERE session_id = ? AND event_type = ?
788
- ORDER BY id DESC
789
- LIMIT 1
790
- """, (session_id, event_type))
791
- row = cursor.fetchone()
792
- if not row:
793
- return None
794
- res = dict(row)
795
- try:
796
- parsed = json.loads(res["details"]) if res.get("details") else {}
797
- res["details"] = parsed if isinstance(parsed, dict) else {}
798
- except Exception:
799
- res["details"] = {}
800
- return res
904
+ return self.get_last_events(session_id, [event_type]).get(str(event_type))
801
905
 
802
906
  def recalculate_sessions(self):
803
907
  """Recalculates sessions table aggregates directly from events table."""
@@ -984,6 +1088,9 @@ class MetricsTracker:
984
1088
 
985
1089
  def vacuum(self):
986
1090
  """Reclaims unused disk space by running VACUUM on SQLite."""
1091
+ # VACUUM wants the database to itself: an idle cached handle can hold a
1092
+ # read mark (and blocks the rewrite on Windows), so drop ours first.
1093
+ self.close()
987
1094
  try:
988
1095
  conn = sqlite3.connect(self.db_path, isolation_level=None)
989
1096
  conn.execute("VACUUM")
package/src/savings.py CHANGED
@@ -5,8 +5,8 @@ one source of truth is the canonical data dir resolved by ``src.paths``
5
5
  (``TOKENSAFE_DATA_DIR`` or ``~/.tokensafe/data``). This module exposes it as a
6
6
  single JSON-able report, including the difference between:
7
7
  * live events still in ``events`` / ``lifetime_aggregates``, and
8
- * totals already pruned from the local DB but counted in the cloud mirror
9
- (``pruned_synced_*``).
8
+ * how much of that history has already been synced to the cloud mirror
9
+ (``pruned_synced_*``), a subset of the live total, not an addition.
10
10
 
11
11
  Repository-local ``data/metrics.db`` files are legacy/test artifacts and are NOT
12
12
  read here.
@@ -45,7 +45,11 @@ def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str,
45
45
 
46
46
  live_saved = int(summary.get("total_saved_tokens", 0))
47
47
  pruned = _pruned_synced(tracker.db_path)
48
- cumulative = live_saved + pruned["saved_tokens"]
48
+ # summary already folds pruned events into lifetime_aggregates; the
49
+ # pruned_synced_* columns hold the subset of that history already pushed to
50
+ # the cloud mirror (telemetry_sync sends total - pruned_synced), so adding
51
+ # them here would count the same tokens twice.
52
+ cumulative = live_saved
49
53
 
50
54
  last_event = None
51
55
  if last_events:
@@ -76,7 +80,8 @@ def build_savings_report(tracker: Optional[MetricsTracker] = None) -> Dict[str,
76
80
  "reduction_pct": summary.get("overall_reduction_pct", 0.0),
77
81
  "last_event": last_event,
78
82
  "note": (
79
- "cumulative = live events + totals pruned locally but already synced; "
83
+ "cumulative = live events incl. locally pruned rollups; pruned_synced_* "
84
+ "is the already-synced subset, not additive; "
80
85
  "per-turn delta must be read from last_event, never guessed"
81
86
  ),
82
87
  }
@@ -311,7 +311,7 @@ class TelemetrySync:
311
311
  current_last_id = last_id
312
312
  headers = {
313
313
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.15.0"
314
+ "User-Agent": "TokenSafe-Sync/4.15.1"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.15.0"
20
+ CURRENT_VERSION = "4.15.1"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage