tokensafe 3.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +60 -28
  2. package/bin/tokensafe.js +25 -9
  3. package/hooks/claude_code_hook.py +7 -0
  4. package/hooks/pre_tool_use.py +24 -0
  5. package/hooks/session_start.py +8 -0
  6. package/package.json +2 -2
  7. package/plugin.json +1 -1
  8. package/rules/AGENTS.md +13 -7
  9. package/server.json +3 -3
  10. package/skills/token-optimizer/SKILL.md +7 -2
  11. package/skills/token-optimizer/references/cli-reference.md +11 -1
  12. package/skills/token-optimizer/references/mcp-tools.md +44 -2
  13. package/src/bench_scenarios.json +376 -0
  14. package/src/cache_normalizer.py +21 -0
  15. package/src/cli.py +234 -2
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/competitors.py +179 -0
  18. package/src/environment_auditor.py +110 -1
  19. package/src/format_parsers/__init__.py +20 -0
  20. package/src/format_parsers/ansi.py +41 -0
  21. package/src/format_parsers/compiler_errors.py +159 -0
  22. package/src/format_parsers/docker_k8s.py +95 -0
  23. package/src/format_parsers/json_log.py +89 -0
  24. package/src/format_parsers/lockfiles.py +157 -0
  25. package/src/format_parsers/tabular.py +175 -0
  26. package/src/fts_index.py +296 -0
  27. package/src/graph_engine.py +395 -48
  28. package/src/image_downscale.py +228 -0
  29. package/src/loop_detector.py +5 -0
  30. package/src/mcp_config_manager.py +197 -0
  31. package/src/mcp_proxy.py +154 -0
  32. package/src/mcp_server.py +215 -1
  33. package/src/mistakes.py +203 -0
  34. package/src/result_ledger.py +8 -1
  35. package/src/scoped_search.py +32 -0
  36. package/src/stash.py +199 -0
  37. package/src/superseded.py +220 -0
  38. package/src/telemetry_sync.py +1 -1
  39. package/src/test_parsers.py +271 -0
  40. package/src/version_checker.py +1 -1
  41. package/src/web_reader.py +202 -0
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": "3.2.0"
45
+ "version": "4.0.0"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -276,6 +276,68 @@ TOOLS = [
276
276
  },
277
277
  "required": ["query"]
278
278
  }
279
+ },
280
+ {
281
+ "name": "expand_ref",
282
+ "description": "Expands a previously folded or stashed tool, command, file, or MCP result by its 8-character hex hash anchor (e.g. 'a1b2c3d4' or '#a1b2c3d4'). Returns the full original text that TokenSafe folded.",
283
+ "inputSchema": {
284
+ "type": "object",
285
+ "properties": {
286
+ "hash": {
287
+ "type": "string",
288
+ "description": "8-character hex hash from the fold marker (e.g. 'a1b2c3d4' or '#a1b2c3d4')"
289
+ }
290
+ },
291
+ "required": ["hash"]
292
+ }
293
+ },
294
+ {
295
+ "name": "read_web_page",
296
+ "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).",
297
+ "inputSchema": {
298
+ "type": "object",
299
+ "properties": {
300
+ "url": {
301
+ "type": "string",
302
+ "description": "Web URL to fetch and convert to Markdown"
303
+ }
304
+ },
305
+ "required": ["url"]
306
+ }
307
+ },
308
+ {
309
+ "name": "optimize_image",
310
+ "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).",
311
+ "inputSchema": {
312
+ "type": "object",
313
+ "properties": {
314
+ "image_path": {"type": "string", "description": "Absolute or relative path to the image file"},
315
+ "max_edge": {"type": "integer", "description": "Maximum width/height in pixels (default: 1024)"}
316
+ },
317
+ "required": ["image_path"]
318
+ }
319
+ },
320
+ {
321
+ "name": "prune_superseded",
322
+ "description": "Prunes obsolete intermediate tool read outputs in long conversation transcripts that have since been modified by subsequent edits or re-read in later steps (-30-40% context mass).",
323
+ "inputSchema": {
324
+ "type": "object",
325
+ "properties": {
326
+ "transcript_path": {"type": "string", "description": "Path to the JSONL conversation transcript to prune"}
327
+ },
328
+ "required": ["transcript_path"]
329
+ }
330
+ },
331
+ {
332
+ "name": "get_mistakes",
333
+ "description": "Returns known dead-ends, failed hypotheses, and reverted code changes for this project to prevent repeating unsuccessful approaches.",
334
+ "inputSchema": {
335
+ "type": "object",
336
+ "properties": {
337
+ "project_root": {"type": "string", "description": "Optional project root directory (defaults to current project)"},
338
+ "clear": {"type": "boolean", "description": "If true, clears the mistakes ledger"}
339
+ }
340
+ }
279
341
  }
280
342
  ]
281
343
 
@@ -765,6 +827,59 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
765
827
  if _is_binary_file(path):
766
828
  return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
767
829
 
830
+ # Bloated lockfiles (package-lock.json, Cargo.lock, poetry.lock, pnpm-lock.yaml):
831
+ # Extract compact dependency bill with reversible hash anchor instead of a 30k token dump.
832
+ from src.format_parsers.lockfiles import LockfileReducer
833
+ if LockfileReducer.is_lockfile(path):
834
+ try:
835
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
836
+ raw_lock_text = f.read()
837
+ reduced_lock, was_reduced = LockfileReducer.reduce(raw_lock_text, os.path.basename(path))
838
+ if was_reduced:
839
+ orig_t = count_tokens(raw_lock_text)
840
+ opt_t = count_tokens(reduced_lock)
841
+ tracker.record_event(
842
+ session_id=_mcp_session_id(),
843
+ event_type="LOCKFILE_REDUCE",
844
+ original_tokens=orig_t,
845
+ optimized_tokens=opt_t,
846
+ details={"file": os.path.basename(path), "saved": orig_t - opt_t}
847
+ )
848
+ return {"content": [{"type": "text", "text": reduced_lock}]}
849
+ except Exception:
850
+ pass
851
+
852
+ # Tabular and database dump files (CSV, TSV, SQL, HAR):
853
+ # Extract schema, data types, and sample rows instead of dumping 10k rows into context.
854
+ from src.format_parsers.tabular import TabularReducer
855
+ if TabularReducer.is_tabular_or_dump(path):
856
+ try:
857
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
858
+ raw_data_text = f.read()
859
+ ext_lower = os.path.splitext(path)[1].lower()
860
+ if ext_lower in (".csv", ".tsv"):
861
+ reduced_tab, was_reduced = TabularReducer.reduce_csv(raw_data_text)
862
+ elif ext_lower == ".sql":
863
+ reduced_tab, was_reduced = TabularReducer.reduce_sql_dump(raw_data_text)
864
+ elif ext_lower == ".har":
865
+ reduced_tab, was_reduced = TabularReducer.reduce_har(raw_data_text)
866
+ else:
867
+ reduced_tab, was_reduced = raw_data_text, False
868
+
869
+ if was_reduced:
870
+ orig_t = count_tokens(raw_data_text)
871
+ opt_t = count_tokens(reduced_tab)
872
+ tracker.record_event(
873
+ session_id=_mcp_session_id(),
874
+ event_type="TABULAR_REDUCE",
875
+ original_tokens=orig_t,
876
+ optimized_tokens=opt_t,
877
+ details={"file": os.path.basename(path), "saved": orig_t - opt_t}
878
+ )
879
+ return {"content": [{"type": "text", "text": reduced_tab}]}
880
+ except Exception:
881
+ pass
882
+
768
883
  # Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
769
884
  # generic AST skeletonization does not apply — route to the schema slicer.
770
885
  # `symbol` carries the target (a spec path, model, type or table); an empty
@@ -1562,6 +1677,105 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1562
1677
  )
1563
1678
  return {"content": [{"type": "text", "text": md_text}]}
1564
1679
 
1680
+ elif name == "expand_ref":
1681
+ raw_hash = args.get("hash") or args.get("ref") or args.get("id") or ""
1682
+ if not raw_hash:
1683
+ return _fallback_error("expand_ref", "missing required 'hash' argument")
1684
+ try:
1685
+ from src.stash import retrieve_block
1686
+ content = retrieve_block(str(raw_hash))
1687
+ if content is None:
1688
+ return {
1689
+ "isError": True,
1690
+ "content": [{"type": "text", "text": f"Error: Stashed reference '{raw_hash}' not found or expired (retention is 7 days)."}]
1691
+ }
1692
+ return {"content": [{"type": "text", "text": content}]}
1693
+ except Exception as e:
1694
+ return _fallback_error("expand_ref", f"cannot retrieve stashed ref: {e}")
1695
+
1696
+ elif name == "read_web_page":
1697
+ target_url = str(args.get("url") or args.get("link") or "").strip()
1698
+ if not target_url:
1699
+ return _fallback_error("read_web_page", "missing required 'url' argument")
1700
+ try:
1701
+ from src.web_reader import WebReader
1702
+ content, ok, err = WebReader.fetch_url(target_url)
1703
+ if not ok:
1704
+ return _fallback_error("read_web_page", err or "failed to fetch web page")
1705
+ orig_t = max(1000, len(content) // 2)
1706
+ opt_t = count_tokens(content)
1707
+ tracker.record_event(
1708
+ session_id=_mcp_session_id(),
1709
+ event_type="WEB_READ",
1710
+ original_tokens=orig_t,
1711
+ optimized_tokens=opt_t,
1712
+ details={"url": target_url[:80], "saved": max(0, orig_t - opt_t)}
1713
+ )
1714
+ return {"content": [{"type": "text", "text": content}]}
1715
+ except Exception as e:
1716
+ return _fallback_error("read_web_page", f"error reading web page: {e}")
1717
+
1718
+ elif name == "optimize_image":
1719
+ img_path = str(args.get("image_path") or args.get("path") or "").strip()
1720
+ if not img_path:
1721
+ return _fallback_error("optimize_image", "missing required 'image_path' argument")
1722
+ try:
1723
+ max_edge = _safe_int(args.get("max_edge"), 1024, lo=256, hi=4096)
1724
+ from src.image_downscale import ImageDownscaler
1725
+ res = ImageDownscaler.optimize(img_path, max_edge=max_edge)
1726
+ if not res.get("success"):
1727
+ return _fallback_error("optimize_image", res.get("error", "optimization failed"))
1728
+ if res.get("was_downscaled"):
1729
+ tracker.record_event(
1730
+ session_id=_mcp_session_id(),
1731
+ event_type="IMAGE_OPTIMIZATION",
1732
+ original_tokens=res.get("orig_tokens", 1000),
1733
+ optimized_tokens=res.get("new_tokens", 500),
1734
+ details={"path": os.path.basename(img_path), "saved": res.get("saved_tokens", 0)}
1735
+ )
1736
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
1737
+ except Exception as e:
1738
+ return _fallback_error("optimize_image", f"error optimizing image: {e}")
1739
+
1740
+ elif name == "prune_superseded":
1741
+ t_path = str(args.get("transcript_path") or "").strip()
1742
+ if not t_path:
1743
+ return _fallback_error("prune_superseded", "missing required 'transcript_path' argument")
1744
+ try:
1745
+ from src.superseded import SupersededPruner
1746
+ res = SupersededPruner.prune_transcript(t_path)
1747
+ if not res.get("success"):
1748
+ return _fallback_error("prune_superseded", res.get("error", "pruning failed"))
1749
+ if res.get("saved_tokens", 0) > 0:
1750
+ tracker.record_event(
1751
+ session_id=_mcp_session_id(),
1752
+ event_type="SUPERSEDED_PRUNE",
1753
+ original_tokens=res.get("orig_tokens", 0),
1754
+ optimized_tokens=res.get("pruned_tokens", 0),
1755
+ details={"pruned_count": res.get("pruned_count", 0), "saved": res.get("saved_tokens", 0)}
1756
+ )
1757
+ return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
1758
+ except Exception as e:
1759
+ return _fallback_error("prune_superseded", f"error pruning transcript: {e}")
1760
+
1761
+ elif name == "get_mistakes":
1762
+ proj_root = str(args.get("project_root") or "").strip() or None
1763
+ if args.get("clear"):
1764
+ from src.mistakes import MistakesLedger
1765
+ cleared = MistakesLedger.clear_mistakes(project_root=proj_root)
1766
+ return {"content": [{"type": "text", "text": json.dumps({"cleared": cleared}, indent=2)}]}
1767
+ try:
1768
+ from src.mistakes import MistakesLedger
1769
+ entries = MistakesLedger.list_mistakes(project_root=proj_root)
1770
+ guard = MistakesLedger.get_guard_prompt(project_root=proj_root)
1771
+ return {"content": [{"type": "text", "text": json.dumps({
1772
+ "count": len(entries),
1773
+ "entries": entries,
1774
+ "active_guard": guard
1775
+ }, indent=2, ensure_ascii=False)}]}
1776
+ except Exception as e:
1777
+ return _fallback_error("get_mistakes", f"error reading mistakes ledger: {e}")
1778
+
1565
1779
  return _fallback_error(name, f"unknown tool '{name}'")
1566
1780
 
1567
1781
 
@@ -0,0 +1,203 @@
1
+ """
2
+ TokenSafe Persistent Revert & Failure Memory (Mistakes Ledger) (v3.3.0).
3
+
4
+ Prevents AI coding agents from repeating known dead-ends, failed hypotheses,
5
+ and reverted code patterns across turns and sessions.
6
+
7
+ Synergizes directly with:
8
+ 1. `LoopDetector`: Captures repetitive tool-execution loops and converts them to persistent memory.
9
+ 2. Git Rollback Tracking: Detects git reverts/checkouts and logs the abandoned direction.
10
+ 3. Anti-Stuck Prompt Guard: Injects a compact (<80 tokens) warning into context before execution.
11
+ """
12
+
13
+ import os
14
+ import json
15
+ import time
16
+ import hashlib
17
+ import subprocess
18
+ from typing import Dict, Any, List, Optional
19
+ from src.paths import resolve_data_dir
20
+
21
+
22
+ def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
23
+ """Finds or creates .tokensafe/mistakes.jsonl in project or user data dir."""
24
+ if project_root and os.path.isdir(project_root):
25
+ proj_dir = os.path.join(project_root, ".tokensafe")
26
+ try:
27
+ os.makedirs(proj_dir, exist_ok=True)
28
+ return os.path.join(proj_dir, "mistakes.jsonl")
29
+ except Exception:
30
+ pass
31
+ # Fallback to global data dir
32
+ global_dir = resolve_data_dir()
33
+ os.makedirs(global_dir, exist_ok=True)
34
+ return os.path.join(global_dir, "mistakes.jsonl")
35
+
36
+
37
+ class MistakesLedger:
38
+ """Persistent ledger of failed hypotheses and reverted code patterns."""
39
+
40
+ MAX_ENTRIES = 50
41
+
42
+ @classmethod
43
+ def record_failure(
44
+ cls,
45
+ summary: str,
46
+ file_path: Optional[str] = None,
47
+ source: str = "loop_guard",
48
+ details: Optional[str] = None,
49
+ project_root: Optional[str] = None
50
+ ) -> Dict[str, Any]:
51
+ """
52
+ Records a failed attempt or dead-end in the persistent ledger.
53
+ """
54
+ ledger_path = _find_project_mistakes_file(project_root)
55
+ f_basename = os.path.basename(file_path) if file_path else ""
56
+
57
+ entry = {
58
+ "id": hashlib.sha256(f"{f_basename}:{summary}:{time.time()}".encode("utf-8")).hexdigest()[:12],
59
+ "timestamp": time.time(),
60
+ "source": source,
61
+ "file": f_basename,
62
+ "file_full": file_path or "",
63
+ "summary": summary.strip()[:200],
64
+ "details": (details or "").strip()[:500],
65
+ "active": True
66
+ }
67
+
68
+ entries = cls.list_mistakes(project_root=project_root, active_only=False)
69
+
70
+ # Deduplicate identical summary + file
71
+ filtered = [
72
+ e for e in entries
73
+ if not (e.get("file") == entry["file"] and e.get("summary") == entry["summary"])
74
+ ]
75
+ filtered.append(entry)
76
+
77
+ # Cap to MAX_ENTRIES
78
+ if len(filtered) > cls.MAX_ENTRIES:
79
+ filtered = filtered[-cls.MAX_ENTRIES:]
80
+
81
+ tmp_path = f"{ledger_path}.tmp.{os.getpid()}"
82
+ try:
83
+ with open(tmp_path, "w", encoding="utf-8") as f:
84
+ for e in filtered:
85
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
86
+ os.replace(tmp_path, ledger_path)
87
+ except Exception:
88
+ try:
89
+ if os.path.exists(tmp_path):
90
+ os.unlink(tmp_path)
91
+ except OSError:
92
+ pass
93
+
94
+ return entry
95
+
96
+ @classmethod
97
+ def record_from_loop(
98
+ cls,
99
+ tool_name: str,
100
+ args: Dict[str, Any],
101
+ repeats: int,
102
+ project_root: Optional[str] = None
103
+ ) -> Dict[str, Any]:
104
+ """
105
+ Anti-stuck synergy: converts a tripped LoopDetector event into a persistent mistake record.
106
+ """
107
+ target = args.get("Path") or args.get("path") or args.get("CommandLine") or args.get("command") or ""
108
+ target_str = str(target)
109
+ if len(target_str) > 80:
110
+ target_str = target_str[:80] + "..."
111
+
112
+ summary = f"Tool '{tool_name}' stuck in {repeats}x loop with target: {target_str}"
113
+ fpath = args.get("Path") or args.get("path")
114
+ return cls.record_failure(
115
+ summary=summary,
116
+ file_path=str(fpath) if fpath else None,
117
+ source="loop_detector",
118
+ details=f"Identical parameters executed {repeats} times in a row without progress.",
119
+ project_root=project_root
120
+ )
121
+
122
+ @classmethod
123
+ def record_revert(
124
+ cls,
125
+ file_path: str,
126
+ reason: str,
127
+ project_root: Optional[str] = None
128
+ ) -> Dict[str, Any]:
129
+ """
130
+ Records a reverted code change or git rollback.
131
+ """
132
+ summary = f"Reverted change: {reason.strip()}"
133
+ return cls.record_failure(
134
+ summary=summary,
135
+ file_path=file_path,
136
+ source="git_revert",
137
+ project_root=project_root
138
+ )
139
+
140
+ @classmethod
141
+ def list_mistakes(
142
+ cls,
143
+ project_root: Optional[str] = None,
144
+ active_only: bool = True
145
+ ) -> List[Dict[str, Any]]:
146
+ """Loads all recorded mistakes from the ledger."""
147
+ ledger_path = _find_project_mistakes_file(project_root)
148
+ if not os.path.exists(ledger_path):
149
+ return []
150
+
151
+ entries = []
152
+ try:
153
+ with open(ledger_path, "r", encoding="utf-8", errors="replace") as f:
154
+ for line in f:
155
+ line = line.strip()
156
+ if line:
157
+ try:
158
+ item = json.loads(line)
159
+ if not active_only or item.get("active", True):
160
+ entries.append(item)
161
+ except Exception:
162
+ pass
163
+ except Exception:
164
+ return []
165
+
166
+ return entries
167
+
168
+ @classmethod
169
+ def clear_mistakes(cls, project_root: Optional[str] = None) -> int:
170
+ """Clears all entries from the mistakes ledger."""
171
+ ledger_path = _find_project_mistakes_file(project_root)
172
+ if os.path.exists(ledger_path):
173
+ try:
174
+ entries = cls.list_mistakes(project_root=project_root, active_only=False)
175
+ os.remove(ledger_path)
176
+ return len(entries)
177
+ except Exception:
178
+ pass
179
+ return 0
180
+
181
+ @classmethod
182
+ def get_guard_prompt(
183
+ cls,
184
+ project_root: Optional[str] = None,
185
+ max_items: int = 3
186
+ ) -> Optional[str]:
187
+ """
188
+ Generates a compact (<80 tokens) prompt guard from recent active mistakes.
189
+ Injectable into system instructions or PreInvocation hooks.
190
+ """
191
+ mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
192
+ if not mistakes:
193
+ return None
194
+
195
+ # Take the most recent active entries
196
+ recent = mistakes[-max_items:]
197
+ lines = ["[TokenSafe Anti-Stuck Guard: Prior Dead-Ends to Avoid in this Project]:"]
198
+ for m in reversed(recent):
199
+ f = m.get("file")
200
+ f_prefix = f"{f}: " if f else ""
201
+ lines.append(f"• {f_prefix}{m.get('summary', '')}")
202
+
203
+ return "\n".join(lines)
@@ -114,6 +114,13 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
114
114
 
115
115
  def _compact_command_result(text: str) -> Optional[str]:
116
116
  """Test summaries first (PASS: ...), log-style head/tail otherwise."""
117
+ try:
118
+ from src.test_parsers import TestOutputParser
119
+ compacted, was_test = TestOutputParser.compact(text)
120
+ if was_test:
121
+ return compacted
122
+ except Exception:
123
+ pass
117
124
  try:
118
125
  from src.command_sanitizer import CommandSanitizer
119
126
  compacted = CommandSanitizer.compact_test_output(text, 0)
@@ -183,7 +190,7 @@ def _fold_anchor(tool_name: str, preview: str, orig_tokens: int, new_tokens: int
183
190
  return (
184
191
  f"{FOLD_MARKER} {tool_name} ({preview}) result consumed earlier — folded "
185
192
  f"~{orig_tokens}→{new_tokens} tokens (sha256:{sha[:8]}).{archive_note} "
186
- f"To re-inspect: re-run {tool_name}, or use smart_read_file(force_full=true) for file reads.]"
193
+ f"To re-inspect: call tokensafe:expand_ref('{sha[:8]}'), re-run {tool_name}, or use smart_read_file(force_full=true).]"
187
194
  )
188
195
 
189
196
 
@@ -165,6 +165,38 @@ class ScopedSearch:
165
165
  "markdown": f"Regex compilation error: {str(e)}"
166
166
  }
167
167
 
168
+ # Fast-path: SQLite FTS5 trigram BM25 search for plain identifier queries
169
+ if not regex_mode and len(query) >= 3 and not any(c in query for c in "*?[]{}()^$+\\|"):
170
+ try:
171
+ from src.fts_index import CodeFTSIndex
172
+ fts = CodeFTSIndex(root_dir)
173
+ fts_results = fts.search(query, limit=max_results)
174
+ if fts_results:
175
+ fts_matches = []
176
+ fts_hit_files = set()
177
+ for r in fts_results:
178
+ f_rel = r["file"]
179
+ if cls.is_match_file(os.path.basename(f_rel), f_rel, scope):
180
+ fts_matches.append({
181
+ "file": f_rel,
182
+ "line": r["line"],
183
+ "content": r["content"]
184
+ })
185
+ fts_hit_files.add(f_rel)
186
+ if fts_matches:
187
+ return {
188
+ "success": True,
189
+ "query": query,
190
+ "scope": scope,
191
+ "total_scanned_files": len(fts_hit_files),
192
+ "total_matches": len(fts_matches),
193
+ "timed_out": False,
194
+ "matches": fts_matches,
195
+ "markdown": cls._render_markdown(query, fts_matches, len(fts_hit_files), False, max_results)
196
+ }
197
+ except Exception:
198
+ pass # Seamless fallback to disk scan
199
+
168
200
  matches: List[Dict[str, Any]] = []
169
201
  total_scanned_files = 0
170
202
  hit_files = set()