tokensafe 4.16.2 → 5.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 (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +8 -3
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2429
  26. package/src/mcp_server.py +11 -5024
  27. package/src/proxy.py +11 -1803
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +42 -17
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +68 -9
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +769 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/tokensafe/ingress_staging.py +384 -0
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/tokensafe/read_baseline.py +192 -0
  100. package/tokensafe/repo_compute.py +332 -0
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -0,0 +1,1191 @@
1
+ """
2
+ TokenSafe Batch Search Engine (v3.5.0).
3
+
4
+ Executes up to 20 heterogeneous code, path, and read-only git searches
5
+ concurrently in one MCP call, cutting round-trip LLM turns and avoiding
6
+ per-command remote safety evaluation overheads.
7
+
8
+ Supported query types:
9
+ - 'text': literal substring search.
10
+ - 'regex': regular expression pattern matching.
11
+ - 'glob': file name and path pattern matching.
12
+ - 'fuzzy': case-insensitive fuzzy path and symbol search.
13
+ - 'git': read-only git queries (status, diff, log, show, branch, rev-parse,
14
+ ls-files, blame, shortlog, describe, tag) with writing/escaping flags blocked.
15
+
16
+ `path` may point to a directory or to a single file. A missing path, an
17
+ uncompilable regex, and an unknown `file_type` are reported as per-query
18
+ errors instead of silent zero-hit results.
19
+ """
20
+
21
+ import base64
22
+ import json
23
+ import os
24
+ import re
25
+ import stat
26
+ import fnmatch
27
+ import shutil
28
+ import subprocess
29
+ import threading
30
+ import time
31
+ from concurrent.futures import ThreadPoolExecutor, wait
32
+ from typing import Dict, Any, Iterator, List, Optional, Tuple
33
+
34
+ from tokensafe.scoped_search import ScopedSearch, IGNORED_DIRS, IGNORED_EXTENSIONS, CODE_EXTENSIONS
35
+ from tokensafe.globmatch import GlobPatternError, compile_patterns, matches_any
36
+ from tokensafe.format_parsers.ansi import strip_ansi
37
+
38
+ MAX_BATCH_QUERIES = 20
39
+ MAX_OUTPUT_CHARS = 8000
40
+ DEFAULT_QUERY_RESULTS = 25
41
+
42
+
43
+ def _env_float(name: str, default: float) -> float:
44
+ try:
45
+ value = float(os.environ.get(name, "") or default)
46
+ except ValueError:
47
+ return default
48
+ return value if value > 0 else default
49
+
50
+
51
+ # Wall-clock budget for one whole batch. It sits below the MCP transport's 8 s
52
+ # timeout so the workers return partial results themselves instead of being
53
+ # abandoned (and left running) by the transport's watchdog thread.
54
+ BATCH_DEADLINE_SECONDS = _env_float("TOKENSAFE_BATCH_SEARCH_BUDGET", 6.0)
55
+ # Extra time the batch waits for workers that already passed the deadline to
56
+ # notice it and hand back what they found.
57
+ _DEADLINE_GRACE_SECONDS = 1.0
58
+ # Pure-Python fallback caps (ripgrep has its own native limits).
59
+ FALLBACK_MAX_FILE_BYTES = 1024 * 1024
60
+ FALLBACK_MAX_TOTAL_BYTES = 32 * 1024 * 1024
61
+ FALLBACK_MAX_FILES = 5000
62
+ _BINARY_PROBE_BYTES = 8192
63
+
64
+
65
+ class SearchBudget:
66
+ """Shared wall-clock deadline that every search worker checks cooperatively.
67
+
68
+ Python threads cannot be killed, so a timeout only helps when the workers
69
+ themselves stop: they poll `expired()` between files (and between lines of
70
+ a long file) and return what they have so far.
71
+ """
72
+
73
+ def __init__(self, seconds: float):
74
+ self.deadline = time.monotonic() + max(0.0, float(seconds))
75
+ self._cancelled = threading.Event()
76
+
77
+ def cancel(self) -> None:
78
+ self._cancelled.set()
79
+
80
+ def expired(self) -> bool:
81
+ if self._cancelled.is_set():
82
+ return True
83
+ if time.monotonic() >= self.deadline:
84
+ self._cancelled.set()
85
+ return True
86
+ return False
87
+
88
+ def remaining(self) -> float:
89
+ if self._cancelled.is_set():
90
+ return 0.0
91
+ return max(0.0, self.deadline - time.monotonic())
92
+
93
+ ALLOWED_GIT_COMMANDS = {
94
+ "status", "diff", "log", "show", "branch", "rev-parse",
95
+ "ls-files", "blame", "shortlog", "describe", "tag"
96
+ }
97
+
98
+ HARDENED_GIT_BASE_ARGS = [
99
+ "--no-optional-locks",
100
+ "-c", "core.fsmonitor=false",
101
+ "-c", "core.quotePath=false",
102
+ "-c", "diff.external=",
103
+ "-c", "gpg.program=false",
104
+ "--no-pager",
105
+ ]
106
+
107
+ # Subcommands that support --no-textconv (a per-command option, not a global one)
108
+ _TEXTCONV_SUBCOMMANDS = frozenset({"diff", "log", "show", "blame"})
109
+
110
+
111
+ # Real git long options that happen to be prefixes of a blocked one. git's
112
+ # parse-options takes an exact match over an abbreviation, so these stay legal.
113
+ _EXACT_SAFE_GIT_LONG_OPTIONS = frozenset({"--text"})
114
+
115
+
116
+ def _abbreviates_blocked_git_option(tok: str, blocked: Tuple[str, ...]) -> bool:
117
+ """True when `tok` is an abbreviation git would expand to a blocked long option.
118
+
119
+ git accepts any unambiguous prefix of a long option, so `--cont /etc/hosts`
120
+ means `--contents /etc/hosts` and the exact-match block list missed it.
121
+ """
122
+ if not tok.startswith("--") or len(tok) <= 2:
123
+ return False
124
+ name = tok.split("=", 1)[0].lower()
125
+ if name in _EXACT_SAFE_GIT_LONG_OPTIONS:
126
+ return False
127
+ return any(p.startswith("--") and p != name and p.startswith(name) for p in blocked)
128
+
129
+
130
+ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
131
+ """Checks if git command is strictly read-only and returns tokens."""
132
+ tokens = [t for t in re.split(r"\s+", args_str.strip()) if t]
133
+ if not tokens:
134
+ return False, "Empty git command.", []
135
+ subcmd = tokens[0].lower()
136
+ if subcmd.startswith("git"):
137
+ tokens = tokens[1:]
138
+ if not tokens:
139
+ return False, "Empty git command.", []
140
+ subcmd = tokens[0].lower()
141
+
142
+ if subcmd not in ALLOWED_GIT_COMMANDS:
143
+ return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
144
+
145
+ # Block destructive, config-overriding, escaping, or helper-executing options.
146
+ # --no-index/--contents/--pathspec-from-file read arbitrary files outside the
147
+ # workspace root the MCP handler confines sub-queries to; --textconv runs
148
+ # repo-configured helpers, so it is blocked and --no-textconv is forced below.
149
+ _BLOCKED_GIT_PREFIXES = (
150
+ "-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output",
151
+ "--ext-diff", "--exec", "--no-index", "--contents", "--pathspec-from-file",
152
+ "--textconv",
153
+ )
154
+ _READ_ONLY_BRANCH_TAG_FLAGS = {
155
+ "-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
156
+ "--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
157
+ "--sort", "--format", "--points-at", "--color", "--no-color", "--abbrev",
158
+ }
159
+ for idx, tok in enumerate(tokens[1:], start=1):
160
+ low_tok = tok.lower()
161
+ if tok in ("--delete", "-d", "-D", "-m", "-M", "--hard", "--reset", "--force", "-f", "--interactive", "-i"):
162
+ return False, f"Destructive flag '{tok}' is disallowed in batch_search.", []
163
+ if any(tok == p or tok.startswith(p + "=") for p in _BLOCKED_GIT_PREFIXES):
164
+ return False, f"Git flag '{tok}' is disallowed in batch_search.", []
165
+ if _abbreviates_blocked_git_option(tok, _BLOCKED_GIT_PREFIXES):
166
+ return False, f"Git flag '{tok}' abbreviates a disallowed option in batch_search.", []
167
+ if subcmd in ("branch", "tag") and not tok.startswith("-"):
168
+ prev = tokens[idx - 1]
169
+ if prev not in ("--contains", "--no-contains", "--merged", "--no-merged", "--sort", "--format", "--points-at", "-l", "--list"):
170
+ return False, f"Positional argument '{tok}' with git {subcmd} is disallowed (read-only flags only).", []
171
+ elif subcmd in ("branch", "tag") and tok.startswith("-") and tok.split("=", 1)[0] not in _READ_ONLY_BRANCH_TAG_FLAGS:
172
+ return False, f"Flag '{tok}' with git {subcmd} is not in read-only list.", []
173
+
174
+ return True, "", tokens
175
+
176
+
177
+ def _run_git_query(
178
+ pattern: str,
179
+ cwd: str,
180
+ timeout_sec: float = 5,
181
+ max_results: int = 50,
182
+ budget: Optional[SearchBudget] = None,
183
+ ) -> Dict[str, Any]:
184
+ """Runs a read-only git query."""
185
+ is_safe, err_msg, tokens = _is_git_command_safe(pattern)
186
+ if not is_safe:
187
+ return {"error": err_msg, "matches": [], "count": 0}
188
+ if budget is not None:
189
+ if budget.expired():
190
+ return {"error": "batch search deadline reached before this git query ran",
191
+ "matches": [], "count": 0, "partial": True, "stopped_reason": "time_budget"}
192
+ timeout_sec = max(0.5, min(float(timeout_sec), budget.remaining()))
193
+
194
+ git_bin = shutil.which("git")
195
+ if not git_bin:
196
+ return {"error": "git executable not found in PATH", "matches": [], "count": 0}
197
+
198
+ # --no-textconv is a per-subcommand option (diff/log/show/blame), so it must
199
+ # follow the subcommand, not sit in the global option block.
200
+ if tokens and tokens[0].lower() in _TEXTCONV_SUBCOMMANDS:
201
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, tokens[0], "--no-textconv", *tokens[1:]]
202
+ else:
203
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
204
+
205
+ env = os.environ.copy()
206
+ env["GIT_TERMINAL_PROMPT"] = "0"
207
+ env["GIT_PAGER"] = "cat"
208
+ # Never let git consume the MCP server's own stdin (rev-parse --parseopt blocks on it).
209
+ stdin_devnull = subprocess.DEVNULL
210
+
211
+ try:
212
+ proc = subprocess.run(
213
+ cmd,
214
+ cwd=cwd,
215
+ stdin=stdin_devnull,
216
+ stdout=subprocess.PIPE,
217
+ stderr=subprocess.PIPE,
218
+ text=True,
219
+ timeout=timeout_sec,
220
+ env=env
221
+ )
222
+ if proc.returncode != 0:
223
+ err = proc.stderr.strip() or f"git exited with code {proc.returncode}"
224
+ return {"error": err, "matches": [], "count": 0}
225
+
226
+ raw_out = strip_ansi(proc.stdout or "").strip()
227
+ lines = [l for l in raw_out.splitlines() if l.strip()]
228
+ limited = lines[:max_results]
229
+ return {
230
+ "matches": limited,
231
+ # count is the true number of matching lines; matches may be truncated.
232
+ "count": len(lines),
233
+ "truncated": len(lines) > len(limited),
234
+ "raw": "\n".join(limited),
235
+ }
236
+ except subprocess.TimeoutExpired:
237
+ return {"error": f"git query timed out after {timeout_sec:.1f}s", "matches": [], "count": 0}
238
+ except Exception as e:
239
+ return {"error": f"git execution error: {e}", "matches": [], "count": 0}
240
+
241
+
242
+ def _rg_json_text(field: Any) -> Optional[str]:
243
+ """Decodes a ripgrep JSON `{"text": ...}` / `{"bytes": base64}` value."""
244
+ if not isinstance(field, dict):
245
+ return None
246
+ if isinstance(field.get("text"), str):
247
+ return field["text"]
248
+ raw = field.get("bytes")
249
+ if isinstance(raw, str):
250
+ try:
251
+ return base64.b64decode(raw).decode("utf-8", errors="replace")
252
+ except Exception:
253
+ return None
254
+ return None
255
+
256
+
257
+ def _parse_rg_json(
258
+ stdout: Any,
259
+ cwd: str,
260
+ scope: str = "all",
261
+ max_results: int = 25,
262
+ ) -> List[Dict[str, Any]]:
263
+ """Parses `rg --json` output into match dicts.
264
+
265
+ The JSON stream carries the path, the line number and the line text as
266
+ separate fields, so a colon in the matched text (`10:30:45`) or in the path
267
+ (`C:\\repo`, `a:b.txt`) can no longer shift the path/line/text split the
268
+ way the old `^(.*):(\\d+):(.*)$` text parse did. A truncated stream (rg was
269
+ killed at the deadline) simply ends: its incomplete last line is skipped.
270
+ """
271
+ if isinstance(stdout, bytes):
272
+ stdout = stdout.decode("utf-8", errors="replace")
273
+ scope_all = str(scope or "all").lower() in ("", "all")
274
+ matches: List[Dict[str, Any]] = []
275
+ for raw_line in (stdout or "").splitlines():
276
+ if len(matches) >= max_results:
277
+ break
278
+ raw_line = raw_line.strip()
279
+ if not raw_line:
280
+ continue
281
+ try:
282
+ event = json.loads(raw_line)
283
+ except ValueError:
284
+ continue
285
+ if not isinstance(event, dict) or event.get("type") != "match":
286
+ continue
287
+ data = event.get("data") or {}
288
+ raw_file = _rg_json_text(data.get("path"))
289
+ if not raw_file:
290
+ continue
291
+ try:
292
+ l_num = int(data.get("line_number") or 0)
293
+ except (TypeError, ValueError):
294
+ l_num = 0
295
+ text = _rg_json_text(data.get("lines")) or ""
296
+ abs_file = raw_file if os.path.isabs(raw_file) else os.path.join(cwd, raw_file)
297
+ f_path = os.path.relpath(abs_file, cwd)
298
+ # ripgrep has no notion of TokenSafe scopes: apply the same matcher
299
+ # the Python fallback uses so results do not change with rg presence.
300
+ if not scope_all:
301
+ try:
302
+ if not ScopedSearch.is_match_file(f_path, f_path, str(scope).lower()):
303
+ continue
304
+ except Exception:
305
+ pass
306
+ matches.append({"file": f_path, "line": l_num, "content": text.strip()[:180]})
307
+ return matches
308
+
309
+
310
+ def _run_rg_query(
311
+ pattern: str,
312
+ cwd: str,
313
+ path_filter: Optional[str] = None,
314
+ is_regex: bool = False,
315
+ case_sensitive: bool = False,
316
+ file_type: Optional[str] = None,
317
+ glob_filter: Optional[str] = None,
318
+ max_results: int = 25,
319
+ scope: str = "all",
320
+ budget: Optional[SearchBudget] = None,
321
+ stats: Optional[Dict[str, Any]] = None,
322
+ ) -> Optional[List[Dict[str, Any]]]:
323
+ """Attempts fast search via ripgrep if available.
324
+
325
+ Returns None when ripgrep is missing or failed, so the caller falls back to
326
+ the pure-Python search. A ripgrep run cut by the deadline returns the
327
+ matches it streamed before it was killed and reports `time_budget` in
328
+ `stats` instead of restarting the whole search in Python.
329
+ """
330
+ rg_bin = shutil.which("rg")
331
+ if not rg_bin:
332
+ return None
333
+
334
+ stats = stats if stats is not None else {}
335
+ timeout = 5.0
336
+ if budget is not None:
337
+ if budget.expired():
338
+ stats["stopped_reason"] = "time_budget"
339
+ return []
340
+ timeout = max(0.1, min(timeout, budget.remaining()))
341
+
342
+ # --json reports every path even for a single-file target and keeps the
343
+ # path, line number and text in separate fields (see _parse_rg_json).
344
+ cmd = [rg_bin, "--json", "--color=never", "--max-count", str(max_results)]
345
+ if not is_regex:
346
+ cmd.append("--fixed-strings")
347
+ if not case_sensitive:
348
+ cmd.append("--ignore-case")
349
+ else:
350
+ cmd.append("--case-sensitive")
351
+
352
+ if file_type:
353
+ cmd.extend(["--type", file_type])
354
+ if glob_filter:
355
+ cmd.extend(["--glob", glob_filter])
356
+
357
+ # Ignore default heavy folders
358
+ for d in ("node_modules", ".git", "dist", "build", ".venv", "__pycache__"):
359
+ cmd.extend(["--glob", f"!{d}/**"])
360
+
361
+ target_path = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
362
+ cmd.extend(["--", pattern, target_path])
363
+
364
+ try:
365
+ proc = subprocess.run(
366
+ cmd,
367
+ cwd=cwd,
368
+ stdin=subprocess.DEVNULL,
369
+ stdout=subprocess.PIPE,
370
+ stderr=subprocess.PIPE,
371
+ text=True,
372
+ timeout=timeout,
373
+ )
374
+ except subprocess.TimeoutExpired as exc:
375
+ stats["stopped_reason"] = "time_budget"
376
+ return _parse_rg_json(exc.stdout or exc.output or "", cwd, scope, max_results)
377
+ except Exception:
378
+ return None
379
+
380
+ try:
381
+ err_text = (proc.stderr or "").strip()
382
+ # rg exits 1 for "no matches" (not an error) and 2 for real failures.
383
+ if proc.returncode not in (0, 1) and err_text:
384
+ raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
385
+ matches = _parse_rg_json(proc.stdout, cwd, scope, max_results)
386
+ if len(matches) >= max_results:
387
+ stats["stopped_reason"] = "max_results"
388
+ return matches
389
+ except Exception:
390
+ return None
391
+
392
+
393
+ def _rg_submatch_texts(data: Dict[str, Any]) -> List[str]:
394
+ out: List[str] = []
395
+ for sub in data.get("submatches") or []:
396
+ if isinstance(sub, dict):
397
+ text = _rg_json_text(sub.get("match"))
398
+ if text:
399
+ out.append(text)
400
+ return out
401
+
402
+
403
+ def _run_rg_text_group(
404
+ patterns: List[str],
405
+ cwd: str,
406
+ path_filter: Optional[str] = None,
407
+ case_sensitive: bool = False,
408
+ file_type: Optional[str] = None,
409
+ glob_filter: Optional[str] = None,
410
+ max_results: Optional[List[int]] = None,
411
+ scope: str = "all",
412
+ budget: Optional[SearchBudget] = None,
413
+ ) -> Optional[List[Tuple[List[Dict[str, Any]], Dict[str, Any]]]]:
414
+ """Runs several literal-text queries that share every option in ONE rg pass.
415
+
416
+ A batch of 20 text queries used to start 20 rg processes, each walking the
417
+ same tree. Here rg gets every pattern (`-e`) and streams JSON matches;
418
+ each matching line is attributed to every query whose literal occurs in it
419
+ (case-folded like `--ignore-case`, or exactly), and rg is stopped as soon
420
+ as every query has its `max_results`. There is no `--max-count`: one
421
+ shared per-file cap would let a frequent pattern starve the others.
422
+
423
+ Returns one (matches, stats) pair per pattern, or None when rg is missing
424
+ or failed (callers then run each query on its own).
425
+ """
426
+ rg_bin = shutil.which("rg")
427
+ if not rg_bin or not patterns:
428
+ return None
429
+ caps = list(max_results or [DEFAULT_QUERY_RESULTS] * len(patterns))
430
+ results: List[List[Dict[str, Any]]] = [[] for _ in patterns]
431
+ stats: List[Dict[str, Any]] = [{} for _ in patterns]
432
+
433
+ timeout = 5.0
434
+ if budget is not None:
435
+ if budget.expired():
436
+ return [([], {"stopped_reason": "time_budget"}) for _ in patterns]
437
+ timeout = max(0.1, min(timeout, budget.remaining()))
438
+
439
+ cmd = [rg_bin, "--json", "--color=never", "--fixed-strings"]
440
+ cmd.append("--case-sensitive" if case_sensitive else "--ignore-case")
441
+ if file_type:
442
+ cmd.extend(["--type", file_type])
443
+ if glob_filter:
444
+ cmd.extend(["--glob", glob_filter])
445
+ for d in ("node_modules", ".git", "dist", "build", ".venv", "__pycache__"):
446
+ cmd.extend(["--glob", f"!{d}/**"])
447
+ for pat in patterns:
448
+ cmd.extend(["-e", pat])
449
+ target_path = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
450
+ cmd.extend(["--", target_path])
451
+
452
+ needles = patterns if case_sensitive else [p.lower() for p in patterns]
453
+ scope_all = str(scope or "all").lower() in ("", "all")
454
+ killed = {"deadline": False, "done": False}
455
+
456
+ import tempfile
457
+ try:
458
+ err_file = tempfile.TemporaryFile()
459
+ proc = subprocess.Popen(
460
+ cmd, cwd=cwd, stdin=subprocess.DEVNULL,
461
+ stdout=subprocess.PIPE, stderr=err_file,
462
+ )
463
+ except Exception:
464
+ return None
465
+
466
+ def _on_deadline() -> None:
467
+ killed["deadline"] = True
468
+ try:
469
+ proc.kill()
470
+ except Exception:
471
+ pass
472
+
473
+ timer = threading.Timer(timeout, _on_deadline)
474
+ timer.daemon = True
475
+ timer.start()
476
+ try:
477
+ assert proc.stdout is not None
478
+ for raw in proc.stdout:
479
+ if all(len(r) >= c for r, c in zip(results, caps)):
480
+ killed["done"] = True
481
+ break
482
+ try:
483
+ event = json.loads(raw)
484
+ except ValueError:
485
+ continue
486
+ if not isinstance(event, dict) or event.get("type") != "match":
487
+ continue
488
+ data = event.get("data") or {}
489
+ raw_file = _rg_json_text(data.get("path"))
490
+ if not raw_file:
491
+ continue
492
+ try:
493
+ l_num = int(data.get("line_number") or 0)
494
+ except (TypeError, ValueError):
495
+ l_num = 0
496
+ text = _rg_json_text(data.get("lines")) or ""
497
+ abs_file = raw_file if os.path.isabs(raw_file) else os.path.join(cwd, raw_file)
498
+ f_path = os.path.relpath(abs_file, cwd)
499
+ if not scope_all:
500
+ try:
501
+ if not ScopedSearch.is_match_file(f_path, f_path, str(scope).lower()):
502
+ continue
503
+ except Exception:
504
+ pass
505
+ hay = text if case_sensitive else text.lower()
506
+ subs = _rg_submatch_texts(data)
507
+ if not case_sensitive:
508
+ subs = [x.lower() for x in subs]
509
+ entry = {"file": f_path, "line": l_num, "content": text.strip()[:180]}
510
+ for i, needle in enumerate(needles):
511
+ if len(results[i]) >= caps[i]:
512
+ continue
513
+ if needle in hay or needle in subs:
514
+ results[i].append(dict(entry))
515
+ except Exception:
516
+ try:
517
+ proc.kill()
518
+ except Exception:
519
+ pass
520
+ timer.cancel()
521
+ try:
522
+ err_file.close()
523
+ except Exception:
524
+ pass
525
+ return None
526
+ finally:
527
+ if killed["done"]:
528
+ try:
529
+ proc.kill()
530
+ except Exception:
531
+ pass
532
+ timer.cancel()
533
+ try:
534
+ proc.wait(timeout=1.0)
535
+ except Exception:
536
+ pass
537
+ try:
538
+ proc.stdout.close() # type: ignore[union-attr]
539
+ except Exception:
540
+ pass
541
+
542
+ err_text = ""
543
+ try:
544
+ if not killed["deadline"] and not killed["done"]:
545
+ err_file.seek(0)
546
+ err_text = err_file.read().decode("utf-8", errors="replace").strip()
547
+ except Exception:
548
+ err_text = ""
549
+ finally:
550
+ try:
551
+ err_file.close()
552
+ except Exception:
553
+ pass
554
+ if err_text and proc.returncode not in (0, 1):
555
+ return None
556
+
557
+ for i, cap in enumerate(caps):
558
+ if len(results[i]) >= cap:
559
+ stats[i]["stopped_reason"] = "max_results"
560
+ elif killed["deadline"]:
561
+ stats[i]["stopped_reason"] = "time_budget"
562
+ return list(zip(results, stats))
563
+
564
+
565
+ def _rg_group_key(query_dict: Any, cwd: str) -> Optional[Tuple[Any, ...]]:
566
+ """Grouping key for queries one rg pass can answer, or None.
567
+
568
+ Only literal `text` queries qualify (a match's attribution to a regex
569
+ would need Rust-regex semantics in Python); they must share path, case,
570
+ file type, glob and scope, and have a pattern rg accepts as one line.
571
+ """
572
+ if not isinstance(query_dict, dict):
573
+ return None
574
+ q_type = str(query_dict.get("type") or "text").lower().strip()
575
+ if q_type != "text":
576
+ return None
577
+ pattern = str(query_dict.get("pattern") or query_dict.get("query") or "").strip()
578
+ if not pattern or "\n" in pattern or "\r" in pattern:
579
+ return None
580
+ path_filter = query_dict.get("path")
581
+ if path_filter and not os.path.exists(os.path.normpath(os.path.join(cwd, str(path_filter)))):
582
+ return None
583
+ try:
584
+ int(query_dict.get("max_results") or DEFAULT_QUERY_RESULTS)
585
+ except (TypeError, ValueError):
586
+ return None
587
+ return (
588
+ str(path_filter or ""),
589
+ bool(query_dict.get("case_sensitive")),
590
+ str(query_dict.get("file_type") or ""),
591
+ str(query_dict.get("glob") or ""),
592
+ str(query_dict.get("scope") or "all").lower(),
593
+ )
594
+
595
+
596
+ def _iter_search_files(
597
+ search_root: str,
598
+ cwd: str,
599
+ budget: Optional[SearchBudget] = None,
600
+ ) -> Iterator[Tuple[str, str]]:
601
+ """Yields (full_path, rel_path) for an explicit file target or a directory tree.
602
+
603
+ Stops early once `budget` expires; callers check `budget.expired()` to tell
604
+ a finished walk from a cut one.
605
+ """
606
+ if os.path.isfile(search_root):
607
+ yield search_root, os.path.relpath(search_root, cwd)
608
+ return
609
+ for root, dirs, files in os.walk(search_root):
610
+ if budget is not None and budget.expired():
611
+ return
612
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
613
+ for f in files:
614
+ if budget is not None and budget.expired():
615
+ return
616
+ full_path = os.path.join(root, f)
617
+ yield full_path, os.path.relpath(full_path, cwd)
618
+
619
+
620
+ def _read_regular_file(full_path: str, limit: int) -> Optional[Tuple[bytes, bool]]:
621
+ """Reads at most `limit` bytes of a regular file; None for anything else.
622
+
623
+ FIFOs, sockets and devices are rejected by `stat` before any `open`: opening
624
+ a FIFO for reading blocks until a writer appears, and a device such as
625
+ /dev/zero never ends. The descriptor is opened non-blocking and re-checked
626
+ with `fstat`, so a path swapped for a FIFO after the `stat` still cannot hang.
627
+ Returns (data, cut) where `cut` says the file was longer than `limit`.
628
+ """
629
+ try:
630
+ if not stat.S_ISREG(os.stat(full_path).st_mode):
631
+ return None
632
+ except OSError:
633
+ return None
634
+ flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
635
+ try:
636
+ fd = os.open(full_path, flags)
637
+ except OSError:
638
+ return None
639
+ try:
640
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
641
+ return None
642
+ chunks: List[bytes] = []
643
+ remaining = limit + 1
644
+ while remaining > 0:
645
+ chunk = os.read(fd, min(65536, remaining))
646
+ if not chunk:
647
+ break
648
+ chunks.append(chunk)
649
+ remaining -= len(chunk)
650
+ except OSError:
651
+ return None
652
+ finally:
653
+ os.close(fd)
654
+ data = b"".join(chunks)
655
+ if len(data) > limit:
656
+ return data[:limit], True
657
+ return data, False
658
+
659
+
660
+ # Approximation of ripgrep's --type map for the pure-Python fallback, so the
661
+ # file_type filter is not silently ignored when rg is unavailable.
662
+ FILE_TYPE_EXTENSIONS = {
663
+ "typescript": {".ts", ".tsx", ".mts", ".cts"},
664
+ "ts": {".ts", ".tsx", ".mts", ".cts"},
665
+ "javascript": {".js", ".jsx", ".mjs", ".cjs"},
666
+ "js": {".js", ".jsx", ".mjs", ".cjs"},
667
+ "python": {".py", ".pyi"},
668
+ "py": {".py", ".pyi"},
669
+ "rust": {".rs"},
670
+ "go": {".go"},
671
+ "java": {".java"},
672
+ "ruby": {".rb"},
673
+ "php": {".php"},
674
+ "c": {".c", ".h"},
675
+ "cpp": {".cpp", ".cc", ".cxx", ".hpp", ".hh"},
676
+ "csharp": {".cs"},
677
+ "markdown": {".md", ".markdown"},
678
+ "md": {".md", ".markdown"},
679
+ "json": {".json"},
680
+ "yaml": {".yaml", ".yml"},
681
+ "toml": {".toml"},
682
+ "html": {".html", ".htm"},
683
+ "css": {".css", ".scss", ".sass", ".less"},
684
+ "sql": {".sql"},
685
+ "shell": {".sh", ".bash", ".zsh"},
686
+ "swift": {".swift"},
687
+ "kotlin": {".kt", ".kts"},
688
+ }
689
+
690
+
691
+ def _run_python_text_search(
692
+ pattern: str,
693
+ cwd: str,
694
+ path_filter: Optional[str] = None,
695
+ is_regex: bool = False,
696
+ case_sensitive: bool = False,
697
+ scope: str = "all",
698
+ glob_filter: Optional[str] = None,
699
+ file_type: Optional[str] = None,
700
+ max_results: int = 25,
701
+ budget: Optional[SearchBudget] = None,
702
+ stats: Optional[Dict[str, Any]] = None,
703
+ max_file_bytes: int = FALLBACK_MAX_FILE_BYTES,
704
+ max_total_bytes: int = FALLBACK_MAX_TOTAL_BYTES,
705
+ max_files: int = FALLBACK_MAX_FILES,
706
+ ) -> List[Dict[str, Any]]:
707
+ """Pure Python search fallback. Raises ValueError for an unusable regex or file_type.
708
+
709
+ Bounded like ripgrep would be: only regular files are read (never FIFOs,
710
+ sockets or devices), each file is read up to `max_file_bytes`, the walk
711
+ stops after `max_files` files or `max_total_bytes`, and the shared `budget`
712
+ deadline is checked between files and every few thousand lines. `stats`,
713
+ when given, receives scanned_files, bytes_scanned, files_cut (files longer
714
+ than the per-file cap) and stopped_reason (complete, max_results,
715
+ time_budget, file_budget or byte_budget).
716
+ """
717
+ stats = stats if stats is not None else {}
718
+ stats.update({"scanned_files": 0, "bytes_scanned": 0, "files_cut": 0, "stopped_reason": "complete"})
719
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
720
+ if not os.path.exists(search_root):
721
+ return []
722
+
723
+ type_exts = None
724
+ if file_type:
725
+ type_exts = FILE_TYPE_EXTENSIONS.get(str(file_type).lower().lstrip("."))
726
+ if type_exts is None:
727
+ raise ValueError(
728
+ f"unsupported file_type '{file_type}' (known: {', '.join(sorted(FILE_TYPE_EXTENSIONS))})"
729
+ )
730
+
731
+ regex = None
732
+ if is_regex:
733
+ flags = 0 if case_sensitive else re.IGNORECASE
734
+ try:
735
+ regex = re.compile(pattern, flags)
736
+ except re.error as e:
737
+ # Never degrade to a literal search: that silently returns bogus hits.
738
+ raise ValueError(f"invalid regular expression: {e}")
739
+
740
+ matches: List[Dict[str, Any]] = []
741
+ target_lower = pattern if case_sensitive else pattern.lower()
742
+ explicit_file = os.path.isfile(search_root)
743
+ scope_all = str(scope or "all").lower() in ("", "all")
744
+
745
+ for full_path, rel_p in _iter_search_files(search_root, cwd, budget):
746
+ # An explicitly named file is searched as-is: extension, scope, and glob
747
+ # filters only make sense when walking a directory tree.
748
+ if not explicit_file:
749
+ ext = os.path.splitext(full_path)[1].lower()
750
+ if ext in IGNORED_EXTENSIONS:
751
+ continue
752
+ # One matcher for every scope ("code", "config", extensions, globs):
753
+ # reusing ScopedSearch keeps the fallback identical to the rg path.
754
+ if not scope_all:
755
+ try:
756
+ if not ScopedSearch.is_match_file(full_path, rel_p, str(scope).lower()):
757
+ continue
758
+ except Exception:
759
+ if scope == "code" and ext not in CODE_EXTENSIONS:
760
+ continue
761
+ if type_exts is not None and ext not in type_exts:
762
+ continue
763
+ if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
764
+ continue
765
+
766
+ if stats["scanned_files"] >= max_files:
767
+ stats["stopped_reason"] = "file_budget"
768
+ break
769
+ if stats["bytes_scanned"] >= max_total_bytes:
770
+ stats["stopped_reason"] = "byte_budget"
771
+ break
772
+
773
+ read = _read_regular_file(full_path, min(max_file_bytes, max_total_bytes - stats["bytes_scanned"]))
774
+ if read is None:
775
+ continue
776
+ data, cut = read
777
+ stats["scanned_files"] += 1
778
+ stats["bytes_scanned"] += len(data)
779
+ if cut:
780
+ stats["files_cut"] += 1
781
+ # Skip binary files when walking a tree, as ripgrep does.
782
+ if not explicit_file and b"\x00" in data[:_BINARY_PROBE_BYTES]:
783
+ continue
784
+
785
+ text = data.decode("utf-8", errors="replace")
786
+ # Split on "\n" only, so line numbers agree with ripgrep's.
787
+ lines = text.split("\n")
788
+ if lines and lines[-1] == "":
789
+ lines.pop()
790
+ for line_idx, line in enumerate(lines):
791
+ if line_idx and line_idx % 2048 == 0 and budget is not None and budget.expired():
792
+ stats["stopped_reason"] = "time_budget"
793
+ return matches
794
+ if regex:
795
+ hit = bool(regex.search(line))
796
+ elif case_sensitive:
797
+ hit = pattern in line
798
+ else:
799
+ hit = target_lower in line.lower()
800
+
801
+ if hit:
802
+ matches.append({
803
+ "file": rel_p,
804
+ "line": line_idx + 1,
805
+ "content": line.strip()[:180]
806
+ })
807
+ if len(matches) >= max_results:
808
+ stats["stopped_reason"] = "max_results"
809
+ return matches
810
+
811
+ if stats["stopped_reason"] == "complete" and budget is not None and budget.expired():
812
+ stats["stopped_reason"] = "time_budget"
813
+ return matches
814
+
815
+
816
+ def _run_glob_search(
817
+ pattern: str,
818
+ cwd: str,
819
+ path_filter: Optional[str] = None,
820
+ max_results: int = 50,
821
+ budget: Optional[SearchBudget] = None,
822
+ ) -> Tuple[List[str], int, Optional[int]]:
823
+ """Finds matching files by a brace-aware glob.
824
+
825
+ Returns (hits, scanned, total); the walk completes unless the batch deadline
826
+ cuts it, in which case total is None so the caller reports partial coverage.
827
+ """
828
+ patterns = compile_patterns(pattern)
829
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
830
+ if not os.path.exists(search_root):
831
+ raise FileNotFoundError(search_root)
832
+
833
+ if os.path.isfile(search_root):
834
+ rel_p = os.path.relpath(search_root, cwd).replace("\\", "/")
835
+ return ([rel_p] if matches_any(patterns, rel_p) else []), 1, 1
836
+
837
+ results: List[str] = []
838
+ scanned = 0
839
+ for full_path, rel_p in _iter_search_files(search_root, cwd, budget):
840
+ scanned += 1
841
+ rel_p = rel_p.replace("\\", "/")
842
+ if matches_any(patterns, rel_p, os.path.basename(full_path)):
843
+ if len(results) < max_results:
844
+ results.append(rel_p)
845
+ if budget is not None and budget.expired():
846
+ return results, scanned, None
847
+ return results, scanned, scanned
848
+
849
+
850
+ def _run_fuzzy_search(
851
+ pattern: str,
852
+ cwd: str,
853
+ path_filter: Optional[str] = None,
854
+ max_results: int = 30,
855
+ budget: Optional[SearchBudget] = None,
856
+ ) -> List[str]:
857
+ """Case-insensitive fuzzy match across relative file paths."""
858
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
859
+ if not os.path.exists(search_root):
860
+ return []
861
+
862
+ pat_lower = pattern.lower().replace(" ", "")
863
+ results = []
864
+ for _, rel_p in _iter_search_files(search_root, cwd, budget):
865
+ name_lower = rel_p.lower()
866
+ # Subsequence match
867
+ it = iter(name_lower)
868
+ if all(ch in it for ch in pat_lower):
869
+ results.append(rel_p)
870
+ if len(results) >= max_results:
871
+ return results
872
+ return results
873
+
874
+
875
+ def _execute_single_query(
876
+ query_dict: Dict[str, Any],
877
+ cwd: str,
878
+ budget: Optional[SearchBudget] = None,
879
+ rg_result: Optional[Tuple[List[Dict[str, Any]], Dict[str, Any]]] = None,
880
+ ) -> Dict[str, Any]:
881
+ """Executes a single search query dict.
882
+
883
+ `budget` is the batch's shared deadline; without one a private budget of
884
+ BATCH_DEADLINE_SECONDS applies, so a direct call is bounded too.
885
+ """
886
+ if budget is None:
887
+ budget = SearchBudget(BATCH_DEADLINE_SECONDS)
888
+ pattern = str(query_dict.get("pattern") or query_dict.get("query") or "").strip()
889
+ q_type = str(query_dict.get("type") or "text").lower().strip()
890
+ path_filter = query_dict.get("path")
891
+ max_res = int(query_dict.get("max_results") or DEFAULT_QUERY_RESULTS)
892
+ case_sensitive = bool(query_dict.get("case_sensitive"))
893
+ output_mode = str(query_dict.get("output_mode") or "content").lower()
894
+ file_type = query_dict.get("file_type")
895
+ glob_filter = query_dict.get("glob")
896
+ scope = str(query_dict.get("scope") or "all").lower()
897
+
898
+ if not pattern and q_type != "git":
899
+ return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
900
+
901
+ # A path that does not exist must be an explicit error: an empty result list
902
+ # is indistinguishable from a genuine zero-hit search.
903
+ if path_filter:
904
+ search_root = os.path.normpath(os.path.join(cwd, str(path_filter)))
905
+ if not os.path.exists(search_root):
906
+ return {
907
+ "type": q_type,
908
+ "pattern": pattern,
909
+ "error": f"path does not exist: {path_filter}",
910
+ "matches": [],
911
+ "count": 0,
912
+ }
913
+
914
+ if q_type == "git":
915
+ git_cwd = os.path.normpath(os.path.join(cwd, str(path_filter))) if path_filter else cwd
916
+ res = _run_git_query(pattern, git_cwd, max_results=max_res, budget=budget)
917
+ return {"type": "git", "pattern": pattern, **res}
918
+
919
+ if q_type == "glob":
920
+ try:
921
+ matched_paths, scanned, total = _run_glob_search(
922
+ pattern, cwd, path_filter=path_filter, max_results=max_res, budget=budget
923
+ )
924
+ except GlobPatternError as e:
925
+ return {
926
+ "type": "glob", "pattern": pattern,
927
+ "error": f"invalid glob pattern: {e}",
928
+ "matches": [], "count": 0,
929
+ "scanned_files": 0, "total_files": None, "partial": False,
930
+ }
931
+ partial = total is None
932
+ base = {
933
+ "type": "glob", "pattern": pattern,
934
+ "scanned_files": scanned, "total_files": total,
935
+ "partial": partial, "truncated": len(matched_paths) >= max_res,
936
+ }
937
+ if partial:
938
+ base["stopped_reason"] = "time_budget"
939
+ if not matched_paths:
940
+ base["note"] = "glob matched no files (braces are expanded; ** is accepted)"
941
+ if output_mode == "count":
942
+ return {**base, "count": len(matched_paths)}
943
+ return {**base, "matches": matched_paths, "count": len(matched_paths)}
944
+
945
+ if q_type == "fuzzy":
946
+ matched_paths = _run_fuzzy_search(
947
+ pattern, cwd, path_filter=path_filter, max_results=max_res, budget=budget
948
+ )
949
+ fuzzy_extra: Dict[str, Any] = {}
950
+ if len(matched_paths) < max_res and budget.expired():
951
+ fuzzy_extra = {"partial": True, "stopped_reason": "time_budget"}
952
+ if output_mode == "count":
953
+ return {"type": "fuzzy", "pattern": pattern, "count": len(matched_paths), **fuzzy_extra}
954
+ return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths,
955
+ "count": len(matched_paths), **fuzzy_extra}
956
+
957
+ is_regex = (q_type == "regex")
958
+ stats: Dict[str, Any] = {}
959
+ if rg_result is not None:
960
+ # Answered by a shared rg pass over the batch (_run_rg_text_group).
961
+ rg_matches, stats = rg_result[0], dict(rg_result[1])
962
+ else:
963
+ # Try ripgrep first
964
+ rg_matches = _run_rg_query(
965
+ pattern=pattern,
966
+ cwd=cwd,
967
+ path_filter=path_filter,
968
+ is_regex=is_regex,
969
+ case_sensitive=case_sensitive,
970
+ file_type=file_type,
971
+ glob_filter=glob_filter,
972
+ max_results=max_res,
973
+ scope=scope,
974
+ budget=budget,
975
+ stats=stats,
976
+ )
977
+
978
+ try:
979
+ if rg_matches is not None:
980
+ matches = rg_matches
981
+ source = "ripgrep"
982
+ else:
983
+ stats = {}
984
+ matches = _run_python_text_search(
985
+ pattern=pattern,
986
+ cwd=cwd,
987
+ path_filter=path_filter,
988
+ is_regex=is_regex,
989
+ case_sensitive=case_sensitive,
990
+ scope=scope,
991
+ glob_filter=glob_filter,
992
+ file_type=file_type,
993
+ max_results=max_res,
994
+ budget=budget,
995
+ stats=stats,
996
+ )
997
+ source = "python"
998
+ except ValueError as e:
999
+ return {"type": q_type, "pattern": pattern, "error": str(e), "matches": [], "count": 0}
1000
+
1001
+ # Caps are reported the way glob reports them: `truncated` for the result
1002
+ # cap, `partial` (+ stopped_reason) when a budget cut the search short.
1003
+ stopped_reason = str(stats.get("stopped_reason") or "complete")
1004
+ meta: Dict[str, Any] = {
1005
+ "source": source,
1006
+ "truncated": len(matches) >= max_res,
1007
+ "partial": stopped_reason in ("time_budget", "file_budget", "byte_budget"),
1008
+ }
1009
+ if stopped_reason != "complete":
1010
+ meta["stopped_reason"] = stopped_reason
1011
+ if source == "python":
1012
+ meta["scanned_files"] = stats.get("scanned_files", 0)
1013
+ if stats.get("files_cut"):
1014
+ meta["files_cut"] = stats["files_cut"]
1015
+
1016
+ if output_mode == "files_with_matches":
1017
+ unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
1018
+ return {"type": q_type, "pattern": pattern, "matches": unique_files, "count": len(unique_files), **meta}
1019
+ elif output_mode == "count":
1020
+ return {"type": q_type, "pattern": pattern, "count": len(matches), **meta}
1021
+
1022
+ return {"type": q_type, "pattern": pattern, "matches": matches, "count": len(matches), **meta}
1023
+
1024
+
1025
+ _STOP_LABELS = {
1026
+ "time_budget": "deadline reached",
1027
+ "file_budget": f"file cap ({FALLBACK_MAX_FILES} files) reached",
1028
+ "byte_budget": f"byte cap ({FALLBACK_MAX_TOTAL_BYTES // (1024 * 1024)} MiB) reached",
1029
+ }
1030
+
1031
+
1032
+ def _coverage_note(res: Dict[str, Any]) -> Optional[str]:
1033
+ """One compact line saying why a query's results may be incomplete."""
1034
+ if not res.get("partial"):
1035
+ return None
1036
+ reason = _STOP_LABELS.get(str(res.get("stopped_reason") or ""), "search stopped early")
1037
+ scanned = res.get("scanned_files")
1038
+ scanned_txt = f" after {scanned} files" if isinstance(scanned, int) else ""
1039
+ return f"_partial: {reason}{scanned_txt}; narrow `path` for a complete search._"
1040
+
1041
+
1042
+ def execute_batch_search(
1043
+ queries: List[Dict[str, Any]],
1044
+ cwd: Optional[str] = None,
1045
+ deadline_s: Optional[float] = None,
1046
+ ) -> Dict[str, Any]:
1047
+ """
1048
+ Executes up to 20 mixed search queries concurrently and returns a consolidated report.
1049
+
1050
+ Every worker shares one wall-clock deadline (`deadline_s`, default
1051
+ BATCH_DEADLINE_SECONDS) and checks it cooperatively, so the batch returns
1052
+ partial results instead of outliving the caller's own timeout.
1053
+ """
1054
+ if not isinstance(queries, list) or not queries:
1055
+ return {
1056
+ "success": False,
1057
+ "error": "Queries must be a non-empty array of query specifications.",
1058
+ "results": [],
1059
+ "summary_md": "Error: queries array is empty."
1060
+ }
1061
+
1062
+ if len(queries) > MAX_BATCH_QUERIES:
1063
+ return {
1064
+ "success": False,
1065
+ "error": f"Batch search exceeds maximum of {MAX_BATCH_QUERIES} queries (got {len(queries)}).",
1066
+ "results": [],
1067
+ "summary_md": "Error: query count exceeds maximum."
1068
+ }
1069
+
1070
+ base_dir = os.path.abspath(cwd or os.getcwd())
1071
+ results: List[Dict[str, Any]] = [{} for _ in queries]
1072
+ budget = SearchBudget(BATCH_DEADLINE_SECONDS if deadline_s is None else deadline_s)
1073
+
1074
+ # Concurrent execution across queries. The executor is not used as a
1075
+ # context manager: its __exit__ joins every worker, which would block past
1076
+ # the deadline on a worker stuck in one slow system call.
1077
+ # Literal text queries that share every option run as one rg pass.
1078
+ groups: Dict[Tuple[Any, ...], List[int]] = {}
1079
+ for i, q in enumerate(queries):
1080
+ key = _rg_group_key(q, base_dir)
1081
+ if key is not None:
1082
+ groups.setdefault(key, []).append(i)
1083
+ jobs: List[List[int]] = []
1084
+ grouped = set()
1085
+ if shutil.which("rg"):
1086
+ for members in groups.values():
1087
+ if len(members) > 1:
1088
+ jobs.append(members)
1089
+ grouped.update(members)
1090
+ jobs.extend([i] for i in range(len(queries)) if i not in grouped)
1091
+
1092
+ def _run_job(members: List[int]) -> List[Tuple[int, Dict[str, Any]]]:
1093
+ if len(members) == 1:
1094
+ i = members[0]
1095
+ return [(i, _execute_single_query(queries[i], base_dir, budget))]
1096
+ qs = [queries[i] for i in members]
1097
+ path_filter = qs[0].get("path")
1098
+ group = _run_rg_text_group(
1099
+ [str(q.get("pattern") or q.get("query") or "").strip() for q in qs],
1100
+ base_dir,
1101
+ path_filter=path_filter,
1102
+ case_sensitive=bool(qs[0].get("case_sensitive")),
1103
+ file_type=qs[0].get("file_type"),
1104
+ glob_filter=qs[0].get("glob"),
1105
+ max_results=[int(q.get("max_results") or DEFAULT_QUERY_RESULTS) for q in qs],
1106
+ scope=str(qs[0].get("scope") or "all").lower(),
1107
+ budget=budget,
1108
+ )
1109
+ out = []
1110
+ for pos, i in enumerate(members):
1111
+ pre = group[pos] if group is not None else None
1112
+ out.append((i, _execute_single_query(queries[i], base_dir, budget, rg_result=pre)))
1113
+ return out
1114
+
1115
+ executor = ThreadPoolExecutor(max_workers=min(len(jobs), 8))
1116
+ try:
1117
+ future_to_members = {
1118
+ executor.submit(_run_job, members): members for members in jobs
1119
+ }
1120
+ done, not_done = wait(
1121
+ list(future_to_members), timeout=budget.remaining() + _DEADLINE_GRACE_SECONDS
1122
+ )
1123
+ for future in done:
1124
+ members = future_to_members[future]
1125
+ try:
1126
+ for idx, res in future.result():
1127
+ results[idx] = res
1128
+ except Exception as e:
1129
+ for idx in members:
1130
+ results[idx] = {"error": str(e), "matches": [], "count": 0}
1131
+ for future in not_done:
1132
+ future.cancel()
1133
+ for idx in future_to_members[future]:
1134
+ q = queries[idx] if isinstance(queries[idx], dict) else {}
1135
+ results[idx] = {
1136
+ "type": str(q.get("type") or "text").lower(),
1137
+ "pattern": str(q.get("pattern") or q.get("query") or ""),
1138
+ "error": "batch search deadline reached before this query finished",
1139
+ "matches": [], "count": 0,
1140
+ "partial": True, "stopped_reason": "time_budget",
1141
+ }
1142
+ finally:
1143
+ # Tell any straggler to stop at its next checkpoint, then return
1144
+ # without waiting for it.
1145
+ budget.cancel()
1146
+ executor.shutdown(wait=False, cancel_futures=True)
1147
+
1148
+ # Format into markdown summary
1149
+ md_lines: List[str] = [f"## TokenSafe Batch Search Report ({len(queries)} queries)"]
1150
+ for i, res in enumerate(results):
1151
+ q_type = res.get("type", "search")
1152
+ pattern = res.get("pattern", "")
1153
+ count = res.get("count", 0)
1154
+ err = res.get("error")
1155
+
1156
+ if err:
1157
+ md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — Error: {err}")
1158
+ continue
1159
+
1160
+ md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — {count} match(es)")
1161
+ matches = res.get("matches") or []
1162
+
1163
+ if q_type == "git":
1164
+ raw_git = res.get("raw")
1165
+ if raw_git:
1166
+ md_lines.append("```text\n" + raw_git + "\n```")
1167
+ elif not matches:
1168
+ md_lines.append("*(clean / no output)*")
1169
+ elif isinstance(matches, list):
1170
+ # Honor the caller's max_results instead of a fixed 15-item cap;
1171
+ # the Zero-Spill Guard folds oversized payloads at the MCP boundary.
1172
+ for m in matches:
1173
+ if isinstance(m, dict):
1174
+ f_name = m.get("file", "")
1175
+ l_num = m.get("line", "")
1176
+ content = m.get("content", "")
1177
+ md_lines.append(f"- `{f_name}:{l_num}`: {content}")
1178
+ elif isinstance(m, str):
1179
+ md_lines.append(f"- `{m}`")
1180
+ note = _coverage_note(res)
1181
+ if note:
1182
+ md_lines.append(note)
1183
+
1184
+ summary_md = "\n".join(md_lines)
1185
+ errored = [r for r in results if isinstance(r, dict) and r.get("error")]
1186
+ return {
1187
+ "success": not (errored and len(errored) == len(results)),
1188
+ "query_count": len(queries),
1189
+ "results": results,
1190
+ "summary_md": summary_md
1191
+ }