tokensafe 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,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
+ }
package/src/installer.py CHANGED
@@ -30,6 +30,18 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
30
  MCP_SERVER_PATH = os.path.join(PROJECT_ROOT, "src", "mcp_server.py")
31
31
  PYTHON_BIN = sys.executable
32
32
 
33
+ UNIFIED_TOKENSAFE_RULE = (
34
+ "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
35
+ "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
36
+ "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
37
+ "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
38
+ "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
39
+ "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
40
+ "5. **Proof-of-Savings Turn Footer (English default)**:\n"
41
+ "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"
42
+ "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`\n"
43
+ )
44
+
33
45
  AGENTS_REGISTRY = {
34
46
  "antigravity": {
35
47
  "name": "Google Antigravity",
@@ -57,12 +69,14 @@ AGENTS_REGISTRY = {
57
69
  "name": "Windsurf",
58
70
  "type": "mcp_json",
59
71
  "config_path": os.path.join(HOME, ".codeium", "windsurf", "mcp_config.json"),
72
+ "rules_path": os.path.join(HOME, ".codeium", "windsurf", "memories", "global_rules.md"),
60
73
  "detect_path": os.path.join(HOME, ".codeium", "windsurf")
61
74
  },
62
75
  "cline": {
63
76
  "name": "Cline / Roo Code (VS Code)",
64
77
  "type": "mcp_json",
65
78
  "config_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "cline_mcp_settings.json"),
79
+ "rules_path": os.path.join(HOME, "Library", "Application Support", "Code", "User", "globalStorage", "saoudrizwan.claude-dev", "settings", "Rule_TokenSafe.md"),
66
80
  "detect_path": os.path.join(HOME, "Library", "Application Support", "Code")
67
81
  },
68
82
  "claude_code": {
@@ -171,14 +185,11 @@ class AgentInstaller:
171
185
  "globs: *\n"
172
186
  "alwaysApply: true\n"
173
187
  "---\n\n"
174
- "# TokenSafe Graph-First Optimization Protocol\n"
175
- "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
176
- "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
177
- "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
178
- "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
179
- "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
188
+ + UNIFIED_TOKENSAFE_RULE
180
189
  )
181
190
  cls._write_file_safely(info["rules_path"], rule_text)
191
+ cursorrules = os.path.join(HOME, ".cursorrules")
192
+ cls._inject_global_rule(cursorrules, UNIFIED_TOKENSAFE_RULE)
182
193
 
183
194
  return True, f"Configured MCP, Extension & Rule for Cursor"
184
195
 
@@ -215,6 +226,9 @@ class AgentInstaller:
215
226
  if "skills_path" in info:
216
227
  cls._symlink_skill(info["skills_path"])
217
228
 
229
+ if "rules_path" in info:
230
+ cls._inject_global_rule(info["rules_path"], UNIFIED_TOKENSAFE_RULE)
231
+
218
232
  return True, f"Updated MCP configuration at {config_file}"
219
233
 
220
234
  elif info["type"] == "codex_toml":
@@ -252,15 +266,7 @@ class AgentInstaller:
252
266
  cls._symlink_dir(PROJECT_ROOT, info["plugin_path"])
253
267
 
254
268
  if "agents_md_path" in info:
255
- codex_rule = (
256
- "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
257
- "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n"
258
- "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
259
- "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
260
- "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
261
- "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
262
- )
263
- cls._inject_global_rule(info["agents_md_path"], codex_rule)
269
+ cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
264
270
 
265
271
  return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
266
272
 
@@ -284,15 +290,7 @@ class AgentInstaller:
284
290
  json.dump(data, f, indent=2)
285
291
 
286
292
  if "agents_md_path" in info:
287
- claude_rule = (
288
- "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
289
- "Always prioritize `tokensafe` MCP tools over default raw file reads or recursive grep/find.\n"
290
- "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
291
- "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
292
- "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
293
- "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
294
- )
295
- cls._inject_global_rule(info["agents_md_path"], claude_rule)
293
+ cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
296
294
 
297
295
  if "skills_path" in info:
298
296
  cls._symlink_skill(info["skills_path"])
@@ -354,15 +352,7 @@ class AgentInstaller:
354
352
  cls._symlink_dir(PROJECT_ROOT, info["plugin_path"])
355
353
 
356
354
  if "agents_md_path" in info:
357
- zcode_rule = (
358
- "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
359
- "Always prioritize `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n"
360
- "1. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph` before grep or multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
361
- "2. **Graph-Guided Symbol Inspection**: When inspecting code implementations, prioritize `tokensafe:smart_read_file` with the targeted `symbol`. Returns full executable bodies for the symbol and 1-hop dependencies while folding inert code into signatures (-85% to -92% tokens).\n"
362
- "3. **No Unconstrained Shell Grep/Find**: Strictly avoid running raw recursive grep/find across projects. Use `get_architecture_graph` or `get_api_surface`.\n"
363
- "4. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
364
- )
365
- cls._inject_global_rule(info["agents_md_path"], zcode_rule)
355
+ cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
366
356
 
367
357
  return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
368
358
 
@@ -422,6 +412,87 @@ class AgentInstaller:
422
412
  skill_src = os.path.join(PROJECT_ROOT, "skills", "token-optimizer")
423
413
  cls._symlink_dir(skill_src, target_path)
424
414
 
415
+ @classmethod
416
+ def install_project(cls, project_dir: Optional[str] = None) -> Dict[str, Any]:
417
+ """Injects TokenSafe rules and MCP configs directly into a target project workspace."""
418
+ if not project_dir:
419
+ project_dir = os.getcwd()
420
+ project_dir = os.path.abspath(project_dir)
421
+
422
+ rule_files = [
423
+ os.path.join(project_dir, "AGENTS.md"),
424
+ os.path.join(project_dir, "CLAUDE.md"),
425
+ os.path.join(project_dir, ".cursorrules"),
426
+ os.path.join(project_dir, ".windsurfrules"),
427
+ os.path.join(project_dir, ".clinerules"),
428
+ os.path.join(project_dir, ".github", "copilot-instructions.md"),
429
+ os.path.join(project_dir, ".cursor", "rules", "tokensafe.mdc"),
430
+ ]
431
+
432
+ cursor_mdc_header = (
433
+ "---\n"
434
+ "description: TokenSafe token economy, graph-first navigation and context optimization protocol\n"
435
+ "globs: *\n"
436
+ "alwaysApply: true\n"
437
+ "---\n\n"
438
+ )
439
+
440
+ created = []
441
+ for rf in rule_files:
442
+ try:
443
+ if rf.endswith(".mdc"):
444
+ cls._write_file_safely(rf, cursor_mdc_header + UNIFIED_TOKENSAFE_RULE)
445
+ else:
446
+ cls._inject_global_rule(rf, UNIFIED_TOKENSAFE_RULE)
447
+ created.append(os.path.relpath(rf, project_dir))
448
+ except Exception:
449
+ pass
450
+
451
+ # Also inject project-local .cursor/mcp.json
452
+ cursor_mcp = os.path.join(project_dir, ".cursor", "mcp.json")
453
+ try:
454
+ os.makedirs(os.path.dirname(cursor_mcp), exist_ok=True)
455
+ data = {}
456
+ if os.path.exists(cursor_mcp):
457
+ try:
458
+ with open(cursor_mcp, "r", encoding="utf-8") as f:
459
+ data = json.load(f)
460
+ except Exception:
461
+ data = {}
462
+ if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
463
+ data["mcpServers"] = {}
464
+ data["mcpServers"]["tokensafe"] = {
465
+ "command": PYTHON_BIN,
466
+ "args": [MCP_SERVER_PATH]
467
+ }
468
+ with open(cursor_mcp, "w", encoding="utf-8") as f:
469
+ json.dump(data, f, indent=2)
470
+ created.append(".cursor/mcp.json")
471
+ except Exception:
472
+ pass
473
+
474
+ return {
475
+ "success": True,
476
+ "project_dir": project_dir,
477
+ "created_rules": created
478
+ }
479
+
480
+ @classmethod
481
+ def install_all(cls, force: bool = False) -> Dict[str, Any]:
482
+ """Automatically installs TokenSafe to all detected (or all registered) AI agents."""
483
+ agents = cls.detect_available_agents()
484
+ results = {}
485
+ for key, info in agents.items():
486
+ if info["installed"] or force:
487
+ ok, msg = cls.install_mcp_config(key)
488
+ results[key] = {"name": info["name"], "success": ok, "message": msg}
489
+ # Also configure project rules
490
+ proj_res = cls.install_project(os.getcwd())
491
+ return {
492
+ "agents": results,
493
+ "project_rules": proj_res.get("created_rules", [])
494
+ }
495
+
425
496
  @classmethod
426
497
  def run_interactive(cls):
427
498
  """Interactive terminal UI asking developer which agents to connect."""