tokensafe 4.3.3 → 4.4.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.
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.3.3"
45
+ "version": "4.4.1"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -295,18 +295,62 @@ TOOLS = [
295
295
  },
296
296
  {
297
297
  "name": "read_web_page",
298
- "description": "Fetches a web page URL and converts it to clean, readable Markdown, stripping scripts, styles, navbars, and ads (-80-95% tokens compared to raw HTML).",
298
+ "description": "Fetches a web page URL and converts it to clean, readable Markdown with L1 memory, L2 SQLite (web_cache.db), and L3 Team Sync caching (-80-95% tokens compared to raw HTML, 0ms on cache hits).",
299
299
  "inputSchema": {
300
300
  "type": "object",
301
301
  "properties": {
302
302
  "url": {
303
303
  "type": "string",
304
304
  "description": "Web URL to fetch and convert to Markdown"
305
+ },
306
+ "force_refresh": {
307
+ "type": "boolean",
308
+ "description": "If true, bypasses L1/L2/L3 cache and fetches fresh page content from network"
305
309
  }
306
310
  },
307
311
  "required": ["url"]
308
312
  }
309
313
  },
314
+ {
315
+ "name": "query_dependency",
316
+ "description": "Fast targeted lookup of a package in project lockfiles (package-lock.json, bun.lock, Cargo.lock, pnpm-lock.yaml) returning exact version and direct dependencies in <20 tokens without dumping massive lockfiles.",
317
+ "inputSchema": {
318
+ "type": "object",
319
+ "properties": {
320
+ "package_name": {
321
+ "type": "string",
322
+ "description": "Name of the dependency package to inspect (e.g. 'zod', 'react', 'tokio')"
323
+ },
324
+ "lockfile_path": {
325
+ "type": "string",
326
+ "description": "Optional explicit path to lockfile; defaults to nearest lockfile in project"
327
+ }
328
+ },
329
+ "required": ["package_name"]
330
+ }
331
+ },
332
+ {
333
+ "name": "slice_external_type",
334
+ "description": "Extracts targeted type signatures, interfaces, or class declarations from 3rd-party library declaration files (.d.ts) in node_modules without directory crawling or reading multi-megabyte bundles.",
335
+ "inputSchema": {
336
+ "type": "object",
337
+ "properties": {
338
+ "package_name": {
339
+ "type": "string",
340
+ "description": "Name of the npm package (e.g. '@stripe/stripe-js', 'fastify', 'zod')"
341
+ },
342
+ "symbol": {
343
+ "type": "string",
344
+ "description": "Name of the interface, type, or function to extract (e.g. 'Stripe', 'FastifyReply')"
345
+ },
346
+ "project_root": {
347
+ "type": "string",
348
+ "description": "Optional project root directory"
349
+ }
350
+ },
351
+ "required": ["package_name", "symbol"]
352
+ }
353
+ },
310
354
  {
311
355
  "name": "optimize_image",
312
356
  "description": "Downscales oversized screenshots/diagrams before passing them to LLM vision endpoints. Resizes images exceeding max_edge (default: 1024px) while preserving aspect ratio and crispness, keeping the original image intact on disk (-50-75% vision tokens).",
@@ -546,6 +590,8 @@ class _NoOpTracker:
546
590
  return {}
547
591
  def get_last_event(self, *args, **kwargs):
548
592
  return None
593
+ def get_monthly_saved_tokens(self, *args, **kwargs):
594
+ return 0
549
595
 
550
596
 
551
597
  class _SafeTrackerProxy:
@@ -1793,26 +1839,81 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1793
1839
 
1794
1840
  elif name == "read_web_page":
1795
1841
  target_url = str(args.get("url") or args.get("link") or "").strip()
1842
+ force_refresh = bool(args.get("force_refresh", False))
1796
1843
  if not target_url:
1797
1844
  return _fallback_error("read_web_page", "missing required 'url' argument")
1798
1845
  try:
1799
1846
  from src.web_reader import WebReader
1800
- content, ok, err = WebReader.fetch_url(target_url)
1847
+ content, ok, err = WebReader.fetch_url(target_url, force_refresh=force_refresh)
1801
1848
  if not ok:
1802
1849
  return _fallback_error("read_web_page", err or "failed to fetch web page")
1803
1850
  orig_t = max(1000, len(content) // 2)
1804
1851
  opt_t = count_tokens(content)
1852
+ tier = getattr(WebReader, "last_tier", "live")
1805
1853
  tracker.record_event(
1806
1854
  session_id=_mcp_session_id(),
1807
1855
  event_type="WEB_READ",
1808
1856
  original_tokens=orig_t,
1809
1857
  optimized_tokens=opt_t,
1810
- details={"url": target_url[:80], "saved": max(0, orig_t - opt_t)}
1858
+ details={"url": target_url[:80], "tier": tier, "saved": max(0, orig_t - opt_t)}
1811
1859
  )
1812
1860
  return {"content": [{"type": "text", "text": content}]}
1813
1861
  except Exception as e:
1814
1862
  return _fallback_error("read_web_page", f"error reading web page: {e}")
1815
1863
 
1864
+ elif name == "query_dependency":
1865
+ pkg = str(args.get("package_name") or args.get("package") or "").strip()
1866
+ lock_p = str(args.get("lockfile_path") or args.get("path") or "").strip() or None
1867
+ if not pkg:
1868
+ return _fallback_error("query_dependency", "missing required 'package_name' argument")
1869
+ try:
1870
+ from src.format_parsers.lockfiles import LockfileReducer
1871
+ res = LockfileReducer.query_dependency(lock_p, pkg)
1872
+ lock_bytes = res.pop("_lockfile_bytes", 0)
1873
+ json_text = json.dumps(res, indent=2, ensure_ascii=False)
1874
+ opt_tokens = count_tokens(json_text)
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
1879
+ tracker.record_event(
1880
+ session_id=_mcp_session_id(),
1881
+ event_type="LOCKFILE_QUERY",
1882
+ original_tokens=orig_tokens,
1883
+ optimized_tokens=opt_tokens,
1884
+ details={"package": pkg, "source": res.get("source", "parsed"), "found": res.get("found", False)}
1885
+ )
1886
+ return {"content": [{"type": "text", "text": json_text}]}
1887
+ except Exception as e:
1888
+ return _fallback_error("query_dependency", f"error resolving dependency: {e}")
1889
+
1890
+ elif name == "slice_external_type":
1891
+ pkg = str(args.get("package_name") or args.get("package") or "").strip()
1892
+ sym = str(args.get("symbol") or args.get("type") or args.get("type_name") or "").strip()
1893
+ proj_root = str(args.get("project_root") or "").strip() or None
1894
+ if not pkg or not sym:
1895
+ return _fallback_error("slice_external_type", "missing required 'package_name' or 'symbol' argument")
1896
+ try:
1897
+ from src.type_slicer import TypeSlicer
1898
+ res = TypeSlicer.slice_package_type(pkg, sym, project_root=proj_root)
1899
+ dts_bytes = res.pop("_dts_bytes", 0)
1900
+ json_text = json.dumps(res, indent=2, ensure_ascii=False)
1901
+ opt_tokens = count_tokens(json_text)
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
1906
+ tracker.record_event(
1907
+ session_id=_mcp_session_id(),
1908
+ event_type="TYPE_SLICE",
1909
+ original_tokens=orig_tokens,
1910
+ optimized_tokens=opt_tokens,
1911
+ details={"package": pkg, "symbol": sym, "source": res.get("source", "parsed"), "found": res.get("found", False)}
1912
+ )
1913
+ return {"content": [{"type": "text", "text": json_text}]}
1914
+ except Exception as e:
1915
+ return _fallback_error("slice_external_type", f"error slicing external type: {e}")
1916
+
1816
1917
  elif name == "optimize_image":
1817
1918
  img_path = str(args.get("image_path") or args.get("path") or "").strip()
1818
1919
  if not img_path:
@@ -1865,10 +1966,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1865
1966
  try:
1866
1967
  from src.mistakes import MistakesLedger
1867
1968
  entries = MistakesLedger.list_mistakes(project_root=proj_root)
1969
+ team_entries = MistakesLedger.get_team_mistakes()
1868
1970
  guard = MistakesLedger.get_guard_prompt(project_root=proj_root)
1869
1971
  return {"content": [{"type": "text", "text": json.dumps({
1870
1972
  "count": len(entries),
1871
1973
  "entries": entries,
1974
+ "team_entries": team_entries,
1872
1975
  "active_guard": guard
1873
1976
  }, indent=2, ensure_ascii=False)}]}
1874
1977
  except Exception as e:
package/src/mistakes.py CHANGED
@@ -14,9 +14,11 @@ import os
14
14
  import json
15
15
  import time
16
16
  import hashlib
17
+ import threading
17
18
  import subprocess
18
- from typing import Dict, Any, List, Optional
19
+ from typing import Dict, Any, List, Optional, Tuple
19
20
  from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
21
+ from src.secret_redactor import SecretRedactor
20
22
 
21
23
 
22
24
  def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
@@ -92,6 +94,16 @@ class MistakesLedger:
92
94
  except OSError:
93
95
  pass
94
96
 
97
+ # Broadcast to L3 Team Sync (scrubbed, non-blocking)
98
+ try:
99
+ from src.team_cache import TeamCache
100
+ safe_summary, _, _ = SecretRedactor.redact_text(summary.strip())
101
+ h = hashlib.sha256(f"{f_basename}:{safe_summary}".encode("utf-8")).hexdigest()[:16]
102
+ payload = json.dumps({"file": f_basename, "summary": safe_summary[:160], "timestamp": int(time.time())})
103
+ TeamCache.put("TEAM_MISTAKE", h, payload, tokens_saved=120)
104
+ except Exception:
105
+ pass
106
+
95
107
  return entry
96
108
 
97
109
  @classmethod
@@ -179,6 +191,94 @@ class MistakesLedger:
179
191
  pass
180
192
  return 0
181
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
+
231
+ @classmethod
232
+ def should_force_ask(
233
+ cls,
234
+ target: str,
235
+ action_type: str = "command",
236
+ project_root: Optional[str] = None
237
+ ) -> Tuple[bool, str]:
238
+ """
239
+ Two-tier hybrid escalation policy:
240
+ - Returns (True, reason) ONLY if identical action/target failed > 2 times in last 30 minutes.
241
+ - Returns (False, reason) if 1-2 failures exist (soft advisory warning).
242
+ - Returns (False, "") if no recent failure detected.
243
+ """
244
+ if not target:
245
+ return False, ""
246
+ norm_target = target.strip().lower()
247
+ now = time.time()
248
+ window = 1800.0 # 30 minutes
249
+ mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
250
+
251
+ matching = []
252
+ for m in mistakes:
253
+ if now - float(m.get("timestamp", 0) or 0) > window:
254
+ continue
255
+ f = (m.get("file") or "").lower()
256
+ s = (m.get("summary") or "").lower()
257
+ det = (m.get("details") or "").lower()
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:
271
+ matching.append(m)
272
+
273
+ count = len(matching)
274
+ if count > 2:
275
+ last = matching[-1].get("summary", "")
276
+ return True, f"Dead-End Loop: Action on '{target[:60]}' repeatedly failed {count}x in last 30m. Prior failure: {last}"
277
+ elif count > 0:
278
+ last = matching[-1].get("summary", "")
279
+ return False, f"Advisory: Prior failure recorded on '{target[:50]}': {last}"
280
+ return False, ""
281
+
182
282
  @classmethod
183
283
  def get_guard_prompt(
184
284
  cls,
@@ -186,19 +286,40 @@ class MistakesLedger:
186
286
  max_items: int = 3
187
287
  ) -> Optional[str]:
188
288
  """
189
- 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.
190
290
  Injectable into system instructions or PreInvocation hooks.
191
291
  """
192
- mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
193
- 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:
194
295
  return None
195
296
 
196
- # Take the most recent active entries
197
- recent = mistakes[-max_items:]
198
- lines = ["[TokenSafe Anti-Stuck Guard: Prior Dead-Ends to Avoid in this Project]:"]
199
- 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())
200
304
  f = m.get("file")
201
305
  f_prefix = f"{f}: " if f else ""
202
- 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
203
324
 
204
325
  return "\n".join(lines)
@@ -86,9 +86,18 @@ def _head_tail(text: str, head: int = HEAD_LINES, tail: int = TAIL_LINES) -> str
86
86
 
87
87
 
88
88
  def _compact_read_result(text: str, path: str) -> Optional[str]:
89
- """AST skeleton for source reads; head/tail fallback for unknown types.
90
- Produces both candidates when possible and returns the shortest — the
89
+ """AST skeleton for source reads; lockfile reduction for lockfiles; head/tail fallback for unknown types.
90
+ Produces candidates when possible and returns the shortest — the
91
91
  skeleton only wins when it actually compresses substantially."""
92
+ try:
93
+ from src.format_parsers.lockfiles import LockfileReducer
94
+ if LockfileReducer.is_lockfile(path):
95
+ compacted_l, was_l = LockfileReducer.reduce(text, path)
96
+ if was_l:
97
+ return compacted_l
98
+ except Exception:
99
+ pass
100
+
92
101
  ext = os.path.splitext(path or "")[1].lower() or None
93
102
  candidates: List[str] = []
94
103
  lines = text.splitlines()
@@ -18,8 +18,14 @@ smart_read_file so agents use one familiar entry point.
18
18
  import json
19
19
  import os
20
20
  import re
21
+ import hashlib
22
+ import sqlite3
23
+ import time
24
+ import threading
25
+ from collections import OrderedDict
21
26
 
22
27
  from src.tokenizer import count_tokens
28
+ from src.paths import resolve_data_dir
23
29
  from typing import Any, Dict, List, Optional, Tuple
24
30
 
25
31
  _MAX_REF_CHAIN = 15
@@ -27,7 +33,134 @@ _MAX_SQL_BYTES = 4 * 1024 * 1024
27
33
 
28
34
 
29
35
  class SchemaSlicer:
30
- """Detects schema files and produces targeted, token-cheap slices."""
36
+ """Detects schema files and produces targeted, token-cheap slices with L1/L2/L3 caching."""
37
+
38
+ _mem_cache: "OrderedDict[str, Tuple[str, Dict[str, Any]]]" = OrderedDict()
39
+ _mem_lock = threading.Lock()
40
+ _db_init_done = False
41
+ _db_init_lock = threading.Lock()
42
+
43
+ @classmethod
44
+ def clear_memory_cache(cls):
45
+ with cls._mem_lock:
46
+ cls._mem_cache.clear()
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
+
73
+ @classmethod
74
+ def _get_db_path(cls) -> str:
75
+ data_dir = resolve_data_dir()
76
+ os.makedirs(data_dir, exist_ok=True)
77
+ return os.path.join(data_dir, "type_cache.db")
78
+
79
+ @classmethod
80
+ def _init_db(cls):
81
+ db_path = cls._get_db_path()
82
+ with cls._db_init_lock:
83
+ if cls._db_init_done == db_path and os.path.exists(db_path):
84
+ return
85
+ conn = None
86
+ try:
87
+ conn = sqlite3.connect(db_path, timeout=5.0)
88
+ conn.execute("PRAGMA journal_mode=WAL;")
89
+ conn.execute("PRAGMA busy_timeout=5000;")
90
+ conn.execute("""
91
+ CREATE TABLE IF NOT EXISTS schema_cache (
92
+ cache_key TEXT PRIMARY KEY,
93
+ schema_kind TEXT NOT NULL,
94
+ fingerprint TEXT NOT NULL,
95
+ target TEXT NOT NULL,
96
+ sliced_text TEXT NOT NULL,
97
+ info_json TEXT NOT NULL,
98
+ cached_at INTEGER NOT NULL
99
+ );
100
+ """)
101
+ conn.commit()
102
+ cls._db_init_done = db_path
103
+ except Exception:
104
+ pass
105
+ finally:
106
+ if conn:
107
+ try:
108
+ conn.close()
109
+ except Exception:
110
+ pass
111
+
112
+ @classmethod
113
+ def compute_schema_fingerprint(cls, path: str, kind: str) -> str:
114
+ """
115
+ Computes deterministic composite fingerprint:
116
+ - For single file: SHA-256(content)[:16]
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
119
+ """
120
+ abs_p = os.path.abspath(path)
121
+ base_dir = os.path.dirname(abs_p)
122
+
123
+ # Multi-file Prisma check
124
+ if kind == "prisma" and os.path.basename(base_dir).lower() == "schema":
125
+ try:
126
+ prisma_files = sorted([
127
+ os.path.join(base_dir, f) for f in os.listdir(base_dir) if f.endswith(".prisma")
128
+ ])
129
+ if len(prisma_files) > 1:
130
+ hasher = hashlib.sha256()
131
+ for pf in prisma_files:
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"))
136
+ return hasher.hexdigest()[:16]
137
+ except Exception:
138
+ pass
139
+
140
+ # Single file hash or OpenAPI $ref
141
+ try:
142
+ with open(abs_p, "rb") as f:
143
+ content = f.read()
144
+ h = hashlib.sha256(content).hexdigest()[:16]
145
+ if kind == "openapi" and b"$ref" in content:
146
+ ref_matches = re.findall(rb'["\']?\$ref["\']?\s*:\s*["\'](\.[^"\'#]+)', content)
147
+ if ref_matches:
148
+ hasher = hashlib.sha256(content)
149
+ for rm in sorted(set(ref_matches)):
150
+ ref_rel = rm.decode("utf-8", errors="ignore")
151
+ cand = os.path.normpath(os.path.join(base_dir, ref_rel))
152
+ if os.path.isfile(cand):
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
160
+ return hasher.hexdigest()[:16]
161
+ return h
162
+ except Exception:
163
+ return "unknown_fp"
31
164
 
32
165
  @classmethod
33
166
  def detect(cls, path: str) -> Optional[str]:
@@ -57,19 +190,91 @@ class SchemaSlicer:
57
190
 
58
191
  @classmethod
59
192
  def slice_file(cls, path: str, target: str = "") -> Tuple[str, Dict[str, Any]]:
60
- """Returns (sliced_text, info). Empty `target` yields a compact overview.
193
+ """Returns (sliced_text, info). Empty `target` yields a compact overview with L1/L2/L3 caching."""
194
+ kind = cls.detect(path)
195
+ if not kind:
196
+ return "", {"kind": None}
197
+
198
+ # 1. Compute composite fingerprint and cache key
199
+ norm_target = target.strip().lower()
200
+ fp = cls.compute_schema_fingerprint(path, kind)
201
+ cache_key = f"{kind}::{fp}::{norm_target}"
202
+
203
+ # 2. Check L1 Memory
204
+ with cls._mem_lock:
205
+ if cache_key in cls._mem_cache:
206
+ cls._mem_cache.move_to_end(cache_key)
207
+ hit_text, hit_info = cls._mem_cache[cache_key]
208
+ hit_info = dict(hit_info)
209
+ hit_info["source"] = "L1_memory"
210
+ return hit_text, hit_info
211
+
212
+ # 3. Check L2 SQLite
213
+ cls._init_db()
214
+ db_path = cls._get_db_path()
215
+ l2_conn = None
216
+ try:
217
+ l2_conn = sqlite3.connect(db_path, timeout=5.0)
218
+ l2_conn.execute("PRAGMA busy_timeout=5000;")
219
+ row = l2_conn.execute(
220
+ "SELECT sliced_text, info_json FROM schema_cache WHERE cache_key = ?",
221
+ (cache_key,)
222
+ ).fetchone()
223
+ if row:
224
+ text_cached, info_raw = row[0], row[1]
225
+ info_dict = json.loads(info_raw)
226
+ info_dict["source"] = "L2_sqlite"
227
+ cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
228
+ return text_cached, info_dict
229
+ except Exception:
230
+ pass
231
+ finally:
232
+ if l2_conn:
233
+ try:
234
+ l2_conn.close()
235
+ except Exception:
236
+ pass
237
+
238
+ # 4. Check L3 Team Sync
239
+ try:
240
+ from src.team_cache import TeamCache
241
+ team_val = TeamCache.get("SCHEMA_CONTRACTS", cache_key, timeout=0.5)
242
+ if team_val:
243
+ parsed_team = json.loads(team_val)
244
+ text_cached = parsed_team.get("sliced", "")
245
+ info_dict = parsed_team.get("info", {})
246
+ info_dict["source"] = "L3_team_cache"
247
+ cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
248
+ # Store back to L2
249
+ back_conn = None
250
+ try:
251
+ back_conn = sqlite3.connect(db_path, timeout=5.0)
252
+ back_conn.execute("""
253
+ INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
254
+ VALUES (?, ?, ?, ?, ?, ?, ?)
255
+ """, (cache_key, kind, fp, norm_target, text_cached, json.dumps(info_dict), int(time.time())))
256
+ cls._maybe_evict(back_conn)
257
+ back_conn.commit()
258
+ except Exception:
259
+ pass
260
+ finally:
261
+ if back_conn:
262
+ try:
263
+ back_conn.close()
264
+ except Exception:
265
+ pass
266
+ return text_cached, info_dict
267
+ except Exception:
268
+ pass
61
269
 
62
- Never EXPANDS: when the slice is not smaller than the raw file (tiny
63
- toy schemas — QA sweep found 14-token graphql fixtures growing to 23),
64
- the raw text is returned unchanged, same honest pass-through as
65
- DiffSlicer."""
270
+ # 5. Compute fresh slice
66
271
  raw_text = ""
67
272
  try:
68
273
  with open(path, "r", encoding="utf-8", errors="replace") as f:
69
274
  raw_text = f.read()
70
275
  except OSError:
71
276
  pass
72
- kind = cls.detect(path)
277
+
73
278
  sliced = ""
74
279
  if kind == "openapi":
75
280
  sliced, info = cls._slice_openapi(path, target.strip())
@@ -81,8 +286,39 @@ class SchemaSlicer:
81
286
  sliced, info = cls._slice_sql(path, target.strip())
82
287
  else:
83
288
  return "", {"kind": None}
289
+
84
290
  if not target.strip() and count_tokens(sliced) >= count_tokens(raw_text):
85
- return raw_text, info # overview pass-through; targeted slices keep precision semantics
291
+ return raw_text, info
292
+
293
+ # 6. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
294
+ info["source"] = "parsed_live"
295
+ cls._mem_put(cache_key, (sliced, info), max_items=80)
296
+
297
+ save_conn = None
298
+ try:
299
+ save_conn = sqlite3.connect(db_path, timeout=5.0)
300
+ save_conn.execute("""
301
+ INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
302
+ VALUES (?, ?, ?, ?, ?, ?, ?)
303
+ """, (cache_key, kind, fp, norm_target, sliced, json.dumps(info), int(time.time())))
304
+ cls._maybe_evict(save_conn)
305
+ save_conn.commit()
306
+ except Exception:
307
+ pass
308
+ finally:
309
+ if save_conn:
310
+ try:
311
+ save_conn.close()
312
+ except Exception:
313
+ pass
314
+
315
+ try:
316
+ from src.team_cache import TeamCache
317
+ payload = json.dumps({"sliced": sliced, "info": info}, ensure_ascii=False)
318
+ TeamCache.put("SCHEMA_CONTRACTS", cache_key, payload, tokens_saved=max(40, count_tokens(raw_text) - count_tokens(sliced)))
319
+ except Exception:
320
+ pass
321
+
86
322
  return sliced, info
87
323
 
88
324
  # ------------------------------------------------------------------ OpenAPI
@@ -238,7 +474,7 @@ class SchemaSlicer:
238
474
  out = [f"# Prisma {kind_name} {target}", body]
239
475
  # 1-hop: capitalized field types that are themselves defined blocks
240
476
  refs = set()
241
- for fm in re.finditer(r"^\s{2,}\w+\??\s+([A-Z]\w*)(?:\[\])?(?:\s|$)", body, re.MULTILINE):
477
+ for fm in re.finditer(r"^\s{2,}\w+\s+([A-Z]\w*)(?:\?|\[\])?(?:\s|$)", body, re.MULTILINE):
242
478
  if fm.group(1) in blocks and fm.group(1) != target:
243
479
  refs.add(fm.group(1))
244
480
  if refs: