tokensafe 5.0.0 → 5.0.2
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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/assets/logo.svg +1 -13
- package/hooks/claude_code_hook.py +5 -1
- package/hooks/cursor_hook.py +1 -1
- package/kimi.plugin.json +3 -2
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -3
- package/server.json +3 -3
- package/skills/oumv-protocol/SKILL.md +59 -0
- package/skills/token-optimizer/SKILL.md +5 -3
- package/skills/token-optimizer/references/mcp-tools.md +1 -1
- package/tokensafe/adapter_core.py +62 -18
- package/tokensafe/atomic_io.py +20 -16
- package/tokensafe/auto_inject.py +2 -2
- package/tokensafe/backend_release.py +3 -3
- package/tokensafe/batch_editor.py +299 -10
- package/tokensafe/batch_search.py +53 -0
- package/tokensafe/bounded_flock.py +60 -0
- package/tokensafe/burn_monitor.py +60 -2
- package/tokensafe/call_context.py +158 -0
- package/tokensafe/cli.py +41 -13
- package/tokensafe/compactor.py +87 -5
- package/tokensafe/context_index.py +3 -0
- package/tokensafe/dashboard.py +119 -43
- package/tokensafe/environment_auditor.py +30 -2
- package/tokensafe/fts_index.py +3 -0
- package/tokensafe/graph_engine.py +246 -29
- package/tokensafe/installer.py +72 -13
- package/tokensafe/loop_detector.py +8 -20
- package/tokensafe/mcp_server.py +1084 -188
- package/tokensafe/metrics.py +173 -46
- package/tokensafe/oumv_brief.py +144 -8
- package/tokensafe/oumv_gateway.py +689 -222
- package/tokensafe/oumv_home.py +259 -0
- package/tokensafe/oumv_policy.py +64 -1
- package/tokensafe/proc_run.py +162 -0
- package/tokensafe/proxy.py +78 -8
- package/tokensafe/retrofit.py +484 -82
- package/tokensafe/route_index.py +2 -0
- package/tokensafe/savings.py +10 -2
- package/tokensafe/scoped_search.py +77 -0
- package/tokensafe/session_brief.py +17 -2
- package/tokensafe/stack_summary.py +73 -0
- package/tokensafe/syntax_guard.py +8 -2
- package/tokensafe/telemetry_sync.py +1 -1
- package/tokensafe/version_checker.py +1 -1
- package/tokensafe/web_reader.py +53 -4
- package/tokensafe/workspace_roots.py +127 -9
- package/assets/social/linkedin_banner.png +0 -0
- package/assets/social/tokensafe_logo_square.png +0 -0
package/tokensafe/metrics.py
CHANGED
|
@@ -46,8 +46,35 @@ ESTIMATED_EVENT_TYPES = frozenset({
|
|
|
46
46
|
"GUARD_JUNK_READ",
|
|
47
47
|
"GUARD_INFINITE",
|
|
48
48
|
"GUARD_RAW_CODE_SEARCH",
|
|
49
|
+
# Re-read mass of a stale file is a bytes/4 guess of a read that never ran.
|
|
50
|
+
"STALE_EDIT_ASK",
|
|
49
51
|
})
|
|
50
52
|
|
|
53
|
+
# PRAGMA user_version this module migrates to. v7 split the lifetime rollup
|
|
54
|
+
# into measured / estimated columns; mass rolled up before v7 has no reliable
|
|
55
|
+
# split and is reported as "legacy unclassified", never as measured.
|
|
56
|
+
SCHEMA_VERSION = 7
|
|
57
|
+
|
|
58
|
+
# Lifetime rollup split columns (user_version 7). Pre-v7 rollup mass is
|
|
59
|
+
# total_* minus these, i.e. legacy.
|
|
60
|
+
_LIFETIME_SPLIT_COLUMNS = (
|
|
61
|
+
("measured_original_tokens", "INTEGER NOT NULL DEFAULT 0"),
|
|
62
|
+
("measured_saved_tokens", "INTEGER NOT NULL DEFAULT 0"),
|
|
63
|
+
("measured_usd_saved", "REAL NOT NULL DEFAULT 0.0"),
|
|
64
|
+
("estimated_original_tokens", "INTEGER NOT NULL DEFAULT 0"),
|
|
65
|
+
("estimated_saved_tokens", "INTEGER NOT NULL DEFAULT 0"),
|
|
66
|
+
("estimated_usd_saved", "REAL NOT NULL DEFAULT 0.0"),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# v7 relabel: every GUARD_* event is a counterfactual (blocked payloads never
|
|
70
|
+
# reach the model) and STALE_EDIT_ASK is a bytes/4 guess; rows recorded before
|
|
71
|
+
# those rules existed carried the old 'measured' default.
|
|
72
|
+
_V7_RELABEL_SQL = (
|
|
73
|
+
"UPDATE events SET measurement = 'estimated' "
|
|
74
|
+
"WHERE measurement = 'measured' AND "
|
|
75
|
+
"(event_type LIKE 'GUARD\\_%' ESCAPE '\\' OR event_type = 'STALE_EDIT_ASK');"
|
|
76
|
+
)
|
|
77
|
+
|
|
51
78
|
def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
|
|
52
79
|
"""Resolves the measurement label for an event: explicit override wins,
|
|
53
80
|
then the GUARD_ counterfactual prefix (blocked payloads never reach the
|
|
@@ -59,6 +86,27 @@ def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
|
|
|
59
86
|
return "estimated"
|
|
60
87
|
return "estimated" if event_type in ESTIMATED_EVENT_TYPES else "measured"
|
|
61
88
|
|
|
89
|
+
|
|
90
|
+
def source_basis(event_type: str, data: Dict[str, Any]) -> str:
|
|
91
|
+
"""Honesty marker for one breakdown row: 'measured', 'estimated' or 'mixed'.
|
|
92
|
+
|
|
93
|
+
`data` is a breakdown entry ({saved, estimated_saved}). GUARD_* rows are
|
|
94
|
+
always estimated (any 'measured' share there is a pre-relabel legacy label);
|
|
95
|
+
otherwise the recorded split decides, falling back to the type's rule.
|
|
96
|
+
"""
|
|
97
|
+
rule = resolve_measurement(event_type)
|
|
98
|
+
if event_type.startswith("GUARD_"):
|
|
99
|
+
return "estimated"
|
|
100
|
+
saved = int((data or {}).get("saved", 0) or 0)
|
|
101
|
+
est = int((data or {}).get("estimated_saved", 0) or 0)
|
|
102
|
+
if saved <= 0:
|
|
103
|
+
return rule
|
|
104
|
+
if est >= saved:
|
|
105
|
+
return "estimated"
|
|
106
|
+
if est == 0:
|
|
107
|
+
return rule
|
|
108
|
+
return "mixed"
|
|
109
|
+
|
|
62
110
|
_METRICS_INIT_LOCK = threading.Lock()
|
|
63
111
|
_INITIALIZED_METRICS_DBS: set = set()
|
|
64
112
|
# Retention / telemetry cadence is wall-clock based (marker file) rather than
|
|
@@ -273,6 +321,20 @@ class MetricsTracker:
|
|
|
273
321
|
except sqlite3.OperationalError:
|
|
274
322
|
pass
|
|
275
323
|
|
|
324
|
+
@staticmethod
|
|
325
|
+
def _ensure_lifetime_split_columns(cursor) -> None:
|
|
326
|
+
"""Adds the user_version 7 measured/estimated rollup columns.
|
|
327
|
+
|
|
328
|
+
Idempotent: a duplicate column (or a legacy DB without the table)
|
|
329
|
+
raises OperationalError, swallowed per statement. Defaults are 0, so a
|
|
330
|
+
migrated database keeps its pre-v7 totals as legacy unclassified.
|
|
331
|
+
"""
|
|
332
|
+
for column, decl in _LIFETIME_SPLIT_COLUMNS:
|
|
333
|
+
try:
|
|
334
|
+
cursor.execute(f"ALTER TABLE lifetime_aggregates ADD COLUMN {column} {decl};")
|
|
335
|
+
except sqlite3.OperationalError:
|
|
336
|
+
pass
|
|
337
|
+
|
|
276
338
|
def _init_db(self):
|
|
277
339
|
with _METRICS_INIT_LOCK:
|
|
278
340
|
if self.db_path in _INITIALIZED_METRICS_DBS and os.path.exists(self.db_path) and os.path.getsize(self.db_path) > 0:
|
|
@@ -284,7 +346,7 @@ class MetricsTracker:
|
|
|
284
346
|
user_ver = int(uv_row[0]) if uv_row else 0
|
|
285
347
|
except Exception:
|
|
286
348
|
user_ver = 0
|
|
287
|
-
if user_ver >=
|
|
349
|
+
if user_ver >= SCHEMA_VERSION:
|
|
288
350
|
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
289
351
|
return
|
|
290
352
|
if user_ver >= 2:
|
|
@@ -329,8 +391,14 @@ class MetricsTracker:
|
|
|
329
391
|
# session's peak prompt, its host compactions and the
|
|
330
392
|
# uncached reads are what a long session is billed for.
|
|
331
393
|
self._ensure_usage_context_columns(cursor)
|
|
394
|
+
# user_version 7: measured/estimated lifetime split.
|
|
395
|
+
# New columns start at 0, so all pre-v7 rollup mass
|
|
396
|
+
# reads as legacy unclassified (total minus split).
|
|
397
|
+
self._ensure_lifetime_split_columns(cursor)
|
|
398
|
+
if user_ver < 7:
|
|
399
|
+
cursor.execute(_V7_RELABEL_SQL)
|
|
332
400
|
try:
|
|
333
|
-
cursor.execute("PRAGMA user_version =
|
|
401
|
+
cursor.execute(f"PRAGMA user_version = {SCHEMA_VERSION};")
|
|
334
402
|
except sqlite3.Error:
|
|
335
403
|
pass
|
|
336
404
|
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
@@ -383,6 +451,7 @@ class MetricsTracker:
|
|
|
383
451
|
"'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
|
|
384
452
|
"'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
|
|
385
453
|
)
|
|
454
|
+
cursor.execute(_V7_RELABEL_SQL)
|
|
386
455
|
cursor.execute("""
|
|
387
456
|
CREATE TABLE IF NOT EXISTS lifetime_aggregates (
|
|
388
457
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
@@ -394,9 +463,16 @@ class MetricsTracker:
|
|
|
394
463
|
breakdown TEXT DEFAULT '{}',
|
|
395
464
|
pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0,
|
|
396
465
|
pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0,
|
|
397
|
-
pruned_synced_usd REAL NOT NULL DEFAULT 0.0
|
|
466
|
+
pruned_synced_usd REAL NOT NULL DEFAULT 0.0,
|
|
467
|
+
measured_original_tokens INTEGER NOT NULL DEFAULT 0,
|
|
468
|
+
measured_saved_tokens INTEGER NOT NULL DEFAULT 0,
|
|
469
|
+
measured_usd_saved REAL NOT NULL DEFAULT 0.0,
|
|
470
|
+
estimated_original_tokens INTEGER NOT NULL DEFAULT 0,
|
|
471
|
+
estimated_saved_tokens INTEGER NOT NULL DEFAULT 0,
|
|
472
|
+
estimated_usd_saved REAL NOT NULL DEFAULT 0.0
|
|
398
473
|
)
|
|
399
474
|
""")
|
|
475
|
+
self._ensure_lifetime_split_columns(cursor)
|
|
400
476
|
for alter_sql in (
|
|
401
477
|
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0;",
|
|
402
478
|
"ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0;",
|
|
@@ -458,7 +534,7 @@ class MetricsTracker:
|
|
|
458
534
|
GROUP BY substr(timestamp, 1, 10)
|
|
459
535
|
""", (cutoff_30,))
|
|
460
536
|
try:
|
|
461
|
-
cursor.execute("PRAGMA user_version =
|
|
537
|
+
cursor.execute(f"PRAGMA user_version = {SCHEMA_VERSION};")
|
|
462
538
|
except sqlite3.Error:
|
|
463
539
|
pass
|
|
464
540
|
_INITIALIZED_METRICS_DBS.add(self.db_path)
|
|
@@ -487,32 +563,17 @@ class MetricsTracker:
|
|
|
487
563
|
os.makedirs(parent, exist_ok=True)
|
|
488
564
|
lock_path = mirror_path + ".lock"
|
|
489
565
|
fh = open(lock_path, "a+")
|
|
490
|
-
|
|
491
|
-
locked_win = False
|
|
566
|
+
kind = ""
|
|
492
567
|
try:
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
try:
|
|
499
|
-
import msvcrt
|
|
500
|
-
msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, 1)
|
|
501
|
-
locked_win = True
|
|
502
|
-
except Exception:
|
|
503
|
-
pass
|
|
568
|
+
# Bounded: the lock file is shared with hook processes, and a hung
|
|
569
|
+
# hook must not stall every tool call. Past 2 s the merge runs
|
|
570
|
+
# unlocked (as it already did where no lock primitive exists).
|
|
571
|
+
from tokensafe.bounded_flock import lock_file
|
|
572
|
+
kind = lock_file(fh, 2.0)
|
|
504
573
|
return mutate_fn()
|
|
505
574
|
finally:
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
import fcntl
|
|
509
|
-
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
|
510
|
-
elif locked_win:
|
|
511
|
-
import msvcrt
|
|
512
|
-
fh.seek(0)
|
|
513
|
-
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
|
|
514
|
-
except Exception:
|
|
515
|
-
pass
|
|
575
|
+
from tokensafe.bounded_flock import unlock_file
|
|
576
|
+
unlock_file(fh, kind)
|
|
516
577
|
fh.close()
|
|
517
578
|
|
|
518
579
|
def _sync_quota_mirror(self, day_key: str, delta_measured: int = 0) -> int:
|
|
@@ -740,16 +801,26 @@ class MetricsTracker:
|
|
|
740
801
|
def get_weekly_saved(self, days: int = 7) -> Dict[str, Any]:
|
|
741
802
|
"""Rolling-window savings totals for the quick `tokensafe status` view.
|
|
742
803
|
Reads raw events only (lifetime rollups have no timestamp and are
|
|
743
|
-
deliberately excluded — this is the recent-activity signal).
|
|
804
|
+
deliberately excluded — this is the recent-activity signal).
|
|
805
|
+
|
|
806
|
+
``events`` / ``saved_tokens`` / ``usd_saved`` are MEASURED only; the
|
|
807
|
+
counterfactual share is reported apart under the ``*_estimated`` keys."""
|
|
744
808
|
days = max(1, int(days))
|
|
745
809
|
cutoff = (datetime.now() - timedelta(days=days)).isoformat()
|
|
810
|
+
empty = {
|
|
811
|
+
"events": 0, "saved_tokens": 0, "usd_saved": 0.0,
|
|
812
|
+
"events_estimated": 0, "saved_tokens_estimated": 0, "usd_saved_estimated": 0.0,
|
|
813
|
+
}
|
|
746
814
|
try:
|
|
747
815
|
with self._get_connection() as conn:
|
|
748
816
|
row = conn.cursor().execute(
|
|
749
817
|
"""
|
|
750
|
-
SELECT
|
|
751
|
-
COALESCE(SUM(saved_tokens), 0) AS saved_tokens,
|
|
752
|
-
COALESCE(SUM(est_usd_saved), 0.0) AS usd_saved
|
|
818
|
+
SELECT COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 1 ELSE 0 END), 0) AS events,
|
|
819
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN saved_tokens ELSE 0 END), 0) AS saved_tokens,
|
|
820
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN est_usd_saved ELSE 0.0 END), 0.0) AS usd_saved,
|
|
821
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0 ELSE 1 END), 0) AS events_est,
|
|
822
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0 ELSE saved_tokens END), 0) AS saved_est,
|
|
823
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0.0 ELSE est_usd_saved END), 0.0) AS usd_est
|
|
753
824
|
FROM events
|
|
754
825
|
WHERE timestamp >= ? AND saved_tokens > 0
|
|
755
826
|
""", (cutoff,)
|
|
@@ -758,9 +829,12 @@ class MetricsTracker:
|
|
|
758
829
|
"events": int(row["events"] or 0),
|
|
759
830
|
"saved_tokens": int(row["saved_tokens"] or 0),
|
|
760
831
|
"usd_saved": round(float(row["usd_saved"] or 0.0), 4),
|
|
832
|
+
"events_estimated": int(row["events_est"] or 0),
|
|
833
|
+
"saved_tokens_estimated": int(row["saved_est"] or 0),
|
|
834
|
+
"usd_saved_estimated": round(float(row["usd_est"] or 0.0), 4),
|
|
761
835
|
}
|
|
762
836
|
except Exception:
|
|
763
|
-
return
|
|
837
|
+
return dict(empty)
|
|
764
838
|
|
|
765
839
|
def get_cache_obs(self, limit: int = 300) -> Dict[str, Any]:
|
|
766
840
|
"""Aggregates CACHE_OBS proxy events into clean-vs-mutated cache-hit
|
|
@@ -828,8 +902,19 @@ class MetricsTracker:
|
|
|
828
902
|
life_saved = life_row["total_saved_tokens"] if life_row else 0
|
|
829
903
|
life_usd = life_row["total_usd_saved"] if life_row else 0.0
|
|
830
904
|
life_breakdown = json.loads(life_row["breakdown"] or "{}") if life_row else {}
|
|
905
|
+
life_keys = set(life_row.keys()) if life_row else set()
|
|
831
906
|
|
|
832
|
-
|
|
907
|
+
def _life(col: str, default=0):
|
|
908
|
+
return (life_row[col] or default) if col in life_keys else default
|
|
909
|
+
|
|
910
|
+
life_m_orig = int(_life("measured_original_tokens"))
|
|
911
|
+
life_m_saved = int(_life("measured_saved_tokens"))
|
|
912
|
+
life_m_usd = float(_life("measured_usd_saved", 0.0))
|
|
913
|
+
life_e_orig = int(_life("estimated_original_tokens"))
|
|
914
|
+
life_e_saved = int(_life("estimated_saved_tokens"))
|
|
915
|
+
life_e_usd = float(_life("estimated_usd_saved", 0.0))
|
|
916
|
+
|
|
917
|
+
# 2. Active events (anything not labelled 'measured' counts as estimated)
|
|
833
918
|
cursor.execute("""
|
|
834
919
|
SELECT
|
|
835
920
|
COUNT(*) as active_events,
|
|
@@ -838,7 +923,10 @@ class MetricsTracker:
|
|
|
838
923
|
COALESCE(SUM(saved_tokens), 0) as active_saved,
|
|
839
924
|
COALESCE(SUM(est_usd_saved), 0.0) as active_usd,
|
|
840
925
|
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN saved_tokens ELSE 0 END), 0) as active_saved_measured,
|
|
841
|
-
COALESCE(SUM(CASE WHEN measurement = '
|
|
926
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0 ELSE saved_tokens END), 0) as active_saved_estimated,
|
|
927
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN original_tokens ELSE 0 END), 0) as active_orig_measured,
|
|
928
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN est_usd_saved ELSE 0.0 END), 0.0) as active_usd_measured,
|
|
929
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0.0 ELSE est_usd_saved END), 0.0) as active_usd_estimated
|
|
842
930
|
FROM events
|
|
843
931
|
""")
|
|
844
932
|
ev_row = cursor.fetchone()
|
|
@@ -873,16 +961,26 @@ class MetricsTracker:
|
|
|
873
961
|
total_usd = life_usd + (ev_row["active_usd"] if ev_row else 0.0)
|
|
874
962
|
overall_reduction = (total_saved / total_orig * 100.0) if total_orig > 0 else 0.0
|
|
875
963
|
|
|
876
|
-
# Honesty split
|
|
877
|
-
#
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
)
|
|
882
|
-
|
|
883
|
-
|
|
964
|
+
# Honesty split. Active events are split by their measurement column;
|
|
965
|
+
# the lifetime rollup by the user_version 7 split columns (filled by
|
|
966
|
+
# prune). Rollup mass from before v7 has no trustworthy split (labels
|
|
967
|
+
# were looser then), so it is reported as legacy unclassified — never
|
|
968
|
+
# folded into the measured figure.
|
|
969
|
+
def _ev(col: str, default=0):
|
|
970
|
+
return (ev_row[col] or default) if ev_row else default
|
|
971
|
+
|
|
972
|
+
saved_measured = int(_ev("active_saved_measured")) + life_m_saved
|
|
973
|
+
saved_estimated = int(_ev("active_saved_estimated")) + life_e_saved
|
|
974
|
+
saved_legacy = max(0, int(life_saved or 0) - life_m_saved - life_e_saved)
|
|
975
|
+
orig_measured = int(_ev("active_orig_measured")) + life_m_orig
|
|
976
|
+
orig_legacy = max(0, int(life_orig or 0) - life_m_orig - life_e_orig)
|
|
977
|
+
usd_measured = float(_ev("active_usd_measured", 0.0)) + life_m_usd
|
|
978
|
+
usd_estimated = float(_ev("active_usd_estimated", 0.0)) + life_e_usd
|
|
979
|
+
usd_legacy = max(0.0, float(life_usd or 0.0) - life_m_usd - life_e_usd)
|
|
980
|
+
measured_reduction = (saved_measured / orig_measured * 100.0) if orig_measured > 0 else 0.0
|
|
981
|
+
if saved_measured and (saved_estimated or saved_legacy):
|
|
884
982
|
savings_basis = "mixed"
|
|
885
|
-
elif saved_estimated:
|
|
983
|
+
elif saved_estimated or saved_legacy:
|
|
886
984
|
savings_basis = "estimated"
|
|
887
985
|
else:
|
|
888
986
|
savings_basis = "measured"
|
|
@@ -892,12 +990,21 @@ class MetricsTracker:
|
|
|
892
990
|
"total_events": total_events,
|
|
893
991
|
"total_original_tokens": total_orig,
|
|
894
992
|
"total_optimized_tokens": total_opt,
|
|
993
|
+
# Sum of measured + estimated + legacy: kept for API compatibility,
|
|
994
|
+
# never a headline (see dashboard.py).
|
|
895
995
|
"total_saved_tokens": total_saved,
|
|
896
996
|
"total_saved_tokens_measured": saved_measured,
|
|
897
997
|
"total_saved_tokens_estimated": saved_estimated,
|
|
998
|
+
"total_saved_tokens_legacy": saved_legacy,
|
|
898
999
|
"total_saved_tokens_basis": savings_basis,
|
|
1000
|
+
"total_original_tokens_measured": orig_measured,
|
|
1001
|
+
"total_original_tokens_legacy": orig_legacy,
|
|
1002
|
+
"measured_reduction_pct": round(measured_reduction, 1),
|
|
899
1003
|
"overall_reduction_pct": round(overall_reduction, 1),
|
|
900
1004
|
"total_usd_saved": round(total_usd, 4),
|
|
1005
|
+
"total_usd_saved_measured": round(usd_measured, 4),
|
|
1006
|
+
"total_usd_saved_estimated": round(usd_estimated, 4),
|
|
1007
|
+
"total_usd_saved_legacy": round(usd_legacy, 4),
|
|
901
1008
|
"total_usd_saved_approx": True, # USD is a derived estimate (~$3.0/M Claude Sonnet baseline), never a bill
|
|
902
1009
|
"by_agent": self.get_by_agent(),
|
|
903
1010
|
"breakdown": combined_breakdown
|
|
@@ -1192,7 +1299,13 @@ class MetricsTracker:
|
|
|
1192
1299
|
COALESCE(SUM(original_tokens), 0) as orig,
|
|
1193
1300
|
COALESCE(SUM(optimized_tokens), 0) as opt,
|
|
1194
1301
|
COALESCE(SUM(saved_tokens), 0) as saved,
|
|
1195
|
-
COALESCE(SUM(est_usd_saved), 0.0) as usd
|
|
1302
|
+
COALESCE(SUM(est_usd_saved), 0.0) as usd,
|
|
1303
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN original_tokens ELSE 0 END), 0) as m_orig,
|
|
1304
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN saved_tokens ELSE 0 END), 0) as m_saved,
|
|
1305
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN est_usd_saved ELSE 0.0 END), 0.0) as m_usd,
|
|
1306
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0 ELSE original_tokens END), 0) as e_orig,
|
|
1307
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0 ELSE saved_tokens END), 0) as e_saved,
|
|
1308
|
+
COALESCE(SUM(CASE WHEN measurement = 'measured' THEN 0.0 ELSE est_usd_saved END), 0.0) as e_usd
|
|
1196
1309
|
FROM events
|
|
1197
1310
|
WHERE {combined_where}
|
|
1198
1311
|
""", params)
|
|
@@ -1266,13 +1379,21 @@ class MetricsTracker:
|
|
|
1266
1379
|
breakdown = ?,
|
|
1267
1380
|
pruned_synced_orig_tokens = COALESCE(pruned_synced_orig_tokens, 0) + ?,
|
|
1268
1381
|
pruned_synced_saved_tokens = COALESCE(pruned_synced_saved_tokens, 0) + ?,
|
|
1269
|
-
pruned_synced_usd = COALESCE(pruned_synced_usd, 0.0) +
|
|
1382
|
+
pruned_synced_usd = COALESCE(pruned_synced_usd, 0.0) + ?,
|
|
1383
|
+
measured_original_tokens = COALESCE(measured_original_tokens, 0) + ?,
|
|
1384
|
+
measured_saved_tokens = COALESCE(measured_saved_tokens, 0) + ?,
|
|
1385
|
+
measured_usd_saved = COALESCE(measured_usd_saved, 0.0) + ?,
|
|
1386
|
+
estimated_original_tokens = COALESCE(estimated_original_tokens, 0) + ?,
|
|
1387
|
+
estimated_saved_tokens = COALESCE(estimated_saved_tokens, 0) + ?,
|
|
1388
|
+
estimated_usd_saved = COALESCE(estimated_usd_saved, 0.0) + ?
|
|
1270
1389
|
WHERE id = 1
|
|
1271
1390
|
""", (
|
|
1272
1391
|
agg_row["cnt"], agg_row["orig"], agg_row["opt"],
|
|
1273
1392
|
agg_row["saved"], agg_row["usd"],
|
|
1274
1393
|
json.dumps(current_breakdown, ensure_ascii=False),
|
|
1275
1394
|
synced_orig, synced_saved, synced_usd,
|
|
1395
|
+
agg_row["m_orig"], agg_row["m_saved"], agg_row["m_usd"],
|
|
1396
|
+
agg_row["e_orig"], agg_row["e_saved"], agg_row["e_usd"],
|
|
1276
1397
|
))
|
|
1277
1398
|
|
|
1278
1399
|
# 5. Delete pruned events
|
|
@@ -1326,7 +1447,13 @@ class MetricsTracker:
|
|
|
1326
1447
|
breakdown = '{}',
|
|
1327
1448
|
pruned_synced_orig_tokens = 0,
|
|
1328
1449
|
pruned_synced_saved_tokens = 0,
|
|
1329
|
-
pruned_synced_usd = 0.0
|
|
1450
|
+
pruned_synced_usd = 0.0,
|
|
1451
|
+
measured_original_tokens = 0,
|
|
1452
|
+
measured_saved_tokens = 0,
|
|
1453
|
+
measured_usd_saved = 0.0,
|
|
1454
|
+
estimated_original_tokens = 0,
|
|
1455
|
+
estimated_saved_tokens = 0,
|
|
1456
|
+
estimated_usd_saved = 0.0
|
|
1330
1457
|
WHERE id = 1
|
|
1331
1458
|
""")
|
|
1332
1459
|
self.vacuum()
|
package/tokensafe/oumv_brief.py
CHANGED
|
@@ -41,6 +41,126 @@ def _braced_block(code: str, open_idx: int) -> Optional[str]:
|
|
|
41
41
|
return None
|
|
42
42
|
|
|
43
43
|
|
|
44
|
+
_DESTRUCTURE_LEAD_RE = re.compile(r"^\s*(?:\(\s*|function\s*[\w$]*\s*(?:<[^>]*>)?\s*\(\s*)?$")
|
|
45
|
+
_OPENERS = {"{": "}", "[": "]", "(": ")", "<": ">"}
|
|
46
|
+
_CLOSERS = {v: k for k, v in _OPENERS.items()}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _strip_js_comments(text: str) -> str:
|
|
50
|
+
"""Drops `//` and `/* */` comments; string and template literals are kept."""
|
|
51
|
+
out: List[str] = []
|
|
52
|
+
i, n = 0, len(text)
|
|
53
|
+
quote: Optional[str] = None
|
|
54
|
+
while i < n:
|
|
55
|
+
ch = text[i]
|
|
56
|
+
if quote:
|
|
57
|
+
out.append(ch)
|
|
58
|
+
if ch == "\\" and i + 1 < n:
|
|
59
|
+
out.append(text[i + 1])
|
|
60
|
+
i += 2
|
|
61
|
+
continue
|
|
62
|
+
if ch == quote:
|
|
63
|
+
quote = None
|
|
64
|
+
i += 1
|
|
65
|
+
continue
|
|
66
|
+
if ch in ("'", '"', "`"):
|
|
67
|
+
quote = ch
|
|
68
|
+
out.append(ch)
|
|
69
|
+
i += 1
|
|
70
|
+
continue
|
|
71
|
+
if text.startswith("//", i):
|
|
72
|
+
end = text.find("\n", i)
|
|
73
|
+
i = n if end == -1 else end
|
|
74
|
+
continue
|
|
75
|
+
if text.startswith("/*", i):
|
|
76
|
+
end = text.find("*/", i + 2)
|
|
77
|
+
i = n if end == -1 else end + 2
|
|
78
|
+
out.append(" ")
|
|
79
|
+
continue
|
|
80
|
+
out.append(ch)
|
|
81
|
+
i += 1
|
|
82
|
+
return "".join(out)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _scan_top_level(text: str):
|
|
86
|
+
"""Yields (index, char, depth) outside string literals; `=>` is not a `>`."""
|
|
87
|
+
depth = 0
|
|
88
|
+
quote: Optional[str] = None
|
|
89
|
+
i, n = 0, len(text)
|
|
90
|
+
while i < n:
|
|
91
|
+
ch = text[i]
|
|
92
|
+
if quote:
|
|
93
|
+
if ch == "\\":
|
|
94
|
+
i += 2
|
|
95
|
+
continue
|
|
96
|
+
if ch == quote:
|
|
97
|
+
quote = None
|
|
98
|
+
i += 1
|
|
99
|
+
continue
|
|
100
|
+
if ch in ("'", '"', "`"):
|
|
101
|
+
quote = ch
|
|
102
|
+
elif ch in _OPENERS:
|
|
103
|
+
depth += 1
|
|
104
|
+
elif ch in _CLOSERS and not (ch == ">" and i > 0 and text[i - 1] == "="):
|
|
105
|
+
depth = max(0, depth - 1)
|
|
106
|
+
yield i, ch, depth
|
|
107
|
+
i += 1
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _split_top_level(text: str, sep: str) -> List[str]:
|
|
111
|
+
"""Splits on `sep` outside (), [], {}, <> and string literals."""
|
|
112
|
+
parts: List[str] = []
|
|
113
|
+
start = 0
|
|
114
|
+
for i, ch, depth in _scan_top_level(text):
|
|
115
|
+
if ch == sep and depth == 0:
|
|
116
|
+
parts.append(text[start:i])
|
|
117
|
+
start = i + 1
|
|
118
|
+
parts.append(text[start:])
|
|
119
|
+
return parts
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _top_level_index(text: str, ch_wanted: str) -> int:
|
|
123
|
+
for i, ch, depth in _scan_top_level(text):
|
|
124
|
+
if ch == ch_wanted and depth == 0:
|
|
125
|
+
if ch_wanted == "=" and (text[i + 1:i + 2] in ("=", ">") or text[i - 1:i] in ("!", "<", ">", "=")):
|
|
126
|
+
continue
|
|
127
|
+
return i
|
|
128
|
+
return -1
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _js_braced_block(code: str, open_idx: int) -> Optional[str]:
|
|
132
|
+
"""Like `_braced_block`, but braces inside strings and comments do not count."""
|
|
133
|
+
depth = 0
|
|
134
|
+
i, n = open_idx, len(code)
|
|
135
|
+
quote: Optional[str] = None
|
|
136
|
+
while i < n:
|
|
137
|
+
ch = code[i]
|
|
138
|
+
if quote:
|
|
139
|
+
if ch == "\\":
|
|
140
|
+
i += 2
|
|
141
|
+
continue
|
|
142
|
+
if ch == quote:
|
|
143
|
+
quote = None
|
|
144
|
+
elif ch in ("'", '"', "`"):
|
|
145
|
+
quote = ch
|
|
146
|
+
elif code.startswith("//", i):
|
|
147
|
+
end = code.find("\n", i)
|
|
148
|
+
i = n if end == -1 else end
|
|
149
|
+
continue
|
|
150
|
+
elif code.startswith("/*", i):
|
|
151
|
+
end = code.find("*/", i + 2)
|
|
152
|
+
i = n if end == -1 else end + 2
|
|
153
|
+
continue
|
|
154
|
+
elif ch == "{":
|
|
155
|
+
depth += 1
|
|
156
|
+
elif ch == "}":
|
|
157
|
+
depth -= 1
|
|
158
|
+
if depth == 0:
|
|
159
|
+
return code[open_idx + 1:i]
|
|
160
|
+
i += 1
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
|
|
44
164
|
def _parse_members(body: str) -> List[Dict[str, Any]]:
|
|
45
165
|
members: List[Dict[str, Any]] = []
|
|
46
166
|
for raw_line in body.splitlines():
|
|
@@ -101,22 +221,30 @@ def _extract_public_props(code: str, component_names: List[str]) -> Optional[Dic
|
|
|
101
221
|
open_idx = code.find("{", decl.end())
|
|
102
222
|
if open_idx == -1:
|
|
103
223
|
continue
|
|
104
|
-
|
|
105
|
-
|
|
224
|
+
# The brace must open the first parameter (`Foo({` / `memo(({` /
|
|
225
|
+
# `memo(function Foo({`), never the function body of `Foo(props) {`.
|
|
226
|
+
if not _DESTRUCTURE_LEAD_RE.match(_strip_js_comments(code[decl.end():open_idx])):
|
|
227
|
+
continue
|
|
228
|
+
body = _js_braced_block(code, open_idx)
|
|
229
|
+
if not body:
|
|
106
230
|
continue
|
|
107
231
|
members: List[Dict[str, Any]] = []
|
|
108
|
-
for part in body
|
|
109
|
-
part = part.
|
|
232
|
+
for part in _split_top_level(_strip_js_comments(body), ","):
|
|
233
|
+
part = " ".join(part.split())
|
|
110
234
|
if not part or part.startswith("..."):
|
|
111
235
|
continue
|
|
112
|
-
|
|
236
|
+
colon = _top_level_index(part, ":")
|
|
237
|
+
equals = _top_level_index(part, "=")
|
|
238
|
+
cut = min(i for i in (colon, equals, len(part)) if i >= 0)
|
|
239
|
+
raw_name = part[:cut].strip()
|
|
113
240
|
if not re.match(r"^[A-Za-z_$][\w$]*$", raw_name):
|
|
114
241
|
continue
|
|
115
|
-
|
|
116
|
-
|
|
242
|
+
type_str = ""
|
|
243
|
+
if colon >= 0 and (equals < 0 or colon < equals):
|
|
244
|
+
type_str = part[colon + 1:equals if equals > colon else len(part)].strip()
|
|
117
245
|
members.append({
|
|
118
246
|
"name": raw_name,
|
|
119
|
-
"optional":
|
|
247
|
+
"optional": equals >= 0,
|
|
120
248
|
"type": type_str or "unknown",
|
|
121
249
|
})
|
|
122
250
|
if members:
|
|
@@ -261,6 +389,14 @@ def build_brief(workspace: str, target: str, symbol: Optional[str] = None) -> Di
|
|
|
261
389
|
|
|
262
390
|
graph = GraphEngine.get_instance(workspace)
|
|
263
391
|
graph.scan()
|
|
392
|
+
# One graph version for the whole brief: tool calls run concurrently, and a
|
|
393
|
+
# rescan publishing between two lookups mixed file_symbols of one version
|
|
394
|
+
# with symbols of another.
|
|
395
|
+
with graph.snapshot():
|
|
396
|
+
return _build_brief_from_graph(graph, raw, symbol, evidence)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _build_brief_from_graph(graph: Any, raw: str, symbol: Optional[str], evidence: Dict[str, Any]) -> Dict[str, Any]:
|
|
264
400
|
rel = graph._as_repo_rel(raw)
|
|
265
401
|
target_symbol = (symbol or "").strip() or None
|
|
266
402
|
warnings: List[str] = []
|