tokensafe 2.4.3 → 2.5.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.
package/src/governor.py CHANGED
@@ -1,10 +1,9 @@
1
1
  """
2
- TokenSafe Context Window Governor & Token Ceiling Engine.
3
- Enforces deterministic token limits per turn or session (Budget Autothrottle).
4
- If context exceeds threshold, applies multi-stage cascading reduction:
5
- Stage 1: AST-folds large inert code blocks into signatures
6
- Stage 2: Compacts intermediate user turns into TOCP Intent IR
7
- Stage 3: Consolidates oldest middle history into State Ledger
2
+ TokenSafe Context Window Governor & Epoch Rollover Engine.
3
+ Operates in Append-Only Epoch mode by default so historical turns remain
4
+ byte-identical for LLM KV-cache hits until context reaches 80% of the model
5
+ window, at which point an atomic Epoch Rollover consolidates deep history
6
+ into a Consolidated State Ledger.
8
7
  """
9
8
 
10
9
  import os
@@ -15,129 +14,186 @@ from src.skeletonizer import Skeletonizer
15
14
  from src.compactor import PromptCompactor
16
15
  from src.metrics import MetricsTracker
17
16
 
17
+
18
18
  class ContextGovernor:
19
- """Monitors and enforces context ceilings before LLM dispatch."""
19
+ """Monitors and enforces context ceilings with cache-safe Append-Only Epochs."""
20
20
 
21
+ EPOCH_WINDOW_RATIO = 0.80
21
22
  DEFAULT_MAX_TURN_TOKENS = int(os.environ.get("TOKENSAFE_MAX_TURN_TOKENS", "16000"))
22
23
  DEFAULT_TARGET_TURN_TOKENS = int(os.environ.get("TOKENSAFE_TARGET_TURN_TOKENS", "10000"))
23
24
 
24
25
  CODE_BLOCK_REGEX = re.compile(r"```([a-zA-Z0-9_\-+]*)\n(.*?)```", re.DOTALL)
25
26
 
27
+ @classmethod
28
+ def resolve_epoch_limit(cls, model: str = "", window_tokens: Optional[int] = None) -> int:
29
+ """Hardcoded epoch ceiling at 80% of the resolved model context window."""
30
+ window = ContextBudget.resolve_window(model, window_tokens)
31
+ return max(1, int(window * cls.EPOCH_WINDOW_RATIO))
32
+
33
+ @staticmethod
34
+ def _calculate_total_tokens(msgs: List[Dict[str, Any]]) -> int:
35
+ total = 0
36
+ for m in msgs:
37
+ c = m.get("content")
38
+ if isinstance(c, str):
39
+ total += count_tokens(c)
40
+ elif isinstance(c, list):
41
+ for item in c:
42
+ if isinstance(item, dict) and "text" in item:
43
+ total += count_tokens(item["text"])
44
+ return total
45
+
46
+ @classmethod
47
+ def _fold_code_blocks_in_message(cls, msg: Dict[str, Any]) -> bool:
48
+ content = msg.get("content")
49
+ if not isinstance(content, str) or "```" not in content:
50
+ return False
51
+
52
+ def fold_match(match):
53
+ lang = (match.group(1) or "py").lower()
54
+ code_text = match.group(2)
55
+ lines = code_text.splitlines()
56
+ if len(lines) < 25:
57
+ return match.group(0)
58
+
59
+ ext = f".{lang}" if not lang.startswith(".") else lang
60
+ if ext not in (".py", ".ts", ".js", ".tsx", ".jsx", ".go", ".java", ".rs", ".c", ".cpp"):
61
+ ext = ".py"
62
+
63
+ skel = Skeletonizer.skeletonize_code(code_text, ext)
64
+ if count_tokens(skel) < count_tokens(code_text) - 50:
65
+ return f"```{lang}\n// [Context Governor: AST-folded {len(lines)} lines]\n{skel}\n```"
66
+ return match.group(0)
67
+
68
+ new_content = cls.CODE_BLOCK_REGEX.sub(fold_match, content)
69
+ if new_content != content:
70
+ msg["content"] = new_content
71
+ return True
72
+ return False
73
+
74
+ @staticmethod
75
+ def _consolidate_middle_turns(
76
+ governed_messages: List[Dict[str, Any]],
77
+ label: str = "Context Governor Ledger",
78
+ ) -> List[Dict[str, Any]]:
79
+ sys_msg = (
80
+ governed_messages[0]
81
+ if governed_messages[0].get("role") in ("system", "developer")
82
+ else None
83
+ )
84
+ recent_turns = governed_messages[-3:]
85
+ middle_turns = governed_messages[1:-3] if sys_msg else governed_messages[:-3]
86
+
87
+ middle_user_intents = []
88
+ for m in middle_turns:
89
+ c = m.get("content", "")
90
+ if m.get("role") == "user" and isinstance(c, str):
91
+ first_line = c.splitlines()[0][:80]
92
+ if first_line:
93
+ middle_user_intents.append(f"- {first_line}")
94
+
95
+ summary_note = (
96
+ f"[{label}: Consolidated {len(middle_turns)} turns]\n"
97
+ f"Historical turn goals:\n" + "\n".join(middle_user_intents[:8]) + "\n..."
98
+ )
99
+ consolidated = []
100
+ if sys_msg:
101
+ consolidated.append(sys_msg)
102
+ consolidated.append({"role": "system", "content": summary_note})
103
+ consolidated.extend(recent_turns)
104
+ return consolidated
105
+
26
106
  @classmethod
27
107
  def govern_messages(
28
108
  cls,
29
109
  messages: List[Dict[str, Any]],
30
110
  max_tokens: Optional[int] = None,
31
111
  target_tokens: Optional[int] = None,
32
- session_id: str = "governor_session"
112
+ session_id: str = "governor_session",
113
+ model: str = "",
114
+ append_only: Optional[bool] = None,
33
115
  ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
34
116
  """
35
- Inspects message list. If total tokens exceed max_tokens, applies cascading
36
- reductions until within target_tokens budget.
117
+ Inspects message list and enforces context budgets.
118
+ - When max_tokens is omitted (auto epoch mode) or append_only=True:
119
+ never mutates historical turns messages[0..N-2] within an epoch;
120
+ only folds the newly appended tail message or performs an atomic
121
+ Epoch Rollover when exceeding 80% of the model's context window.
122
+ - When explicit max_tokens is passed with append_only=False (default
123
+ for explicit ceilings): runs cascading 3-stage reduction.
37
124
  """
38
- max_budget = max_tokens if max_tokens is not None else cls.DEFAULT_MAX_TURN_TOKENS
39
- target_budget = target_tokens if target_tokens is not None else cls.DEFAULT_TARGET_TURN_TOKENS
125
+ is_append_only = (max_tokens is None) if append_only is None else bool(append_only)
126
+ if max_tokens is not None:
127
+ max_budget = max_tokens
128
+ target_budget = target_tokens if target_tokens is not None else cls.DEFAULT_TARGET_TURN_TOKENS
129
+ else:
130
+ max_budget = cls.resolve_epoch_limit(model)
131
+ target_budget = target_tokens if target_tokens is not None else int(max_budget * 0.65)
40
132
 
41
133
  if max_budget <= 0:
42
- return messages, {"throttled": False, "saved_tokens": 0}
43
-
44
- def calculate_total_tokens(msgs: List[Dict[str, Any]]) -> int:
45
- total = 0
46
- for m in msgs:
47
- c = m.get("content")
48
- if isinstance(c, str):
49
- total += count_tokens(c)
50
- elif isinstance(c, list):
51
- for item in c:
52
- if isinstance(item, dict) and "text" in item:
53
- total += count_tokens(item["text"])
54
- return total
55
-
56
- initial_tokens = calculate_total_tokens(messages)
134
+ return messages, {"throttled": False, "epoch_rollover": False, "saved_tokens": 0}
135
+
136
+ initial_tokens = cls._calculate_total_tokens(messages)
57
137
  if initial_tokens <= max_budget:
58
138
  return messages, {
59
139
  "throttled": False,
140
+ "epoch_rollover": False,
60
141
  "initial_tokens": initial_tokens,
61
142
  "current_tokens": initial_tokens,
62
143
  "saved_tokens": 0,
63
- "actions": []
144
+ "actions": [],
145
+ "epoch_limit": max_budget,
64
146
  }
65
147
 
66
148
  actions_taken = []
67
149
  governed_messages = [dict(m) for m in messages]
68
150
  current_tokens = initial_tokens
69
-
70
- # --- Stage 1: AST Skeletonize large inert code blocks in previous turns ---
71
- for idx in range(len(governed_messages) - 1): # leave last user turn untouched
72
- msg = governed_messages[idx]
73
- content = msg.get("content")
74
- if not isinstance(content, str) or "```" not in content:
75
- continue
76
-
77
- def fold_match(match):
78
- lang = (match.group(1) or "py").lower()
79
- code_text = match.group(2)
80
- lines = code_text.splitlines()
81
- if len(lines) < 25:
82
- return match.group(0)
83
-
84
- ext = f".{lang}" if not lang.startswith(".") else lang
85
- if ext not in (".py", ".ts", ".js", ".tsx", ".jsx", ".go", ".java", ".rs", ".c", ".cpp"):
86
- ext = ".py"
87
-
88
- skel = Skeletonizer.skeletonize_code(code_text, ext)
89
- if count_tokens(skel) < count_tokens(code_text) - 50:
90
- return f"```{lang}\n// [Context Governor: AST-folded {len(lines)} lines]\n{skel}\n```"
91
- return match.group(0)
92
-
93
- new_content = cls.CODE_BLOCK_REGEX.sub(fold_match, content)
94
- if new_content != content:
95
- governed_messages[idx]["content"] = new_content
96
-
97
- current_tokens = calculate_total_tokens(governed_messages)
98
- if current_tokens < initial_tokens:
99
- actions_taken.append("ast_fold_code_blocks")
100
-
101
- # --- Stage 2: S-Expression Compaction of older user prompts ---
102
- if current_tokens > target_budget:
151
+ epoch_rollover = False
152
+
153
+ if is_append_only:
154
+ # Tail-only fold: never mutate messages[0..N-2] so prefix KV-cache holds
155
+ if governed_messages and cls._fold_code_blocks_in_message(governed_messages[-1]):
156
+ current_tokens = cls._calculate_total_tokens(governed_messages)
157
+ actions_taken.append("ast_fold_tail_code")
158
+
159
+ # Atomic Epoch Rollover only when still above epoch limit
160
+ if current_tokens > max_budget and len(governed_messages) > 6:
161
+ governed_messages = cls._consolidate_middle_turns(
162
+ governed_messages, label="Epoch Ledger"
163
+ )
164
+ actions_taken.append("epoch_rollover")
165
+ epoch_rollover = True
166
+ current_tokens = cls._calculate_total_tokens(governed_messages)
167
+ else:
168
+ # Explicit tight-budget cascading reduction
169
+ folded_any = False
103
170
  for idx in range(len(governed_messages) - 1):
104
- msg = governed_messages[idx]
105
- if msg.get("role") == "user" and isinstance(msg.get("content"), str):
106
- raw_user = msg["content"]
107
- if len(raw_user.strip()) > 15 and "[TOCP Intent]" not in raw_user:
108
- comp = PromptCompactor.compact(raw_user, enable_deepseek=False)
109
- if comp["saved_tokens"] >= 5:
110
- msg["content"] = f"[TOCP Intent]: {comp['compact_text']}"
111
- current_tokens = calculate_total_tokens(governed_messages)
112
- if "ast_fold_code_blocks" not in actions_taken or current_tokens < initial_tokens:
113
- actions_taken.append("compact_user_history")
114
-
115
- # --- Stage 3: Sliding ledger summarization of deep history if still over target ---
116
- if current_tokens > target_budget and len(governed_messages) > 6:
117
- # Keep first system message and last 3 turns intact, fold middle
118
- sys_msg = governed_messages[0] if governed_messages[0].get("role") == "system" else None
119
- recent_turns = governed_messages[-3:]
120
- middle_turns = governed_messages[1:-3] if sys_msg else governed_messages[:-3]
121
-
122
- middle_user_intents = []
123
- for m in middle_turns:
124
- c = m.get("content", "")
125
- if m.get("role") == "user" and isinstance(c, str):
126
- first_line = c.splitlines()[0][:80]
127
- middle_user_intents.append(f"- {first_line}")
128
-
129
- summary_note = (
130
- f"[Context Governor Ledger: Consolidated {len(middle_turns)} turns]\n"
131
- f"Historical turn goals:\n" + "\n".join(middle_user_intents[:5]) + "\n..."
132
- )
133
- consolidated = []
134
- if sys_msg:
135
- consolidated.append(sys_msg)
136
- consolidated.append({"role": "system", "content": summary_note})
137
- consolidated.extend(recent_turns)
138
- governed_messages = consolidated
139
- actions_taken.append("consolidate_deep_history")
140
- current_tokens = calculate_total_tokens(governed_messages)
171
+ if cls._fold_code_blocks_in_message(governed_messages[idx]):
172
+ folded_any = True
173
+
174
+ current_tokens = cls._calculate_total_tokens(governed_messages)
175
+ if folded_any and current_tokens < initial_tokens:
176
+ actions_taken.append("ast_fold_code_blocks")
177
+
178
+ if current_tokens > target_budget:
179
+ for idx in range(len(governed_messages) - 1):
180
+ msg = governed_messages[idx]
181
+ if msg.get("role") == "user" and isinstance(msg.get("content"), str):
182
+ raw_user = msg["content"]
183
+ if len(raw_user.strip()) > 15 and "[TOCP Intent]" not in raw_user:
184
+ comp = PromptCompactor.compact(raw_user, enable_deepseek=False)
185
+ if comp["saved_tokens"] >= 5:
186
+ msg["content"] = f"[TOCP Intent]: {comp['compact_text']}"
187
+ current_tokens = cls._calculate_total_tokens(governed_messages)
188
+ if "ast_fold_code_blocks" not in actions_taken or current_tokens < initial_tokens:
189
+ actions_taken.append("compact_user_history")
190
+
191
+ if current_tokens > target_budget and len(governed_messages) > 6:
192
+ governed_messages = cls._consolidate_middle_turns(
193
+ governed_messages, label="Context Governor Ledger"
194
+ )
195
+ actions_taken.append("consolidate_deep_history")
196
+ current_tokens = cls._calculate_total_tokens(governed_messages)
141
197
 
142
198
  saved = max(0, initial_tokens - current_tokens)
143
199
  if saved > 0:
@@ -145,24 +201,28 @@ class ContextGovernor:
145
201
  tracker = MetricsTracker()
146
202
  tracker.record_event(
147
203
  session_id=session_id,
148
- event_type="CONTEXT_GOVERNOR",
204
+ event_type="EPOCH_ROLLOVER" if epoch_rollover else "CONTEXT_GOVERNOR",
149
205
  original_tokens=initial_tokens,
150
206
  optimized_tokens=current_tokens,
151
207
  details={
152
208
  "actions": actions_taken,
153
209
  "max_budget": max_budget,
154
- "target_budget": target_budget
155
- }
210
+ "target_budget": target_budget,
211
+ "epoch_rollover": epoch_rollover,
212
+ },
213
+ measurement="measured",
156
214
  )
157
215
  except Exception:
158
216
  pass
159
217
 
160
218
  return governed_messages, {
161
- "throttled": True,
219
+ "throttled": saved > 0 or epoch_rollover,
220
+ "epoch_rollover": epoch_rollover,
162
221
  "initial_tokens": initial_tokens,
163
222
  "current_tokens": current_tokens,
164
223
  "saved_tokens": saved,
165
- "actions": actions_taken
224
+ "actions": actions_taken,
225
+ "epoch_limit": max_budget,
166
226
  }
167
227
 
168
228
 
@@ -207,6 +267,7 @@ class ContextBudget:
207
267
  "SCOPED_SEARCH": "tools", "DIR_LIST": "tools", "COMMAND_FILTER": "tools",
208
268
  "TEAM_CACHE_HIT": "tools", "SUBAGENT_DEDUP": "tools",
209
269
  "HISTORY_FOLD": "history",
270
+ "EPOCH_ROLLOVER": "history",
210
271
  "PROMPT": "prompts",
211
272
  "CONTEXT_GOVERNOR": "other", "OUTPUT_GUARD": "other", "SECRET_GUARD": "other",
212
273
  "GRAPH_TOPOLOGY": "other",
@@ -322,13 +322,23 @@ class CodeGraph:
322
322
  "one_hop": one_hop
323
323
  }
324
324
 
325
- def graph_guided_skeletonize(self, full_path: str, target_symbol: Optional[str] = None, include_deps: bool = True) -> str:
325
+ def graph_guided_skeletonize(
326
+ self,
327
+ full_path: str,
328
+ target_symbol: Optional[str] = None,
329
+ include_deps: bool = True,
330
+ dep_mode: str = "full",
331
+ collapse_imports: bool = False,
332
+ ) -> str:
326
333
  """
327
334
  Surgically folds code based on graph connectivity:
328
335
  - target_symbol: Retains FULL function body.
329
- - 1-hop dependencies: Retained if include_deps=True.
336
+ - 1-hop dependencies:
337
+ * include_deps=True, dep_mode='full': retains full 1-hop bodies in file.
338
+ * include_deps=True, dep_mode='signature': folds 1-hop bodies into signatures
339
+ and prepends compact 1-line external dependency signatures.
340
+ * include_deps=False: 0-hop surgical single-symbol isolation.
330
341
  - 2-hop / Unrelated functions in the same file: Stripped to AST signatures (ellipsis).
331
- Yields up to 90% token reduction without breaking context.
332
342
  """
333
343
  try:
334
344
  with open(full_path, "r", encoding="utf-8", errors="replace") as f:
@@ -341,15 +351,42 @@ class CodeGraph:
341
351
  ext = ext.lower()
342
352
 
343
353
  if not target_symbol:
344
- return Skeletonizer.skeletonize_code(code, ext)
354
+ return Skeletonizer.skeletonize_code(code, ext, collapse_imports=collapse_imports)
345
355
 
346
356
  keep_full_names = {target_symbol}
357
+ external_dep_lines: List[str] = []
358
+ mode = (dep_mode or "full").strip().lower()
359
+
347
360
  if include_deps:
348
361
  neighborhood = self.get_neighborhood(target_symbol)
349
- for k in neighborhood.get("one_hop", set()):
350
- keep_full_names.add(k.split("::")[-1])
351
-
352
- return Skeletonizer.skeletonize_code(code, ext, keep_symbols=keep_full_names)
362
+ one_hop = sorted(neighborhood.get("one_hop", set()))
363
+ if mode == "signature":
364
+ try:
365
+ target_rel = os.path.relpath(os.path.abspath(full_path), self.root_dir).replace("\\", "/")
366
+ except ValueError:
367
+ target_rel = ""
368
+ comment_prefix = "#" if ext == ".py" else "//"
369
+ for k in one_hop:
370
+ sym = self.symbols.get(k)
371
+ if sym and sym.file_path != target_rel and len(external_dep_lines) < 10:
372
+ external_dep_lines.append(
373
+ f"{comment_prefix} - {sym.file_path} (L{sym.line_start}): {sym.signature}"
374
+ )
375
+ else:
376
+ for k in one_hop:
377
+ keep_full_names.add(k.split("::")[-1])
378
+
379
+ skel = Skeletonizer.skeletonize_code(
380
+ code,
381
+ ext,
382
+ keep_symbols=keep_full_names,
383
+ collapse_imports=collapse_imports,
384
+ )
385
+ if external_dep_lines:
386
+ comment_prefix = "#" if ext == ".py" else "//"
387
+ dep_header = f"{comment_prefix} 1-hop external dependencies (signatures):\n" + "\n".join(external_dep_lines)
388
+ return dep_header + "\n\n" + skel
389
+ return skel
353
390
 
354
391
  # -------------------------------------------------------------
355
392
  # 3. API Surface Generator (tokensafe-out/API_SURFACE.md)
package/src/installer.py CHANGED
@@ -37,11 +37,12 @@ UNIFIED_TOKENSAFE_RULE = (
37
37
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
38
38
  "Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
39
39
  "1. **Zero Raw Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.\n"
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"
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`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context.\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
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 — 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"
44
- "6. **Proof-of-Savings Turn Footer (always in English)**:\n"
44
+ "6. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage; when it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` before continuing.\n"
45
+ "7. **Proof-of-Savings Turn Footer (always in English)**:\n"
45
46
  "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
47
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
47
48
  )
@@ -11,6 +11,8 @@ import time
11
11
  import hmac
12
12
  import hashlib
13
13
  import base64
14
+ import platform
15
+ import uuid
14
16
  import threading
15
17
  from typing import Dict, Any, Tuple, Optional, List
16
18
 
@@ -24,14 +26,16 @@ GLOBAL_LICENSE_FILE = os.path.join(GLOBAL_DATA_DIR, "license.json")
24
26
  _DEFAULT_LICENSE_FILE = LICENSE_FILE
25
27
  _DEFAULT_GLOBAL_LICENSE_FILE = GLOBAL_LICENSE_FILE
26
28
 
27
- # Master Public Key for client-side offline verification (RFC 8032 Ed25519)
28
- DEFAULT_ED25519_PUBLIC_KEY = os.environ.get("TOKENSAFE_PUBLIC_KEY", "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430")
29
- # Pre-rotation public keys accepted for backwards compatibility
30
- LEGACY_ED25519_PUBLIC_KEYS = ("8a2c9d550180ab5b00a06174cb6aecfd712740c59d0bdcff66a56515348c855e",)
29
+ # Master Public Key for client-side offline verification (RFC 8032 Ed25519).
30
+ # Hardcoded intentionally so environment overrides cannot substitute an attacker key.
31
+ EMBEDDED_ED25519_PUBLIC_KEY = "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430"
32
+ DEFAULT_ED25519_PUBLIC_KEY = EMBEDDED_ED25519_PUBLIC_KEY
33
+ # Retired keys (never include unit-test public keys here)
34
+ LEGACY_ED25519_PUBLIC_KEYS: Tuple[str, ...] = ()
31
35
  # Private key for cloud server signing (never distributed to client, loaded strictly from environment)
32
36
  DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "")
33
- # Rotated HMAC salt for backward compatibility with TS1 legacy licenses
34
- ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "ts-sec-rotated-7b3f9c2d1e0a4f5b6829e1c3a70428e5")
37
+ # Server-only HMAC salt for legacy TS1 migration (never hardcoded in clients)
38
+ ROTATED_HMAC_SALT = os.environ.get("TOKENSAFE_HMAC_SALT", "")
35
39
  DEFAULT_SIGNING_SALT = ROTATED_HMAC_SALT
36
40
 
37
41
  # ---------------------------------------------------------------------------
@@ -93,7 +97,7 @@ def _ed_decodepoint(s: bytes) -> Optional[list]:
93
97
  return None
94
98
  return pt
95
99
 
96
- def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes) -> bytes:
100
+ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes = b"") -> bytes:
97
101
  try:
98
102
  from cryptography.hazmat.primitives.asymmetric import ed25519
99
103
  priv_obj = ed25519.Ed25519PrivateKey.from_private_bytes(priv_bytes)
@@ -101,10 +105,12 @@ def _ed25519_sign_bytes(msg: bytes, priv_bytes: bytes, pub_bytes: bytes) -> byte
101
105
  except Exception:
102
106
  h = hashlib.sha512(priv_bytes).digest()
103
107
  a = 2**254 + sum(2**i * _ed_bit(h, i) for i in range(3, 254))
108
+ # Always derive the RFC 8032 public point from priv_bytes so env/global overrides cannot desync H(R||A||M).
109
+ derived_pub = _ed_encodepoint(_ed_scalarmult(_ED_B, a))
104
110
  r = int.from_bytes(hashlib.sha512(h[32:] + msg).digest(), "little")
105
111
  r_pt = _ed_scalarmult(_ED_B, r)
106
112
  r_bytes = _ed_encodepoint(r_pt)
107
- k = int.from_bytes(hashlib.sha512(r_bytes + pub_bytes + msg).digest(), "little")
113
+ k = int.from_bytes(hashlib.sha512(r_bytes + derived_pub + msg).digest(), "little")
108
114
  s = (r + k * a) % _ED25519_L
109
115
  return r_bytes + int.to_bytes(s, 32, "little")
110
116
 
@@ -145,6 +151,7 @@ class LicenseManager:
145
151
  _VALIDATION_CACHE_LOCK = threading.Lock()
146
152
  _VALIDATION_CACHE_TTL = 3600.0 # 1 hour
147
153
  _VALIDATION_CACHE_MAX = 64
154
+ _QUOTA_TURN_COUNTERS: Dict[str, int] = {}
148
155
 
149
156
  TIERS = {
150
157
  "free": {"max_tokens_monthly": 500_000, "deepseek_cloud": False, "team_analytics": False},
@@ -153,6 +160,12 @@ class LicenseManager:
153
160
  "enterprise": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": True, "self_hosted": True}
154
161
  }
155
162
 
163
+ @classmethod
164
+ def get_machine_fingerprint(cls) -> str:
165
+ """One-way anonymized machine identifier for server-side free-tier quota continuity."""
166
+ raw = f"ts:{platform.system()}:{platform.node()}:{uuid.getnode()}:{os.path.expanduser('~')}"
167
+ return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
168
+
156
169
  @classmethod
157
170
  def generate_license(
158
171
  cls,
@@ -200,8 +213,10 @@ class LicenseManager:
200
213
  sig_b64 = base64.urlsafe_b64encode(sig_raw).decode("ascii").rstrip("=")
201
214
  return f"TS2.{payload_b64}.{sig_b64}"
202
215
 
203
- # Fallback to TS1 HMAC format
204
- hmac_key = signing_key or ROTATED_HMAC_SALT
216
+ # Fallback to TS1 HMAC format (server/test explicit signing_key only)
217
+ hmac_key = signing_key or ROTATED_HMAC_SALT or os.environ.get("TOKENSAFE_HMAC_SALT", "")
218
+ if not hmac_key:
219
+ raise ValueError("TOKENSAFE_HMAC_SALT is required to sign legacy TS1 licenses.")
205
220
  sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
206
221
  return f"TS1.{payload_b64}.{sig}"
207
222
 
@@ -209,13 +224,14 @@ class LicenseManager:
209
224
  def validate_license(
210
225
  cls,
211
226
  license_key: str,
212
- public_key: Optional[str] = None
227
+ public_key: Optional[str] = None,
228
+ allow_legacy_ts1: bool = False,
213
229
  ) -> Tuple[bool, Dict[str, Any], str]:
214
230
  """
215
231
  Validates the license key signature and expiration.
216
232
  Supports:
217
- - TS2: Asymmetric Ed25519 verification using public key (Offline-safe, impossible to forge)
218
- - TS1: Legacy HMAC-SHA256 verification with rotated salt
233
+ - TS2: Asymmetric Ed25519 verification using embedded public key (Offline-safe, impossible to forge)
234
+ - TS1: Legacy HMAC-SHA256 rejected offline (server-side migration only when allow_legacy_ts1=True)
219
235
  Returns (is_valid, payload_dict, reason_str).
220
236
  """
221
237
  if not license_key or not isinstance(license_key, str):
@@ -226,7 +242,8 @@ class LicenseManager:
226
242
  # Fast path: recently verified signature (avoids ~0.6s pure-Python Ed25519
227
243
  # verification on every hook invocation when the 'cryptography' package is absent)
228
244
  now = time.time()
229
- cache_key = f"{public_key or ''}|{license_key}"
245
+ effective_pub = public_key or DEFAULT_ED25519_PUBLIC_KEY
246
+ cache_key = f"{effective_pub}|{int(bool(allow_legacy_ts1))}|{license_key}"
230
247
  with cls._VALIDATION_CACHE_LOCK:
231
248
  cached = cls._VALIDATION_CACHE.get(cache_key)
232
249
  if cached and now < cached[1]:
@@ -246,7 +263,7 @@ class LicenseManager:
246
263
 
247
264
  # 1. Asymmetric Ed25519 Verification (TS2)
248
265
  if schema_ver == "TS2":
249
- pub_hex = public_key or os.environ.get("TOKENSAFE_PUBLIC_KEY") or DEFAULT_ED25519_PUBLIC_KEY
266
+ pub_hex = public_key or DEFAULT_ED25519_PUBLIC_KEY
250
267
  try:
251
268
  pub_bytes = bytes.fromhex(pub_hex)
252
269
  padded_sig = sig_part + "=" * (-len(sig_part) % 4)
@@ -267,16 +284,20 @@ class LicenseManager:
267
284
  if not verified:
268
285
  return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
269
286
 
270
- # 2. Legacy TS1 Verification
287
+ # 2. Legacy TS1 Verification (disabled offline to eliminate public-salt forgery)
271
288
  else:
272
- hmac_key = public_key or ROTATED_HMAC_SALT
289
+ if not allow_legacy_ts1:
290
+ return (
291
+ False,
292
+ {},
293
+ "Legacy TS1 offline verification is disabled; reconnect to upgrade to a TS2 Ed25519 license.",
294
+ )
295
+ hmac_key = public_key or ROTATED_HMAC_SALT or os.environ.get("TOKENSAFE_HMAC_SALT", "")
296
+ if not hmac_key:
297
+ return False, {}, "Legacy TS1 verification requires server-side HMAC salt configuration"
273
298
  expected_sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
274
299
  if not hmac.compare_digest(sig_part, expected_sig):
275
- # Try fallback default salt if user had old key
276
- old_salt = "ts-core-sec-9a4f8b2c1e7d3a506198fbcde40231aa"
277
- fallback_sig = hmac.new(old_salt.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
278
- if not hmac.compare_digest(sig_part, fallback_sig):
279
- return False, {}, "Invalid signature: legacy license key has been tampered with"
300
+ return False, {}, "Invalid signature: legacy license key has been tampered with"
280
301
 
281
302
  # Check expiration
282
303
  now = int(time.time())
@@ -448,14 +469,16 @@ class LicenseManager:
448
469
  if exceeded:
449
470
  warning = (
450
471
  f"⚡ **TokenSafe Quota Alert**: Community Edition limit reached "
451
- f"({monthly_saved:,}/{max_tokens:,} tokens saved this month). "
452
- f"Advanced optimization is throttled. Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or visit https://tokensafe.dev."
472
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens saved this month). "
473
+ f"Graph/signature AST slicing, pointer dedup, history compaction & KV-cache prefix locking are paused "
474
+ f"(Security Guard stays active). Upgrade to Solo ($9/mo) or 7-Day Team Trial: "
475
+ f"`tokensafe activate <key>` or visit https://tokensafe.dev/#pricing"
453
476
  )
454
477
  elif monthly_saved >= int(max_tokens * 0.85):
455
478
  warning = (
456
479
  f"⚡ **TokenSafe Quota Notice**: Community Edition is at {int(monthly_saved / max_tokens * 100)}% of monthly limit "
457
- f"({monthly_saved:,}/{max_tokens:,} tokens). "
458
- f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev."
480
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens). "
481
+ f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev/#pricing"
459
482
  )
460
483
 
461
484
  return {
@@ -463,5 +486,46 @@ class LicenseManager:
463
486
  "is_quota_exceeded": exceeded,
464
487
  "monthly_limit": max_tokens,
465
488
  "monthly_saved": monthly_saved,
489
+ "remaining_tokens": max(0, max_tokens - monthly_saved),
466
490
  "warning": warning
467
491
  }
492
+
493
+ @classmethod
494
+ def should_emit_quota_banner(
495
+ cls,
496
+ tracker: Optional[Any] = None,
497
+ session_id: str = "default_session",
498
+ every_n_turns: int = 5,
499
+ ) -> bool:
500
+ """Returns True on turn #1 of quota exceedance per session and every N turns thereafter."""
501
+ sid = session_id or "default_session"
502
+ n = max(1, int(every_n_turns or 5))
503
+ if tracker is not None and hasattr(tracker, "_get_connection"):
504
+ try:
505
+ with tracker._get_connection() as conn:
506
+ conn.execute("""
507
+ CREATE TABLE IF NOT EXISTS quota_banner_state (
508
+ session_id TEXT PRIMARY KEY,
509
+ turns INTEGER NOT NULL DEFAULT 0,
510
+ updated_at INTEGER NOT NULL
511
+ )
512
+ """)
513
+ row = conn.execute(
514
+ "SELECT turns FROM quota_banner_state WHERE session_id = ?",
515
+ (sid,),
516
+ ).fetchone()
517
+ turn_no = (int(row["turns"]) if row else 0) + 1
518
+ conn.execute("""
519
+ INSERT INTO quota_banner_state (session_id, turns, updated_at)
520
+ VALUES (?, ?, ?)
521
+ ON CONFLICT(session_id) DO UPDATE SET
522
+ turns = excluded.turns,
523
+ updated_at = excluded.updated_at
524
+ """, (sid, turn_no, int(time.time())))
525
+ return turn_no == 1 or (turn_no % n == 0)
526
+ except Exception:
527
+ pass
528
+ with cls._VALIDATION_CACHE_LOCK:
529
+ turn_no = cls._QUOTA_TURN_COUNTERS.get(sid, 0) + 1
530
+ cls._QUOTA_TURN_COUNTERS[sid] = turn_no
531
+ return turn_no == 1 or (turn_no % n == 0)