tokensafe 4.15.0 → 4.16.0

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.
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):
@@ -139,6 +217,27 @@ class MetricsTracker:
139
217
  except Exception:
140
218
  pass
141
219
 
220
+ @staticmethod
221
+ def _ensure_usage_context_columns(cursor) -> None:
222
+ """Adds the user_version 6 context/cache columns to an existing table.
223
+
224
+ Both init branches reach an existing ``usage_sessions`` table: the
225
+ legacy one through user_version >= 2 and the fresh one when events is
226
+ missing. ALTER is idempotent here because the duplicate column raises
227
+ OperationalError, which is swallowed per statement.
228
+ """
229
+ for alter_sql in (
230
+ "ALTER TABLE usage_sessions ADD COLUMN peak_context_tokens INTEGER NOT NULL DEFAULT 0;",
231
+ "ALTER TABLE usage_sessions ADD COLUMN last_context_tokens INTEGER NOT NULL DEFAULT 0;",
232
+ "ALTER TABLE usage_sessions ADD COLUMN compactions INTEGER NOT NULL DEFAULT 0;",
233
+ "ALTER TABLE usage_sessions ADD COLUMN miss_tokens INTEGER NOT NULL DEFAULT 0;",
234
+ "ALTER TABLE usage_sessions ADD COLUMN miss_events INTEGER NOT NULL DEFAULT 0;",
235
+ ):
236
+ try:
237
+ cursor.execute(alter_sql)
238
+ except sqlite3.OperationalError:
239
+ pass
240
+
142
241
  def _init_db(self):
143
242
  with _METRICS_INIT_LOCK:
144
243
  if self.db_path in _INITIALIZED_METRICS_DBS and os.path.exists(self.db_path) and os.path.getsize(self.db_path) > 0:
@@ -150,7 +249,7 @@ class MetricsTracker:
150
249
  user_ver = int(uv_row[0]) if uv_row else 0
151
250
  except Exception:
152
251
  user_ver = 0
153
- if user_ver >= 4:
252
+ if user_ver >= 6:
154
253
  _INITIALIZED_METRICS_DBS.add(self.db_path)
155
254
  return
156
255
  if user_ver >= 2:
@@ -174,8 +273,29 @@ class MetricsTracker:
174
273
  cursor.execute(alter_sql)
175
274
  except sqlite3.OperationalError:
176
275
  pass
276
+ cursor.execute("""
277
+ CREATE TABLE IF NOT EXISTS usage_sessions (
278
+ session_id TEXT PRIMARY KEY,
279
+ updated_at TEXT NOT NULL,
280
+ agent TEXT NOT NULL DEFAULT '',
281
+ model TEXT NOT NULL DEFAULT '',
282
+ source TEXT NOT NULL DEFAULT 'measured',
283
+ llm_turns INTEGER NOT NULL DEFAULT 0,
284
+ tool_calls INTEGER NOT NULL DEFAULT 0,
285
+ input_tokens INTEGER NOT NULL DEFAULT 0,
286
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
287
+ output_tokens INTEGER NOT NULL DEFAULT 0,
288
+ reasoning_chars INTEGER NOT NULL DEFAULT 0,
289
+ visible_chars INTEGER NOT NULL DEFAULT 0,
290
+ offset INTEGER NOT NULL DEFAULT 0
291
+ )
292
+ """)
293
+ # Context/cache accounting arrived in user_version 6: a
294
+ # session's peak prompt, its host compactions and the
295
+ # uncached reads are what a long session is billed for.
296
+ self._ensure_usage_context_columns(cursor)
177
297
  try:
178
- cursor.execute("PRAGMA user_version = 4;")
298
+ cursor.execute("PRAGMA user_version = 6;")
179
299
  except sqlite3.Error:
180
300
  pass
181
301
  _INITIALIZED_METRICS_DBS.add(self.db_path)
@@ -260,6 +380,30 @@ class MetricsTracker:
260
380
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp)")
261
381
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_session_id ON events(session_id)")
262
382
  cursor.execute("CREATE INDEX IF NOT EXISTS idx_events_measurement_type ON events(measurement, event_type)")
383
+ cursor.execute("""
384
+ CREATE TABLE IF NOT EXISTS usage_sessions (
385
+ session_id TEXT PRIMARY KEY,
386
+ updated_at TEXT NOT NULL,
387
+ agent TEXT NOT NULL DEFAULT '',
388
+ model TEXT NOT NULL DEFAULT '',
389
+ source TEXT NOT NULL DEFAULT 'measured',
390
+ llm_turns INTEGER NOT NULL DEFAULT 0,
391
+ tool_calls INTEGER NOT NULL DEFAULT 0,
392
+ input_tokens INTEGER NOT NULL DEFAULT 0,
393
+ cache_read_tokens INTEGER NOT NULL DEFAULT 0,
394
+ output_tokens INTEGER NOT NULL DEFAULT 0,
395
+ reasoning_chars INTEGER NOT NULL DEFAULT 0,
396
+ visible_chars INTEGER NOT NULL DEFAULT 0,
397
+ peak_context_tokens INTEGER NOT NULL DEFAULT 0,
398
+ last_context_tokens INTEGER NOT NULL DEFAULT 0,
399
+ compactions INTEGER NOT NULL DEFAULT 0,
400
+ miss_tokens INTEGER NOT NULL DEFAULT 0,
401
+ miss_events INTEGER NOT NULL DEFAULT 0,
402
+ offset INTEGER NOT NULL DEFAULT 0
403
+ )
404
+ """)
405
+ cursor.execute("CREATE INDEX IF NOT EXISTS idx_usage_updated ON usage_sessions(updated_at)")
406
+ self._ensure_usage_context_columns(cursor)
263
407
  cursor.execute("""
264
408
  CREATE TABLE IF NOT EXISTS quota_daily (
265
409
  day_key TEXT PRIMARY KEY,
@@ -279,7 +423,7 @@ class MetricsTracker:
279
423
  GROUP BY substr(timestamp, 1, 10)
280
424
  """, (cutoff_30,))
281
425
  try:
282
- cursor.execute("PRAGMA user_version = 4;")
426
+ cursor.execute("PRAGMA user_version = 6;")
283
427
  except sqlite3.Error:
284
428
  pass
285
429
  _INITIALIZED_METRICS_DBS.add(self.db_path)
@@ -484,6 +628,14 @@ class MetricsTracker:
484
628
 
485
629
  if measurement_label == "measured" and saved_tokens > 0:
486
630
  self._sync_quota_mirror(now_iso[:10], saved_tokens)
631
+ # Measured savings are what the quota counts: drop the short-lived
632
+ # aggregate so no quota check can read a figure from before this
633
+ # write (estimated events leave it alone — that is the hook path).
634
+ try:
635
+ from src.license_manager import LicenseManager
636
+ LicenseManager.note_quota_activity(saved_tokens)
637
+ except Exception:
638
+ pass
487
639
 
488
640
  # Wall-clock auto-retention (marker-file gated, cross-process safe)
489
641
  self._maybe_autoprune(self.db_path)
@@ -716,6 +868,117 @@ class MetricsTracker:
716
868
  "breakdown": combined_breakdown
717
869
  }
718
870
 
871
+ def get_usage_session(self, session_id: str) -> Optional[Dict[str, Any]]:
872
+ """Returns the stored transcript-usage row for one session, if any."""
873
+ try:
874
+ with self._get_connection() as conn:
875
+ row = conn.cursor().execute(
876
+ "SELECT * FROM usage_sessions WHERE session_id = ?", (session_id,)
877
+ ).fetchone()
878
+ return dict(row) if row else None
879
+ except Exception:
880
+ return None
881
+
882
+ def upsert_usage(
883
+ self,
884
+ session_id: str,
885
+ agent: str,
886
+ model: str,
887
+ source: str,
888
+ llm_turns: int,
889
+ tool_calls: int,
890
+ input_tokens: int,
891
+ cache_read_tokens: int,
892
+ output_tokens: int,
893
+ reasoning_chars: int,
894
+ visible_chars: int,
895
+ offset: int,
896
+ peak_context_tokens: int = 0,
897
+ last_context_tokens: int = 0,
898
+ compactions: int = 0,
899
+ miss_tokens: int = 0,
900
+ miss_events: int = 0,
901
+ ) -> None:
902
+ """Upserts one session's measured transcript totals plus the byte offset."""
903
+ now = datetime.now().isoformat()
904
+ with self._get_connection() as conn:
905
+ conn.execute(
906
+ """
907
+ INSERT INTO usage_sessions (
908
+ session_id, updated_at, agent, model, source, llm_turns, tool_calls,
909
+ input_tokens, cache_read_tokens, output_tokens, reasoning_chars,
910
+ visible_chars, offset, peak_context_tokens, last_context_tokens,
911
+ compactions, miss_tokens, miss_events
912
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
913
+ ON CONFLICT(session_id) DO UPDATE SET
914
+ updated_at = excluded.updated_at,
915
+ agent = excluded.agent,
916
+ model = excluded.model,
917
+ source = excluded.source,
918
+ llm_turns = excluded.llm_turns,
919
+ tool_calls = excluded.tool_calls,
920
+ input_tokens = excluded.input_tokens,
921
+ cache_read_tokens = excluded.cache_read_tokens,
922
+ output_tokens = excluded.output_tokens,
923
+ reasoning_chars = excluded.reasoning_chars,
924
+ visible_chars = excluded.visible_chars,
925
+ offset = excluded.offset,
926
+ peak_context_tokens = excluded.peak_context_tokens,
927
+ last_context_tokens = excluded.last_context_tokens,
928
+ compactions = excluded.compactions,
929
+ miss_tokens = excluded.miss_tokens,
930
+ miss_events = excluded.miss_events
931
+ """,
932
+ (
933
+ session_id, now, agent, model, source, int(llm_turns), int(tool_calls),
934
+ int(input_tokens), int(cache_read_tokens), int(output_tokens),
935
+ int(reasoning_chars), int(visible_chars), int(offset),
936
+ int(peak_context_tokens), int(last_context_tokens), int(compactions),
937
+ int(miss_tokens), int(miss_events),
938
+ ),
939
+ )
940
+
941
+ def get_usage_summary(self) -> Dict[str, Any]:
942
+ """Aggregates measured output usage. Steps-only sessions never enter
943
+ token averages: an unknown is reported as unknown, never estimated."""
944
+ with self._get_connection() as conn:
945
+ rows = [dict(r) for r in conn.cursor().execute(
946
+ "SELECT * FROM usage_sessions ORDER BY output_tokens DESC"
947
+ ).fetchall()]
948
+ measured = [r for r in rows if (r.get("source") or "") == "measured"]
949
+
950
+ def total(key: str) -> int:
951
+ return int(sum((r.get(key) or 0) for r in measured))
952
+
953
+ output = total("output_tokens")
954
+ turns = total("llm_turns")
955
+ tools = total("tool_calls")
956
+ reason = total("reasoning_chars")
957
+ visible = total("visible_chars")
958
+ return {
959
+ "sessions": len(rows),
960
+ "measured_sessions": len(measured),
961
+ "steps_only_sessions": len(rows) - len(measured),
962
+ "llm_turns": turns,
963
+ "tool_calls": tools,
964
+ "input_tokens": total("input_tokens"),
965
+ "cache_read_tokens": total("cache_read_tokens"),
966
+ "output_tokens": output,
967
+ "output_per_call": round(output / turns, 1) if turns else 0.0,
968
+ "output_per_tool_call": round(output / tools, 1) if tools else 0.0,
969
+ "reasoning_chars": reason,
970
+ "visible_chars": visible,
971
+ "reasoning_share_pct": round(reason / (reason + visible) * 100.0, 1) if (reason + visible) else 0.0,
972
+ "top": rows[:5],
973
+ }
974
+
975
+ def get_usage_rows(self) -> List[Dict[str, Any]]:
976
+ """All transcript-usage rows (measured and steps-only) for calibration."""
977
+ with self._get_connection() as conn:
978
+ return [dict(r) for r in conn.cursor().execute(
979
+ "SELECT * FROM usage_sessions ORDER BY updated_at DESC"
980
+ ).fetchall()]
981
+
719
982
  def get_monthly_saved_tokens(self, measured_only: bool = True) -> int:
720
983
  """Returns trailing 30-day tokens saved for quota calculations (measured-only by default).
721
984
 
@@ -776,28 +1039,46 @@ class MetricsTracker:
776
1039
  events.append(ev)
777
1040
  return events
778
1041
 
1042
+ @staticmethod
1043
+ def _event_row(row) -> Dict[str, Any]:
1044
+ res = dict(row)
1045
+ try:
1046
+ parsed = json.loads(res["details"]) if res.get("details") else {}
1047
+ res["details"] = parsed if isinstance(parsed, dict) else {}
1048
+ except Exception:
1049
+ res["details"] = {}
1050
+ return res
1051
+
1052
+ def get_last_events(self, session_id: str, event_types: List[str]) -> Dict[str, Dict[str, Any]]:
1053
+ """Most recent event per type for a session, in ONE query.
1054
+
1055
+ The per-turn hook asks for up to five types (history fold, guard, protocol
1056
+ reminder, budget warning, notification turn); five round trips cost more
1057
+ than the scan itself and the hook is on the keystroke path.
1058
+ """
1059
+ wanted = [str(event_type) for event_type in (event_types or []) if event_type]
1060
+ if not wanted:
1061
+ return {}
1062
+ placeholders = ",".join("?" for _ in wanted)
1063
+ sql = (
1064
+ "SELECT id, session_id, timestamp, event_type, original_tokens, optimized_tokens,"
1065
+ " saved_tokens, reduction_pct, est_usd_saved, details FROM ("
1066
+ " SELECT id, session_id, timestamp, event_type, original_tokens, optimized_tokens,"
1067
+ " saved_tokens, reduction_pct, est_usd_saved, details,"
1068
+ " ROW_NUMBER() OVER (PARTITION BY event_type ORDER BY id DESC) AS rn"
1069
+ " FROM events WHERE session_id = ? AND event_type IN (" + placeholders + ")"
1070
+ ") WHERE rn = 1"
1071
+ )
1072
+ latest: Dict[str, Dict[str, Any]] = {}
1073
+ with self._get_connection() as conn:
1074
+ for row in conn.execute(sql, (session_id, *wanted)).fetchall():
1075
+ res = self._event_row(row)
1076
+ latest[str(res.get("event_type"))] = res
1077
+ return latest
1078
+
779
1079
  def get_last_event(self, session_id: str, event_type: str) -> Optional[Dict[str, Any]]:
780
1080
  """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
1081
+ return self.get_last_events(session_id, [event_type]).get(str(event_type))
801
1082
 
802
1083
  def recalculate_sessions(self):
803
1084
  """Recalculates sessions table aggregates directly from events table."""
@@ -984,6 +1265,9 @@ class MetricsTracker:
984
1265
 
985
1266
  def vacuum(self):
986
1267
  """Reclaims unused disk space by running VACUUM on SQLite."""
1268
+ # VACUUM wants the database to itself: an idle cached handle can hold a
1269
+ # read mark (and blocks the rewrite on Windows), so drop ours first.
1270
+ self.close()
987
1271
  try:
988
1272
  conn = sqlite3.connect(self.db_path, isolation_level=None)
989
1273
  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
  }
@@ -258,6 +258,9 @@ class Skeletonizer:
258
258
  if ext == ".py":
259
259
  res = cls._skeletonize_python(code, keep_symbols=keep_symbols)
260
260
  return cls._collapse_import_lines(res, ext) if (collapse_imports and keep_symbols) else res
261
+ elif ext == ".gd":
262
+ # GDScript is indentation-scoped like Python, not brace-scoped.
263
+ return cls._skeletonize_gdscript(code, keep_symbols=keep_symbols)
261
264
  elif ext in (
262
265
  ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
263
266
  ".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp",
@@ -276,6 +279,54 @@ class Skeletonizer:
276
279
  return cls._skeletonize_css(code, ext, keep_symbols=keep_symbols)
277
280
  return code
278
281
 
282
+ _GD_FUNC_RE = re.compile(r"^(?:static\s+)?func\s+([A-Za-z_]\w*)")
283
+ _GD_CLASS_RE = re.compile(r"^(?:class|inner\s+class)\s+([A-Za-z_]\w*)")
284
+ _GD_DECL_RE = re.compile(
285
+ r"^(?:@?\w+\s*)*(?:class_name|extends|signal|enum|const|var)\b|^@(export|onready|tool)\b"
286
+ )
287
+
288
+ @classmethod
289
+ def _skeletonize_gdscript(cls, code: str, keep_symbols: Optional[Set[str]] = None) -> str:
290
+ """GDScript skeleton: declarations and signatures, folded function bodies.
291
+
292
+ GDScript is indentation-scoped (like Python), so the brace fallback would
293
+ mangle it. With `keep_symbols` the named functions keep their bodies; every
294
+ other body folds to a single `# ...` line.
295
+ """
296
+ keep = {str(s).strip() for s in (keep_symbols or set())}
297
+ out = []
298
+ block_indent: Optional[int] = None
299
+ keep_block = False
300
+ folded = 0
301
+ for raw in code.splitlines():
302
+ if not raw.strip():
303
+ continue
304
+ indent = len(raw) - len(raw.lstrip(" "))
305
+ stripped = raw.strip()
306
+ if block_indent is not None:
307
+ if indent > block_indent:
308
+ if keep_block:
309
+ out.append(raw.rstrip())
310
+ else:
311
+ folded += 1
312
+ continue
313
+ if folded and not keep_block:
314
+ out.append(" " * block_indent + " # ...")
315
+ folded = 0
316
+ block_indent = None
317
+ keep_block = False
318
+ decl = cls._GD_FUNC_RE.match(stripped) or cls._GD_CLASS_RE.match(stripped)
319
+ if decl:
320
+ keep_block = bool(keep) and decl.group(1) in keep
321
+ block_indent = indent
322
+ out.append(raw.rstrip())
323
+ continue
324
+ if stripped.startswith("#") or cls._GD_DECL_RE.match(stripped):
325
+ out.append(raw.rstrip())
326
+ if folded and block_indent is not None and not keep_block:
327
+ out.append(" " * block_indent + " # ...")
328
+ return "\n".join(out)
329
+
279
330
  @classmethod
280
331
  def _skeletonize_python(cls, code: str, keep_symbols: Optional[Set[str]] = None) -> str:
281
332
  """Uses Python standard library `ast` to fold function bodies cleanly."""
@@ -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.16.0"
315
315
  }
316
316
  if active_key:
317
317
  headers["Authorization"] = f"Bearer {active_key}"