tokensafe 1.3.0 → 1.3.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.
@@ -0,0 +1,305 @@
1
+ """
2
+ TokenSafe Weekly Team ROI Digest Engine.
3
+ Generates automated weekly performance digests for engineering teamleads every Friday.
4
+ Aggregates:
5
+ - Total team tokens and USD saved over the past 7 days
6
+ - Engineer leaderboard ranking team members by token economy contribution
7
+ - Optimization category breakdown (Skeletons, Compactor, Deduplication, Sanitization)
8
+ - Formats Apple-style responsive dark-mode email and plain text versions
9
+ """
10
+
11
+ import os
12
+ import sys
13
+ import time
14
+ import json
15
+ import sqlite3
16
+ from typing import Dict, List, Any, Optional, Tuple
17
+
18
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+ DATA_DIR = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(PROJECT_ROOT, "data"))
20
+ CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
21
+
22
+ def format_token_number(n: int) -> str:
23
+ """Formats large token count into human-readable 1.2M, 450K, etc."""
24
+ if n >= 1_000_000:
25
+ return f"{n / 1_000_000:.1f}M"
26
+ if n >= 1_000:
27
+ return f"{n / 1_000:.1f}K"
28
+ return str(n)
29
+
30
+ class WeeklyDigestGenerator:
31
+ """Compiles weekly team ROI statistics and email templates."""
32
+
33
+ @classmethod
34
+ def get_team_weekly_stats(
35
+ cls,
36
+ owner_email: str,
37
+ now: Optional[int] = None,
38
+ db_path: str = CLOUD_DB_PATH
39
+ ) -> Optional[Dict[str, Any]]:
40
+ """
41
+ Retrieves 7-day telemetry for team owned by owner_email.
42
+ Returns aggregated digest data or None if no team records found.
43
+ """
44
+ now = now or int(time.time())
45
+ seven_days_ago = now - (7 * 86400)
46
+
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()
58
+
59
+ if not owner or owner["tier"] not in ("team", "enterprise"):
60
+ return None
61
+
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()
67
+
68
+ team_emails = {owner_email.lower()}
69
+ for lic in licenses:
70
+ if lic["customer_email"]:
71
+ team_emails.add(lic["customer_email"].lower())
72
+
73
+ placeholders = ",".join(["?"] * len(team_emails))
74
+ params = list(team_emails) + [seven_days_ago]
75
+
76
+ # 3. Aggregate 7-day telemetry
77
+ events = conn.execute(f"""
78
+ SELECT * FROM telemetry
79
+ WHERE customer_email IN ({placeholders}) AND timestamp >= ?
80
+ ORDER BY timestamp DESC;
81
+ """, params).fetchall()
82
+
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)
86
+ event_count = len(events)
87
+ reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 76.5
88
+
89
+ # 4. Engineer leaderboard
90
+ engineer_stats: Dict[str, Dict[str, Any]] = {}
91
+ for em in team_emails:
92
+ engineer_stats[em] = {
93
+ "email": em,
94
+ "saved_tokens": 0,
95
+ "original_tokens": 0,
96
+ "usd_saved": 0.0,
97
+ "event_count": 0
98
+ }
99
+
100
+ category_breakdown: Dict[str, int] = {}
101
+
102
+ for e in events:
103
+ em = e["customer_email"].lower()
104
+ if em not in engineer_stats:
105
+ engineer_stats[em] = {
106
+ "email": em,
107
+ "saved_tokens": 0,
108
+ "original_tokens": 0,
109
+ "usd_saved": 0.0,
110
+ "event_count": 0
111
+ }
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"]
115
+ engineer_stats[em]["event_count"] += 1
116
+
117
+ ev_type = e["event_type"]
118
+ category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + e["saved_tokens"]
119
+
120
+ leaderboard = sorted(
121
+ engineer_stats.values(),
122
+ key=lambda x: x["saved_tokens"],
123
+ reverse=True
124
+ )
125
+
126
+ # Assign ranks
127
+ for idx, eng in enumerate(leaderboard, 1):
128
+ eng["rank"] = idx
129
+ eng["saved_tokens_human"] = format_token_number(eng["saved_tokens"])
130
+ eng["usd_saved_formatted"] = f"${eng['usd_saved']:.2f}"
131
+
132
+ return {
133
+ "owner_email": owner_email,
134
+ "tier": owner["tier"],
135
+ "seats_total": owner["seats_total"],
136
+ "active_members_count": len([e for e in leaderboard if e["event_count"] > 0]),
137
+ "total_members_count": len(team_emails),
138
+ "total_original_tokens": total_orig,
139
+ "total_saved_tokens": total_saved,
140
+ "total_saved_human": format_token_number(total_saved),
141
+ "total_usd_saved": round(total_usd, 2),
142
+ "total_events": event_count,
143
+ "reduction_pct": reduction_pct,
144
+ "leaderboard": leaderboard,
145
+ "category_breakdown": category_breakdown,
146
+ "start_time": seven_days_ago,
147
+ "end_time": now
148
+ }
149
+ finally:
150
+ conn.close()
151
+
152
+ @classmethod
153
+ def render_email_html(cls, digest: Dict[str, Any]) -> str:
154
+ """Generates Apple-style responsive dark-mode HTML email."""
155
+ owner_email = digest["owner_email"]
156
+ total_saved_human = digest["total_saved_human"]
157
+ usd_saved = f"${digest['total_usd_saved']:.2f}"
158
+ reduction_pct = digest["reduction_pct"]
159
+ leaderboard = digest["leaderboard"]
160
+ seats_total = digest["seats_total"]
161
+ active_count = digest["active_members_count"]
162
+
163
+ # Build leaderboard rows
164
+ rows_html = ""
165
+ for eng in leaderboard[:10]:
166
+ rank = eng["rank"]
167
+ medal = "🥇 " if rank == 1 else "🥈 " if rank == 2 else "🥉 " if rank == 3 else f"#{rank} "
168
+ email_mask = eng["email"].split("@")[0] + "@..."
169
+ rows_html += f"""
170
+ <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
171
+ <td style="padding: 12px 8px; font-weight: 700; color: #10b981;">{medal}</td>
172
+ <td style="padding: 12px 8px; font-family: monospace; color: #e5e7eb; font-size: 13px;">{email_mask}</td>
173
+ <td style="padding: 12px 8px; text-align: right; font-weight: 700; color: #ffffff;">{eng['saved_tokens_human']}</td>
174
+ <td style="padding: 12px 8px; text-align: right; color: #10b981; font-weight: 600;">{eng['usd_saved_formatted']}</td>
175
+ </tr>
176
+ """
177
+
178
+ html = f"""<!DOCTYPE html>
179
+ <html>
180
+ <head>
181
+ <meta charset="utf-8">
182
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
183
+ <title>TokenSafe Weekly Team ROI Digest</title>
184
+ </head>
185
+ <body style="margin: 0; padding: 0; background-color: #030712; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #f3f4f6;">
186
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #030712; padding: 40px 16px;">
187
+ <tr>
188
+ <td align="center">
189
+ <table role="presentation" width="100%" style="max-width: 600px; background-color: #0f172a; border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 16px; padding: 32px; box-shadow: 0 20px 40px rgba(0,0,0,0.5);">
190
+
191
+ <!-- Header -->
192
+ <tr>
193
+ <td style="padding-bottom: 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.08);">
194
+ <span style="font-size: 20px; font-weight: 800; color: #ffffff; letter-spacing: -0.5px;">
195
+ Token<span style="color: #10b981;">Safe</span>
196
+ </span>
197
+ <span style="float: right; font-size: 11px; font-weight: 700; color: #10b981; background: rgba(16, 185, 129, 0.12); border: 1px solid rgba(16, 185, 129, 0.25); padding: 4px 10px; border-radius: 999px;">
198
+ WEEKLY DIGEST • FRIDAY
199
+ </span>
200
+ </td>
201
+ </tr>
202
+
203
+ <!-- Hero Headline -->
204
+ <tr>
205
+ <td style="padding: 28px 0 16px;">
206
+ <h1 style="margin: 0 0 8px; font-size: 24px; font-weight: 800; color: #ffffff; line-height: 1.3;">
207
+ TokenSafe saved your team <span style="color: #10b981;">{total_saved_human} tokens</span> ({usd_saved}) this week
208
+ </h1>
209
+ <p style="margin: 0; font-size: 14px; color: #94a3b8; line-height: 1.5;">
210
+ Friday engineering summary for <strong>{owner_email}</strong>. Active seats: {active_count}/{seats_total}.
211
+ </p>
212
+ </td>
213
+ </tr>
214
+
215
+ <!-- Key Metrics Grid -->
216
+ <tr>
217
+ <td style="padding: 12px 0 24px;">
218
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
219
+ <tr>
220
+ <td width="32%" style="background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 16px; text-align: center;">
221
+ <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Tokens Saved</div>
222
+ <div style="font-size: 22px; font-weight: 800; color: #10b981; margin-top: 4px;">{total_saved_human}</div>
223
+ </td>
224
+ <td width="2%"></td>
225
+ <td width="32%" style="background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 16px; text-align: center;">
226
+ <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Est. Cost Saved</div>
227
+ <div style="font-size: 22px; font-weight: 800; color: #ffffff; margin-top: 4px;">{usd_saved}</div>
228
+ </td>
229
+ <td width="2%"></td>
230
+ <td width="32%" style="background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 16px; text-align: center;">
231
+ <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Net Reduction</div>
232
+ <div style="font-size: 22px; font-weight: 800; color: #06b6d4; margin-top: 4px;">-{reduction_pct}%</div>
233
+ </td>
234
+ </tr>
235
+ </table>
236
+ </td>
237
+ </tr>
238
+
239
+ <!-- Leaderboard Table -->
240
+ <tr>
241
+ <td style="padding: 12px 0 20px;">
242
+ <h3 style="margin: 0 0 12px; font-size: 15px; font-weight: 700; color: #ffffff; text-transform: uppercase; letter-spacing: 0.5px;">
243
+ 🏆 Engineer Savings Leaderboard
244
+ </h3>
245
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse; background: rgba(0,0,0,0.2); border-radius: 10px; overflow: hidden;">
246
+ <thead>
247
+ <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.08); background: rgba(255, 255, 255, 0.02); font-size: 11px; color: #94a3b8; text-transform: uppercase;">
248
+ <th style="padding: 10px 8px; text-align: left;">Rank</th>
249
+ <th style="padding: 10px 8px; text-align: left;">Engineer</th>
250
+ <th style="padding: 10px 8px; text-align: right;">Saved</th>
251
+ <th style="padding: 10px 8px; text-align: right;">Value</th>
252
+ </tr>
253
+ </thead>
254
+ <tbody>
255
+ {rows_html}
256
+ </tbody>
257
+ </table>
258
+ </td>
259
+ </tr>
260
+
261
+ <!-- CTA Button -->
262
+ <tr>
263
+ <td style="padding: 24px 0 16px; text-align: center;">
264
+ <a href="https://tokensafe.dev/dashboard" style="display: inline-block; background: #10b981; color: #000000; font-weight: 700; font-size: 14px; text-decoration: none; padding: 14px 28px; border-radius: 10px; box-shadow: 0 4px 14px rgba(16, 185, 129, 0.35);">
265
+ Open Live Team Dashboard ➔
266
+ </a>
267
+ </td>
268
+ </tr>
269
+
270
+ <!-- Footer -->
271
+ <tr>
272
+ <td style="padding-top: 24px; border-top: 1px solid rgba(255, 255, 255, 0.06); font-size: 12px; color: #64748b; text-align: center;">
273
+ TokenSafe Enterprise • Automatic Friday ROI Digest • <a href="https://tokensafe.dev" style="color: #10b981; text-decoration: none;">tokensafe.dev</a>
274
+ </td>
275
+ </tr>
276
+
277
+ </table>
278
+ </td>
279
+ </tr>
280
+ </table>
281
+ </body>
282
+ </html>"""
283
+ return html
284
+
285
+ @classmethod
286
+ def render_email_text(cls, digest: Dict[str, Any]) -> str:
287
+ """Generates clean plain-text version for terminal or fallback."""
288
+ owner_email = digest["owner_email"]
289
+ total_saved = digest["total_saved_human"]
290
+ usd = f"${digest['total_usd_saved']:.2f}"
291
+ reduction = digest["reduction_pct"]
292
+
293
+ lines = [
294
+ f"⚡ TOKENSAFE WEEKLY TEAM ROI DIGEST",
295
+ f"Recipient: {owner_email}",
296
+ f"Period: Last 7 Days (Delivered Friday)\n",
297
+ f"TokenSafe saved your team {total_saved} tokens ({usd}) this week!",
298
+ f"Net Context Reduction: -{reduction}%\n",
299
+ f"--- 🏆 ENGINEER SAVINGS LEADERBOARD ---"
300
+ ]
301
+ for eng in digest["leaderboard"]:
302
+ lines.append(f"#{eng['rank']:<2} {eng['email']:<28} {eng['saved_tokens_human']:>8} ({eng['usd_saved_formatted']})")
303
+
304
+ lines.append(f"\nOpen your live dashboard: https://tokensafe.dev/dashboard")
305
+ return "\n".join(lines)