tokensafe 4.1.4 → 4.1.6

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/README.md CHANGED
@@ -6,9 +6,9 @@
6
6
  <!-- mcp-name: dev.tokensafe/tokensafe -->
7
7
 
8
8
  <p align="center">
9
- <b>Make AI coding agents 3x faster without burning team quotas.</b><br>
10
- Exact code context. Fewer tokens. Safer changes.<br>
11
- TokenSafe intercepts AI tool calls locally, replacing thousands of lines of irrelevant code with precise function bodies and typed signatures. Preserve prompt caches and protect secrets before they reach your AI transcripts.<br>
9
+ <b>Your coding agent isn't getting dumber. Your context is just full of trash.</b><br>
10
+ When chat sessions fill up with massive lockfiles and endless build logs, your AI loses focus.<br>
11
+ TokenSafe strips the noise with Tree-sitter AST slicing so your agent stays razor-sharp, changes only the lines you asked for, and never leaks your secrets.<br>
12
12
  Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
13
13
  </p>
14
14
 
@@ -231,8 +231,8 @@ def handle(event: str, payload: dict) -> dict:
231
231
  return {
232
232
  "decision": "block",
233
233
  "reason": (
234
- f"[TokenSafe] {tool} succeeded (exit 0) — verbose stdout auto-compacted "
235
- f"({orig:,} → {new:,} chars). Command already completed; do not retry. Summary:\n{compacted}"
234
+ f"[TokenSafe] {tool} output auto-compacted "
235
+ f"({orig:,} → {new:,} chars). Output summary:\n{compacted}"
236
236
  ),
237
237
  }
238
238
  return {}
@@ -61,8 +61,9 @@ def main():
61
61
  workspace_paths = raw_ws if isinstance(raw_ws, list) else []
62
62
  workspace_root = str(workspace_paths[0]) if workspace_paths else os.getcwd()
63
63
  try:
64
- from src.paths import save_active_workspace
64
+ from src.paths import save_active_workspace, ensure_tokensafe_gitignore
65
65
  save_active_workspace(workspace_root)
66
+ ensure_tokensafe_gitignore(workspace_root)
66
67
  except Exception:
67
68
  pass
68
69
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.1.4",
5
- "description": "Make AI coding agents 3x faster without burning team quotas. Exact code context. Fewer tokens. Safer changes.",
4
+ "version": "4.1.6",
5
+ "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
8
8
  "tokensafe": "bin/tokensafe.js"
@@ -14,6 +14,7 @@
14
14
  "src/",
15
15
  "!src/cloud_backend.py",
16
16
  "!src/mailer.py",
17
+ "!src/weekly_digest.py",
17
18
  "!**/__pycache__/**",
18
19
  "!**/*.pyc",
19
20
  "rules/",
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.1.4",
4
+ "version": "4.1.6",
5
5
  "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
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": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "4.1.4",
6
+ "version": "4.1.6",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "4.1.4",
33
+ "version": "4.1.6",
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": "4.1.4",
49
+ "version": "4.1.6",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -153,6 +153,16 @@ class BuildOutputParser:
153
153
  error_lines.append(ln)
154
154
 
155
155
  result = "\n".join(error_lines).strip()
156
+ # If the build failure contains TypeScript compiler error cascades (e.g. vue-tsc, vite build type error),
157
+ # compact using CompilerErrorCompactor to save massive token cascades.
158
+ try:
159
+ from src.format_parsers.compiler_errors import CompilerErrorCompactor
160
+ if CompilerErrorCompactor.is_tsc_output(result or cleaned):
161
+ compacted_tsc, was_tsc = CompilerErrorCompactor.compact_tsc(result or cleaned)
162
+ if was_tsc:
163
+ return compacted_tsc, True
164
+ except Exception:
165
+ pass
156
166
  return result or cleaned.strip(), True
157
167
 
158
168
  @classmethod
package/src/cli.py CHANGED
@@ -105,7 +105,6 @@ def _print_help():
105
105
  print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
106
106
  print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
107
107
  print(" test <prompt> Preview TOCP S-expression prompt compaction")
108
- print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
109
108
  print(" guard <command> Pre-flight safety check for a shell command")
110
109
  print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
111
110
  print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
@@ -1022,6 +1021,27 @@ def main(argv: Optional[List[str]] = None):
1022
1021
  print(compacted_build)
1023
1022
  sys.exit(proc.returncode)
1024
1023
 
1024
+ # Container build reducer (docker build, docker compose build)
1025
+ try:
1026
+ from src.format_parsers.docker_k8s import ContainerAndK8sReducer
1027
+ compacted_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
1028
+ if was_docker:
1029
+ print(compacted_docker)
1030
+ sys.exit(proc.returncode)
1031
+ except Exception:
1032
+ pass
1033
+
1034
+ # Structured NDJSON / JSON log reducer
1035
+ try:
1036
+ from src.format_parsers.json_log import JSONLogReducer
1037
+ if JSONLogReducer.is_ndjson_log(raw):
1038
+ compacted_logs, was_logs = JSONLogReducer.reduce(raw)
1039
+ if was_logs:
1040
+ print(compacted_logs)
1041
+ sys.exit(proc.returncode)
1042
+ except Exception:
1043
+ pass
1044
+
1025
1045
  lines = raw.splitlines()
1026
1046
  if len(lines) > 40:
1027
1047
  head = lines[:15]
@@ -1110,69 +1130,6 @@ def main(argv: Optional[List[str]] = None):
1110
1130
  b_after = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
1111
1131
  print(f"\033[32m✔ Database compacted + session aggregates rebuilt. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
1112
1132
 
1113
- elif command in ("digest", "weekly-digest"):
1114
- from src.weekly_digest import WeeklyDigestGenerator
1115
-
1116
- target_email = None
1117
- do_send = "--send" in args
1118
-
1119
- idx = 1
1120
- while idx < len(args):
1121
- a = args[idx]
1122
- if a.startswith("--email="):
1123
- target_email = a.split("=", 1)[1].strip()
1124
- elif a == "--email" and idx + 1 < len(args):
1125
- target_email = args[idx + 1].strip()
1126
- idx += 1
1127
- idx += 1
1128
-
1129
- if not target_email:
1130
- from src.license_manager import LicenseManager
1131
- _, payload = LicenseManager.get_active_license()
1132
- target_email = payload.get("email") or "teamlead@example.com"
1133
-
1134
- print(f"\n\033[1m\033[36m⚡ COMPILING FRIDAY TEAM ROI DIGEST ⚡\033[0m")
1135
- print(f"Target Teamlead: {target_email}")
1136
-
1137
- stats = WeeklyDigestGenerator.get_team_weekly_stats(target_email)
1138
- if not stats:
1139
- stats = {
1140
- "owner_email": target_email,
1141
- "tier": "team",
1142
- "seats_total": 1,
1143
- "active_members_count": 0,
1144
- "total_members_count": 0,
1145
- "total_original_tokens": 0,
1146
- "total_saved_tokens": 0,
1147
- "total_saved_human": "0",
1148
- "total_usd_saved": 0.0,
1149
- "total_events": 0,
1150
- "reduction_pct": 0.0,
1151
- "leaderboard": [],
1152
- }
1153
-
1154
- print(WeeklyDigestGenerator.render_email_text(stats))
1155
-
1156
- from src.paths import resolve_data_dir
1157
- out_html = os.path.join(resolve_data_dir(), "weekly_digest_preview.html")
1158
- os.makedirs(os.path.dirname(out_html), exist_ok=True)
1159
- with open(out_html, "w", encoding="utf-8") as f:
1160
- f.write(WeeklyDigestGenerator.render_email_html(stats))
1161
- print(f"\n📧 Apple-style email HTML preview generated at: {out_html}")
1162
-
1163
- if do_send:
1164
- try:
1165
- from src.mailer import TokenSafeMailer
1166
- ok = TokenSafeMailer.send_weekly_digest(target_email, stats, sync=True)
1167
- if ok:
1168
- print(f"\033[32m✔ Weekly digest successfully dispatched to {target_email}!\033[0m\n")
1169
- else:
1170
- print(f"\033[33m○ Digest dispatch queued (SMTP_PASS not configured in local environment).\033[0m\n")
1171
- except ImportError:
1172
- print("\n\033[33m○ Email delivery is handled by TokenSafe Cloud; preview HTML saved locally.\033[0m\n")
1173
- else:
1174
- print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
1175
-
1176
1133
  elif command in ("expand-ref", "expand_ref", "expand"):
1177
1134
  if len(args) < 2:
1178
1135
  print("Usage: tokensafe expand-ref <hash8>")
@@ -540,6 +540,10 @@ class CommandSanitizer:
540
540
  return None
541
541
 
542
542
  is_build = False
543
+ saved = 1800
544
+ reason = "Wrapped build command with tokensafe wrap to fold progress noise and asset tables"
545
+
546
+ # 1. Build commands
543
547
  if cmd_tok == "npm":
544
548
  is_build = any(a in ("build", "build:prod", "build:cloud") or a.startswith("build:") for a in cmd_args) or (
545
549
  "run" in cmd_args and any("build" in a for a in cmd_args)
@@ -555,6 +559,37 @@ class CommandSanitizer:
555
559
  elif cmd_tok == "cargo" and cmd_args[:1] == ["build"]:
556
560
  is_build = True
557
561
 
562
+ # 2. TypeScript compiler & type-checking commands (tsc, npx tsc, npm run typecheck)
563
+ if not is_build:
564
+ if cmd_tok == "tsc":
565
+ is_build = True
566
+ saved = 2500
567
+ reason = "Wrapped TypeScript compiler command with tokensafe wrap to compact error cascades"
568
+ elif cmd_tok in ("npx", "bunx") and "tsc" in cmd_args:
569
+ is_build = True
570
+ saved = 2500
571
+ reason = f"Wrapped {cmd_tok} tsc command with tokensafe wrap to compact error cascades"
572
+ elif cmd_tok in ("npm", "yarn", "pnpm", "bun"):
573
+ typecheck_hit = any(
574
+ a in ("typecheck", "type-check", "tsc", "check-types") or "typecheck" in a or "type-check" in a
575
+ for a in cmd_args
576
+ )
577
+ if typecheck_hit:
578
+ is_build = True
579
+ saved = 2500
580
+ reason = f"Wrapped {cmd_tok} typecheck command with tokensafe wrap to compact error cascades"
581
+
582
+ # 3. Linter commands (eslint, npx eslint, biome, npx biome)
583
+ if not is_build:
584
+ if cmd_tok in ("eslint", "biome"):
585
+ is_build = True
586
+ saved = 1500
587
+ reason = f"Wrapped {cmd_tok} linter command with tokensafe wrap to bound output"
588
+ elif cmd_tok in ("npx", "bunx") and any(a in ("eslint", "biome") for a in cmd_args):
589
+ is_build = True
590
+ saved = 1500
591
+ reason = f"Wrapped {cmd_tok} linter command with tokensafe wrap to bound output"
592
+
558
593
  if not is_build:
559
594
  return None
560
595
 
@@ -562,15 +597,21 @@ class CommandSanitizer:
562
597
  import shutil
563
598
  has_tokensafe = bool(shutil.which("tokensafe"))
564
599
  if not has_tokensafe:
565
- bin_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe")
566
- if os.path.exists(bin_path):
567
- has_tokensafe = True
600
+ for candidate in (
601
+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe"),
602
+ os.path.expanduser("~/.tokensafe/bin/tokensafe"),
603
+ os.path.expanduser("~/.local/bin/tokensafe"),
604
+ "/usr/local/bin/tokensafe"
605
+ ):
606
+ if os.path.exists(candidate):
607
+ has_tokensafe = True
608
+ break
568
609
 
569
610
  if not has_tokensafe:
570
611
  return None
571
612
 
572
613
  wrapped = f"tokensafe wrap {shlex.quote(stage)}"
573
- return wrapped, 1800, "Wrapped build command with tokensafe wrap to fold progress noise and asset tables", None
614
+ return wrapped, saved, reason, None
574
615
 
575
616
  @classmethod
576
617
  def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
@@ -787,6 +828,17 @@ class CommandSanitizer:
787
828
  return None
788
829
  resolved_exit = 0
789
830
  elif resolved_exit != 0:
831
+ # Check test & compiler error compactor first (tsc error cascades, pytest failures)
832
+ from src.test_parsers import TestOutputParser
833
+ compacted_test, was_test = TestOutputParser.compact(raw)
834
+ if was_test and len(compacted_test) < len(raw) * 0.85:
835
+ return compacted_test, len(raw), len(compacted_test)
836
+
837
+ from src.build_parsers import BuildOutputParser
838
+ compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
839
+ if was_build and len(compacted_build) < len(raw) * 0.85:
840
+ return compacted_build, len(raw), len(compacted_build)
841
+
790
842
  # Failed run: failure noise (progress dots / blank runs / verbose PASSED lines)
791
843
  # is stripped while every traceback frame stays intact; skip when it saves <15%.
792
844
  stripped = cls._strip_failure_noise(raw)
package/src/fts_index.py CHANGED
@@ -13,6 +13,7 @@ import os
13
13
  import sqlite3
14
14
  import time
15
15
  import hashlib
16
+ import shutil
16
17
  from typing import List, Dict, Any, Optional, Tuple
17
18
 
18
19
  from src.paths import resolve_data_dir
@@ -41,18 +42,36 @@ CODE_EXTS = {
41
42
  }
42
43
 
43
44
 
45
+ from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
46
+
47
+
44
48
  def _resolve_fts_db_path(project_root: str) -> str:
45
- """Returns path to the SQLite FTS database for a project."""
46
- # Check if project has a .tokensafe directory
49
+ """Returns path to the SQLite FTS database for a project.
50
+
51
+ Always stores index in global user cache ~/.tokensafe/cache/fts/<project_hash>.db
52
+ so the project working tree is never polluted with binary database files.
53
+ """
54
+ ensure_tokensafe_gitignore(project_root)
55
+
56
+ # Legacy cleanup: if fts.db was mistakenly created in project .tokensafe, migrate or remove
47
57
  proj_tokensafe = os.path.join(project_root, ".tokensafe")
48
- if os.path.isdir(proj_tokensafe):
49
- return os.path.join(proj_tokensafe, "fts.db")
58
+ legacy_file = os.path.join(proj_tokensafe, "fts.db")
50
59
 
51
- # Otherwise store in ~/.tokensafe/cache/fts/<project_hash>.db
52
60
  cache_dir = os.path.join(resolve_data_dir(), "cache", "fts")
53
61
  os.makedirs(cache_dir, exist_ok=True)
54
62
  p_hash = hashlib.sha256(os.path.abspath(project_root).encode("utf-8")).hexdigest()[:16]
55
- return os.path.join(cache_dir, f"fts_{p_hash}.db")
63
+ target_path = os.path.join(cache_dir, f"fts_{p_hash}.db")
64
+
65
+ if os.path.isfile(legacy_file) and not os.path.isfile(target_path):
66
+ try:
67
+ shutil.move(legacy_file, target_path)
68
+ for extra in (f"{legacy_file}-wal", f"{legacy_file}-shm"):
69
+ if os.path.isfile(extra):
70
+ os.remove(extra)
71
+ except Exception:
72
+ pass
73
+
74
+ return target_path
56
75
 
57
76
 
58
77
  class CodeFTSIndex:
package/src/installer.py CHANGED
@@ -53,7 +53,7 @@ UNIFIED_TOKENSAFE_RULE = (
53
53
  "5. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path='.')` before exploratory multi-file reading (`project_path` defaults to active workspace). Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
54
54
  "6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path='.')` to get all exported classes, types, and interfaces in a single markdown map without crawling files.\n"
55
55
  "7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path='.', depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path='src'`).\n"
56
- "8. **Command Sanitization, Build Compaction & Compact Tests**: 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`, and build commands like `npm run build`, `vite build`, `next build`, `cargo build`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 3-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
56
+ "8. **Command Sanitization, Build Compaction & Compact Tests**: 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`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 3-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
57
57
  "9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
58
58
  "10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage and Context Quality Score (Grade S-F); when it reports `warning` or `critical` (or Grade C/F), call `tokensafe:compact_conversation(transcript_path=...)` to fold history into a State Ledger with a 3-line Post-Compaction Orientation Digest before continuing.\n"
59
59
  "11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
@@ -1016,6 +1016,13 @@ WantedBy=default.target
1016
1016
  cls._write_agents_plugins_config(project_dir, agents_plugin_path)
1017
1017
  created.append(".agents/plugins.json")
1018
1018
 
1019
+ try:
1020
+ from src.paths import ensure_tokensafe_gitignore
1021
+ if ensure_tokensafe_gitignore(project_dir):
1022
+ created.append(".gitignore (.tokensafe/ registered)")
1023
+ except Exception:
1024
+ pass
1025
+
1019
1026
  return {
1020
1027
  "success": True,
1021
1028
  "project_dir": project_dir,
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.1.4"
45
+ "version": "4.1.6"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -189,9 +189,9 @@ TOOLS = [
189
189
  "type": "object",
190
190
  "properties": {
191
191
  "command": {"type": "string", "description": "Raw bash command line"},
192
+ "cmd": {"type": "string", "description": "Alias for command"},
192
193
  "cwd": {"type": "string", "description": "Optional working directory the command will run in; enables the package.json peek that identifies the runner behind opaque yarn/npm test scripts"}
193
- },
194
- "required": ["command"]
194
+ }
195
195
  }
196
196
  },
197
197
  {
@@ -221,6 +221,7 @@ TOOLS = [
221
221
  "type": "object",
222
222
  "properties": {
223
223
  "command": {"type": "string", "description": "Optional: Terminal command line to audit"},
224
+ "cmd": {"type": "string", "description": "Alias for command"},
224
225
  "code": {"type": "string", "description": "Optional: Code snippet, replacement diff, or file content to audit"},
225
226
  "file_path": {"type": "string", "description": "Optional: File path being written or modified"}
226
227
  }
@@ -735,8 +736,8 @@ def handle_tool_call(name: str, args: dict) -> dict:
735
736
  if name == "smart_read_file" and isinstance(result, dict) and not result.get("isError"):
736
737
  content_parts = result.get("content") or []
737
738
  text_out = "".join(p.get("text", "") for p in content_parts if isinstance(p, dict))
738
- path = args.get("path", "")
739
- symbol = (args.get("symbol") or "").strip()
739
+ path = args.get("path") or args.get("file_path") or args.get("file") or ""
740
+ symbol = (args.get("symbol") or args.get("sym") or args.get("target") or "").strip()
740
741
  _, eff_dep_mode = _resolve_dep_mode(args)
741
742
  cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
742
743
  is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
@@ -779,8 +780,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
779
780
  is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
780
781
 
781
782
  if name == "smart_read_file":
782
- path = args.get("path", "")
783
- symbol = args.get("symbol", "")
783
+ path = args.get("path") or args.get("file_path") or args.get("file") or ""
784
+ symbol = args.get("symbol") or args.get("sym") or args.get("target") or ""
784
785
  inc_deps, eff_dep_mode = _resolve_dep_mode(args)
785
786
  force_full = bool(args.get("force_full", False))
786
787
  start_line = args.get("start_line")
@@ -880,6 +881,49 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
880
881
  except Exception:
881
882
  pass
882
883
 
884
+ # Kubernetes manifests (.yaml / .yml with multiple resources):
885
+ if path.lower().endswith((".yaml", ".yml")):
886
+ from src.format_parsers.docker_k8s import ContainerAndK8sReducer
887
+ try:
888
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
889
+ raw_k8s_text = f.read()
890
+ reduced_k8s, was_k8s = ContainerAndK8sReducer.reduce_k8s_yaml(raw_k8s_text)
891
+ if was_k8s:
892
+ orig_t = count_tokens(raw_k8s_text)
893
+ opt_t = count_tokens(reduced_k8s)
894
+ tracker.record_event(
895
+ session_id=_mcp_session_id(),
896
+ event_type="K8S_MANIFEST_REDUCE",
897
+ original_tokens=orig_t,
898
+ optimized_tokens=opt_t,
899
+ details={"file": os.path.basename(path), "saved": orig_t - opt_t}
900
+ )
901
+ return {"content": [{"type": "text", "text": reduced_k8s}]}
902
+ except Exception:
903
+ pass
904
+
905
+ # Structured NDJSON / JSON log files (.ndjson, .log, .jsonl):
906
+ if path.lower().endswith((".ndjson", ".log", ".jsonl")):
907
+ from src.format_parsers.json_log import JSONLogReducer
908
+ try:
909
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
910
+ raw_log_text = f.read()
911
+ if JSONLogReducer.is_ndjson_log(raw_log_text):
912
+ reduced_log, was_log = JSONLogReducer.reduce(raw_log_text)
913
+ if was_log:
914
+ orig_t = count_tokens(raw_log_text)
915
+ opt_t = count_tokens(reduced_log)
916
+ tracker.record_event(
917
+ session_id=_mcp_session_id(),
918
+ event_type="JSON_LOG_REDUCE",
919
+ original_tokens=orig_t,
920
+ optimized_tokens=opt_t,
921
+ details={"file": os.path.basename(path), "saved": orig_t - opt_t}
922
+ )
923
+ return {"content": [{"type": "text", "text": reduced_log}]}
924
+ except Exception:
925
+ pass
926
+
883
927
  # Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
884
928
  # generic AST skeletonization does not apply — route to the schema slicer.
885
929
  # `symbol` carries the target (a spec path, model, type or table); an empty
@@ -1274,7 +1318,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1274
1318
  }, indent=2, ensure_ascii=False)}]}
1275
1319
 
1276
1320
  elif name == "sanitize_command":
1277
- cmd = args.get("command", "")
1321
+ cmd = args.get("command") or args.get("cmd") or args.get("c") or ""
1278
1322
  # Step 1: TokenSafe Guard security inspection
1279
1323
  guard_res = TokenSafeGuard.inspect_command(cmd)
1280
1324
  if guard_res.blocked:
@@ -1323,9 +1367,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1323
1367
  return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
1324
1368
 
1325
1369
  elif name == "guard_inspect":
1326
- cmd = args.get("command")
1327
- code = args.get("code")
1328
- file_path = args.get("file_path", "")
1370
+ cmd = args.get("command") or args.get("cmd") or args.get("c")
1371
+ code = args.get("code") or args.get("snippet")
1372
+ file_path = args.get("file_path") or args.get("path") or args.get("file") or ""
1329
1373
 
1330
1374
  results = []
1331
1375
  if cmd is not None:
@@ -1618,7 +1662,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1618
1662
  return {"content": [{"type": "text", "text": tree_output}]}
1619
1663
 
1620
1664
  elif name == "scoped_search":
1621
- query = args.get("query", "")
1665
+ query = args.get("query") or args.get("q") or args.get("pattern") or args.get("text") or ""
1622
1666
  if not query:
1623
1667
  return _fallback_error("scoped_search", "missing required 'query' argument")
1624
1668
 
package/src/mistakes.py CHANGED
@@ -16,7 +16,7 @@ import time
16
16
  import hashlib
17
17
  import subprocess
18
18
  from typing import Dict, Any, List, Optional
19
- from src.paths import resolve_data_dir
19
+ from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
20
20
 
21
21
 
22
22
  def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
@@ -25,6 +25,7 @@ def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
25
25
  proj_dir = os.path.join(project_root, ".tokensafe")
26
26
  try:
27
27
  os.makedirs(proj_dir, exist_ok=True)
28
+ ensure_tokensafe_gitignore(project_root)
28
29
  return os.path.join(proj_dir, "mistakes.jsonl")
29
30
  except Exception:
30
31
  pass
package/src/paths.py CHANGED
@@ -157,3 +157,47 @@ def get_active_workspace() -> Optional[str]:
157
157
  except Exception:
158
158
  pass
159
159
  return None
160
+
161
+
162
+ def ensure_tokensafe_gitignore(project_root: Optional[str]) -> bool:
163
+ """
164
+ Ensures .tokensafe/ and local caches never leak into git.
165
+ 1. If <project_root>/.tokensafe exists, drops an internal .gitignore (*\n!.gitignore\n).
166
+ 2. If <project_root>/.gitignore exists, ensures .tokensafe/ is ignored.
167
+ """
168
+ if not project_root or not os.path.isdir(project_root):
169
+ return False
170
+
171
+ updated = False
172
+ proj_tokensafe = os.path.join(project_root, ".tokensafe")
173
+ if os.path.isdir(proj_tokensafe):
174
+ inner_ignore = os.path.join(proj_tokensafe, ".gitignore")
175
+ if not os.path.isfile(inner_ignore):
176
+ try:
177
+ with open(inner_ignore, "w", encoding="utf-8") as f:
178
+ f.write("# TokenSafe local runtime artifacts & caches\n*\n!.gitignore\n")
179
+ updated = True
180
+ except Exception:
181
+ pass
182
+
183
+ root_gitignore = os.path.join(project_root, ".gitignore")
184
+ if os.path.isfile(root_gitignore):
185
+ try:
186
+ with open(root_gitignore, "r", encoding="utf-8", errors="replace") as f:
187
+ content = f.read()
188
+ lines = [ln.strip() for ln in content.splitlines()]
189
+ has_entry = any(
190
+ ln in (".tokensafe", ".tokensafe/", "/.tokensafe", "/.tokensafe/")
191
+ for ln in lines
192
+ )
193
+ if not has_entry:
194
+ with open(root_gitignore, "a", encoding="utf-8") as f:
195
+ if content and not content.endswith("\n"):
196
+ f.write("\n")
197
+ f.write("\n# TokenSafe local cache & runtime metrics\n.tokensafe/\n")
198
+ updated = True
199
+ except Exception:
200
+ pass
201
+
202
+ return updated
203
+
@@ -113,7 +113,7 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
113
113
 
114
114
 
115
115
  def _compact_command_result(text: str) -> Optional[str]:
116
- """Test summaries first (PASS: ...), log-style head/tail otherwise."""
116
+ """Test summaries first (PASS: ...), build/docker/log compaction next, log-style head/tail otherwise."""
117
117
  try:
118
118
  from src.test_parsers import TestOutputParser
119
119
  compacted, was_test = TestOutputParser.compact(text)
@@ -121,6 +121,28 @@ def _compact_command_result(text: str) -> Optional[str]:
121
121
  return compacted
122
122
  except Exception:
123
123
  pass
124
+ try:
125
+ from src.build_parsers import BuildOutputParser
126
+ compacted_b, was_b = BuildOutputParser.compact(text)
127
+ if was_b:
128
+ return compacted_b
129
+ except Exception:
130
+ pass
131
+ try:
132
+ from src.format_parsers.docker_k8s import ContainerAndK8sReducer
133
+ compacted_d, was_d = ContainerAndK8sReducer.reduce_docker_build(text)
134
+ if was_d:
135
+ return compacted_d
136
+ except Exception:
137
+ pass
138
+ try:
139
+ from src.format_parsers.json_log import JSONLogReducer
140
+ if JSONLogReducer.is_ndjson_log(text):
141
+ compacted_j, was_j = JSONLogReducer.reduce(text)
142
+ if was_j:
143
+ return compacted_j
144
+ except Exception:
145
+ pass
124
146
  try:
125
147
  from src.command_sanitizer import CommandSanitizer
126
148
  compacted = CommandSanitizer.compact_test_output(text, 0)
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.1.4"
244
+ "User-Agent": "TokenSafe-Sync/4.1.6"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.1.4"
20
+ CURRENT_VERSION = "4.1.6"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage
@@ -1,386 +0,0 @@
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 html as _html
14
- import time
15
- import json
16
- import sqlite3
17
- from contextlib import contextmanager
18
- from typing import Dict, List, Any, Optional, Tuple
19
-
20
- from src.paths import resolve_data_dir
21
-
22
- PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23
- DATA_DIR = resolve_data_dir()
24
- CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
25
-
26
-
27
- @contextmanager
28
- def _open_digest_db(db_path: str):
29
- """Yields Cloud DB/cloud connection for default DB path, or local sqlite3 for custom paths."""
30
- if db_path == CLOUD_DB_PATH:
31
- try:
32
- from src.cloud.db import get_db_connection
33
- from src.cloud.config import CLOUD_DB_URL, CLOUD_DB_TOKEN, CLOUD_DB_PATH as CLOUD_CFG_DB_PATH
34
-
35
- if (CLOUD_DB_URL and CLOUD_DB_TOKEN) or os.path.exists(CLOUD_CFG_DB_PATH):
36
- with get_db_connection() as conn:
37
- yield conn
38
- return
39
- yield None
40
- return
41
- except ImportError:
42
- pass
43
-
44
- if not os.path.exists(db_path):
45
- yield None
46
- return
47
-
48
- conn = sqlite3.connect(db_path)
49
- conn.row_factory = sqlite3.Row
50
- try:
51
- yield conn
52
- finally:
53
- conn.close()
54
-
55
- def format_token_number(n: int) -> str:
56
- """Formats large token count into human-readable 1.2M, 450K, etc."""
57
- if n >= 1_000_000:
58
- return f"{n / 1_000_000:.1f}M"
59
- if n >= 1_000:
60
- return f"{n / 1_000:.1f}K"
61
- return str(n)
62
-
63
- class WeeklyDigestGenerator:
64
- """Compiles weekly team ROI statistics and email templates."""
65
-
66
- @classmethod
67
- def get_team_weekly_stats(
68
- cls,
69
- owner_email: str,
70
- now: Optional[int] = None,
71
- db_path: str = CLOUD_DB_PATH,
72
- allow_any_tier: bool = False
73
- ) -> Optional[Dict[str, Any]]:
74
- """
75
- Retrieves 7-day telemetry for team owned by owner_email.
76
- Supports both Cloud DB (cloud) and local SQLite databases.
77
- Returns aggregated digest data or None if no eligible records found.
78
- """
79
- clean_email = (owner_email or "").strip().lower()
80
- if not clean_email or "@" not in clean_email:
81
- return None
82
-
83
- now = now or int(time.time())
84
- seven_days_ago = now - (7 * 86400)
85
-
86
- with _open_digest_db(db_path) as conn:
87
- if conn is None:
88
- return None
89
-
90
- # 1. Verify owner and active team/enterprise entitlement across customers & organizations
91
- owner = conn.execute(
92
- "SELECT * FROM customers WHERE email = ?;",
93
- (clean_email,),
94
- ).fetchone()
95
-
96
- orgs = []
97
- try:
98
- orgs = conn.execute(
99
- "SELECT * FROM organizations WHERE owner_email = ? AND status = 'active' ORDER BY is_primary DESC, created_at ASC;",
100
- (clean_email,),
101
- ).fetchall()
102
- except sqlite3.OperationalError:
103
- orgs = []
104
-
105
- cust_active = bool(owner and str(owner["status"] or "").lower() == "active")
106
- cust_tier = str(owner["tier"] or "").lower() if owner else ""
107
- team_orgs = [o for o in orgs if str(o["tier"] or "").lower() in ("team", "enterprise")]
108
-
109
- if team_orgs:
110
- effective_tier = str(team_orgs[0]["tier"] or "team").lower()
111
- effective_seats = sum(int(o["seats_total"] or 1) for o in team_orgs)
112
- elif cust_active and cust_tier in ("team", "enterprise"):
113
- effective_tier = cust_tier
114
- effective_seats = int(owner["seats_total"] or 1)
115
- elif allow_any_tier and (cust_active or orgs):
116
- if orgs:
117
- effective_tier = str(orgs[0]["tier"] or cust_tier or "solo").lower()
118
- effective_seats = int(orgs[0]["seats_total"] or 1)
119
- else:
120
- effective_tier = cust_tier or "solo"
121
- effective_seats = int(owner["seats_total"] or 1)
122
- else:
123
- return None
124
-
125
- # 2. Find all member emails and license keys in this team / owned organizations
126
- licenses = conn.execute(
127
- "SELECT * FROM licenses WHERE parent_email = ? OR customer_email = ?;",
128
- (clean_email, clean_email),
129
- ).fetchall()
130
-
131
- team_emails = {clean_email}
132
- for lic in licenses:
133
- if lic["customer_email"]:
134
- team_emails.add(str(lic["customer_email"]).strip().lower())
135
-
136
- org_ids = [o["id"] for o in (team_orgs if team_orgs else orgs) if o["id"]]
137
- if org_ids:
138
- org_placeholders = ",".join(["?"] * len(org_ids))
139
- org_lics = conn.execute(
140
- f"SELECT customer_email FROM licenses WHERE org_id IN ({org_placeholders});",
141
- org_ids,
142
- ).fetchall()
143
- for lic in org_lics:
144
- if lic["customer_email"]:
145
- team_emails.add(str(lic["customer_email"]).strip().lower())
146
-
147
- placeholders = ",".join(["?"] * len(team_emails))
148
- params = list(team_emails) + [seven_days_ago, now]
149
-
150
- # 3. Aggregate 7-day telemetry (bounded [seven_days_ago, now], excluding synthetic ROLLUP_LIFETIME)
151
- events = conn.execute(
152
- f"""
153
- SELECT * FROM telemetry
154
- WHERE customer_email IN ({placeholders})
155
- AND timestamp >= ?
156
- AND timestamp <= ?
157
- AND COALESCE(event_type, '') != 'ROLLUP_LIFETIME'
158
- ORDER BY timestamp DESC;
159
- """,
160
- params,
161
- ).fetchall()
162
-
163
- total_orig = sum(int(e["original_tokens"] or 0) for e in events)
164
- total_saved = sum(int(e["saved_tokens"] or 0) for e in events)
165
- total_usd = sum(float(e["usd_saved"] or 0.0) for e in events)
166
- event_count = len(events)
167
- reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 0.0
168
-
169
- # 4. Engineer leaderboard
170
- engineer_stats: Dict[str, Dict[str, Any]] = {}
171
- for em in team_emails:
172
- engineer_stats[em] = {
173
- "email": em,
174
- "saved_tokens": 0,
175
- "original_tokens": 0,
176
- "usd_saved": 0.0,
177
- "event_count": 0
178
- }
179
-
180
- category_breakdown: Dict[str, int] = {}
181
-
182
- for e in events:
183
- em = str(e["customer_email"] or clean_email).strip().lower()
184
- if em not in engineer_stats:
185
- engineer_stats[em] = {
186
- "email": em,
187
- "saved_tokens": 0,
188
- "original_tokens": 0,
189
- "usd_saved": 0.0,
190
- "event_count": 0
191
- }
192
- saved_toks = int(e["saved_tokens"] or 0)
193
- orig_toks = int(e["original_tokens"] or 0)
194
- usd_val = float(e["usd_saved"] or 0.0)
195
- engineer_stats[em]["saved_tokens"] += saved_toks
196
- engineer_stats[em]["original_tokens"] += orig_toks
197
- engineer_stats[em]["usd_saved"] += usd_val
198
- engineer_stats[em]["event_count"] += 1
199
-
200
- ev_type = str(e["event_type"] or "PROMPT")
201
- category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + saved_toks
202
-
203
- leaderboard = sorted(
204
- engineer_stats.values(),
205
- key=lambda x: x["saved_tokens"],
206
- reverse=True
207
- )
208
-
209
- # Assign ranks
210
- for idx, eng in enumerate(leaderboard, 1):
211
- eng["rank"] = idx
212
- eng["saved_tokens_human"] = format_token_number(eng["saved_tokens"])
213
- eng["usd_saved_formatted"] = f"${eng['usd_saved']:.2f}"
214
-
215
- return {
216
- "owner_email": clean_email,
217
- "tier": effective_tier,
218
- "seats_total": effective_seats,
219
- "active_members_count": len([e for e in leaderboard if e["event_count"] > 0]),
220
- "total_members_count": len(team_emails),
221
- "total_original_tokens": total_orig,
222
- "total_saved_tokens": total_saved,
223
- "total_saved_human": format_token_number(total_saved),
224
- "total_usd_saved": round(total_usd, 2),
225
- "total_events": event_count,
226
- "reduction_pct": reduction_pct,
227
- "leaderboard": leaderboard,
228
- "category_breakdown": category_breakdown,
229
- "start_time": seven_days_ago,
230
- "end_time": now
231
- }
232
-
233
- @classmethod
234
- def render_email_html(cls, digest: Dict[str, Any]) -> str:
235
- """Generates Apple-style responsive dark-mode HTML email."""
236
- owner_email = _html.escape(str(digest["owner_email"]))
237
- total_saved_human = _html.escape(str(digest["total_saved_human"]))
238
- usd_saved = f"${digest['total_usd_saved']:.2f}"
239
- reduction_pct = digest["reduction_pct"]
240
- leaderboard = digest["leaderboard"]
241
- seats_total = digest["seats_total"]
242
- active_count = digest["active_members_count"]
243
-
244
- # Build leaderboard rows
245
- rows_html = ""
246
- for eng in leaderboard[:10]:
247
- rank = eng["rank"]
248
- medal = "🥇 " if rank == 1 else "🥈 " if rank == 2 else "🥉 " if rank == 3 else f"#{rank} "
249
- email_mask = _html.escape(eng["email"].split("@")[0] + "@...")
250
- rows_html += f"""
251
- <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
252
- <td style="padding: 12px 8px; font-weight: 700; color: #10b981;">{medal}</td>
253
- <td style="padding: 12px 8px; font-family: monospace; color: #e5e7eb; font-size: 13px;">{email_mask}</td>
254
- <td style="padding: 12px 8px; text-align: right; font-weight: 700; color: #ffffff;">{eng['saved_tokens_human']}</td>
255
- <td style="padding: 12px 8px; text-align: right; color: #10b981; font-weight: 600;">{eng['usd_saved_formatted']}</td>
256
- </tr>
257
- """
258
-
259
- html = f"""<!DOCTYPE html>
260
- <html>
261
- <head>
262
- <meta charset="utf-8">
263
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
264
- <title>TokenSafe Weekly Team ROI Digest</title>
265
- </head>
266
- <body style="margin: 0; padding: 0; background-color: #030712; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #f3f4f6;">
267
- <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #030712; padding: 40px 16px;">
268
- <tr>
269
- <td align="center">
270
- <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);">
271
-
272
- <!-- Header -->
273
- <tr>
274
- <td style="padding-bottom: 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.08);">
275
- <span style="font-size: 20px; font-weight: 800; color: #ffffff; letter-spacing: -0.5px;">
276
- Token<span style="color: #10b981;">Safe</span>
277
- </span>
278
- <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;">
279
- WEEKLY DIGEST • FRIDAY
280
- </span>
281
- </td>
282
- </tr>
283
-
284
- <!-- Hero Headline -->
285
- <tr>
286
- <td style="padding: 28px 0 16px;">
287
- <h1 style="margin: 0 0 8px; font-size: 24px; font-weight: 800; color: #ffffff; line-height: 1.3;">
288
- TokenSafe saved your team <span style="color: #10b981;">{total_saved_human} tokens</span> ({usd_saved}) this week
289
- </h1>
290
- <p style="margin: 0; font-size: 14px; color: #94a3b8; line-height: 1.5;">
291
- Friday engineering summary for <strong>{owner_email}</strong>. Active seats: {active_count}/{seats_total}.
292
- </p>
293
- </td>
294
- </tr>
295
-
296
- <!-- Key Metrics Grid -->
297
- <tr>
298
- <td style="padding: 12px 0 24px;">
299
- <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
300
- <tr>
301
- <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;">
302
- <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Tokens Saved</div>
303
- <div style="font-size: 22px; font-weight: 800; color: #10b981; margin-top: 4px;">{total_saved_human}</div>
304
- </td>
305
- <td width="2%"></td>
306
- <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;">
307
- <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Est. Cost Saved</div>
308
- <div style="font-size: 22px; font-weight: 800; color: #ffffff; margin-top: 4px;">{usd_saved}</div>
309
- </td>
310
- <td width="2%"></td>
311
- <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;">
312
- <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Net Reduction</div>
313
- <div style="font-size: 22px; font-weight: 800; color: #06b6d4; margin-top: 4px;">-{reduction_pct}%</div>
314
- </td>
315
- </tr>
316
- </table>
317
- </td>
318
- </tr>
319
-
320
- <!-- Leaderboard Table -->
321
- <tr>
322
- <td style="padding: 12px 0 20px;">
323
- <h3 style="margin: 0 0 12px; font-size: 15px; font-weight: 700; color: #ffffff; text-transform: uppercase; letter-spacing: 0.5px;">
324
- 🏆 Engineer Savings Leaderboard
325
- </h3>
326
- <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;">
327
- <thead>
328
- <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;">
329
- <th style="padding: 10px 8px; text-align: left;">Rank</th>
330
- <th style="padding: 10px 8px; text-align: left;">Engineer</th>
331
- <th style="padding: 10px 8px; text-align: right;">Saved</th>
332
- <th style="padding: 10px 8px; text-align: right;">Value</th>
333
- </tr>
334
- </thead>
335
- <tbody>
336
- {rows_html}
337
- </tbody>
338
- </table>
339
- </td>
340
- </tr>
341
-
342
- <!-- CTA Button -->
343
- <tr>
344
- <td style="padding: 24px 0 16px; text-align: center;">
345
- <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);">
346
- Open Live Team Dashboard ➔
347
- </a>
348
- </td>
349
- </tr>
350
-
351
- <!-- Footer -->
352
- <tr>
353
- <td style="padding-top: 24px; border-top: 1px solid rgba(255, 255, 255, 0.06); font-size: 12px; color: #64748b; text-align: center;">
354
- TokenSafe Enterprise • Automatic Friday ROI Digest • <a href="https://tokensafe.dev" style="color: #10b981; text-decoration: none;">tokensafe.dev</a>
355
- </td>
356
- </tr>
357
-
358
- </table>
359
- </td>
360
- </tr>
361
- </table>
362
- </body>
363
- </html>"""
364
- return html
365
-
366
- @classmethod
367
- def render_email_text(cls, digest: Dict[str, Any]) -> str:
368
- """Generates clean plain-text version for terminal or fallback."""
369
- owner_email = digest["owner_email"]
370
- total_saved = digest["total_saved_human"]
371
- usd = f"${digest['total_usd_saved']:.2f}"
372
- reduction = digest["reduction_pct"]
373
-
374
- lines = [
375
- f"⚡ TOKENSAFE WEEKLY TEAM ROI DIGEST",
376
- f"Recipient: {owner_email}",
377
- f"Period: Last 7 Days (Delivered Friday)\n",
378
- f"TokenSafe saved your team {total_saved} tokens ({usd}) this week!",
379
- f"Net Context Reduction: -{reduction}%\n",
380
- f"--- 🏆 ENGINEER SAVINGS LEADERBOARD ---"
381
- ]
382
- for eng in digest["leaderboard"]:
383
- lines.append(f"#{eng['rank']:<2} {eng['email']:<28} {eng['saved_tokens_human']:>8} ({eng['usd_saved_formatted']})")
384
-
385
- lines.append(f"\nOpen your live dashboard: https://tokensafe.dev/dashboard")
386
- return "\n".join(lines)