tokensafe 2.2.1 → 2.4.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.
@@ -9,12 +9,28 @@ so rewrites never leak pathspecs into an unrelated stage (e.g. lockfile
9
9
  excludes landing on `npm test` after `git diff && npm test`).
10
10
  """
11
11
 
12
+ import json
13
+ import os
12
14
  import re
13
15
  from typing import Tuple, Dict, Any, List, Optional
14
16
 
15
17
  class CommandSanitizer:
16
18
  """Optimizes terminal command lines to eliminate token waste."""
17
19
 
20
+ # Test-runner guard: spots jest/vitest/package-manager test stages so they
21
+ # can be forced into run-once mode (a watch-mode command never exits, and
22
+ # an agent blocked on its completion waits forever)
23
+ _TOKENSAFE_TESTS_RE = re.compile(r"\btokensafe\s+tests?\b")
24
+ _VITEST_RE = re.compile(r"^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?vitest(?:\s|$)")
25
+ _JEST_RE = re.compile(r"^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+)?(?:npx\s+|yarn\s+|pnpm\s+|bunx\s+)?jest(?:\s|$)")
26
+ _JEST_SCRIPT_RE = re.compile(r"\b(?:react-scripts|craco)\s+test\b")
27
+ _PKG_MANAGER_TEST_RE = re.compile(r"\b(?:yarn|npm|pnpm|bun)\s+(?:run\s+)?test\b")
28
+ # Jest-only flags positively fingerprint jest behind an opaque test script
29
+ _JEST_FINGERPRINT_RE = re.compile(r"--watchAll|--detectOpenHandles|--testPathPattern|--testMatch|--runInBand")
30
+ _BARE_WATCH_RE = re.compile(r"\s--watch(?=[\s]|$)")
31
+ _NPM_TEST_RE = re.compile(r"\bnpm\s+(?:run\s+)?test[\w:./-]*")
32
+ _CD_RE = re.compile(r'^\s*cd\s+(["\']?)(.+?)\1\s*$')
33
+
18
34
  # Lockfiles and binary patterns that should never be dumped in git diffs or searches
19
35
  LOCKFILE_EXCLUDES = [
20
36
  "':!package-lock.json'",
@@ -151,7 +167,7 @@ class CommandSanitizer:
151
167
  return bool(re.search(r"(^|\s)[0-9&]*>{1,2}", stage))
152
168
 
153
169
  @classmethod
154
- def _optimize_stage(cls, stage: str) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
170
+ def _optimize_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, Optional[Tuple[str, int]]]]:
155
171
  """
156
172
  Applies one rewrite rule to a single stage.
157
173
  Returns (new_stage, est_saved, reason, cap_spec) or None.
@@ -190,6 +206,12 @@ class CommandSanitizer:
190
206
  if not has_tb:
191
207
  return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
192
208
 
209
+ # test runners: agents block on these in the background; watch mode or
210
+ # an unclosed jest handle means the process never exits (infinite wait)
211
+ guard = cls._optimize_test_stage(stage, cwd)
212
+ if guard:
213
+ return guard
214
+
193
215
  # find: prune unbounded recursion
194
216
  if re.search(r"\bfind\s+(\.|\/|\w+)\s*$", stage) or re.search(r"\bfind\s+\.\s+-name\b", stage):
195
217
  if "node_modules" not in stage and ".git" not in stage:
@@ -274,11 +296,132 @@ class CommandSanitizer:
274
296
  return None
275
297
 
276
298
  @classmethod
277
- def sanitize(cls, command: str) -> Tuple[Optional[str], int, str]:
299
+ def _optimize_test_stage(cls, stage: str, cwd: Optional[str] = None) -> Optional[Tuple[str, int, str, None]]:
300
+ """
301
+ Forces run-once mode on JS test-runner stages. Agents launch these in
302
+ the background and block until process exit; watch mode or an unclosed
303
+ jest handle ("Jest did not exit one second after the test run has
304
+ completed") means the process never terminates and the agent waits
305
+ forever. The guard:
306
+ - normalizes bare --watch / --watchAll to =false for jest-family,
307
+ - rewrites bare `vitest` to `vitest run` (--watch=false is unreliable),
308
+ - appends --forceExit for jest-family so open handles cannot stall exit,
309
+ - inserts ` -- ` after `npm test` so args reach the runner (npm
310
+ silently swallows them otherwise, leaving default watch mode on),
311
+ - prepends CI=true as a run-once fallback for opaque package scripts
312
+ (CRA and vitest both gate watch mode on the CI variable).
313
+ An opaque `yarn/npm test` script is classified via a jest-only flag
314
+ fingerprint (--watchAll, --detectOpenHandles...) when present; without
315
+ one, `cwd` unlocks a package.json peek at scripts.test ("react-scripts
316
+ test" -> script-jest, "vitest" -> script-vitest). No cwd or an
317
+ unrecognized script falls back to the conservative generic treatment.
318
+ """
319
+ if cls._TOKENSAFE_TESTS_RE.search(stage):
320
+ return None
321
+ if cls._VITEST_RE.match(stage):
322
+ runner = "vitest"
323
+ elif cls._JEST_RE.match(stage) or cls._JEST_SCRIPT_RE.search(stage):
324
+ runner = "jest"
325
+ elif cls._PKG_MANAGER_TEST_RE.search(stage):
326
+ if cls._JEST_FINGERPRINT_RE.search(stage):
327
+ runner = "jest"
328
+ else:
329
+ script_runner = cls._peek_test_script_runner(cwd)
330
+ runner = {"jest": "script-jest", "vitest": "script-vitest"}.get(script_runner, "generic")
331
+ else:
332
+ return None
333
+
334
+ new_stage = stage
335
+ reasons: List[str] = []
336
+ saved = 0
337
+
338
+ if runner in ("vitest", "script-vitest"):
339
+ if cls._BARE_WATCH_RE.search(new_stage):
340
+ new_stage = cls._BARE_WATCH_RE.sub("", new_stage)
341
+ reasons.append("Dropped bare --watch from vitest command")
342
+ saved += 300
343
+ if runner == "vitest" and not re.search(r"\bvitest\s+run\b", new_stage):
344
+ new_stage = re.sub(r"\bvitest\b", "vitest run", new_stage, count=1)
345
+ reasons.append("Rewrote vitest to one-shot `vitest run`")
346
+ saved += 400
347
+ elif runner in ("jest", "script-jest"):
348
+ if cls._BARE_WATCH_RE.search(new_stage):
349
+ new_stage = cls._BARE_WATCH_RE.sub(" --watch=false", new_stage)
350
+ reasons.append("Normalized bare --watch to --watch=false")
351
+ saved += 400
352
+ if re.search(r"\s--watchAll(?=[\s]|$)", new_stage):
353
+ new_stage = re.sub(r"\s--watchAll(?=[\s]|$)", " --watchAll=false", new_stage)
354
+ reasons.append("Normalized bare --watchAll to --watchAll=false")
355
+ saved += 400
356
+ if runner == "script-jest" and "--watch=false" not in new_stage:
357
+ # A script like "jest --watch" can bake watch mode in; jest's
358
+ # yargs parser takes the last flag, so this one wins over it
359
+ new_stage += " --watch=false"
360
+ reasons.append("Appended --watch=false (package.json script may bake watch mode in)")
361
+ saved += 300
362
+ if "--forceExit" not in new_stage:
363
+ new_stage += " --forceExit"
364
+ reasons.append("Appended --forceExit so jest exits despite open handles")
365
+ saved += 800
366
+
367
+ # npm silently swallows args without ` -- `: in `npm test --watchAll=false`
368
+ # the flag never reaches jest, which then stays on its default watch mode
369
+ npm_match = cls._NPM_TEST_RE.search(new_stage)
370
+ if npm_match and " -- " not in new_stage and new_stage[npm_match.end():].strip():
371
+ new_stage = new_stage[:npm_match.end()] + " -- " + new_stage[npm_match.end():].lstrip()
372
+ reasons.append("Inserted ` -- ` so npm forwards args to the test runner")
373
+ saved += 600
374
+
375
+ if not re.search(r"\bCI=", new_stage):
376
+ new_stage = f"CI=true {new_stage}"
377
+ saved += 300
378
+ if runner == "generic":
379
+ reasons.append("Prepended CI=true so an unknown test runner stays in run-once mode")
380
+ else:
381
+ reasons.append("Prepended CI=true for run-once mode")
382
+
383
+ if not reasons:
384
+ return None
385
+ return new_stage, saved, "; ".join(reasons), None
386
+
387
+ @classmethod
388
+ def _peek_test_script_runner(cls, cwd: Optional[str]) -> Optional[str]:
389
+ """
390
+ Classifies the runner behind an opaque package.json test script
391
+ (e.g. "test": "react-scripts test" -> "jest"). Returns "jest",
392
+ "vitest", or None when cwd is unknown, package.json is missing or
393
+ unreadable, or the script is an unrecognized runner — callers then
394
+ fall back to the conservative generic treatment.
395
+ """
396
+ if not cwd:
397
+ return None
398
+ try:
399
+ with open(os.path.join(cwd, "package.json"), "r", encoding="utf-8") as fh:
400
+ data = json.load(fh)
401
+ except (OSError, ValueError):
402
+ return None
403
+ if not isinstance(data, dict):
404
+ return None
405
+ scripts = data.get("scripts")
406
+ script = scripts.get("test") if isinstance(scripts, dict) else None
407
+ if not isinstance(script, str):
408
+ return None
409
+ if re.search(r"\bvitest\b", script):
410
+ return "vitest"
411
+ if re.search(r"\bjest\b", script) or cls._JEST_SCRIPT_RE.search(script):
412
+ return "jest"
413
+ return None
414
+
415
+ @classmethod
416
+ def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
278
417
  """
279
418
  Analyzes a shell command stage by stage. If any stage creates massive
280
419
  token waste, returns (rewritten_command, est_tokens_saved, reason).
281
420
  If no change is needed, returns (None, 0, "").
421
+ `cwd` is the working directory the command will run in; when provided,
422
+ the test-runner guard may read <cwd>/package.json to identify the
423
+ runner behind an opaque test script. A `cd` stage updates that
424
+ directory for the stages that follow (cd app && yarn test ...).
282
425
  """
283
426
  if not command or not command.strip():
284
427
  return None, 0, ""
@@ -288,9 +431,18 @@ class CommandSanitizer:
288
431
  total_saved = 0
289
432
  reasons: List[str] = []
290
433
  cap_spec: Optional[Tuple[str, int]] = None
434
+ current_dir = os.path.abspath(os.path.expanduser(cwd)) if cwd else None
291
435
 
292
436
  for i, (op, stage) in enumerate(pairs):
293
- res = cls._optimize_stage(stage)
437
+ cd_match = cls._CD_RE.match(stage)
438
+ if cd_match:
439
+ target = os.path.expanduser(cd_match.group(2).strip())
440
+ if target and target != "-":
441
+ base = current_dir or os.getcwd()
442
+ current_dir = os.path.normpath(
443
+ target if os.path.isabs(target) else os.path.join(base, target)
444
+ )
445
+ res = cls._optimize_stage(stage, current_dir)
294
446
  if not res:
295
447
  continue
296
448
  new_stage, saved, reason, rule_cap = res
package/src/compactor.py CHANGED
@@ -268,7 +268,6 @@ class PromptCompactor:
268
268
  (re.compile(r"\b(mysql)\b", re.I), "mysql"),
269
269
  (re.compile(r"\b(prisma|призма)\b", re.I), "prisma"),
270
270
  (re.compile(r"\b(docker|докер)\b", re.I), "docker"),
271
- (re.compile(r"\b(bunny|банни)\b", re.I), "bunny"),
272
271
  (re.compile(r"\b(jwt|токен\w*|auth|авторизац\w*|autenticaci[oó]n|authentification|token)\b|(认证|認証)", re.I), "jwt"),
273
272
  (re.compile(r"\b(oauth)\b", re.I), "oauth"),
274
273
  (re.compile(r"\b(zero_alloc|без\s+аллокаций|sin\s+asignaciones|ohne\s+allokation)\b", re.I), "zero_alloc"),
@@ -12,6 +12,8 @@ from collections import OrderedDict
12
12
  from datetime import datetime
13
13
  from typing import Optional, Dict, Any
14
14
 
15
+ from src.paths import resolve_data_dir
16
+
15
17
  class DistillationCache:
16
18
  """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite)."""
17
19
 
@@ -39,8 +41,7 @@ class DistillationCache:
39
41
  if cls._db_path:
40
42
  return cls._db_path
41
43
 
42
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
43
- data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(base_dir, "data"))
44
+ data_dir = resolve_data_dir()
44
45
  os.makedirs(data_dir, exist_ok=True)
45
46
  cls._db_path = os.path.join(data_dir, "metrics.db")
46
47
  return cls._db_path
@@ -2,19 +2,30 @@
2
2
  Environment Auditor & Context Bloat Guard for Antigravity Token Optimizer.
3
3
  Detects heavy MCP servers, redundant tool schemas, and excessive skills that bloat
4
4
  the system prompt on every API turn. Provides one-click enable/disable toggles.
5
+ Also audits always-on rule files against the Antigravity limits (rules.md):
6
+ 24 KB per file after @[label](path) expansion, 20,000-token shared budget.
5
7
  """
6
8
 
7
9
  import os
10
+ import re
8
11
  import json
9
12
  from typing import Dict, List, Any, Optional
10
13
 
14
+ from src.tokenizer import count_tokens
15
+
11
16
  EST_TOKENS_PER_TOOL = 25
12
17
  EST_TOKENS_PER_SKILL = 180
13
18
  CRITICAL_TOOL_COUNT_THRESHOLD = 40
14
19
 
20
+ # rules.md contract limits
21
+ RULE_FILE_LIMIT_BYTES = 24000 # per rule file, after @[label](path) expansion
22
+ RULES_BUDGET_TOKENS = 20000 # shared always-on/global rules budget
23
+
24
+ _RULE_INCLUDE_RE = re.compile(r"@\[[^\]]*\]\(([^)]+)\)")
25
+
15
26
 
16
27
  class EnvironmentAuditor:
17
- """Scans and audits static context overhead (MCP servers and skills)."""
28
+ """Scans and audits static context overhead (MCP servers, skills, rules)."""
18
29
 
19
30
  @classmethod
20
31
  def get_config_paths(cls) -> List[str]:
@@ -29,30 +40,158 @@ class EnvironmentAuditor:
29
40
  return os.path.join(os.path.expanduser("~"), ".gemini", "antigravity", "mcp")
30
41
 
31
42
  @classmethod
32
- def get_skills_dirs(cls) -> List[str]:
43
+ def get_skills_dirs(cls, workspace_root: Optional[str] = None) -> List[str]:
44
+ """Global skill roots plus the workspace `.agents/` customization dir
45
+ (json_configs.md: one level deep, entries scanned for SKILL.md)."""
33
46
  home = os.path.expanduser("~")
34
47
  dirs = [
35
48
  os.path.join(home, ".gemini", "config", "skills"),
36
49
  os.path.join(home, ".gemini", "config", "plugins"),
37
50
  os.path.join(home, ".gemini", "antigravity", "builtin", "skills"),
51
+ os.path.join(workspace_root or os.getcwd(), ".agents"),
38
52
  ]
39
53
  return [d for d in dirs if os.path.isdir(d)]
40
54
 
55
+ @classmethod
56
+ def get_plugins_dir(cls) -> str:
57
+ return os.path.join(os.path.expanduser("~"), ".gemini", "config", "plugins")
58
+
59
+ @classmethod
60
+ def get_enable_state_path(cls) -> str:
61
+ return os.path.join(os.path.expanduser("~"), ".gemini", "config", "config.json")
62
+
63
+ @classmethod
64
+ def _get_disabled_plugin_names(cls) -> set:
65
+ """Plugin directory names that are switched off. plugins.md: the
66
+ enable-state lives in config.json under a `plugins` map keyed by the
67
+ plugin's directory name; a `plugin.json` `"disabled": true` also ships
68
+ a plugin switched off."""
69
+ disabled = set()
70
+ state_path = cls.get_enable_state_path()
71
+ if os.path.isfile(state_path):
72
+ try:
73
+ with open(state_path, "r", encoding="utf-8") as f:
74
+ plugins_state = json.load(f).get("plugins", {})
75
+ for name, state in plugins_state.items():
76
+ if isinstance(state, dict) and state.get("enabled") is False:
77
+ disabled.add(name)
78
+ except Exception:
79
+ pass
80
+ plugins_dir = cls.get_plugins_dir()
81
+ if os.path.isdir(plugins_dir):
82
+ for entry in os.listdir(plugins_dir):
83
+ manifest = os.path.join(plugins_dir, entry, "plugin.json")
84
+ if os.path.isfile(manifest):
85
+ try:
86
+ with open(manifest, "r", encoding="utf-8") as f:
87
+ if json.load(f).get("disabled") is True:
88
+ disabled.add(entry)
89
+ except Exception:
90
+ pass
91
+ return disabled
92
+
41
93
  @classmethod
42
94
  def get_configured_mcp_servers(cls) -> Dict[str, Any]:
95
+ configured: Dict[str, Any] = {}
96
+ # Merge EVERY present config file: both ~/.gemini/config and the
97
+ # antigravity dir can legitimately carry servers (they are merged by
98
+ # Antigravity too), so breaking on the first one undercounts.
43
99
  for p in cls.get_config_paths():
44
100
  if os.path.isfile(p):
45
101
  try:
46
102
  with open(p, "r", encoding="utf-8") as f:
47
- data = json.load(f)
48
- return data.get("mcpServers", {})
103
+ configured.update(json.load(f).get("mcpServers", {}))
104
+ except Exception:
105
+ continue
106
+ # Plugin-declared servers (plugins/<name>/mcp_config.json) are loaded
107
+ # by Antigravity together with the plugin — audit them too, unless the
108
+ # plugin itself is disabled.
109
+ disabled = cls._get_disabled_plugin_names()
110
+ plugins_dir = cls.get_plugins_dir()
111
+ if os.path.isdir(plugins_dir):
112
+ for entry in sorted(os.listdir(plugins_dir)):
113
+ if entry in disabled or entry.endswith(".disabled"):
114
+ continue
115
+ plugin_cfg = os.path.join(plugins_dir, entry, "mcp_config.json")
116
+ if not os.path.isfile(plugin_cfg):
117
+ continue
118
+ try:
119
+ with open(plugin_cfg, "r", encoding="utf-8") as f:
120
+ configured.update(json.load(f).get("mcpServers", {}))
49
121
  except Exception:
50
122
  continue
51
- return {}
123
+ return configured
52
124
 
53
125
  @classmethod
54
- def audit(cls) -> Dict[str, Any]:
55
- """Audits all active MCP servers and skills for context footprint."""
126
+ def _load_rule_text(cls, path: str, depth: int = 1) -> str:
127
+ """Reads a rule file with one level of @[label](path) include expansion."""
128
+ try:
129
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
130
+ text = f.read()
131
+ except Exception:
132
+ return ""
133
+
134
+ if depth <= 0:
135
+ return text
136
+
137
+ def _sub(match: "re.Match[str]") -> str:
138
+ inc = match.group(1)
139
+ if not os.path.isabs(inc):
140
+ inc = os.path.join(os.path.dirname(path), inc)
141
+ try:
142
+ with open(inc, "r", encoding="utf-8", errors="replace") as f:
143
+ return f.read()
144
+ except Exception:
145
+ return ""
146
+
147
+ return _RULE_INCLUDE_RE.sub(_sub, text)
148
+
149
+ @classmethod
150
+ def audit_rules(cls, workspace_root: Optional[str] = None) -> Dict[str, Any]:
151
+ """Audits workspace rule files against the rules.md limits.
152
+
153
+ Scans AGENTS.md / GEMINI.md at the workspace root and .agents/rules/*.md.
154
+ Per-file: effective byte size after include expansion vs the 24 KB cap.
155
+ Aggregate: token count vs the 20,000-token always-on rules budget
156
+ (exceeding it demotes rules to file-path pointers)."""
157
+ root = workspace_root or os.getcwd()
158
+ candidates = [
159
+ os.path.join(root, "AGENTS.md"),
160
+ os.path.join(root, "GEMINI.md"),
161
+ ]
162
+ rules_dir = os.path.join(root, ".agents", "rules")
163
+ if os.path.isdir(rules_dir):
164
+ for entry in sorted(os.listdir(rules_dir)):
165
+ if entry.endswith(".md"):
166
+ candidates.append(os.path.join(rules_dir, entry))
167
+
168
+ violations: List[Dict[str, Any]] = []
169
+ total_tokens = 0
170
+ files_count = 0
171
+ for path in candidates:
172
+ if not os.path.isfile(path):
173
+ continue
174
+ files_count += 1
175
+ text = cls._load_rule_text(path)
176
+ effective_bytes = len(text.encode("utf-8", errors="replace"))
177
+ total_tokens += count_tokens(text)
178
+ if effective_bytes > RULE_FILE_LIMIT_BYTES:
179
+ violations.append({
180
+ "path": os.path.relpath(path, root),
181
+ "effective_bytes": effective_bytes,
182
+ "limit_bytes": RULE_FILE_LIMIT_BYTES,
183
+ })
184
+
185
+ return {
186
+ "files": files_count,
187
+ "total_tokens": total_tokens,
188
+ "budget_exceeded": total_tokens > RULES_BUDGET_TOKENS,
189
+ "violations": violations,
190
+ }
191
+
192
+ @classmethod
193
+ def audit(cls, workspace_root: Optional[str] = None) -> Dict[str, Any]:
194
+ """Audits all active MCP servers, skills and rules for context footprint."""
56
195
  configured = cls.get_configured_mcp_servers()
57
196
  schemas_dir = cls.get_mcp_schemas_dir()
58
197
 
@@ -97,11 +236,14 @@ class EnvironmentAuditor:
97
236
 
98
237
  # 2. Count skills
99
238
  skills_count = 0
100
- for sdir in cls.get_skills_dirs():
239
+ for sdir in cls.get_skills_dirs(workspace_root):
101
240
  for root, dirs, files in os.walk(sdir):
102
241
  if "SKILL.md" in files:
103
242
  skills_count += 1
104
243
 
244
+ # 3. Rule files (rules.md limits)
245
+ rules = cls.audit_rules(workspace_root)
246
+
105
247
  total_mcp_tools = sum(s["tool_count"] for s in servers.values() if s["active"])
106
248
  total_mcp_tokens = sum(s["est_tokens_per_turn"] for s in servers.values() if s["active"])
107
249
  total_skills_tokens = skills_count * EST_TOKENS_PER_SKILL
@@ -118,23 +260,42 @@ class EnvironmentAuditor:
118
260
  "skills_tokens_per_turn": total_skills_tokens,
119
261
  "total_static_tokens_per_turn": total_static_tokens,
120
262
  "bloated_servers": bloated_servers,
121
- "has_critical_bloat": len(bloated_servers) > 0
263
+ "has_critical_bloat": len(bloated_servers) > 0,
264
+ "rules": rules
122
265
  }
123
266
 
124
267
  @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
268
+ def get_bloat_warning(cls, workspace_root: Optional[str] = None) -> Optional[str]:
269
+ """Returns a formatted warning string if critical context bloat or
270
+ rule-file overruns are detected."""
271
+ report = cls.audit(workspace_root)
272
+ parts: List[str] = []
130
273
 
131
- bloated = report["bloated_servers"]
132
- names = ", ".join([f"`{b['name']}` ({b['tool_count']} tools, ~{b['est_tokens_per_turn']:,} tokens/turn)" for b in bloated])
133
- return (
134
- f"⚠️ **TokenSafe Bloat Alert**: Heavy MCP server detected: {names}. "
135
- f"Static context overhead per turn: **~{report['total_static_tokens_per_turn']:,} tokens**. "
136
- f"Disable unused servers via `tokensafe mcp disable <name>`."
137
- )
274
+ if report["has_critical_bloat"]:
275
+ bloated = report["bloated_servers"]
276
+ names = ", ".join([f"`{b['name']}` ({b['tool_count']} tools, ~{b['est_tokens_per_turn']:,} tokens/turn)" for b in bloated])
277
+ parts.append(
278
+ f"Heavy MCP server detected: {names}. "
279
+ f"Static context overhead per turn: **~{report['total_static_tokens_per_turn']:,} tokens**. "
280
+ f"Disable unused servers via `tokensafe mcp disable <name>`."
281
+ )
282
+
283
+ rules = report.get("rules") or {}
284
+ if rules.get("budget_exceeded"):
285
+ parts.append(
286
+ f"Always-on rule files total ~{rules['total_tokens']:,} tokens — over the "
287
+ f"{RULES_BUDGET_TOKENS:,}-token rules budget; over-budget rules degrade to file-path pointers. "
288
+ f"Trim AGENTS.md / .agents/rules/*.md."
289
+ )
290
+ for v in rules.get("violations", []):
291
+ parts.append(
292
+ f"Rule file `{v['path']}` is {v['effective_bytes']:,} bytes after @[label](path) expansion — "
293
+ f"over the {RULE_FILE_LIMIT_BYTES:,}-byte per-file cap; it will be truncated."
294
+ )
295
+
296
+ if not parts:
297
+ return None
298
+ return "⚠️ **TokenSafe Bloat Alert**: " + " ".join(parts)
138
299
 
139
300
  @classmethod
140
301
  def disable_mcp(cls, server_name: str) -> Dict[str, Any]:
@@ -227,9 +388,9 @@ class EnvironmentAuditor:
227
388
  }
228
389
 
229
390
  @classmethod
230
- def format_cli_report(cls) -> str:
391
+ def format_cli_report(cls, workspace_root: Optional[str] = None) -> str:
231
392
  """Formats visual CLI report for tokensafe doctor."""
232
- report = cls.audit()
393
+ report = cls.audit(workspace_root)
233
394
  lines = [
234
395
  "\n\033[1m\033[36m⚡ TOKENSAFE ENVIRONMENT AUDIT (CONTEXT TAX DOCTOR) ⚡\033[0m\n",
235
396
  f" \033[1mTotal Base Context Tax:\033[0m ~{report['total_static_tokens_per_turn']:,} tokens on EVERY API turn\n",
@@ -248,6 +409,13 @@ class EnvironmentAuditor:
248
409
 
249
410
  lines.append(f"\n \033[1mInstalled Skills:\033[0m {report['total_skills']} skills (~{report['skills_tokens_per_turn']:,} tokens/turn)")
250
411
 
412
+ rules = report.get("rules") or {}
413
+ if rules.get("files"):
414
+ budget_flag = "\033[33mover budget\033[0m" if rules.get("budget_exceeded") else "\033[32mwithin budget\033[0m"
415
+ lines.append(f" \033[1mRule Files:\033[0m {rules['files']} files, ~{rules['total_tokens']:,}/20,000 tokens [{budget_flag}]")
416
+ for v in rules.get("violations", []):
417
+ lines.append(f" \033[31m✖ {v['path']}: {v['effective_bytes']:,} bytes > {RULE_FILE_LIMIT_BYTES:,} cap\033[0m")
418
+
251
419
  if report["has_critical_bloat"]:
252
420
  lines.append("\n \033[33m\033[1mDiagnostic Recommendation:\033[0m")
253
421
  for b in report["bloated_servers"]:
@@ -54,12 +54,14 @@ class HistoryCompactor:
54
54
  for tc in tool_calls:
55
55
  name = tc.get("name", "")
56
56
  args = tc.get("args", {})
57
- if name == "read_file":
58
- p = args.get("Path", "")
57
+ if name in ("read_file", "view_file"):
58
+ # 'view_file' is the IDE-surface name for read_file;
59
+ # arg keys keep proto casing but tolerate lowercase.
60
+ p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
59
61
  if p:
60
62
  read_files.add(os.path.basename(p))
61
63
  elif name in ("edit_file", "write_file"):
62
- p = args.get("Path", "")
64
+ p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
63
65
  if p:
64
66
  edited_files.add(os.path.basename(p))
65
67
  elif name == "run_command":