tokensafe 2.7.0 → 2.7.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.
Files changed (44) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +139 -83
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +65 -40
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +74 -47
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +1 -1
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +200 -60
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/slicer.py +15 -3
  39. package/src/team_cache.py +10 -3
  40. package/src/telemetry_sync.py +110 -39
  41. package/src/tokenizer.py +24 -13
  42. package/src/treesitter_backend.py +1 -0
  43. package/src/version_checker.py +67 -32
  44. package/src/weekly_digest.py +6 -3
@@ -24,6 +24,15 @@ _COMBINED_SLOT_RE = re.compile(
24
24
  _UNRESOLVED_SLOT_RE = re.compile(r"<(?:FILE|SYM)_\d+>")
25
25
 
26
26
 
27
+ _BRAND_PROPER_NOUNS = {
28
+ "github", "gitlab", "bitbucket", "deepseek", "openai", "anthropic",
29
+ "typescript", "javascript", "postgresql", "postgres", "mongodb",
30
+ "macos", "iphone", "ipad", "next.js", "node.js", "nuxt.js", "vue.js",
31
+ "cloudflare", "fastapi", "pytorch", "tensorflow", "graphql", "tailwind",
32
+ "oauth", "oauth2", "jwt", "tokensafe", "antigravity",
33
+ }
34
+
35
+
27
36
  class DistillationCache:
28
37
  """Thread-safe two-tier cache (In-Memory LRU + Persistent SQLite) with parametric slot templates."""
29
38
 
@@ -31,6 +40,7 @@ class DistillationCache:
31
40
  _memory_cache: OrderedDict = OrderedDict()
32
41
  _template_memory_cache: OrderedDict = OrderedDict()
33
42
  _MAX_MEMORY_ENTRIES = 1000
43
+ _MAX_SQLITE_ENTRIES = 5000
34
44
  _db_path: Optional[str] = None
35
45
  _initialized_dbs: set = set()
36
46
  _hits: int = 0
@@ -60,6 +70,8 @@ class DistillationCache:
60
70
  nonlocal file_idx, sym_idx
61
71
  file_val = m.group("file")
62
72
  if file_val:
73
+ if file_val.lower() in _BRAND_PROPER_NOUNS:
74
+ return file_val
63
75
  if file_val not in val_to_slot:
64
76
  slot = f"<FILE_{file_idx}>"
65
77
  file_idx += 1
@@ -68,6 +80,9 @@ class DistillationCache:
68
80
  return val_to_slot[file_val]
69
81
  sym_val = m.group("bt_sym") or m.group("sym")
70
82
  if sym_val:
83
+ # Only ignore proper nouns when NOT explicitly backticked
84
+ if not m.group("bt_sym") and sym_val.lower() in _BRAND_PROPER_NOUNS:
85
+ return sym_val
71
86
  if sym_val not in val_to_slot:
72
87
  slot = f"<SYM_{sym_idx}>"
73
88
  sym_idx += 1
@@ -77,33 +92,32 @@ class DistillationCache:
77
92
  return m.group(0)
78
93
 
79
94
  templated = _COMBINED_SLOT_RE.sub(repl_any, norm)
80
- # Lowercase surrounding natural language while keeping uppercase slot tokens intact
81
95
  parts = re.split(r"(<(?:FILE|SYM)_\d+>)", templated)
82
96
  normalized_tmpl = "".join(p if _UNRESOLVED_SLOT_RE.fullmatch(p) else p.lower() for p in parts)
83
97
  return normalized_tmpl, slots
84
98
 
85
99
  @classmethod
86
100
  def _to_template_sexpr(cls, distilled_text: str, slots: Dict[str, str]) -> Optional[str]:
87
- """Replaces extracted slot values in distilled S-Expression with placeholders."""
101
+ """Replaces extracted slot values in distilled S-Expression with placeholders using word boundaries."""
88
102
  if not slots:
89
103
  return None
90
104
  tmpl = distilled_text.strip()
91
- # Sort longest values first to avoid partial substring clashes
92
- replaced_any = False
105
+ replaced_count = 0
93
106
  for slot, val in sorted(slots.items(), key=lambda kv: len(kv[1]), reverse=True):
94
- if val in tmpl:
95
- tmpl = tmpl.replace(val, slot)
96
- replaced_any = True
97
- return tmpl if replaced_any else None
107
+ pat = re.compile(rf"(?<![A-Za-z0-9_]){re.escape(val)}(?![A-Za-z0-9_])")
108
+ tmpl_next, n_sub = pat.subn(slot, tmpl)
109
+ if n_sub > 0:
110
+ tmpl = tmpl_next
111
+ replaced_count += 1
112
+ # Require all extracted slots to be bound in template_sexpr so omitted slots never collide
113
+ return tmpl if replaced_count == len(slots) else None
98
114
 
99
115
  @classmethod
100
116
  def _instantiate_template(cls, template_sexpr: str, slots: Dict[str, str]) -> Optional[str]:
101
- """Substitutes current prompt's slots back into a cached template S-Expression."""
117
+ """Substitutes current prompt's slots back into a cached template S-Expression in a single pass."""
102
118
  if not template_sexpr:
103
119
  return None
104
- out = template_sexpr
105
- for slot, val in slots.items():
106
- out = out.replace(slot, val)
120
+ out = _UNRESOLVED_SLOT_RE.sub(lambda m: slots.get(m.group(0), m.group(0)), template_sexpr)
107
121
  if _UNRESOLVED_SLOT_RE.search(out):
108
122
  return None
109
123
  return out
@@ -112,40 +126,39 @@ class DistillationCache:
112
126
  def _get_db_path(cls) -> str:
113
127
  if cls._db_path:
114
128
  return cls._db_path
115
-
116
129
  data_dir = resolve_data_dir()
117
130
  os.makedirs(data_dir, exist_ok=True)
118
- cls._db_path = os.path.join(data_dir, "metrics.db")
119
- return cls._db_path
131
+ return os.path.join(data_dir, "metrics.db")
120
132
 
121
133
  @classmethod
122
134
  def _init_db(cls, conn: sqlite3.Connection):
123
135
  db_path = cls._get_db_path()
124
- if db_path in cls._initialized_dbs:
125
- return
126
- conn.execute("""
127
- CREATE TABLE IF NOT EXISTS distillation_cache (
128
- prompt_hash TEXT PRIMARY KEY,
129
- prompt_text TEXT,
130
- distilled_text TEXT NOT NULL,
131
- provider TEXT NOT NULL,
132
- created_at TEXT NOT NULL,
133
- hit_count INTEGER DEFAULT 0
134
- );
135
- """)
136
- conn.execute("CREATE INDEX IF NOT EXISTS idx_distill_hash ON distillation_cache(prompt_hash);")
137
- conn.execute("""
138
- CREATE TABLE IF NOT EXISTS distillation_templates (
139
- template_hash TEXT PRIMARY KEY,
140
- template_prompt TEXT,
141
- template_sexpr TEXT NOT NULL,
142
- provider TEXT NOT NULL,
143
- created_at TEXT NOT NULL,
144
- hit_count INTEGER DEFAULT 0
145
- );
146
- """)
147
- conn.commit()
148
- cls._initialized_dbs.add(db_path)
136
+ with cls._lock:
137
+ if db_path in cls._initialized_dbs and os.path.exists(db_path):
138
+ return
139
+ conn.execute("""
140
+ CREATE TABLE IF NOT EXISTS distillation_cache (
141
+ prompt_hash TEXT PRIMARY KEY,
142
+ prompt_text TEXT,
143
+ distilled_text TEXT NOT NULL,
144
+ provider TEXT NOT NULL,
145
+ created_at TEXT NOT NULL,
146
+ hit_count INTEGER DEFAULT 0
147
+ );
148
+ """)
149
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_distill_hash ON distillation_cache(prompt_hash);")
150
+ conn.execute("""
151
+ CREATE TABLE IF NOT EXISTS distillation_templates (
152
+ template_hash TEXT PRIMARY KEY,
153
+ template_prompt TEXT,
154
+ template_sexpr TEXT NOT NULL,
155
+ provider TEXT NOT NULL,
156
+ created_at TEXT NOT NULL,
157
+ hit_count INTEGER DEFAULT 0
158
+ );
159
+ """)
160
+ conn.commit()
161
+ cls._initialized_dbs.add(db_path)
149
162
 
150
163
  @classmethod
151
164
  def get(cls, prompt_text: str) -> Optional[str]:
@@ -211,7 +224,7 @@ class DistillationCache:
211
224
  if tmpl_sexpr:
212
225
  instantiated = cls._instantiate_template(tmpl_sexpr, slots)
213
226
  if instantiated:
214
- cls.set(prompt_text, instantiated, provider="template_cache", sync_remote=False)
227
+ cls.set(prompt_text, instantiated, provider="template_cache", sync_remote=False, store_template=False)
215
228
  with cls._lock:
216
229
  cls._hits += 1
217
230
  return instantiated
@@ -239,7 +252,7 @@ class DistillationCache:
239
252
  cls._template_memory_cache[tmpl_hash] = tmpl_sexpr_db
240
253
  if len(cls._template_memory_cache) > cls._MAX_MEMORY_ENTRIES:
241
254
  cls._template_memory_cache.popitem(last=False)
242
- cls.set(prompt_text, instantiated, provider="template_cache", sync_remote=False)
255
+ cls.set(prompt_text, instantiated, provider="template_cache", sync_remote=False, store_template=False)
243
256
  with cls._lock:
244
257
  cls._hits += 1
245
258
  return instantiated
@@ -277,7 +290,14 @@ class DistillationCache:
277
290
  return None
278
291
 
279
292
  @classmethod
280
- def set(cls, prompt_text: str, distilled_text: str, provider: str = "deepseek", sync_remote: bool = True) -> None:
293
+ def set(
294
+ cls,
295
+ prompt_text: str,
296
+ distilled_text: str,
297
+ provider: str = "deepseek",
298
+ sync_remote: bool = True,
299
+ store_template: bool = True,
300
+ ) -> None:
281
301
  """Stores a distillation result and parametric template into memory, SQLite, and Team Cache."""
282
302
  if not prompt_text or not distilled_text or not distilled_text.strip():
283
303
  return
@@ -287,16 +307,23 @@ class DistillationCache:
287
307
  clean_distilled = distilled_text.strip()
288
308
  now_iso = datetime.now().isoformat()
289
309
 
290
- tmpl_prompt, slots = cls._extract_template(prompt_text)
291
- tmpl_sexpr = cls._to_template_sexpr(clean_distilled, slots) if slots else None
292
- tmpl_hash = hashlib.sha256(tmpl_prompt.encode("utf-8")).hexdigest() if tmpl_sexpr else ""
310
+ tmpl_prompt = ""
311
+ slots: Dict[str, str] = {}
312
+ tmpl_sexpr: Optional[str] = None
313
+ tmpl_hash = ""
314
+ if store_template:
315
+ tmpl_prompt, slots = cls._extract_template(prompt_text)
316
+ tmpl_sexpr = cls._to_template_sexpr(clean_distilled, slots) if slots else None
317
+ tmpl_hash = hashlib.sha256(tmpl_prompt.encode("utf-8")).hexdigest() if tmpl_sexpr else ""
293
318
 
294
319
  with cls._lock:
295
320
  cls._memory_cache[h] = clean_distilled
321
+ cls._memory_cache.move_to_end(h)
296
322
  if len(cls._memory_cache) > cls._MAX_MEMORY_ENTRIES:
297
323
  cls._memory_cache.popitem(last=False)
298
324
  if tmpl_hash and tmpl_sexpr:
299
325
  cls._template_memory_cache[tmpl_hash] = tmpl_sexpr
326
+ cls._template_memory_cache.move_to_end(tmpl_hash)
300
327
  if len(cls._template_memory_cache) > cls._MAX_MEMORY_ENTRIES:
301
328
  cls._template_memory_cache.popitem(last=False)
302
329
 
@@ -313,7 +340,7 @@ class DistillationCache:
313
340
  distilled_text = excluded.distilled_text,
314
341
  provider = excluded.provider
315
342
  """, (h, norm_prompt[:500], clean_distilled, provider, now_iso))
316
- if tmpl_hash and tmpl_sexpr:
343
+ if store_template and tmpl_hash and tmpl_sexpr:
317
344
  cursor.execute("""
318
345
  INSERT INTO distillation_templates (template_hash, template_prompt, template_sexpr, provider, created_at, hit_count)
319
346
  VALUES (?, ?, ?, ?, ?, 0)
@@ -100,7 +100,9 @@ class EnvironmentAuditor:
100
100
  if os.path.isfile(p):
101
101
  try:
102
102
  with open(p, "r", encoding="utf-8") as f:
103
- configured.update(json.load(f).get("mcpServers", {}))
103
+ loaded = json.load(f)
104
+ if isinstance(loaded, dict) and isinstance(loaded.get("mcpServers"), dict):
105
+ configured.update(loaded["mcpServers"])
104
106
  except Exception:
105
107
  continue
106
108
  # Plugin-declared servers (plugins/<name>/mcp_config.json) are loaded
@@ -117,7 +119,9 @@ class EnvironmentAuditor:
117
119
  continue
118
120
  try:
119
121
  with open(plugin_cfg, "r", encoding="utf-8") as f:
120
- configured.update(json.load(f).get("mcpServers", {}))
122
+ loaded = json.load(f)
123
+ if isinstance(loaded, dict) and isinstance(loaded.get("mcpServers"), dict):
124
+ configured.update(loaded["mcpServers"])
121
125
  except Exception:
122
126
  continue
123
127
  return configured
@@ -136,13 +140,15 @@ class EnvironmentAuditor:
136
140
 
137
141
  def _sub(match: "re.Match[str]") -> str:
138
142
  inc = match.group(1)
143
+ if inc.startswith(("http://", "https://")):
144
+ return match.group(0)
139
145
  if not os.path.isabs(inc):
140
146
  inc = os.path.join(os.path.dirname(path), inc)
141
147
  try:
142
148
  with open(inc, "r", encoding="utf-8", errors="replace") as f:
143
149
  return f.read()
144
150
  except Exception:
145
- return ""
151
+ return match.group(0)
146
152
 
147
153
  return _RULE_INCLUDE_RE.sub(_sub, text)
148
154
 
@@ -234,10 +240,23 @@ class EnvironmentAuditor:
234
240
  "is_bloat": False
235
241
  }
236
242
 
237
- # 2. Count skills
243
+ # 2. Count skills (follow symlinked plugins/skills with cycle protection; skip disabled plugins)
238
244
  skills_count = 0
245
+ disabled_plugins = cls._get_disabled_plugin_names()
246
+ plugins_dir = os.path.abspath(cls.get_plugins_dir())
247
+ seen_skill_dirs = set()
239
248
  for sdir in cls.get_skills_dirs(workspace_root):
240
- for root, dirs, files in os.walk(sdir):
249
+ is_plugins_root = os.path.abspath(sdir) == plugins_dir
250
+ for root, dirs, files in os.walk(sdir, followlinks=True):
251
+ real_root = os.path.realpath(root)
252
+ if real_root in seen_skill_dirs:
253
+ dirs[:] = []
254
+ continue
255
+ seen_skill_dirs.add(real_root)
256
+ if is_plugins_root and os.path.abspath(root) == plugins_dir:
257
+ dirs[:] = [d for d in dirs if d not in disabled_plugins and not d.endswith(".disabled")]
258
+ else:
259
+ dirs[:] = [d for d in dirs if d not in ("node_modules", ".git", "__pycache__", ".venv", "venv") and not d.endswith(".disabled")]
241
260
  if "SKILL.md" in files:
242
261
  skills_count += 1
243
262
 
@@ -312,11 +331,12 @@ class EnvironmentAuditor:
312
331
  try:
313
332
  with open(real_path, "r", encoding="utf-8") as f:
314
333
  data = json.load(f)
315
- mcp_servers = data.get("mcpServers", {})
316
- if server_name in mcp_servers:
334
+ if not isinstance(data, dict):
335
+ continue
336
+ mcp_servers = data.get("mcpServers")
337
+ if isinstance(mcp_servers, dict) and server_name in mcp_servers:
317
338
  server_config = mcp_servers.pop(server_name)
318
- # Save disabled config
319
- if "disabledMcpServers" not in data:
339
+ if not isinstance(data.get("disabledMcpServers"), dict):
320
340
  data["disabledMcpServers"] = {}
321
341
  data["disabledMcpServers"][server_name] = server_config
322
342
  with open(real_path, "w", encoding="utf-8") as f:
@@ -357,10 +377,12 @@ class EnvironmentAuditor:
357
377
  try:
358
378
  with open(real_path, "r", encoding="utf-8") as f:
359
379
  data = json.load(f)
360
- disabled_servers = data.get("disabledMcpServers", {})
361
- if server_name in disabled_servers:
380
+ if not isinstance(data, dict):
381
+ continue
382
+ disabled_servers = data.get("disabledMcpServers")
383
+ if isinstance(disabled_servers, dict) and server_name in disabled_servers:
362
384
  srv_cfg = disabled_servers.pop(server_name)
363
- if "mcpServers" not in data:
385
+ if not isinstance(data.get("mcpServers"), dict):
364
386
  data["mcpServers"] = {}
365
387
  data["mcpServers"][server_name] = srv_cfg
366
388
  with open(real_path, "w", encoding="utf-8") as f:
package/src/governor.py CHANGED
@@ -39,40 +39,85 @@ class ContextGovernor:
39
39
  total += count_tokens(c)
40
40
  elif isinstance(c, list):
41
41
  for item in c:
42
- if isinstance(item, dict) and "text" in item:
42
+ if not isinstance(item, dict):
43
+ continue
44
+ if isinstance(item.get("text"), str):
43
45
  total += count_tokens(item["text"])
46
+ elif item.get("type") == "tool_use" and item.get("input") is not None:
47
+ total += count_tokens(json.dumps(item["input"], ensure_ascii=False))
48
+ elif item.get("type") == "tool_result":
49
+ tc = item.get("content")
50
+ if isinstance(tc, str):
51
+ total += count_tokens(tc)
52
+ elif tc is not None:
53
+ total += count_tokens(json.dumps(tc, ensure_ascii=False))
54
+ tcalls = m.get("tool_calls")
55
+ if tcalls:
56
+ total += count_tokens(json.dumps(tcalls, ensure_ascii=False))
44
57
  return total
45
58
 
59
+ _LANG_EXT_MAP = {
60
+ "py": ".py", "python": ".py",
61
+ "ts": ".ts", "typescript": ".ts",
62
+ "js": ".js", "javascript": ".js",
63
+ "tsx": ".tsx", "jsx": ".jsx",
64
+ "go": ".go", "golang": ".go",
65
+ "java": ".java",
66
+ "rs": ".rs", "rust": ".rs",
67
+ "c": ".c", "cpp": ".cpp", "c++": ".cpp",
68
+ "cs": ".cs", "csharp": ".cs",
69
+ "kt": ".kt", "kotlin": ".kt",
70
+ "swift": ".swift", "php": ".php", "rb": ".rb", "ruby": ".rb",
71
+ "css": ".css", "scss": ".scss",
72
+ }
73
+
46
74
  @classmethod
47
75
  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:
76
+ def _fold_text(text: str) -> str:
77
+ def fold_match(match):
78
+ lang = (match.group(1) or "py").lower().strip()
79
+ ext = cls._LANG_EXT_MAP.get(lang)
80
+ if not ext:
81
+ return match.group(0)
82
+ code_text = match.group(2)
83
+ lines = code_text.splitlines()
84
+ if len(lines) < 25:
85
+ return match.group(0)
86
+ skel = Skeletonizer.skeletonize_code(code_text, ext)
87
+ if count_tokens(skel) < count_tokens(code_text) - 50:
88
+ return f"```{lang}\n// [Context Governor: AST-folded {len(lines)} lines]\n{skel}\n```"
57
89
  return match.group(0)
90
+ return cls.CODE_BLOCK_REGEX.sub(fold_match, text)
58
91
 
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)
92
+ content = msg.get("content")
93
+ if isinstance(content, str) and "```" in content:
94
+ new_content = _fold_text(content)
95
+ if new_content != content:
96
+ msg["content"] = new_content
97
+ return True
98
+ elif isinstance(content, list):
99
+ changed = False
100
+ for blk in content:
101
+ if isinstance(blk, dict) and blk.get("type") == "text" and isinstance(blk.get("text"), str) and "```" in blk["text"]:
102
+ new_t = _fold_text(blk["text"])
103
+ if new_t != blk["text"]:
104
+ blk["text"] = new_t
105
+ changed = True
106
+ return changed
107
+ return False
67
108
 
68
- new_content = cls.CODE_BLOCK_REGEX.sub(fold_match, content)
69
- if new_content != content:
70
- msg["content"] = new_content
109
+ @staticmethod
110
+ def _starts_with_tool_result(msg: Dict[str, Any]) -> bool:
111
+ if msg.get("role") == "tool":
71
112
  return True
113
+ c = msg.get("content")
114
+ if isinstance(c, list):
115
+ return any(isinstance(b, dict) and b.get("type") == "tool_result" for b in c)
72
116
  return False
73
117
 
74
- @staticmethod
118
+ @classmethod
75
119
  def _consolidate_middle_turns(
120
+ cls,
76
121
  governed_messages: List[Dict[str, Any]],
77
122
  label: str = "Context Governor Ledger",
78
123
  ) -> List[Dict[str, Any]]:
@@ -81,8 +126,15 @@ class ContextGovernor:
81
126
  if governed_messages[0].get("role") in ("system", "developer")
82
127
  else None
83
128
  )
84
- recent_turns = governed_messages[-3:]
85
- middle_turns = governed_messages[1:-3] if sys_msg else governed_messages[:-3]
129
+ start_idx = max(1 if sys_msg else 0, len(governed_messages) - 3)
130
+ # Never cut inside a tool_use -> tool_result boundary
131
+ while start_idx > (1 if sys_msg else 0) and cls._starts_with_tool_result(governed_messages[start_idx]):
132
+ start_idx -= 1
133
+
134
+ recent_turns = governed_messages[start_idx:]
135
+ middle_turns = governed_messages[(1 if sys_msg else 0):start_idx]
136
+ if not middle_turns:
137
+ return governed_messages
86
138
 
87
139
  middle_user_intents = []
88
140
  for m in middle_turns:
@@ -176,6 +228,7 @@ class ContextGovernor:
176
228
  actions_taken.append("ast_fold_code_blocks")
177
229
 
178
230
  if current_tokens > target_budget:
231
+ compacted_any = False
179
232
  for idx in range(len(governed_messages) - 1):
180
233
  msg = governed_messages[idx]
181
234
  if msg.get("role") == "user" and isinstance(msg.get("content"), str):
@@ -184,8 +237,9 @@ class ContextGovernor:
184
237
  comp = PromptCompactor.compact(raw_user, enable_deepseek=False)
185
238
  if comp["saved_tokens"] >= 5:
186
239
  msg["content"] = f"[TOCP Intent]: {comp['compact_text']}"
240
+ compacted_any = True
187
241
  current_tokens = cls._calculate_total_tokens(governed_messages)
188
- if "ast_fold_code_blocks" not in actions_taken or current_tokens < initial_tokens:
242
+ if compacted_any:
189
243
  actions_taken.append("compact_user_history")
190
244
 
191
245
  if current_tokens > target_budget and len(governed_messages) > 6:
@@ -298,9 +352,12 @@ class ContextBudget:
298
352
  )
299
353
  for row in cursor.fetchall():
300
354
  ev_type = row["event_type"]
355
+ instrumented_events += int(row["cnt"] or 0)
356
+ # Snapshot events (CONTEXT_GOVERNOR / EPOCH_ROLLOVER) reflect whole-context size, not additive intake.
357
+ if ev_type in ("CONTEXT_GOVERNOR", "EPOCH_ROLLOVER"):
358
+ continue
301
359
  bucket = cls.CATEGORY_MAP.get(ev_type, "other")
302
360
  breakdown[bucket] += int(row["received"] or 0)
303
- instrumented_events += int(row["cnt"] or 0)
304
361
  except Exception:
305
362
  pass
306
363
 
@@ -494,7 +494,7 @@ class CodeGraph:
494
494
 
495
495
  container_re = re.compile(
496
496
  r'^(?:export\s+(?:default\s+)?)?(?:pub(?:\([^)]*\))?\s+|public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+|sealed\s+|open\s+|data\s+)*'
497
- r'(?:class|interface|struct|impl(?:\s+[A-Za-z0-9_<>,\s]+?\s+for)?|trait|enum|record|protocol|extension|namespace)\s+([A-Za-z0-9_]+)'
497
+ r'(?:class|interface|struct|impl(?:\s+[A-Za-z0-9_<>,\s]+?\s+for)?|trait|enum|record|protocol|extension|namespace|type)\s+([A-Za-z0-9_]+)'
498
498
  )
499
499
  go_struct_re = re.compile(r'^type\s+([A-Za-z0-9_]+)\s+(?:struct|interface)\b')
500
500
  ts_method_re = re.compile(