tokensafe 2.1.0 → 2.2.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/bin/tokensafe.js CHANGED
@@ -57,6 +57,7 @@ Commands:
57
57
  tokensafe vacuum Compact SQLite metrics database storage
58
58
  tokensafe prune Prune granular telemetry events into lifetime rollup
59
59
  tokensafe digest Preview or send weekly team ROI digest email
60
+ tokensafe tests Run the unit test suite (compact failure report)
60
61
  tokensafe activate <key> Activate commercial Solo or Team seat license key
61
62
  tokensafe license Show current license status and active tier
62
63
  tokensafe update One-click self-update for npm, pip & all AI agent rules
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.1.0",
4
+ "version": "2.2.0",
5
5
  "description": "Local-first AI coding guardrails, context slicing, and team ROI telemetry 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": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.1.0",
4
+ "version": "2.2.0",
5
5
  "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
6
- "version": "2.1.0",
6
+ "version": "2.2.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/NekoSin4eG/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.1.0",
33
+ "version": "2.2.0",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "2.1.0",
49
+ "version": "2.2.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -152,7 +152,7 @@ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
152
152
 
153
153
  | Guard Check | Monitored Operation | Action Taken |
154
154
  |---|---|---|
155
- | **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `smart_read_file` |
155
+ | **RAW_CODE_SEARCH** | Terminal `grep`, `egrep`, `rg`, `find` on source code | **Blocked** (`decision: deny`), directs to `scoped_search` / `smart_read_file` |
156
156
  | **SECRET_FALLBACK** | Hardcoded secrets in `os.environ.get()` / `process.env` | **Blocked** (`decision: deny`), prevents credential commit |
157
157
  | **TLS_VERIFY_BYPASS** | Insecure TLS bypass (`verify=False` / `rejectUnauthorized: false`) | **Blocked** (`decision: deny`), MitM attack prevention |
158
158
  | **SQL_INJECTION** | Unsafe f-string / template string interpolation in queries | **Blocked** (`decision: deny`), enforces parameterized queries |
@@ -160,9 +160,9 @@ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
160
160
  | **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
161
161
  | **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
162
162
  | **PACKAGE_TYPOSQUAT** | Installing known typosquatted packages | **Warning** injected into turn context |
163
- | **INFINITE_STREAM** (adapters) | Never-terminating commands: `tail -f`, `watch`, `docker attach`, `docker/kubectl logs -f` | **Asked** (`decision: ask`) — intentional runs proceed via confirmation |
163
+ | **INFINITE_STREAM** (adapters) | Never-terminating commands: `tail -f`, `watch`, `docker attach`, `docker/kubectl logs -f`, `vitest` (watch by default — use `vitest run`), `jest`/`vitest --watch` | **Asked** (`decision: ask`) — intentional runs proceed via confirmation |
164
164
 
165
- Adapter-level checks (Claude Code / Cursor / ZCode hooks) classify command-level TLS bypass (`curl -k`, `git -c http.sslVerify=false`, `GIT_SSL_NO_VERIFY=1`) and infinite streams as `ask` — TokenSafe Guard's code-level checks above remain `deny`.
165
+ Adapter-level checks (Claude Code / Cursor / ZCode hooks) classify command-level TLS bypass (`curl -k`, `git -c http.sslVerify=false`, `GIT_SSL_NO_VERIFY=1`) and infinite streams as `ask`, and hard-deny raw recursive code search (`grep -rn src/`, `rg`, `find` over source trees) as `RAW_CODE_SEARCH` with a redirect to `tokensafe:scoped_search` — TokenSafe Guard's code-level checks above remain `deny`.
166
166
 
167
167
  ---
168
168
 
@@ -194,6 +194,7 @@ tokensafe --version # Print version and exit (no metrics side effects)
194
194
  tokensafe stats # View terminal report with tokens saved & USD ROI
195
195
  tokensafe html # Launch interactive Apple-style HTML dashboard
196
196
  tokensafe benchmark # Run the zero-context-loss benchmark suite (simulated SWE-bench harness; see BENCHMARK_REPORT.md)
197
+ tokensafe tests [pytest] # Run the unit test suite (compact failure report; --traceback for full stacks)
197
198
 
198
199
  # Code Intelligence & Architecture
199
200
  tokensafe graph [path] # Inspect God Nodes and centrality ranking
@@ -54,6 +54,9 @@ _INFINITE_PATTERNS = [
54
54
  r"\bdocker\s+logs\b[^|;&]*\s(?:-f\b|--follow)",
55
55
  r"\bkubectl\s+logs\b[^|;&]*\s-f\b",
56
56
  r"\bdocker\s+attach\b",
57
+ # vitest runs an interactive watcher unless the `run` subcommand is given
58
+ r"\bvitest\b(?![^|;&]*\brun\b)",
59
+ r"\b(?:jest|vitest)\b[^|;&]*--watch\b",
57
60
  ]
58
61
 
59
62
  # Lockfiles/junk that must never be dumped into an agent context.
@@ -141,6 +144,20 @@ def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, A
141
144
  if re.search(pat, text):
142
145
  blocked("DESTRUCTIVE", "Blocked: irreversible/destructive operation")
143
146
  return result
147
+ # RAW_CODE_SEARCH (deny): recursive grep/rg/find crawls over source trees
148
+ # are the exact workflow the tokensafe MCP tools replace. TokenSafeGuard
149
+ # already enforces this on the Antigravity path (inspect_command) — share
150
+ # its check here so Claude Code / Cursor adapters honor the same policy
151
+ # with the same "use tokensafe:scoped_search" guidance. Fail-open on
152
+ # import problems, like every adapter guard path.
153
+ try:
154
+ from src.guard import TokenSafeGuard
155
+ search_err = TokenSafeGuard._check_raw_code_search(cmd)
156
+ except Exception:
157
+ search_err = None
158
+ if search_err:
159
+ blocked("RAW_CODE_SEARCH", search_err)
160
+ return result
144
161
  for pat in _TLS_BYPASS_PATTERNS:
145
162
  if re.search(pat, text):
146
163
  blocked("TLS_VERIFY_BYPASS", "Certificate verification disabled — confirm this is intentional", decision="ask")
package/src/cli.py CHANGED
@@ -21,6 +21,77 @@ from src.dashboard import Dashboard, render_bar
21
21
  from src.compactor import PromptCompactor
22
22
  from src.tokenizer import count_tokens
23
23
 
24
+ def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
25
+ """Compacts `python3 -m unittest discover` output to what a developer
26
+ actually needs: one green line, or per-failure test name + root cause.
27
+ Keeps the suite run out of the context window (the raw output of a
28
+ 300+ test run with tracebacks is thousands of tokens)."""
29
+ lines = raw.splitlines()
30
+ ran = status = ""
31
+ for ln in lines:
32
+ s = ln.strip()
33
+ if s.startswith("Ran ") and " test" in s:
34
+ ran = s
35
+ elif s == "OK" or s.startswith("FAILED"):
36
+ status = s
37
+ # Failure blocks: one '=' * 70 line PER failure, then the title line,
38
+ # a '-' * 70 rule and the traceback — each block is self-contained.
39
+ blocks, cur = [], None
40
+ for ln in lines:
41
+ if len(ln) >= 10 and set(ln) == {"="}:
42
+ if cur is not None:
43
+ blocks.append(cur)
44
+ cur = []
45
+ continue
46
+ if cur is not None:
47
+ cur.append(ln)
48
+ if cur is not None:
49
+ blocks.append(cur)
50
+
51
+ failures = []
52
+ for block in blocks:
53
+ title_idx = next((j for j, l in enumerate(block) if l.startswith(("FAIL: ", "ERROR: "))), None)
54
+ if title_idx is None:
55
+ continue
56
+ title = block[title_idx]
57
+ body = [l for l in block[title_idx + 1:]
58
+ if not (len(l) >= 10 and set(l) == {"-"})
59
+ and not l.strip().startswith(("Ran ", "FAILED", "OK"))]
60
+ kind, name = title.split(" ", 1)
61
+ if full_traceback:
62
+ detail = [l.rstrip() for l in body if l.strip()]
63
+ else:
64
+ loc = next((l.strip() for l in reversed(body) if l.strip().startswith('File "')), "")
65
+ cause_lines = [l.strip() for l in reversed(body)
66
+ if l.strip() and not l.strip().startswith('File "')
67
+ and not l.strip().startswith(("self.", "assert", "raise"))]
68
+ # assertEqual-style failures end with a diff block ('- a' / '+ b');
69
+ # the actual AssertionError line sits above it.
70
+ cause = next((l for l in cause_lines if not l.startswith(("+", "-", "?", "!"))),
71
+ cause_lines[0] if cause_lines else "")
72
+ if len(cause) > 200:
73
+ cause = cause[:200] + " …"
74
+ detail = [l for l in (loc, cause) if l]
75
+ failures.append((kind.rstrip(": "), name, detail))
76
+
77
+ if not ran and not failures:
78
+ # Crash before unittest could report (import error, bad path):
79
+ # fall back to the tail, which carries the exception.
80
+ tail = [l for l in lines if l.strip()][-15:]
81
+ return "\n".join(tail) if tail else "(no unittest output captured)"
82
+
83
+ if status == "OK":
84
+ return f"\033[32m✓ {ran} — all tests passed\033[0m"
85
+
86
+ out = [f"\033[31m✗ {ran} — {status}\033[0m"]
87
+ for kind, name, detail in failures:
88
+ out.append(f" \033[31m{kind}\033[0m {name}")
89
+ for d in detail:
90
+ out.append(f" {d}")
91
+ out.append("Full output: python3 -m unittest discover tests (or: tokensafe tests --traceback)")
92
+ return "\n".join(out)
93
+
94
+
24
95
  def main():
25
96
  args = sys.argv[1:]
26
97
  command = args[0] if args else "stats"
@@ -352,6 +423,39 @@ def main():
352
423
  print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
353
424
  print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
354
425
 
426
+ elif command in ("tests", "testsuite", "unittest"):
427
+ tests_dir = os.path.join(PROJECT_ROOT, "tests")
428
+ if not os.path.isdir(tests_dir):
429
+ print("No tests/ directory found — run from a repository checkout "
430
+ "(installed packages do not ship the unit-test suite).")
431
+ sys.exit(1)
432
+ verbose = "--verbose" in args or "-v" in args
433
+ full_tb = "--traceback" in args or "-tb" in args
434
+ launcher = next((a for a in args[1:] if not a.startswith("-")), "unittest")
435
+ if launcher == "unittest":
436
+ cmd = [sys.executable, "-m", "unittest", "discover", "tests"]
437
+ elif launcher == "pytest":
438
+ # pytest is natively compact with quiet flags; the wrapper
439
+ # guarantees them instead of trusting the caller.
440
+ cmd = [sys.executable, "-m", "pytest", "-q", "--tb=short"]
441
+ else:
442
+ print(f"Unknown test launcher '{launcher}' — supported: unittest (default), pytest.")
443
+ sys.exit(1)
444
+ print(f"\n⚡ Running the unit test suite ({launcher})...")
445
+ try:
446
+ proc = subprocess.run(cmd, cwd=PROJECT_ROOT, capture_output=True, text=True)
447
+ except FileNotFoundError:
448
+ print(f"Launcher '{launcher}' is not available — install it (e.g. pip install pytest) and retry.")
449
+ sys.exit(1)
450
+ raw = (proc.stdout or "") + (proc.stderr or "")
451
+ if verbose:
452
+ print(raw)
453
+ elif launcher == "pytest":
454
+ print(raw.rstrip() or "(no output)")
455
+ else:
456
+ print(summarize_unittest_output(raw, full_traceback=full_tb))
457
+ sys.exit(proc.returncode)
458
+
355
459
  elif command in ("prune", "cleanup"):
356
460
  days = None
357
461
  max_events = None
@@ -468,6 +572,7 @@ def main():
468
572
  print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
469
573
  print(" guard <command> Pre-flight safety check for a shell command")
470
574
  print(" doctor Audit MCP tool overhead and token tax")
575
+ print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
471
576
  print(" prune [--days N | --max N] Compact metrics database (roll old events)")
472
577
  print(" vacuum Reclaim SQLite disk space")
473
578
  print(" reset Reset all local token metrics")
@@ -480,7 +585,7 @@ def main():
480
585
  print(" --version Print version and exit")
481
586
  sys.exit(0)
482
587
  print(f"Unknown command: {command}")
483
- print("Available commands: stats, sync, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
588
+ print("Available commands: stats, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
484
589
  sys.exit(1)
485
590
 
486
591
  if __name__ == "__main__":
package/src/guard.py CHANGED
@@ -331,7 +331,9 @@ class TokenSafeGuard:
331
331
  if grep_match:
332
332
  has_code_ext = any(ext in sub_cmd for ext in cls.CODE_EXTENSIONS)
333
333
  has_code_dir = any(re.search(rf'\b{re.escape(d)}(?:/|\b)', sub_cmd) for d in cls.CODE_DIRS)
334
- is_recursive_all = bool(re.search(r'\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]\b', sub_cmd)) or \
334
+ # '-rn' / '-Rn' are the canonical recursive forms — the flag
335
+ # regex must accept letters after r/R, plus the long --recursive.
336
+ is_recursive_all = bool(re.search(r'\b(grep|egrep)\b.*?\s(?:-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b', sub_cmd)) or \
335
337
  bool(re.search(r'\brg\b', sub_cmd))
336
338
 
337
339
  if has_code_ext or has_code_dir or is_recursive_all:
package/src/installer.py CHANGED
@@ -40,7 +40,7 @@ UNIFIED_TOKENSAFE_RULE = (
40
40
  "2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. It preserves the full executable target and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
41
41
  "3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
42
42
  "4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
43
- "5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage.\n"
43
+ "5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; never leave `vitest`/`jest` in watch mode.\n"
44
44
  "6. **Proof-of-Savings Turn Footer (always in English)**:\n"
45
45
  "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
46
46
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
package/src/mcp_server.py CHANGED
@@ -39,7 +39,7 @@ from src.scoped_search import ScopedSearch
39
39
 
40
40
  SERVER_INFO = {
41
41
  "name": "tokensafe-mcp",
42
- "version": "2.1.0"
42
+ "version": "2.2.0"
43
43
  }
44
44
 
45
45
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -130,7 +130,8 @@ TOOLS = [
130
130
  "name": "sanitize_command",
131
131
  "description": "Per-stage shell command rewrites: prunes lockfiles, caps unbounded git log/show/blame/rg "
132
132
  "and docker/kubectl logs, quiets npm/pip installs, bounds cat/curl output. Compound commands "
133
- "(a && b ; c) are optimized per stage without breaking operators.",
133
+ "(a && b ; c) are optimized per stage without breaking operators. For unit-test runs prefer "
134
+ "the `tests` CLI wrapper (tokensafe tests [pytest]) over raw `python3 -m unittest discover`.",
134
135
  "inputSchema": {
135
136
  "type": "object",
136
137
  "properties": {
package/src/metrics.py CHANGED
@@ -39,6 +39,7 @@ ESTIMATED_EVENT_TYPES = frozenset({
39
39
  "GUARD_TLS_VERIFY_BYPASS",
40
40
  "GUARD_JUNK_READ",
41
41
  "GUARD_INFINITE",
42
+ "GUARD_RAW_CODE_SEARCH",
42
43
  })
43
44
 
44
45
  def resolve_measurement(event_type: str, explicit: Optional[str] = None) -> str:
@@ -176,7 +177,8 @@ class MetricsTracker:
176
177
  "('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
177
178
  "'COMMAND_FILTER', 'LOOP_GUARD', 'GUARD_SECRET', "
178
179
  "'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
179
- "'GUARD_JUNK_READ', 'GUARD_INFINITE');"
180
+ "'GUARD_JUNK_READ', 'GUARD_INFINITE', "
181
+ "'GUARD_RAW_CODE_SEARCH');"
180
182
  )
181
183
  cursor.execute("""
182
184
  CREATE TABLE IF NOT EXISTS lifetime_aggregates (
@@ -264,7 +264,7 @@ class TelemetrySync:
264
264
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
265
265
  headers = {
266
266
  "Content-Type": "application/json",
267
- "User-Agent": "TokenSafe-Sync/2.1.0"
267
+ "User-Agent": "TokenSafe-Sync/2.2.0"
268
268
  }
269
269
  if active_key:
270
270
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.1.0"
19
+ CURRENT_VERSION = "2.2.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage
@@ -10,15 +10,46 @@ Aggregates:
10
10
 
11
11
  import os
12
12
  import sys
13
+ import html as _html
13
14
  import time
14
15
  import json
15
16
  import sqlite3
17
+ from contextlib import contextmanager
16
18
  from typing import Dict, List, Any, Optional, Tuple
17
19
 
18
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
21
  DATA_DIR = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(PROJECT_ROOT, "data"))
20
22
  CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
21
23
 
24
+
25
+ @contextmanager
26
+ def _open_digest_db(db_path: str):
27
+ """Yields BunnyDB/cloud connection for default DB path, or local sqlite3 for custom paths."""
28
+ if db_path == CLOUD_DB_PATH:
29
+ try:
30
+ from src.cloud.db import get_db_connection
31
+ from src.cloud.config import BUNNY_DB_URL, BUNNY_DB_TOKEN, CLOUD_DB_PATH as CLOUD_CFG_DB_PATH
32
+
33
+ if (BUNNY_DB_URL and BUNNY_DB_TOKEN) or os.path.exists(CLOUD_CFG_DB_PATH):
34
+ with get_db_connection() as conn:
35
+ yield conn
36
+ return
37
+ yield None
38
+ return
39
+ except ImportError:
40
+ pass
41
+
42
+ if not os.path.exists(db_path):
43
+ yield None
44
+ return
45
+
46
+ conn = sqlite3.connect(db_path)
47
+ conn.row_factory = sqlite3.Row
48
+ try:
49
+ yield conn
50
+ finally:
51
+ conn.close()
52
+
22
53
  def format_token_number(n: int) -> str:
23
54
  """Formats large token count into human-readable 1.2M, 450K, etc."""
24
55
  if n >= 1_000_000:
@@ -35,56 +66,100 @@ class WeeklyDigestGenerator:
35
66
  cls,
36
67
  owner_email: str,
37
68
  now: Optional[int] = None,
38
- db_path: str = CLOUD_DB_PATH
69
+ db_path: str = CLOUD_DB_PATH,
70
+ allow_any_tier: bool = False
39
71
  ) -> Optional[Dict[str, Any]]:
40
72
  """
41
73
  Retrieves 7-day telemetry for team owned by owner_email.
42
- Returns aggregated digest data or None if no team records found.
74
+ Supports both BunnyDB (cloud) and local SQLite databases.
75
+ Returns aggregated digest data or None if no eligible records found.
43
76
  """
77
+ clean_email = (owner_email or "").strip().lower()
78
+ if not clean_email or "@" not in clean_email:
79
+ return None
80
+
44
81
  now = now or int(time.time())
45
82
  seven_days_ago = now - (7 * 86400)
46
83
 
47
- if not os.path.exists(db_path):
48
- return None
49
-
50
- conn = sqlite3.connect(db_path)
51
- conn.row_factory = sqlite3.Row
52
- try:
53
- # 1. Verify owner and tier
54
- owner = conn.execute("""
55
- SELECT * FROM customers
56
- WHERE email = ? AND status = 'active';
57
- """, (owner_email.lower(),)).fetchone()
84
+ with _open_digest_db(db_path) as conn:
85
+ if conn is None:
86
+ return None
58
87
 
59
- if not owner or owner["tier"] not in ("team", "enterprise"):
88
+ # 1. Verify owner and active team/enterprise entitlement across customers & organizations
89
+ owner = conn.execute(
90
+ "SELECT * FROM customers WHERE email = ?;",
91
+ (clean_email,),
92
+ ).fetchone()
93
+
94
+ orgs = []
95
+ try:
96
+ orgs = conn.execute(
97
+ "SELECT * FROM organizations WHERE owner_email = ? AND status = 'active' ORDER BY is_primary DESC, created_at ASC;",
98
+ (clean_email,),
99
+ ).fetchall()
100
+ except sqlite3.OperationalError:
101
+ orgs = []
102
+
103
+ cust_active = bool(owner and str(owner["status"] or "").lower() == "active")
104
+ cust_tier = str(owner["tier"] or "").lower() if owner else ""
105
+ team_orgs = [o for o in orgs if str(o["tier"] or "").lower() in ("team", "enterprise")]
106
+
107
+ if team_orgs:
108
+ effective_tier = str(team_orgs[0]["tier"] or "team").lower()
109
+ effective_seats = sum(int(o["seats_total"] or 1) for o in team_orgs)
110
+ elif cust_active and cust_tier in ("team", "enterprise"):
111
+ effective_tier = cust_tier
112
+ effective_seats = int(owner["seats_total"] or 1)
113
+ elif allow_any_tier and (cust_active or orgs):
114
+ if orgs:
115
+ effective_tier = str(orgs[0]["tier"] or cust_tier or "solo").lower()
116
+ effective_seats = int(orgs[0]["seats_total"] or 1)
117
+ else:
118
+ effective_tier = cust_tier or "solo"
119
+ effective_seats = int(owner["seats_total"] or 1)
120
+ else:
60
121
  return None
61
122
 
62
- # 2. Find all member emails and license keys in this team
63
- licenses = conn.execute("""
64
- SELECT * FROM licenses
65
- WHERE parent_email = ? OR customer_email = ?;
66
- """, (owner_email.lower(), owner_email.lower())).fetchall()
123
+ # 2. Find all member emails and license keys in this team / owned organizations
124
+ licenses = conn.execute(
125
+ "SELECT * FROM licenses WHERE parent_email = ? OR customer_email = ?;",
126
+ (clean_email, clean_email),
127
+ ).fetchall()
67
128
 
68
- team_emails = {owner_email.lower()}
129
+ team_emails = {clean_email}
69
130
  for lic in licenses:
70
131
  if lic["customer_email"]:
71
- team_emails.add(lic["customer_email"].lower())
132
+ team_emails.add(str(lic["customer_email"]).strip().lower())
133
+
134
+ org_ids = [o["id"] for o in (team_orgs if team_orgs else orgs) if o["id"]]
135
+ if org_ids:
136
+ org_placeholders = ",".join(["?"] * len(org_ids))
137
+ org_lics = conn.execute(
138
+ f"SELECT customer_email FROM licenses WHERE org_id IN ({org_placeholders});",
139
+ org_ids,
140
+ ).fetchall()
141
+ for lic in org_lics:
142
+ if lic["customer_email"]:
143
+ team_emails.add(str(lic["customer_email"]).strip().lower())
72
144
 
73
145
  placeholders = ",".join(["?"] * len(team_emails))
74
146
  params = list(team_emails) + [seven_days_ago]
75
147
 
76
148
  # 3. Aggregate 7-day telemetry
77
- events = conn.execute(f"""
78
- SELECT * FROM telemetry
149
+ events = conn.execute(
150
+ f"""
151
+ SELECT * FROM telemetry
79
152
  WHERE customer_email IN ({placeholders}) AND timestamp >= ?
80
153
  ORDER BY timestamp DESC;
81
- """, params).fetchall()
154
+ """,
155
+ params,
156
+ ).fetchall()
82
157
 
83
- total_orig = sum(e["original_tokens"] for e in events)
84
- total_saved = sum(e["saved_tokens"] for e in events)
85
- total_usd = sum(e["usd_saved"] for e in events)
158
+ total_orig = sum(int(e["original_tokens"] or 0) for e in events)
159
+ total_saved = sum(int(e["saved_tokens"] or 0) for e in events)
160
+ total_usd = sum(float(e["usd_saved"] or 0.0) for e in events)
86
161
  event_count = len(events)
87
- reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 76.5
162
+ reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 0.0
88
163
 
89
164
  # 4. Engineer leaderboard
90
165
  engineer_stats: Dict[str, Dict[str, Any]] = {}
@@ -100,7 +175,7 @@ class WeeklyDigestGenerator:
100
175
  category_breakdown: Dict[str, int] = {}
101
176
 
102
177
  for e in events:
103
- em = e["customer_email"].lower()
178
+ em = str(e["customer_email"] or clean_email).strip().lower()
104
179
  if em not in engineer_stats:
105
180
  engineer_stats[em] = {
106
181
  "email": em,
@@ -109,13 +184,16 @@ class WeeklyDigestGenerator:
109
184
  "usd_saved": 0.0,
110
185
  "event_count": 0
111
186
  }
112
- engineer_stats[em]["saved_tokens"] += e["saved_tokens"]
113
- engineer_stats[em]["original_tokens"] += e["original_tokens"]
114
- engineer_stats[em]["usd_saved"] += e["usd_saved"]
187
+ saved_toks = int(e["saved_tokens"] or 0)
188
+ orig_toks = int(e["original_tokens"] or 0)
189
+ usd_val = float(e["usd_saved"] or 0.0)
190
+ engineer_stats[em]["saved_tokens"] += saved_toks
191
+ engineer_stats[em]["original_tokens"] += orig_toks
192
+ engineer_stats[em]["usd_saved"] += usd_val
115
193
  engineer_stats[em]["event_count"] += 1
116
194
 
117
- ev_type = e["event_type"]
118
- category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + e["saved_tokens"]
195
+ ev_type = str(e["event_type"] or "PROMPT")
196
+ category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + saved_toks
119
197
 
120
198
  leaderboard = sorted(
121
199
  engineer_stats.values(),
@@ -130,9 +208,9 @@ class WeeklyDigestGenerator:
130
208
  eng["usd_saved_formatted"] = f"${eng['usd_saved']:.2f}"
131
209
 
132
210
  return {
133
- "owner_email": owner_email,
134
- "tier": owner["tier"],
135
- "seats_total": owner["seats_total"],
211
+ "owner_email": clean_email,
212
+ "tier": effective_tier,
213
+ "seats_total": effective_seats,
136
214
  "active_members_count": len([e for e in leaderboard if e["event_count"] > 0]),
137
215
  "total_members_count": len(team_emails),
138
216
  "total_original_tokens": total_orig,
@@ -146,14 +224,12 @@ class WeeklyDigestGenerator:
146
224
  "start_time": seven_days_ago,
147
225
  "end_time": now
148
226
  }
149
- finally:
150
- conn.close()
151
227
 
152
228
  @classmethod
153
229
  def render_email_html(cls, digest: Dict[str, Any]) -> str:
154
230
  """Generates Apple-style responsive dark-mode HTML email."""
155
- owner_email = digest["owner_email"]
156
- total_saved_human = digest["total_saved_human"]
231
+ owner_email = _html.escape(str(digest["owner_email"]))
232
+ total_saved_human = _html.escape(str(digest["total_saved_human"]))
157
233
  usd_saved = f"${digest['total_usd_saved']:.2f}"
158
234
  reduction_pct = digest["reduction_pct"]
159
235
  leaderboard = digest["leaderboard"]
@@ -165,7 +241,7 @@ class WeeklyDigestGenerator:
165
241
  for eng in leaderboard[:10]:
166
242
  rank = eng["rank"]
167
243
  medal = "🥇 " if rank == 1 else "🥈 " if rank == 2 else "🥉 " if rank == 3 else f"#{rank} "
168
- email_mask = eng["email"].split("@")[0] + "@..."
244
+ email_mask = _html.escape(eng["email"].split("@")[0] + "@...")
169
245
  rows_html += f"""
170
246
  <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
171
247
  <td style="padding: 12px 8px; font-weight: 700; color: #10b981;">{medal}</td>