tokensafe 4.4.0 → 4.4.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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.4.0",
2
+ "version": "4.4.2",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -74,6 +74,8 @@ def _handle(payload: dict) -> dict:
74
74
 
75
75
  tracker = MetricsTracker()
76
76
  inject_steps = []
77
+ workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
78
+ hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
77
79
 
78
80
  # 0. Asynchronous telemetry sync (detached & throttled to 20s)
79
81
  try:
@@ -138,7 +140,7 @@ def _handle(payload: dict) -> dict:
138
140
  # 2.5 Proactive Anti-Stuck Guard (Inject recent failure lessons from MistakesLedger)
139
141
  try:
140
142
  from src.mistakes import MistakesLedger
141
- active_guard = MistakesLedger.get_guard_prompt()
143
+ active_guard = MistakesLedger.get_guard_prompt(project_root=hook_cwd)
142
144
  if active_guard:
143
145
  inject_steps.append({
144
146
  "systemMessage": {
@@ -283,22 +285,6 @@ def _handle(payload: dict) -> dict:
283
285
  except Exception:
284
286
  pass
285
287
 
286
- # 6. Anti-Stuck Dead-Ends Guard Prompt
287
- try:
288
- from src.mistakes import MistakesLedger
289
- workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
290
- hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
291
- mistake_guard = MistakesLedger.get_guard_prompt(project_root=hook_cwd)
292
- if mistake_guard:
293
- inject_steps.append({
294
- "systemMessage": {
295
- "systemMessage": mistake_guard,
296
- "metadata": {"source": "anti_stuck_guard"}
297
- }
298
- })
299
- except Exception:
300
- pass
301
-
302
288
  return {"injectSteps": inject_steps} if inject_steps else {}
303
289
 
304
290
 
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.4.0",
3
+ "version": "4.4.2",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.4.0",
4
+ "version": "4.4.2",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.4.0",
4
+ "version": "4.4.2",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "assets/logo.png",
7
7
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.4.0",
6
+ "version": "4.4.2",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.4.0",
26
+ "version": "4.4.2",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.4.0",
42
+ "version": "4.4.2",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
@@ -27,6 +27,8 @@ class LockfileReducer:
27
27
  name = filename_or_path.lower().split("/")[-1].split("\\")[-1]
28
28
  return name in (
29
29
  "package-lock.json",
30
+ "bun.lock",
31
+ "bun.lockb",
30
32
  "pnpm-lock.yaml",
31
33
  "yarn.lock",
32
34
  "cargo.lock",
@@ -36,6 +38,24 @@ class LockfileReducer:
36
38
  "go.sum",
37
39
  )
38
40
 
41
+ @classmethod
42
+ def _load_jsonc(cls, text: str) -> Optional[Dict[str, Any]]:
43
+ """Safely parses JSON or JSONC (JSON with comments and trailing commas)."""
44
+ if not text:
45
+ return None
46
+ try:
47
+ return json.loads(text)
48
+ except Exception:
49
+ pass
50
+ try:
51
+ # Strip whole-line comments // ... without corrupting base64 hashes inside strings
52
+ no_comments = re.sub(r'^\s*//.*$', '', text, flags=re.MULTILINE)
53
+ # Strip trailing commas before } or ]
54
+ cleaned = re.sub(r',(\s*[}\]])', r'\1', no_comments)
55
+ return json.loads(cleaned)
56
+ except Exception:
57
+ return None
58
+
39
59
  @classmethod
40
60
  def reduce(cls, content: str, filename: str = "package-lock.json") -> Tuple[str, bool]:
41
61
  """Reduces lockfile content to a clean summary. Returns (compacted_text, was_compacted)."""
@@ -47,6 +67,8 @@ class LockfileReducer:
47
67
 
48
68
  if fname == "package-lock.json":
49
69
  return cls._reduce_npm_lock(content)
70
+ elif fname in ("bun.lock", "bun.lockb"):
71
+ return cls._reduce_bun_lock(content, fname)
50
72
  elif fname == "cargo.lock":
51
73
  return cls._reduce_cargo_lock(content)
52
74
  elif fname == "poetry.lock":
@@ -54,6 +76,44 @@ class LockfileReducer:
54
76
 
55
77
  return cls._generic_reduce(content, fname)
56
78
 
79
+ @classmethod
80
+ def _reduce_bun_lock(cls, content: str, fname: str = "bun.lock") -> Tuple[str, bool]:
81
+ data = cls._load_jsonc(content)
82
+ if not data or not isinstance(data, dict):
83
+ return cls._generic_reduce(content, fname)
84
+
85
+ packages = data.get("packages", {})
86
+ workspaces = data.get("workspaces", {})
87
+ root_ws = workspaces.get("") if isinstance(workspaces, dict) else {}
88
+ root_deps = {}
89
+ if isinstance(root_ws, dict):
90
+ root_deps = {**root_ws.get("dependencies", {}), **root_ws.get("devDependencies", {})}
91
+
92
+ direct_deps = {}
93
+ total_count = len(packages) if isinstance(packages, dict) else 0
94
+
95
+ for dep_name, range_ver in sorted(root_deps.items()):
96
+ resolved_ver = range_ver
97
+ if isinstance(packages, dict) and dep_name in packages:
98
+ val = packages[dep_name]
99
+ if isinstance(val, list) and len(val) > 0 and isinstance(val[0], str):
100
+ resolved_ver = val[0].rsplit("@", 1)[1] if "@" in val[0] else val[0]
101
+ direct_deps[dep_name] = resolved_ver
102
+
103
+ lines = [
104
+ f"# [TokenSafe Lockfile Summary: {fname}]",
105
+ f"Total installed packages: {total_count}",
106
+ "",
107
+ "## Direct Dependencies:"
108
+ ]
109
+ for dname, dver in sorted(direct_deps.items()):
110
+ lines.append(f" - {dname}: {dver}")
111
+
112
+ hash8, marker = stash_block(content, source="lockfile:bun")
113
+ lines.append("")
114
+ lines.append(marker)
115
+ return "\n".join(lines), True
116
+
57
117
  @classmethod
58
118
  def _reduce_npm_lock(cls, content: str) -> Tuple[str, bool]:
59
119
  try:
@@ -163,7 +223,7 @@ class LockfileReducer:
163
223
 
164
224
  @classmethod
165
225
  def find_lockfile(cls, directory: Optional[str] = None, start_dir: Optional[str] = None) -> Optional[str]:
166
- """Locates the nearest lockfile in directory or parent directories up to git root."""
226
+ """Locates the nearest lockfile in directory or parent directories up to git root, or downward in monorepos."""
167
227
  target = directory or start_dir or os.getcwd()
168
228
  start = os.path.abspath(target)
169
229
  curr = start
@@ -171,6 +231,7 @@ class LockfileReducer:
171
231
  "package-lock.json", "bun.lock", "bun.lockb",
172
232
  "pnpm-lock.yaml", "yarn.lock", "Cargo.lock", "poetry.lock"
173
233
  )
234
+ # 1. Upward search
174
235
  for _ in range(6):
175
236
  for c in candidates:
176
237
  cand_path = os.path.join(curr, c)
@@ -180,6 +241,26 @@ class LockfileReducer:
180
241
  if parent == curr:
181
242
  break
182
243
  curr = parent
244
+
245
+ # 2. Downward search (bounded: depth <= 2, skip heavy/vendor dirs, cap 60 directories)
246
+ dirs_checked = 0
247
+ skip_dirs = {"node_modules", ".git", "dist", "build", ".next", ".cache", "data", "target", ".venv", "venv", "__pycache__"}
248
+ for root, dirs, files in os.walk(start):
249
+ dirs[:] = [d for d in dirs if d not in skip_dirs and not d.startswith(".")]
250
+ dirs_checked += 1
251
+ if dirs_checked > 60:
252
+ break
253
+ rel_path = os.path.relpath(root, start)
254
+ rel_depth = 0 if rel_path == "." else rel_path.count(os.sep) + 1
255
+ if rel_depth > 2:
256
+ dirs[:] = []
257
+ continue
258
+ for c in candidates:
259
+ if c in files:
260
+ cand_path = os.path.join(root, c)
261
+ if os.path.isfile(cand_path):
262
+ return cand_path
263
+
183
264
  return None
184
265
 
185
266
  @classmethod
@@ -188,6 +269,22 @@ class LockfileReducer:
188
269
  os.makedirs(data_dir, exist_ok=True)
189
270
  return os.path.join(data_dir, "lockfile_cache.db")
190
271
 
272
+ @classmethod
273
+ def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 5000) -> None:
274
+ """Evicts oldest entries when lockfile cache exceeds max_rows."""
275
+ try:
276
+ row = conn.execute("SELECT COUNT(*) FROM lockfile_cache;").fetchone()
277
+ count = row[0] if row else 0
278
+ if count > max_rows:
279
+ excess = count - max_rows
280
+ conn.execute(
281
+ "DELETE FROM lockfile_cache WHERE entry_key IN ("
282
+ "SELECT entry_key FROM lockfile_cache ORDER BY cached_at ASC LIMIT ?"
283
+ ");", (excess,)
284
+ )
285
+ except Exception:
286
+ pass
287
+
191
288
  @classmethod
192
289
  def _init_db(cls):
193
290
  db_path = cls._get_db_path()
@@ -231,6 +328,7 @@ class LockfileReducer:
231
328
  try:
232
329
  with open(target_path, "r", encoding="utf-8", errors="replace") as f:
233
330
  content = f.read()
331
+ _lockfile_bytes = os.path.getsize(target_path)
234
332
  except Exception as e:
235
333
  return {"found": False, "package": package_name, "error": f"Failed to read {fname}: {e}"}
236
334
 
@@ -247,8 +345,10 @@ class LockfileReducer:
247
345
  row = conn.execute("SELECT json_result FROM lockfile_cache WHERE entry_key = ?", (entry_key,)).fetchone()
248
346
  if row:
249
347
  res = json.loads(row[0])
250
- res["source"] = "L2_cache"
251
- return res
348
+ if res.get("found"):
349
+ res["source"] = "L2_cache"
350
+ res["_lockfile_bytes"] = _lockfile_bytes
351
+ return res
252
352
  except Exception:
253
353
  pass
254
354
  finally:
@@ -264,25 +364,28 @@ class LockfileReducer:
264
364
  team_val = TeamCache.get("LOCKFILE_INDEX", entry_key, timeout=0.5)
265
365
  if team_val:
266
366
  res = json.loads(team_val)
267
- res["source"] = "L3_team_cache"
268
- # Store back to L2
269
- back_conn = None
270
- try:
271
- back_conn = sqlite3.connect(db_path, timeout=5.0)
272
- back_conn.execute("""
273
- INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
274
- VALUES (?, ?, ?, ?, ?)
275
- """, (entry_key, lockfile_hash, package_name.strip().lower(), team_val, int(time.time())))
276
- back_conn.commit()
277
- except Exception:
278
- pass
279
- finally:
280
- if back_conn:
281
- try:
282
- back_conn.close()
283
- except Exception:
284
- pass
285
- return res
367
+ if res.get("found"):
368
+ res["source"] = "L3_team_cache"
369
+ res["_lockfile_bytes"] = _lockfile_bytes
370
+ # Store back to L2
371
+ back_conn = None
372
+ try:
373
+ back_conn = sqlite3.connect(db_path, timeout=5.0)
374
+ back_conn.execute("""
375
+ INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
376
+ VALUES (?, ?, ?, ?, ?)
377
+ """, (entry_key, lockfile_hash, package_name.strip().lower(), team_val, int(time.time())))
378
+ cls._maybe_evict(back_conn)
379
+ back_conn.commit()
380
+ except Exception:
381
+ pass
382
+ finally:
383
+ if back_conn:
384
+ try:
385
+ back_conn.close()
386
+ except Exception:
387
+ pass
388
+ return res
286
389
  except Exception:
287
390
  pass
288
391
 
@@ -290,40 +393,99 @@ class LockfileReducer:
290
393
  res = cls._parse_dependency(fname, content, package_name)
291
394
  res["lockfile"] = fname
292
395
  res["lockfile_path"] = target_path
396
+ res["_lockfile_bytes"] = _lockfile_bytes
293
397
 
294
- # 4. Save to L2 SQLite and sync to L3 Team Cache
295
- save_conn = None
296
- try:
297
- raw_json = json.dumps(res, ensure_ascii=False)
298
- save_conn = sqlite3.connect(db_path, timeout=5.0)
299
- save_conn.execute("""
300
- INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
301
- VALUES (?, ?, ?, ?, ?)
302
- """, (entry_key, lockfile_hash, package_name.strip().lower(), raw_json, int(time.time())))
303
- save_conn.commit()
304
- except Exception:
305
- pass
306
- finally:
307
- if save_conn:
308
- try:
309
- save_conn.close()
310
- except Exception:
311
- pass
312
-
313
- try:
314
- from src.team_cache import TeamCache
315
- TeamCache.put("LOCKFILE_INDEX", entry_key, json.dumps(res, ensure_ascii=False), tokens_saved=250)
316
- except Exception:
317
- pass
398
+ # 4. Save to L2 SQLite and sync to L3 Team Cache (only positive found lookups)
399
+ if res.get("found"):
400
+ save_conn = None
401
+ try:
402
+ raw_json = json.dumps(res, ensure_ascii=False)
403
+ save_conn = sqlite3.connect(db_path, timeout=5.0)
404
+ save_conn.execute("""
405
+ INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
406
+ VALUES (?, ?, ?, ?, ?)
407
+ """, (entry_key, lockfile_hash, package_name.strip().lower(), raw_json, int(time.time())))
408
+ cls._maybe_evict(save_conn)
409
+ save_conn.commit()
410
+ except Exception:
411
+ pass
412
+ finally:
413
+ if save_conn:
414
+ try:
415
+ save_conn.close()
416
+ except Exception:
417
+ pass
418
+
419
+ # Broadcast to L3 without leaking local filesystem paths or private byte counts
420
+ try:
421
+ from src.team_cache import TeamCache
422
+ team_payload = dict(res)
423
+ team_payload.pop("lockfile_path", None)
424
+ team_payload.pop("_lockfile_bytes", None)
425
+ TeamCache.put("LOCKFILE_INDEX", entry_key, json.dumps(team_payload, ensure_ascii=False), tokens_saved=250)
426
+ except Exception:
427
+ pass
318
428
 
319
429
  res["source"] = "parsed_live"
320
430
  return res
321
431
 
322
432
  @classmethod
323
433
  def _parse_dependency(cls, fname: str, content: str, pkg_name: str) -> Dict[str, Any]:
324
- """Parses dependency entry from npm, cargo, poetry, or pnpm."""
434
+ """Parses dependency entry from npm, cargo, poetry, pnpm, or bun."""
325
435
  norm_pkg = pkg_name.strip()
326
- if "package-lock" in fname or "bun.lock" in fname:
436
+ if "bun.lock" in fname:
437
+ try:
438
+ data = cls._load_jsonc(content)
439
+ if isinstance(data, dict):
440
+ packages = data.get("packages")
441
+ if isinstance(packages, dict):
442
+ # 1. Direct package key (e.g. "marked", "@tanstack/react-query")
443
+ val = packages.get(norm_pkg)
444
+ # 2. Nested or prefixed node_modules/<pkg>
445
+ if not val:
446
+ exact_nm = f"node_modules/{norm_pkg}"
447
+ val = packages.get(exact_nm)
448
+ if not val:
449
+ suffix = f"/node_modules/{norm_pkg}"
450
+ for k, v in packages.items():
451
+ if k.endswith(suffix):
452
+ val = v
453
+ break
454
+ if val and isinstance(val, list) and len(val) > 0:
455
+ spec = val[0] if isinstance(val[0], str) else ""
456
+ ver = spec.rsplit("@", 1)[1] if "@" in spec else spec
457
+ meta = val[2] if len(val) > 2 and isinstance(val[2], dict) else {}
458
+ integrity = val[3] if len(val) > 3 and isinstance(val[3], str) else None
459
+ return {
460
+ "found": True,
461
+ "package": norm_pkg,
462
+ "version": ver,
463
+ "resolved": integrity,
464
+ "dependencies": meta.get("dependencies", {}),
465
+ "peerDependencies": meta.get("peerDependencies", {}),
466
+ "dev": False,
467
+ }
468
+ # 3. Fallback to workspaces[""] direct dependencies
469
+ workspaces = data.get("workspaces", {})
470
+ root_ws = workspaces.get("") if isinstance(workspaces, dict) else {}
471
+ if isinstance(root_ws, dict):
472
+ dev_deps = root_ws.get("devDependencies", {}) or {}
473
+ prod_deps = root_ws.get("dependencies", {}) or {}
474
+ all_root = {**prod_deps, **dev_deps}
475
+ if norm_pkg in all_root:
476
+ return {
477
+ "found": True,
478
+ "package": norm_pkg,
479
+ "version": all_root[norm_pkg],
480
+ "resolved": None,
481
+ "dependencies": {},
482
+ "peerDependencies": {},
483
+ "dev": norm_pkg in dev_deps,
484
+ }
485
+ except Exception:
486
+ pass
487
+
488
+ elif "package-lock" in fname:
327
489
  try:
328
490
  data = json.loads(content)
329
491
  packages = data.get("packages")
package/src/installer.py CHANGED
@@ -63,6 +63,7 @@ UNIFIED_TOKENSAFE_RULE = (
63
63
  "12. **Proof-of-Savings Turn Footer (strictly English)**:\n"
64
64
  "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. The ENTIRE footer is product-facing copy — 100% English, including the savings breakdown in parentheses, regardless of the chat language:\n"
65
65
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
66
+ "13. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.\n"
66
67
  )
67
68
 
68
69
  # Short pointer written into PROJECT-level rule files when the full protocol is
@@ -70,10 +71,11 @@ UNIFIED_TOKENSAFE_RULE = (
70
71
  # Keeps every session's meta-context lean: ~110 tokens instead of ~850.
71
72
  POINTER_RULE = (
72
73
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
73
- "The full 12-point protocol is installed globally in the agent-level instructions "
74
+ "The full 13-point protocol is installed globally in the agent-level instructions "
74
75
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
75
76
  "Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
76
- "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
77
+ "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:slice_external_type`, `tokensafe:query_dependency`, "
78
+ "`tokensafe:smart_bundle` and `tokensafe:list_dir`; "
77
79
  "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
78
80
  "before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
79
81
  "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.4.0"
45
+ "version": "4.4.2"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -1869,9 +1869,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1869
1869
  try:
1870
1870
  from src.format_parsers.lockfiles import LockfileReducer
1871
1871
  res = LockfileReducer.query_dependency(lock_p, pkg)
1872
+ lock_bytes = res.pop("_lockfile_bytes", 0)
1872
1873
  json_text = json.dumps(res, indent=2, ensure_ascii=False)
1873
1874
  opt_tokens = count_tokens(json_text)
1874
- orig_tokens = 50000
1875
+ if res.get("found"):
1876
+ orig_tokens = max(1000, lock_bytes // 4) if lock_bytes else max(opt_tokens, 1000)
1877
+ else:
1878
+ orig_tokens = opt_tokens
1875
1879
  tracker.record_event(
1876
1880
  session_id=_mcp_session_id(),
1877
1881
  event_type="LOCKFILE_QUERY",
@@ -1892,9 +1896,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1892
1896
  try:
1893
1897
  from src.type_slicer import TypeSlicer
1894
1898
  res = TypeSlicer.slice_package_type(pkg, sym, project_root=proj_root)
1899
+ dts_bytes = res.pop("_dts_bytes", 0)
1895
1900
  json_text = json.dumps(res, indent=2, ensure_ascii=False)
1896
1901
  opt_tokens = count_tokens(json_text)
1897
- orig_tokens = 15000
1902
+ if res.get("found"):
1903
+ orig_tokens = max(opt_tokens, dts_bytes // 4) if dts_bytes else max(opt_tokens, 500)
1904
+ else:
1905
+ orig_tokens = opt_tokens
1898
1906
  tracker.record_event(
1899
1907
  session_id=_mcp_session_id(),
1900
1908
  event_type="TYPE_SLICE",
@@ -1958,10 +1966,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1958
1966
  try:
1959
1967
  from src.mistakes import MistakesLedger
1960
1968
  entries = MistakesLedger.list_mistakes(project_root=proj_root)
1969
+ team_entries = MistakesLedger.get_team_mistakes()
1961
1970
  guard = MistakesLedger.get_guard_prompt(project_root=proj_root)
1962
1971
  return {"content": [{"type": "text", "text": json.dumps({
1963
1972
  "count": len(entries),
1964
1973
  "entries": entries,
1974
+ "team_entries": team_entries,
1965
1975
  "active_guard": guard
1966
1976
  }, indent=2, ensure_ascii=False)}]}
1967
1977
  except Exception as e:
package/src/mistakes.py CHANGED
@@ -14,6 +14,7 @@ import os
14
14
  import json
15
15
  import time
16
16
  import hashlib
17
+ import threading
17
18
  import subprocess
18
19
  from typing import Dict, Any, List, Optional, Tuple
19
20
  from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
@@ -190,6 +191,43 @@ class MistakesLedger:
190
191
  pass
191
192
  return 0
192
193
 
194
+ _team_mistakes_cache: List[Dict[str, Any]] = []
195
+ _team_mistakes_fetched_at: float = 0.0
196
+ _team_mistakes_lock = threading.Lock()
197
+
198
+ @classmethod
199
+ def get_team_mistakes(cls, timeout: float = 0.6) -> List[Dict[str, Any]]:
200
+ """Retrieves scrubbed dead-end summaries shared across team members with 300s TTL cache."""
201
+ now = time.time()
202
+ with cls._team_mistakes_lock:
203
+ if cls._team_mistakes_cache and (now - cls._team_mistakes_fetched_at < 300.0):
204
+ return list(cls._team_mistakes_cache)
205
+
206
+ try:
207
+ from src.team_cache import TeamCache
208
+ raw_entries = TeamCache.list_entries("TEAM_MISTAKE", limit=10, timeout=timeout)
209
+ parsed: List[Dict[str, Any]] = []
210
+ for item in raw_entries:
211
+ val = item.get("value") or item.get("cached_value")
212
+ if isinstance(val, str):
213
+ try:
214
+ p_val = json.loads(val)
215
+ if isinstance(p_val, dict):
216
+ parsed.append(p_val)
217
+ else:
218
+ parsed.append({"summary": str(val)[:120]})
219
+ except Exception:
220
+ parsed.append({"summary": str(val)[:120]})
221
+ elif isinstance(val, dict):
222
+ parsed.append(val)
223
+
224
+ with cls._team_mistakes_lock:
225
+ cls._team_mistakes_cache = parsed
226
+ cls._team_mistakes_fetched_at = now
227
+ return list(parsed)
228
+ except Exception:
229
+ return []
230
+
193
231
  @classmethod
194
232
  def should_force_ask(
195
233
  cls,
@@ -217,7 +255,19 @@ class MistakesLedger:
217
255
  f = (m.get("file") or "").lower()
218
256
  s = (m.get("summary") or "").lower()
219
257
  det = (m.get("details") or "").lower()
220
- if (f and f in norm_target) or (norm_target in s) or (norm_target in det):
258
+
259
+ matched = False
260
+ if len(norm_target) >= 12:
261
+ # Substring matching for longer specific commands or file paths
262
+ if (f and f in norm_target) or (norm_target in s) or (norm_target in det):
263
+ matched = True
264
+ else:
265
+ # Short targets (e.g. "npm", "ls"): exact equality against file, summary, or extracted command prefix
266
+ cmd_part = s.split(":", 1)[0].strip() if ":" in s else s.split()[0] if s.split() else ""
267
+ if (f and norm_target == f) or (norm_target == s) or (norm_target == cmd_part):
268
+ matched = True
269
+
270
+ if matched:
221
271
  matching.append(m)
222
272
 
223
273
  count = len(matching)
@@ -236,19 +286,40 @@ class MistakesLedger:
236
286
  max_items: int = 3
237
287
  ) -> Optional[str]:
238
288
  """
239
- Generates a compact (<80 tokens) prompt guard from recent active mistakes.
289
+ Generates a compact (<100 tokens) prompt guard from recent active local and team mistakes.
240
290
  Injectable into system instructions or PreInvocation hooks.
241
291
  """
242
- mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
243
- if not mistakes:
292
+ local_mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
293
+ team_mistakes = cls.get_team_mistakes()
294
+ if not local_mistakes and not team_mistakes:
244
295
  return None
245
296
 
246
- # Take the most recent active entries
247
- recent = mistakes[-max_items:]
248
- lines = ["[TokenSafe Anti-Stuck Guard: Prior Dead-Ends to Avoid in this Project]:"]
249
- for m in reversed(recent):
297
+ lines = ["[TokenSafe Anti-Stuck Guard: Prior Dead-Ends to Avoid]:"]
298
+ local_summaries = set()
299
+
300
+ # Take up to max_items most recent active local entries
301
+ for m in reversed(local_mistakes[-max_items:]):
302
+ s = m.get("summary", "")
303
+ local_summaries.add(s.strip().lower())
250
304
  f = m.get("file")
251
305
  f_prefix = f"{f}: " if f else ""
252
- lines.append(f"• {f_prefix}{m.get('summary', '')}")
306
+ lines.append(f"• {f_prefix}{s}")
307
+
308
+ # Merge up to 2 unique team mistakes
309
+ team_added = 0
310
+ for tm in team_mistakes:
311
+ if team_added >= 2:
312
+ break
313
+ ts = (tm.get("summary") or "").strip()
314
+ if not ts or ts.lower() in local_summaries:
315
+ continue
316
+ tf = tm.get("file")
317
+ tf_prefix = f"{tf}: " if tf else ""
318
+ lines.append(f"• team: {tf_prefix}{ts}")
319
+ local_summaries.add(ts.lower())
320
+ team_added += 1
321
+
322
+ if len(lines) == 1:
323
+ return None
253
324
 
254
325
  return "\n".join(lines)
@@ -45,6 +45,31 @@ class SchemaSlicer:
45
45
  with cls._mem_lock:
46
46
  cls._mem_cache.clear()
47
47
 
48
+ @classmethod
49
+ def _mem_put(cls, key: str, val: Tuple[str, Dict[str, Any]], max_items: int = 80) -> None:
50
+ """Stores entry in LRU memory cache with fixed cap."""
51
+ with cls._mem_lock:
52
+ cls._mem_cache[key] = val
53
+ cls._mem_cache.move_to_end(key)
54
+ if len(cls._mem_cache) > max_items:
55
+ cls._mem_cache.popitem(last=False)
56
+
57
+ @classmethod
58
+ def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 2000) -> None:
59
+ """Evicts oldest entries when schema cache exceeds max_rows."""
60
+ try:
61
+ row = conn.execute("SELECT COUNT(*) FROM schema_cache;").fetchone()
62
+ count = row[0] if row else 0
63
+ if count > max_rows:
64
+ excess = count - max_rows
65
+ conn.execute(
66
+ "DELETE FROM schema_cache WHERE cache_key IN ("
67
+ "SELECT cache_key FROM schema_cache ORDER BY cached_at ASC LIMIT ?"
68
+ ");", (excess,)
69
+ )
70
+ except Exception:
71
+ pass
72
+
48
73
  @classmethod
49
74
  def _get_db_path(cls) -> str:
50
75
  data_dir = resolve_data_dir()
@@ -89,8 +114,8 @@ class SchemaSlicer:
89
114
  """
90
115
  Computes deterministic composite fingerprint:
91
116
  - For single file: SHA-256(content)[:16]
92
- - For multi-file Prisma (prisma/schema/*.prisma): hashes all .prisma files and mtimes
93
- - For OpenAPI with local $ref: hashes root + referenced local files
117
+ - For multi-file Prisma (prisma/schema/*.prisma): content hashes of all .prisma files
118
+ - For OpenAPI with local $ref: content hashes of root + referenced local files
94
119
  """
95
120
  abs_p = os.path.abspath(path)
96
121
  base_dir = os.path.dirname(abs_p)
@@ -104,8 +129,10 @@ class SchemaSlicer:
104
129
  if len(prisma_files) > 1:
105
130
  hasher = hashlib.sha256()
106
131
  for pf in prisma_files:
107
- st = os.stat(pf)
108
- hasher.update(f"{os.path.basename(pf)}:{st.st_mtime}:{st.st_size}".encode("utf-8"))
132
+ with open(pf, "rb") as pff:
133
+ pf_bytes = pff.read()
134
+ pf_hash = hashlib.sha256(pf_bytes).hexdigest()
135
+ hasher.update(f"{os.path.basename(pf)}:{pf_hash}".encode("utf-8"))
109
136
  return hasher.hexdigest()[:16]
110
137
  except Exception:
111
138
  pass
@@ -123,7 +150,13 @@ class SchemaSlicer:
123
150
  ref_rel = rm.decode("utf-8", errors="ignore")
124
151
  cand = os.path.normpath(os.path.join(base_dir, ref_rel))
125
152
  if os.path.isfile(cand):
126
- hasher.update(f"{cand}:{os.path.getmtime(cand)}".encode("utf-8"))
153
+ try:
154
+ with open(cand, "rb") as cf:
155
+ cand_bytes = cf.read()
156
+ cand_hash = hashlib.sha256(cand_bytes).hexdigest()
157
+ hasher.update(f"{ref_rel}:{cand_hash}".encode("utf-8"))
158
+ except Exception:
159
+ pass
127
160
  return hasher.hexdigest()[:16]
128
161
  return h
129
162
  except Exception:
@@ -191,8 +224,7 @@ class SchemaSlicer:
191
224
  text_cached, info_raw = row[0], row[1]
192
225
  info_dict = json.loads(info_raw)
193
226
  info_dict["source"] = "L2_sqlite"
194
- with cls._mem_lock:
195
- cls._mem_cache[cache_key] = (text_cached, info_dict)
227
+ cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
196
228
  return text_cached, info_dict
197
229
  except Exception:
198
230
  pass
@@ -212,8 +244,7 @@ class SchemaSlicer:
212
244
  text_cached = parsed_team.get("sliced", "")
213
245
  info_dict = parsed_team.get("info", {})
214
246
  info_dict["source"] = "L3_team_cache"
215
- with cls._mem_lock:
216
- cls._mem_cache[cache_key] = (text_cached, info_dict)
247
+ cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
217
248
  # Store back to L2
218
249
  back_conn = None
219
250
  try:
@@ -222,6 +253,7 @@ class SchemaSlicer:
222
253
  INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
223
254
  VALUES (?, ?, ?, ?, ?, ?, ?)
224
255
  """, (cache_key, kind, fp, norm_target, text_cached, json.dumps(info_dict), int(time.time())))
256
+ cls._maybe_evict(back_conn)
225
257
  back_conn.commit()
226
258
  except Exception:
227
259
  pass
@@ -260,10 +292,7 @@ class SchemaSlicer:
260
292
 
261
293
  # 6. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
262
294
  info["source"] = "parsed_live"
263
- with cls._mem_lock:
264
- cls._mem_cache[cache_key] = (sliced, info)
265
- if len(cls._mem_cache) > 80:
266
- cls._mem_cache.popitem(last=False)
295
+ cls._mem_put(cache_key, (sliced, info), max_items=80)
267
296
 
268
297
  save_conn = None
269
298
  try:
@@ -272,6 +301,7 @@ class SchemaSlicer:
272
301
  INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
273
302
  VALUES (?, ?, ?, ?, ?, ?, ?)
274
303
  """, (cache_key, kind, fp, norm_target, sliced, json.dumps(info), int(time.time())))
304
+ cls._maybe_evict(save_conn)
275
305
  save_conn.commit()
276
306
  except Exception:
277
307
  pass
package/src/team_cache.py CHANGED
@@ -12,7 +12,7 @@ import threading
12
12
  import urllib.request
13
13
  import urllib.error
14
14
  import urllib.parse
15
- from typing import Optional, Dict, Any, Tuple
15
+ from typing import Optional, Dict, Any, Tuple, List
16
16
  from src.license_manager import LicenseManager
17
17
  from src.ssl_context import shared_ssl_context
18
18
 
@@ -208,6 +208,53 @@ class TeamCache:
208
208
  t = threading.Thread(target=_worker, daemon=True)
209
209
  t.start()
210
210
 
211
+ @classmethod
212
+ def list_entries(
213
+ cls,
214
+ cache_type: str,
215
+ limit: int = 10,
216
+ timeout: Optional[float] = None,
217
+ lic_key: Optional[str] = None,
218
+ ) -> List[Dict[str, Any]]:
219
+ """Queries Shared Team Cache for recent entries of a specific type (e.g. TEAM_MISTAKE)."""
220
+ cloud_url = cls._get_cloud_url()
221
+ if cls._is_in_cooldown(cloud_url):
222
+ return []
223
+ if not lic_key:
224
+ is_team, resolved_key = cls._is_team_tier()
225
+ if not is_team:
226
+ return []
227
+ lic_key = resolved_key
228
+ if not cache_type:
229
+ return []
230
+
231
+ norm_type = cache_type.strip().upper()
232
+ if norm_type not in cls.ALLOWED_CACHE_TYPES:
233
+ return []
234
+
235
+ endpoint = f"{cloud_url}/api/team/cache/list?type={urllib.parse.quote(norm_type)}&limit={max(1, min(50, limit))}"
236
+ req = urllib.request.Request(
237
+ endpoint,
238
+ headers={
239
+ "Authorization": f"Bearer {lic_key}",
240
+ "User-Agent": "TokenSafe-TeamCache/1.0"
241
+ }
242
+ )
243
+ eff_timeout = cls.DEFAULT_TIMEOUT if timeout is None else max(0.05, float(timeout))
244
+ try:
245
+ with urllib.request.urlopen(req, timeout=eff_timeout, context=shared_ssl_context()) as resp:
246
+ if resp.status == 200:
247
+ data = json.loads(resp.read().decode("utf-8"))
248
+ cls._clear_cooldown(cloud_url)
249
+ return data.get("entries") or []
250
+ except urllib.error.HTTPError as he:
251
+ if he.code in (401, 403) or he.code >= 500:
252
+ cls._trip_cooldown(cloud_url)
253
+ return []
254
+ except Exception:
255
+ return []
256
+ return []
257
+
211
258
  @classmethod
212
259
  def get_stats(cls) -> Dict[str, Any]:
213
260
  """Retrieves team cache hit rates and token savings metrics."""
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.4.0"
244
+ "User-Agent": "TokenSafe-Sync/4.4.2"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -27,7 +27,10 @@ from src.paths import resolve_data_dir
27
27
  class TypeSlicer:
28
28
  """Targeted extractor of external library types and interfaces."""
29
29
 
30
- _mem_cache: "OrderedDict[str, str]" = OrderedDict()
30
+ _mem_cache: "OrderedDict[str, Any]" = OrderedDict()
31
+ # Bumped whenever the slicing algorithm changes: stale slices cached under
32
+ # an older key format can never resurface through L1/L2/L3 (poisoning guard).
33
+ _SLICER_VERSION = "v2"
31
34
  _mem_lock = threading.Lock()
32
35
  _db_init_done = False
33
36
  _db_init_lock = threading.Lock()
@@ -37,6 +40,31 @@ class TypeSlicer:
37
40
  with cls._mem_lock:
38
41
  cls._mem_cache.clear()
39
42
 
43
+ @classmethod
44
+ def _mem_put(cls, key: str, val: str, dts_bytes: int = 0, max_items: int = 100) -> None:
45
+ """Stores entry in LRU memory cache with fixed cap."""
46
+ with cls._mem_lock:
47
+ cls._mem_cache[key] = (val, dts_bytes)
48
+ cls._mem_cache.move_to_end(key)
49
+ if len(cls._mem_cache) > max_items:
50
+ cls._mem_cache.popitem(last=False)
51
+
52
+ @classmethod
53
+ def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 5000) -> None:
54
+ """Evicts oldest entries when type cache exceeds max_rows."""
55
+ try:
56
+ row = conn.execute("SELECT COUNT(*) FROM type_cache;").fetchone()
57
+ count = row[0] if row else 0
58
+ if count > max_rows:
59
+ excess = count - max_rows
60
+ conn.execute(
61
+ "DELETE FROM type_cache WHERE type_key IN ("
62
+ "SELECT type_key FROM type_cache ORDER BY cached_at ASC LIMIT ?"
63
+ ");", (excess,)
64
+ )
65
+ except Exception:
66
+ pass
67
+
40
68
  @classmethod
41
69
  def _get_db_path(cls) -> str:
42
70
  data_dir = resolve_data_dir()
@@ -61,10 +89,15 @@ class TypeSlicer:
61
89
  version TEXT NOT NULL,
62
90
  symbol TEXT NOT NULL,
63
91
  type_code TEXT NOT NULL,
92
+ dts_bytes INTEGER DEFAULT 0,
64
93
  cached_at INTEGER NOT NULL,
65
94
  hit_count INTEGER DEFAULT 1
66
95
  );
67
96
  """)
97
+ try:
98
+ conn.execute("ALTER TABLE type_cache ADD COLUMN dts_bytes INTEGER DEFAULT 0;")
99
+ except Exception:
100
+ pass
68
101
  conn.execute("CREATE INDEX IF NOT EXISTS idx_type_pkg ON type_cache(package_name);")
69
102
  conn.commit()
70
103
  cls._db_init_done = db_path
@@ -146,7 +179,7 @@ class TypeSlicer:
146
179
 
147
180
  @classmethod
148
181
  def _extract_symbol_block(cls, content: str, symbol: str) -> Optional[str]:
149
- """Extracts full definition block for interface, type, class, function, or enum."""
182
+ """Extracts full definition block for interface, type, class, function, enum, or namespace with balanced braces."""
150
183
  pattern = re.compile(
151
184
  rf'(?:export\s+)?(?:declare\s+)?(?:default\s+)?(interface|type|class|enum|function|const|namespace)\s+{re.escape(symbol)}\b',
152
185
  re.MULTILINE
@@ -155,14 +188,18 @@ class TypeSlicer:
155
188
  if not match:
156
189
  return None
157
190
 
191
+ kind = match.group(1)
192
+ is_namespace = (kind == "namespace")
193
+ max_lines = 400 if is_namespace else 150
194
+
158
195
  start_pos = match.start()
159
- # Find start of block or statement
160
196
  rest = content[start_pos:]
161
197
  lines = rest.splitlines()
162
198
 
163
199
  collected: List[str] = []
164
200
  open_braces = 0
165
201
  brace_started = False
202
+ truncated = False
166
203
 
167
204
  for line in lines:
168
205
  collected.append(line)
@@ -175,9 +212,15 @@ class TypeSlicer:
175
212
  break
176
213
  if brace_started and open_braces <= 0:
177
214
  break
178
- if len(collected) > 120: # safety cap
215
+ if len(collected) >= max_lines:
216
+ truncated = True
179
217
  break
180
218
 
219
+ if truncated and open_braces > 0:
220
+ collected.append(f" // ... [TokenSafe: truncated {open_braces} nested block(s)]")
221
+ for _ in range(open_braces):
222
+ collected.append("}")
223
+
181
224
  return "\n".join(collected)
182
225
 
183
226
  @classmethod
@@ -243,19 +286,22 @@ class TypeSlicer:
243
286
  except Exception:
244
287
  pass
245
288
 
246
- type_key = f"{pkg_name}@{version}::{sym}"
289
+ type_key = f"{pkg_name}@{version}::{sym}::{cls._SLICER_VERSION}"
247
290
 
248
291
  # 1. Check L1 Memory
249
292
  with cls._mem_lock:
250
293
  if type_key in cls._mem_cache:
251
294
  cls._mem_cache.move_to_end(type_key)
295
+ cached = cls._mem_cache[type_key]
296
+ code_val, dts_val = cached if isinstance(cached, tuple) else (cached, 0)
252
297
  return {
253
298
  "found": True,
254
299
  "package": pkg_name,
255
300
  "version": version,
256
301
  "symbol": sym,
257
- "type_code": cls._mem_cache[type_key],
258
- "source": "L1_memory"
302
+ "type_code": code_val,
303
+ "source": "L1_memory",
304
+ "_dts_bytes": dts_val
259
305
  }
260
306
 
261
307
  # 2. Check L2 SQLite
@@ -266,20 +312,21 @@ class TypeSlicer:
266
312
  l2_conn = sqlite3.connect(db_path, timeout=5.0)
267
313
  l2_conn.execute("PRAGMA busy_timeout=5000;")
268
314
  row = l2_conn.execute(
269
- "SELECT type_code FROM type_cache WHERE type_key = ?",
315
+ "SELECT type_code, dts_bytes FROM type_cache WHERE type_key = ?",
270
316
  (type_key,)
271
317
  ).fetchone()
272
318
  if row:
273
319
  code = row[0]
274
- with cls._mem_lock:
275
- cls._mem_cache[type_key] = code
320
+ dts_b = row[1] if len(row) > 1 and row[1] else 0
321
+ cls._mem_put(type_key, code, dts_bytes=dts_b, max_items=100)
276
322
  return {
277
323
  "found": True,
278
324
  "package": pkg_name,
279
325
  "version": version,
280
326
  "symbol": sym,
281
327
  "type_code": code,
282
- "source": "L2_sqlite"
328
+ "source": "L2_sqlite",
329
+ "_dts_bytes": dts_b
283
330
  }
284
331
  except Exception:
285
332
  pass
@@ -295,16 +342,27 @@ class TypeSlicer:
295
342
  from src.team_cache import TeamCache
296
343
  team_val = TeamCache.get("3RD_PARTY_DTS", type_key, timeout=0.5)
297
344
  if team_val:
298
- with cls._mem_lock:
299
- cls._mem_cache[type_key] = team_val
345
+ code_block = team_val
346
+ dts_bytes = 0
347
+ if team_val.startswith("{"):
348
+ try:
349
+ p_val = json.loads(team_val)
350
+ if isinstance(p_val, dict) and "code" in p_val:
351
+ code_block = str(p_val["code"])
352
+ dts_bytes = int(p_val.get("dts_bytes", 0) or 0)
353
+ except Exception:
354
+ pass
355
+
356
+ cls._mem_put(type_key, code_block, dts_bytes=dts_bytes, max_items=100)
300
357
  # Backfill L2
301
358
  back_conn = None
302
359
  try:
303
360
  back_conn = sqlite3.connect(db_path, timeout=5.0)
304
361
  back_conn.execute("""
305
- INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, cached_at)
306
- VALUES (?, ?, ?, ?, ?, ?)
307
- """, (type_key, pkg_name, version, sym, team_val, int(time.time())))
362
+ INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, dts_bytes, cached_at)
363
+ VALUES (?, ?, ?, ?, ?, ?, ?)
364
+ """, (type_key, pkg_name, version, sym, code_block, dts_bytes, int(time.time())))
365
+ cls._maybe_evict(back_conn)
308
366
  back_conn.commit()
309
367
  except Exception:
310
368
  pass
@@ -319,8 +377,9 @@ class TypeSlicer:
319
377
  "package": pkg_name,
320
378
  "version": version,
321
379
  "symbol": sym,
322
- "type_code": team_val,
323
- "source": "L3_team_cache"
380
+ "type_code": code_block,
381
+ "source": "L3_team_cache",
382
+ "_dts_bytes": dts_bytes
324
383
  }
325
384
  except Exception:
326
385
  pass
@@ -343,6 +402,8 @@ class TypeSlicer:
343
402
  "error": f"No .d.ts declaration file located for '{pkg_name}'."
344
403
  }
345
404
 
405
+ dts_bytes = os.path.getsize(dts_file) if os.path.isfile(dts_file) else 0
406
+
346
407
  code_block = cls.slice_symbol_from_file(dts_file, sym)
347
408
  if not code_block:
348
409
  return {
@@ -354,18 +415,16 @@ class TypeSlicer:
354
415
  }
355
416
 
356
417
  # 5. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
357
- with cls._mem_lock:
358
- cls._mem_cache[type_key] = code_block
359
- if len(cls._mem_cache) > 100:
360
- cls._mem_cache.popitem(last=False)
418
+ cls._mem_put(type_key, code_block, dts_bytes=dts_bytes, max_items=100)
361
419
 
362
420
  save_conn = None
363
421
  try:
364
422
  save_conn = sqlite3.connect(db_path, timeout=5.0)
365
423
  save_conn.execute("""
366
- INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, cached_at)
367
- VALUES (?, ?, ?, ?, ?, ?)
368
- """, (type_key, pkg_name, version, sym, code_block, int(time.time())))
424
+ INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, dts_bytes, cached_at)
425
+ VALUES (?, ?, ?, ?, ?, ?, ?)
426
+ """, (type_key, pkg_name, version, sym, code_block, dts_bytes, int(time.time())))
427
+ cls._maybe_evict(save_conn)
369
428
  save_conn.commit()
370
429
  except Exception:
371
430
  pass
@@ -378,7 +437,9 @@ class TypeSlicer:
378
437
 
379
438
  try:
380
439
  from src.team_cache import TeamCache
381
- TeamCache.put("3RD_PARTY_DTS", type_key, code_block, tokens_saved=max(30, len(code_block)//4))
440
+ payload = json.dumps({"code": code_block, "dts_bytes": dts_bytes}, ensure_ascii=False)
441
+ tokens_saved = max(30, (dts_bytes // 4) if dts_bytes else len(code_block) // 4)
442
+ TeamCache.put("3RD_PARTY_DTS", type_key, payload, tokens_saved=tokens_saved)
382
443
  except Exception:
383
444
  pass
384
445
 
@@ -388,5 +449,6 @@ class TypeSlicer:
388
449
  "version": version,
389
450
  "symbol": sym,
390
451
  "type_code": code_block,
391
- "source": "parsed_live"
452
+ "source": "parsed_live",
453
+ "_dts_bytes": dts_bytes
392
454
  }
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.4.0"
20
+ CURRENT_VERSION = "4.4.2"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage
package/src/web_reader.py CHANGED
@@ -162,9 +162,14 @@ class WebReader:
162
162
 
163
163
  @classmethod
164
164
  def sanitize_url(cls, url: str) -> str:
165
- """Strips sensitive authentication & signature tokens from query strings for clean canonical caching."""
165
+ """Strips userinfo (user:pass@) and sensitive authentication & signature tokens from query strings for clean canonical caching."""
166
166
  try:
167
167
  parsed = urllib.parse.urlparse(url.strip())
168
+ netloc = parsed.netloc
169
+ if "@" in netloc:
170
+ _, _, netloc = netloc.rpartition("@")
171
+ clean_netloc = netloc.lower()
172
+
168
173
  qs = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
169
174
  cleaned_qs = [
170
175
  (k, v) for k, v in qs
@@ -174,7 +179,7 @@ class WebReader:
174
179
  new_query = urllib.parse.urlencode(cleaned_qs)
175
180
  return urllib.parse.urlunparse((
176
181
  parsed.scheme.lower(),
177
- parsed.netloc.lower(),
182
+ clean_netloc,
178
183
  parsed.path,
179
184
  parsed.params,
180
185
  new_query,
@@ -183,6 +188,22 @@ class WebReader:
183
188
  except Exception:
184
189
  return url.strip()
185
190
 
191
+ @classmethod
192
+ def has_auth_or_userinfo(cls, url: str, custom_headers: Optional[Dict[str, str]] = None) -> bool:
193
+ """Checks whether the request carries credentials, auth headers, or userinfo in URL."""
194
+ if custom_headers and any(
195
+ k.lower() in ("authorization", "cookie", "x-api-key")
196
+ for k in custom_headers
197
+ ):
198
+ return True
199
+ try:
200
+ parsed = urllib.parse.urlparse(url.strip())
201
+ if parsed.username or parsed.password or "@" in parsed.netloc:
202
+ return True
203
+ except Exception:
204
+ pass
205
+ return False
206
+
186
207
  @classmethod
187
208
  def _get_db_path(cls) -> str:
188
209
  data_dir = resolve_data_dir()
@@ -279,11 +300,8 @@ class WebReader:
279
300
  except Exception:
280
301
  pass
281
302
 
282
- # 3. Check L3 Team Sync (Only if request carried no custom auth/cookie headers)
283
- has_auth = bool(custom_headers and any(
284
- k.lower() in ("authorization", "cookie", "x-api-key")
285
- for k in custom_headers
286
- ))
303
+ # 3. Check L3 Team Sync (Only if request carried no custom auth/cookie headers or userinfo)
304
+ has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
287
305
  if not has_auth:
288
306
  try:
289
307
  from src.team_cache import TeamCache
@@ -335,10 +353,7 @@ class WebReader:
335
353
  pass
336
354
 
337
355
  # 3. Broadcast to L3 Team Sync
338
- has_auth = bool(custom_headers and any(
339
- k.lower() in ("authorization", "cookie", "x-api-key")
340
- for k in custom_headers
341
- ))
356
+ has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
342
357
  if sync_team and not has_auth:
343
358
  try:
344
359
  from src.team_cache import TeamCache