tokensafe 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ """
2
+ Distillation Cache: Two-tier (In-Memory LRU + SQLite) cache for semantic prompt distillations.
3
+ Prevents duplicate LLM provider API roundtrips (DeepSeek / Gemini / OpenAI).
4
+ Zero external runtime dependencies.
5
+ """
6
+
7
+ import os
8
+ import hashlib
9
+ import sqlite3
10
+ import threading
11
+ from collections import OrderedDict
12
+ from datetime import datetime
13
+ from typing import Optional, Dict, Any
14
+
15
+ class DistillationCache:
16
+ """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite)."""
17
+
18
+ _lock = threading.Lock()
19
+ _memory_cache: OrderedDict = OrderedDict()
20
+ _MAX_MEMORY_ENTRIES = 1000
21
+ _db_path: Optional[str] = None
22
+ _hits: int = 0
23
+ _misses: int = 0
24
+
25
+ @classmethod
26
+ def _normalize_prompt(cls, prompt_text: str) -> str:
27
+ """Strips and normalizes whitespace."""
28
+ return " ".join((prompt_text or "").strip().split())
29
+
30
+ @classmethod
31
+ def _hash_prompt(cls, prompt_text: str) -> str:
32
+ """Returns SHA-256 hash of normalized prompt text."""
33
+ norm = cls._normalize_prompt(prompt_text)
34
+ return hashlib.sha256(norm.encode("utf-8")).hexdigest()
35
+
36
+ @classmethod
37
+ def _get_db_path(cls) -> str:
38
+ if cls._db_path:
39
+ return cls._db_path
40
+
41
+ base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
42
+ data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(base_dir, "data"))
43
+ os.makedirs(data_dir, exist_ok=True)
44
+ cls._db_path = os.path.join(data_dir, "metrics.db")
45
+ return cls._db_path
46
+
47
+ @classmethod
48
+ def _init_db(cls, conn: sqlite3.Connection):
49
+ conn.execute("""
50
+ CREATE TABLE IF NOT EXISTS distillation_cache (
51
+ prompt_hash TEXT PRIMARY KEY,
52
+ prompt_text TEXT,
53
+ distilled_text TEXT NOT NULL,
54
+ provider TEXT NOT NULL,
55
+ created_at TEXT NOT NULL,
56
+ hit_count INTEGER DEFAULT 0
57
+ );
58
+ """)
59
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_distill_hash ON distillation_cache(prompt_hash);")
60
+
61
+ @classmethod
62
+ def get(cls, prompt_text: str) -> Optional[str]:
63
+ """Retrieves cached distillation S-Expression if present."""
64
+ if not prompt_text or not prompt_text.strip():
65
+ return None
66
+
67
+ h = cls._hash_prompt(prompt_text)
68
+
69
+ with cls._lock:
70
+ # 1. Check in-memory LRU
71
+ if h in cls._memory_cache:
72
+ cls._hits += 1
73
+ distilled = cls._memory_cache.pop(h)
74
+ cls._memory_cache[h] = distilled # Move to end (most recently used)
75
+ return distilled
76
+
77
+ # 2. Check SQLite persistent cache
78
+ db_path = cls._get_db_path()
79
+ conn = None
80
+ try:
81
+ conn = sqlite3.connect(db_path, timeout=5.0)
82
+ cls._init_db(conn)
83
+ cursor = conn.cursor()
84
+ cursor.execute(
85
+ "SELECT distilled_text, hit_count FROM distillation_cache WHERE prompt_hash = ?",
86
+ (h,)
87
+ )
88
+ row = cursor.fetchone()
89
+ if row:
90
+ distilled_text, hit_count = row[0], row[1]
91
+ cursor.execute(
92
+ "UPDATE distillation_cache SET hit_count = ? WHERE prompt_hash = ?",
93
+ (hit_count + 1, h)
94
+ )
95
+ conn.commit()
96
+
97
+ with cls._lock:
98
+ cls._hits += 1
99
+ cls._memory_cache[h] = distilled_text
100
+ if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
101
+ cls._memory_cache.popitem(last=False) # Evict oldest
102
+
103
+ return distilled_text
104
+ except Exception:
105
+ pass
106
+ finally:
107
+ if conn:
108
+ try:
109
+ conn.close()
110
+ except Exception:
111
+ pass
112
+
113
+ with cls._lock:
114
+ cls._misses += 1
115
+ return None
116
+
117
+ @classmethod
118
+ def set(cls, prompt_text: str, distilled_text: str, provider: str = "deepseek") -> None:
119
+ """Stores a distillation result into memory LRU and SQLite cache."""
120
+ if not prompt_text or not distilled_text or not distilled_text.strip():
121
+ return
122
+
123
+ h = cls._hash_prompt(prompt_text)
124
+ norm_prompt = cls._normalize_prompt(prompt_text)
125
+ now_iso = datetime.now().isoformat()
126
+
127
+ with cls._lock:
128
+ cls._memory_cache[h] = distilled_text.strip()
129
+ if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
130
+ cls._memory_cache.popitem(last=False)
131
+
132
+ db_path = cls._get_db_path()
133
+ conn = None
134
+ try:
135
+ conn = sqlite3.connect(db_path, timeout=5.0)
136
+ cls._init_db(conn)
137
+ cursor = conn.cursor()
138
+ cursor.execute("""
139
+ INSERT INTO distillation_cache (prompt_hash, prompt_text, distilled_text, provider, created_at, hit_count)
140
+ VALUES (?, ?, ?, ?, ?, 0)
141
+ ON CONFLICT(prompt_hash) DO UPDATE SET
142
+ distilled_text = excluded.distilled_text,
143
+ provider = excluded.provider
144
+ """, (h, norm_prompt[:500], distilled_text.strip(), provider, now_iso))
145
+ conn.commit()
146
+ except Exception:
147
+ pass
148
+ finally:
149
+ if conn:
150
+ try:
151
+ conn.close()
152
+ except Exception:
153
+ pass
154
+
155
+ @classmethod
156
+ def clear(cls) -> None:
157
+ """Clears both in-memory and persistent SQLite cache."""
158
+ with cls._lock:
159
+ cls._memory_cache.clear()
160
+ cls._hits = 0
161
+ cls._misses = 0
162
+
163
+ db_path = cls._get_db_path()
164
+ conn = None
165
+ try:
166
+ conn = sqlite3.connect(db_path, timeout=5.0)
167
+ cls._init_db(conn)
168
+ conn.execute("DELETE FROM distillation_cache;")
169
+ conn.commit()
170
+ except Exception:
171
+ pass
172
+ finally:
173
+ if conn:
174
+ try:
175
+ conn.close()
176
+ except Exception:
177
+ pass
178
+
179
+ @classmethod
180
+ def get_stats(cls) -> Dict[str, Any]:
181
+ """Returns runtime cache statistics."""
182
+ with cls._lock:
183
+ mem_size = len(cls._memory_cache)
184
+ hits = cls._hits
185
+ misses = cls._misses
186
+
187
+ total_db_entries = 0
188
+ db_path = cls._get_db_path()
189
+ conn = None
190
+ try:
191
+ conn = sqlite3.connect(db_path, timeout=5.0)
192
+ cls._init_db(conn)
193
+ cursor = conn.cursor()
194
+ cursor.execute("SELECT count(*) FROM distillation_cache")
195
+ row = cursor.fetchone()
196
+ if row:
197
+ total_db_entries = row[0]
198
+ except Exception:
199
+ pass
200
+ finally:
201
+ if conn:
202
+ try:
203
+ conn.close()
204
+ except Exception:
205
+ pass
206
+
207
+ total_lookups = hits + misses
208
+ hit_ratio = (hits / total_lookups * 100.0) if total_lookups > 0 else 0.0
209
+
210
+ return {
211
+ "memory_entries": mem_size,
212
+ "persistent_entries": total_db_entries,
213
+ "hits": hits,
214
+ "misses": misses,
215
+ "hit_ratio_pct": round(hit_ratio, 1)
216
+ }
@@ -0,0 +1,259 @@
1
+ """
2
+ Environment Auditor & Context Bloat Guard for Antigravity Token Optimizer.
3
+ Detects heavy MCP servers, redundant tool schemas, and excessive skills that bloat
4
+ the system prompt on every API turn. Provides one-click enable/disable toggles.
5
+ """
6
+
7
+ import os
8
+ import json
9
+ from typing import Dict, List, Any, Optional
10
+
11
+ EST_TOKENS_PER_TOOL = 25
12
+ EST_TOKENS_PER_SKILL = 180
13
+ CRITICAL_TOOL_COUNT_THRESHOLD = 40
14
+
15
+
16
+ class EnvironmentAuditor:
17
+ """Scans and audits static context overhead (MCP servers and skills)."""
18
+
19
+ @classmethod
20
+ def get_config_paths(cls) -> List[str]:
21
+ home = os.path.expanduser("~")
22
+ return [
23
+ os.path.join(home, ".gemini", "config", "mcp_config.json"),
24
+ os.path.join(home, ".gemini", "antigravity", "mcp_config.json")
25
+ ]
26
+
27
+ @classmethod
28
+ def get_mcp_schemas_dir(cls) -> str:
29
+ return os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "mcp")
30
+
31
+ @classmethod
32
+ def get_skills_dirs(cls) -> List[str]:
33
+ home = os.path.expanduser("~")
34
+ dirs = [
35
+ os.path.join(home, ".gemini", "config", "skills"),
36
+ os.path.join(home, ".gemini", "config", "plugins"),
37
+ os.path.join(home, ".gemini", "antigravity", "builtin", "skills"),
38
+ ]
39
+ return [d for d in dirs if os.path.isdir(d)]
40
+
41
+ @classmethod
42
+ def get_configured_mcp_servers(cls) -> Dict[str, Any]:
43
+ for p in cls.get_config_paths():
44
+ if os.path.isfile(p):
45
+ try:
46
+ with open(p, "r", encoding="utf-8") as f:
47
+ data = json.load(f)
48
+ return data.get("mcpServers", {})
49
+ except Exception:
50
+ continue
51
+ return {}
52
+
53
+ @classmethod
54
+ def audit(cls) -> Dict[str, Any]:
55
+ """Audits all active MCP servers and skills for context footprint."""
56
+ configured = cls.get_configured_mcp_servers()
57
+ schemas_dir = cls.get_mcp_schemas_dir()
58
+
59
+ servers = {}
60
+ # 1. Discover all servers from schema directories
61
+ if os.path.isdir(schemas_dir):
62
+ for entry in os.listdir(schemas_dir):
63
+ entry_path = os.path.join(schemas_dir, entry)
64
+ if not os.path.isdir(entry_path):
65
+ continue
66
+
67
+ is_disabled = entry.endswith(".disabled")
68
+ srv_name = entry[:-9] if is_disabled else entry
69
+
70
+ # Count tool schemas
71
+ tool_files = [f for f in os.listdir(entry_path) if f.endswith(".json")]
72
+ tool_count = len(tool_files)
73
+
74
+ is_active = (not is_disabled) and (srv_name in configured)
75
+ est_tokens = tool_count * EST_TOKENS_PER_TOOL
76
+
77
+ servers[srv_name] = {
78
+ "name": srv_name,
79
+ "active": is_active,
80
+ "disabled": is_disabled,
81
+ "tool_count": tool_count,
82
+ "est_tokens_per_turn": est_tokens,
83
+ "is_bloat": is_active and (tool_count >= CRITICAL_TOOL_COUNT_THRESHOLD)
84
+ }
85
+
86
+ # Include configured servers that might not have a schema dir cached yet
87
+ for srv_name in configured:
88
+ if srv_name not in servers:
89
+ servers[srv_name] = {
90
+ "name": srv_name,
91
+ "active": True,
92
+ "disabled": False,
93
+ "tool_count": 5, # default estimate
94
+ "est_tokens_per_turn": 5 * EST_TOKENS_PER_TOOL,
95
+ "is_bloat": False
96
+ }
97
+
98
+ # 2. Count skills
99
+ skills_count = 0
100
+ for sdir in cls.get_skills_dirs():
101
+ for root, dirs, files in os.walk(sdir):
102
+ if "SKILL.md" in files:
103
+ skills_count += 1
104
+
105
+ total_mcp_tools = sum(s["tool_count"] for s in servers.values() if s["active"])
106
+ total_mcp_tokens = sum(s["est_tokens_per_turn"] for s in servers.values() if s["active"])
107
+ total_skills_tokens = skills_count * EST_TOKENS_PER_SKILL
108
+ total_static_tokens = total_mcp_tokens + total_skills_tokens
109
+
110
+ bloated_servers = [s for s in servers.values() if s["is_bloat"]]
111
+
112
+ return {
113
+ "servers": servers,
114
+ "total_active_servers": len([s for s in servers.values() if s["active"]]),
115
+ "total_tools": total_mcp_tools,
116
+ "total_skills": skills_count,
117
+ "mcp_tokens_per_turn": total_mcp_tokens,
118
+ "skills_tokens_per_turn": total_skills_tokens,
119
+ "total_static_tokens_per_turn": total_static_tokens,
120
+ "bloated_servers": bloated_servers,
121
+ "has_critical_bloat": len(bloated_servers) > 0
122
+ }
123
+
124
+ @classmethod
125
+ def get_bloat_warning(cls) -> Optional[str]:
126
+ """Returns a formatted warning string if critical context bloat is detected."""
127
+ report = cls.audit()
128
+ if not report["has_critical_bloat"]:
129
+ return None
130
+
131
+ bloated = report["bloated_servers"]
132
+ names = ", ".join([f"`{b['name']}` ({b['tool_count']} инструментов, ~{b['est_tokens_per_turn']:,} токенов/шаг)" for b in bloated])
133
+ return (
134
+ f"⚠️ **TokenSafe Bloat Alert**: Обнаружен тяжелый MCP сервер: {names}. "
135
+ f"Суммарный налог на каждый запрос: **~{report['total_static_tokens_per_turn']:,} токенов**. "
136
+ f"Отключите неиспользуемые серверы через `./bin/agy-tokens mcp disable <name>`."
137
+ )
138
+
139
+ @classmethod
140
+ def disable_mcp(cls, server_name: str) -> Dict[str, Any]:
141
+ """Disables an MCP server in mcp_config.json and renames its schema directory."""
142
+ server_name = server_name.strip()
143
+ schemas_dir = cls.get_mcp_schemas_dir()
144
+
145
+ # 1. Update config files
146
+ modified = False
147
+ server_config = None
148
+ for p in cls.get_config_paths():
149
+ real_path = os.path.realpath(p)
150
+ if os.path.isfile(real_path):
151
+ try:
152
+ with open(real_path, "r", encoding="utf-8") as f:
153
+ data = json.load(f)
154
+ mcp_servers = data.get("mcpServers", {})
155
+ if server_name in mcp_servers:
156
+ server_config = mcp_servers.pop(server_name)
157
+ # Save disabled config
158
+ if "disabledMcpServers" not in data:
159
+ data["disabledMcpServers"] = {}
160
+ data["disabledMcpServers"][server_name] = server_config
161
+ with open(real_path, "w", encoding="utf-8") as f:
162
+ json.dump(data, f, indent=2)
163
+ modified = True
164
+ except Exception:
165
+ pass
166
+
167
+ # 2. Rename schema directory to .disabled
168
+ active_dir = os.path.join(schemas_dir, server_name)
169
+ disabled_dir = os.path.join(schemas_dir, f"{server_name}.disabled")
170
+ renamed = False
171
+ if os.path.isdir(active_dir):
172
+ try:
173
+ os.rename(active_dir, disabled_dir)
174
+ renamed = True
175
+ except Exception:
176
+ pass
177
+
178
+ return {
179
+ "success": modified or renamed,
180
+ "server_name": server_name,
181
+ "config_updated": modified,
182
+ "directory_renamed": renamed
183
+ }
184
+
185
+ @classmethod
186
+ def enable_mcp(cls, server_name: str) -> Dict[str, Any]:
187
+ """Re-enables a previously disabled MCP server."""
188
+ server_name = server_name.strip()
189
+ schemas_dir = cls.get_mcp_schemas_dir()
190
+
191
+ # 1. Update config files
192
+ modified = False
193
+ for p in cls.get_config_paths():
194
+ real_path = os.path.realpath(p)
195
+ if os.path.isfile(real_path):
196
+ try:
197
+ with open(real_path, "r", encoding="utf-8") as f:
198
+ data = json.load(f)
199
+ disabled_servers = data.get("disabledMcpServers", {})
200
+ if server_name in disabled_servers:
201
+ srv_cfg = disabled_servers.pop(server_name)
202
+ if "mcpServers" not in data:
203
+ data["mcpServers"] = {}
204
+ data["mcpServers"][server_name] = srv_cfg
205
+ with open(real_path, "w", encoding="utf-8") as f:
206
+ json.dump(data, f, indent=2)
207
+ modified = True
208
+ except Exception:
209
+ pass
210
+
211
+ # 2. Rename schema directory from .disabled
212
+ disabled_dir = os.path.join(schemas_dir, f"{server_name}.disabled")
213
+ active_dir = os.path.join(schemas_dir, server_name)
214
+ renamed = False
215
+ if os.path.isdir(disabled_dir):
216
+ try:
217
+ os.rename(disabled_dir, active_dir)
218
+ renamed = True
219
+ except Exception:
220
+ pass
221
+
222
+ return {
223
+ "success": modified or renamed,
224
+ "server_name": server_name,
225
+ "config_updated": modified,
226
+ "directory_renamed": renamed
227
+ }
228
+
229
+ @classmethod
230
+ def format_cli_report(cls) -> str:
231
+ """Formats visual CLI report for agy-tokens doctor."""
232
+ report = cls.audit()
233
+ lines = [
234
+ "\n\033[1m\033[36m⚡ TOKENSAFE ENVIRONMENT AUDIT (CONTEXT TAX DOCTOR) ⚡\033[0m\n",
235
+ f" \033[1mTotal Base Context Tax:\033[0m ~{report['total_static_tokens_per_turn']:,} tokens on EVERY API turn\n",
236
+ " \033[1mActive MCP Servers:\033[0m"
237
+ ]
238
+
239
+ for name, s in sorted(report["servers"].items()):
240
+ if s["active"]:
241
+ if s["is_bloat"]:
242
+ status = f"\033[31m\033[1m✖ {name:<18} ({s['tool_count']:>3} tools) [CRITICAL BLOAT: ~{s['est_tokens_per_turn']:,} tok/turn]\033[0m"
243
+ else:
244
+ status = f"\033[32m✔ {name:<18} ({s['tool_count']:>3} tools) [~{s['est_tokens_per_turn']:,} tok/turn]\033[0m"
245
+ else:
246
+ status = f"\033[2m○ {name:<18} ({s['tool_count']:>3} tools) [Disabled]\033[0m"
247
+ lines.append(f" {status}")
248
+
249
+ lines.append(f"\n \033[1mInstalled Skills:\033[0m {report['total_skills']} skills (~{report['skills_tokens_per_turn']:,} tokens/turn)")
250
+
251
+ if report["has_critical_bloat"]:
252
+ lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
253
+ for b in report["bloated_servers"]:
254
+ lines.append(f" ➜ Run: \033[36m./bin/agy-tokens mcp disable {b['name']}\033[0m to save ~{b['est_tokens_per_turn']:,} tokens per turn!")
255
+ else:
256
+ lines.append("\n \033[32m✔ Environment healthy: No critical MCP bloat detected.\033[0m")
257
+
258
+ lines.append("")
259
+ return "\n".join(lines)
@@ -0,0 +1,166 @@
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
8
+ """
9
+
10
+ import os
11
+ import re
12
+ from typing import Dict, List, Any, Tuple, Optional
13
+ from src.tokenizer import count_tokens
14
+ from src.skeletonizer import Skeletonizer
15
+ from src.compactor import PromptCompactor
16
+ from src.metrics import MetricsTracker
17
+
18
+ class ContextGovernor:
19
+ """Monitors and enforces context ceilings before LLM dispatch."""
20
+
21
+ DEFAULT_MAX_TURN_TOKENS = int(os.environ.get("TOKENSAFE_MAX_TURN_TOKENS", "16000"))
22
+ DEFAULT_TARGET_TURN_TOKENS = int(os.environ.get("TOKENSAFE_TARGET_TURN_TOKENS", "10000"))
23
+
24
+ CODE_BLOCK_REGEX = re.compile(r"```([a-zA-Z0-9_\-+]*)\n(.*?)```", re.DOTALL)
25
+
26
+ @classmethod
27
+ def govern_messages(
28
+ cls,
29
+ messages: List[Dict[str, Any]],
30
+ max_tokens: Optional[int] = None,
31
+ target_tokens: Optional[int] = None,
32
+ session_id: str = "governor_session"
33
+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
34
+ """
35
+ Inspects message list. If total tokens exceed max_tokens, applies cascading
36
+ reductions until within target_tokens budget.
37
+ """
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
40
+
41
+ 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)
57
+ if initial_tokens <= max_budget:
58
+ return messages, {
59
+ "throttled": False,
60
+ "initial_tokens": initial_tokens,
61
+ "current_tokens": initial_tokens,
62
+ "saved_tokens": 0,
63
+ "actions": []
64
+ }
65
+
66
+ actions_taken = []
67
+ governed_messages = [dict(m) for m in messages]
68
+ 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:
103
+ 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)
141
+
142
+ saved = max(0, initial_tokens - current_tokens)
143
+ if saved > 0:
144
+ try:
145
+ tracker = MetricsTracker()
146
+ tracker.record_event(
147
+ session_id=session_id,
148
+ event_type="CONTEXT_GOVERNOR",
149
+ original_tokens=initial_tokens,
150
+ optimized_tokens=current_tokens,
151
+ details={
152
+ "actions": actions_taken,
153
+ "max_budget": max_budget,
154
+ "target_budget": target_budget
155
+ }
156
+ )
157
+ except Exception:
158
+ pass
159
+
160
+ return governed_messages, {
161
+ "throttled": True,
162
+ "initial_tokens": initial_tokens,
163
+ "current_tokens": current_tokens,
164
+ "saved_tokens": saved,
165
+ "actions": actions_taken
166
+ }