tokensafe 2.4.2 → 2.5.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/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
  )
@@ -922,7 +923,7 @@ class AgentInstaller:
922
923
  else:
923
924
  print(f" {YELLOW}⚠{RESET} {info['name']}: {msg}")
924
925
 
925
- # 5. Refresh local version cache
926
+ # 5. Refresh local version cache and report the newly installed version in a fresh process
926
927
  try:
927
928
  from src.paths import resolve_data_dir
928
929
  cache_file = os.path.join(resolve_data_dir(), "version_cache.json")
@@ -930,6 +931,12 @@ class AgentInstaller:
930
931
  os.remove(cache_file)
931
932
  except Exception:
932
933
  pass
934
+ try:
935
+ tokensafe_bin = shutil.which("tokensafe")
936
+ sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "src", "cli.py"), "version", "--check"]
937
+ subprocess.run(sync_cmd, capture_output=True, text=True, timeout=5)
938
+ except Exception:
939
+ pass
933
940
 
934
941
  # 6. Restart running MCP server daemons so IDEs load the new version
935
942
  restarted_count = cls.restart_mcp_daemons()