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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -3
- package/bin/agy-tokens +1 -1
- package/bin/tokensafe +1 -1
- package/bin/tokensafe-acp.js +1 -1
- package/bin/tokensafe-mcp +1 -1
- package/bin/tokensafe.js +1 -1
- package/hooks/claude_code_hook.py +49 -45
- package/hooks/cursor_hook.py +8 -8
- package/hooks/kimi_hook.py +23 -23
- package/hooks/post_tool_use.py +6 -6
- package/hooks/pre_invocation.py +21 -17
- package/hooks/pre_tool_use.py +27 -27
- package/hooks/session_start.py +17 -17
- package/hooks/stop_hook.py +3 -3
- package/hooks/zcode_hook.py +2 -2
- package/kimi.plugin.json +2 -2
- package/mcp_config.json +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/__init__.py +9 -5
- package/src/cli.py +11 -2429
- package/src/mcp_server.py +11 -5024
- package/src/proxy.py +11 -1803
- package/tokensafe/__init__.py +6 -0
- package/{src → tokensafe}/acp/__init__.py +2 -2
- package/{src → tokensafe}/acp/server.py +5 -5
- package/{src → tokensafe}/adapter_core.py +42 -17
- package/{src → tokensafe}/agent/__init__.py +1 -1
- package/{src → tokensafe}/agent/context.py +4 -4
- package/{src → tokensafe}/agent/loop.py +4 -4
- package/{src → tokensafe}/agent/providers.py +2 -2
- package/{src → tokensafe}/agent/tools.py +2 -2
- package/{src → tokensafe}/agent_firewall.py +68 -9
- package/{src → tokensafe}/angular_cli.py +4 -4
- package/{src → tokensafe}/auto_inject.py +37 -5
- package/{src → tokensafe}/batch_editor.py +185 -28
- package/tokensafe/batch_search.py +1191 -0
- package/{src → tokensafe}/bench/go_target.py +1 -1
- package/{src → tokensafe}/bench/mechanics.py +1 -1
- package/{src → tokensafe}/bench/react_target.py +1 -1
- package/{src → tokensafe}/bench/runner.py +4 -4
- package/{src → tokensafe}/benchmark.py +12 -12
- package/{src → tokensafe}/benchmark_real.py +18 -18
- package/{src → tokensafe}/build_parsers.py +3 -3
- package/{src → tokensafe}/bundle_probe.py +1 -1
- package/{src → tokensafe}/burn_monitor.py +3 -3
- package/{src → tokensafe}/cache_normalizer.py +1 -1
- package/tokensafe/cli.py +2490 -0
- package/{src → tokensafe}/command_sanitizer.py +94 -26
- package/{src → tokensafe}/compaction_recovery.py +5 -5
- package/{src → tokensafe}/compactor.py +148 -95
- package/{src → tokensafe}/context_index.py +194 -28
- package/{src → tokensafe}/cross_stack.py +2 -2
- package/{src → tokensafe}/dashboard.py +3 -3
- package/{src → tokensafe}/delegation.py +4 -4
- package/{src → tokensafe}/dependency_prefetcher.py +1 -1
- package/{src → tokensafe}/diff_slicer.py +2 -2
- package/{src → tokensafe}/distiller.py +7 -7
- package/{src → tokensafe}/distiller_cache.py +3 -3
- package/{src → tokensafe}/egress_counter.py +1 -1
- package/{src → tokensafe}/environment_auditor.py +7 -7
- package/{src → tokensafe}/file_state.py +2 -2
- package/{src → tokensafe}/format_invariants.py +1 -1
- package/tokensafe/format_parsers/__init__.py +20 -0
- package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
- package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
- package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
- package/{src → tokensafe}/format_parsers/json_log.py +1 -1
- package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
- package/{src → tokensafe}/format_parsers/tabular.py +1 -1
- package/{src → tokensafe}/fts_index.py +20 -11
- package/{src → tokensafe}/governor.py +143 -31
- package/{src → tokensafe}/graph_engine.py +769 -126
- package/{src → tokensafe}/guard.py +80 -25
- package/{src → tokensafe}/history_compactor.py +407 -133
- package/{src → tokensafe}/i18n_catalog.py +39 -14
- package/{src → tokensafe}/image_downscale.py +1 -1
- package/tokensafe/ingress_staging.py +384 -0
- package/{src → tokensafe}/installer.py +118 -61
- package/{src → tokensafe}/license_manager.py +9 -67
- package/{src → tokensafe}/live_relay.py +2 -2
- package/{src → tokensafe}/loop_detector.py +2 -2
- package/{src → tokensafe}/mcp_config_manager.py +2 -2
- package/{src → tokensafe}/mcp_proxy.py +4 -4
- package/tokensafe/mcp_server.py +5664 -0
- package/{src → tokensafe}/metrics.py +56 -21
- package/{src → tokensafe}/mistakes.py +4 -4
- package/{src → tokensafe}/oumv_brief.py +21 -3
- package/{src → tokensafe}/oumv_gateway.py +146 -49
- package/{src → tokensafe}/oumv_policy.py +1 -1
- package/{src → tokensafe}/paths.py +1 -1
- package/{src → tokensafe}/project_memory.py +4 -4
- package/tokensafe/proxy.py +2075 -0
- package/{src → tokensafe}/quality_score.py +4 -4
- package/tokensafe/read_baseline.py +192 -0
- package/tokensafe/repo_compute.py +332 -0
- package/{src → tokensafe}/result_ledger.py +19 -19
- package/{src → tokensafe}/retrofit.py +6 -6
- package/{src → tokensafe}/savings.py +3 -3
- package/tokensafe/schema_slicer.py +1087 -0
- package/{src → tokensafe}/scoped_search.py +144 -6
- package/{src → tokensafe}/secret_redactor.py +22 -0
- package/{src → tokensafe}/session_brief.py +8 -8
- package/{src → tokensafe}/skeletonizer.py +89 -26
- package/{src → tokensafe}/slicer.py +3 -2
- package/{src → tokensafe}/snapshot.py +1 -1
- package/{src → tokensafe}/stash.py +1 -1
- package/{src → tokensafe}/statusline.py +1 -1
- package/{src → tokensafe}/superseded.py +22 -4
- package/{src → tokensafe}/team_cache.py +3 -3
- package/{src → tokensafe}/telemetry_sync.py +63 -11
- package/{src → tokensafe}/test_parsers.py +3 -3
- package/{src → tokensafe}/thinking_fold.py +3 -3
- package/{src → tokensafe}/tokenizer.py +37 -1
- package/{src → tokensafe}/tool_pruner.py +3 -3
- package/{src → tokensafe}/transcript_analyzer.py +1 -1
- package/{src → tokensafe}/transcript_recall.py +8 -8
- package/{src → tokensafe}/type_slicer.py +3 -3
- package/{src → tokensafe}/usage_ledger.py +4 -4
- package/{src → tokensafe}/version_checker.py +6 -6
- package/{src → tokensafe}/web_reader.py +86 -8
- package/{src → tokensafe}/workspace_roots.py +2 -2
- package/src/batch_search.py +0 -589
- package/src/format_parsers/__init__.py +0 -20
- package/src/schema_slicer.py +0 -578
- /package/{src → tokensafe}/agent/pricing.py +0 -0
- /package/{src → tokensafe}/atomic_io.py +0 -0
- /package/{src → tokensafe}/backend_release.py +0 -0
- /package/{src → tokensafe}/bench/__init__.py +0 -0
- /package/{src → tokensafe}/bench/driver.py +0 -0
- /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
- /package/{src → tokensafe}/bench_scenarios.json +0 -0
- /package/{src → tokensafe}/competitors.py +0 -0
- /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
- /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
- /package/{src → tokensafe}/globmatch.py +0 -0
- /package/{src → tokensafe}/host_capabilities.py +0 -0
- /package/{src → tokensafe}/json_repair.py +0 -0
- /package/{src → tokensafe}/route_index.py +0 -0
- /package/{src → tokensafe}/scaffold.py +0 -0
- /package/{src → tokensafe}/session_context.py +0 -0
- /package/{src → tokensafe}/ssl_context.py +0 -0
- /package/{src → tokensafe}/stdio_io.py +0 -0
- /package/{src → tokensafe}/syntax_guard.py +0 -0
- /package/{src → tokensafe}/toml_mcp_config.py +0 -0
- /package/{src → tokensafe}/treesitter_backend.py +0 -0
- /package/{src → tokensafe}/win_paths.py +0 -0
package/src/batch_search.py
DELETED
|
@@ -1,589 +0,0 @@
|
|
|
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 os
|
|
22
|
-
import re
|
|
23
|
-
import fnmatch
|
|
24
|
-
import shutil
|
|
25
|
-
import subprocess
|
|
26
|
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
27
|
-
from typing import Dict, Any, List, Optional, Tuple
|
|
28
|
-
|
|
29
|
-
from src.scoped_search import ScopedSearch, IGNORED_DIRS, IGNORED_EXTENSIONS, CODE_EXTENSIONS
|
|
30
|
-
from src.globmatch import GlobPatternError, compile_patterns, matches_any
|
|
31
|
-
from src.format_parsers.ansi import strip_ansi
|
|
32
|
-
|
|
33
|
-
MAX_BATCH_QUERIES = 20
|
|
34
|
-
MAX_OUTPUT_CHARS = 8000
|
|
35
|
-
DEFAULT_QUERY_RESULTS = 25
|
|
36
|
-
|
|
37
|
-
ALLOWED_GIT_COMMANDS = {
|
|
38
|
-
"status", "diff", "log", "show", "branch", "rev-parse",
|
|
39
|
-
"ls-files", "blame", "shortlog", "describe", "tag"
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
HARDENED_GIT_BASE_ARGS = [
|
|
43
|
-
"--no-optional-locks",
|
|
44
|
-
"-c", "core.fsmonitor=false",
|
|
45
|
-
"-c", "core.quotePath=false",
|
|
46
|
-
"-c", "diff.external=",
|
|
47
|
-
"-c", "gpg.program=false",
|
|
48
|
-
"--no-pager",
|
|
49
|
-
]
|
|
50
|
-
|
|
51
|
-
# Subcommands that support --no-textconv (a per-command option, not a global one)
|
|
52
|
-
_TEXTCONV_SUBCOMMANDS = frozenset({"diff", "log", "show", "blame"})
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
|
|
56
|
-
"""Checks if git command is strictly read-only and returns tokens."""
|
|
57
|
-
tokens = [t for t in re.split(r"\s+", args_str.strip()) if t]
|
|
58
|
-
if not tokens:
|
|
59
|
-
return False, "Empty git command.", []
|
|
60
|
-
subcmd = tokens[0].lower()
|
|
61
|
-
if subcmd.startswith("git"):
|
|
62
|
-
tokens = tokens[1:]
|
|
63
|
-
if not tokens:
|
|
64
|
-
return False, "Empty git command.", []
|
|
65
|
-
subcmd = tokens[0].lower()
|
|
66
|
-
|
|
67
|
-
if subcmd not in ALLOWED_GIT_COMMANDS:
|
|
68
|
-
return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
|
|
69
|
-
|
|
70
|
-
# Block destructive, config-overriding, escaping, or helper-executing options.
|
|
71
|
-
# --no-index/--contents/--pathspec-from-file read arbitrary files outside the
|
|
72
|
-
# workspace root the MCP handler confines sub-queries to; --textconv runs
|
|
73
|
-
# repo-configured helpers, so it is blocked and --no-textconv is forced below.
|
|
74
|
-
_BLOCKED_GIT_PREFIXES = (
|
|
75
|
-
"-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output",
|
|
76
|
-
"--ext-diff", "--exec", "--no-index", "--contents", "--pathspec-from-file",
|
|
77
|
-
"--textconv",
|
|
78
|
-
)
|
|
79
|
-
_READ_ONLY_BRANCH_TAG_FLAGS = {
|
|
80
|
-
"-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
|
|
81
|
-
"--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
|
|
82
|
-
"--sort", "--format", "--points-at", "--color", "--no-color", "--abbrev",
|
|
83
|
-
}
|
|
84
|
-
for idx, tok in enumerate(tokens[1:], start=1):
|
|
85
|
-
low_tok = tok.lower()
|
|
86
|
-
if tok in ("--delete", "-d", "-D", "-m", "-M", "--hard", "--reset", "--force", "-f", "--interactive", "-i"):
|
|
87
|
-
return False, f"Destructive flag '{tok}' is disallowed in batch_search.", []
|
|
88
|
-
if any(tok == p or tok.startswith(p + "=") for p in _BLOCKED_GIT_PREFIXES):
|
|
89
|
-
return False, f"Git flag '{tok}' is disallowed in batch_search.", []
|
|
90
|
-
if subcmd in ("branch", "tag") and not tok.startswith("-"):
|
|
91
|
-
prev = tokens[idx - 1]
|
|
92
|
-
if prev not in ("--contains", "--no-contains", "--merged", "--no-merged", "--sort", "--format", "--points-at", "-l", "--list"):
|
|
93
|
-
return False, f"Positional argument '{tok}' with git {subcmd} is disallowed (read-only flags only).", []
|
|
94
|
-
elif subcmd in ("branch", "tag") and tok.startswith("-") and tok.split("=", 1)[0] not in _READ_ONLY_BRANCH_TAG_FLAGS:
|
|
95
|
-
return False, f"Flag '{tok}' with git {subcmd} is not in read-only list.", []
|
|
96
|
-
|
|
97
|
-
return True, "", tokens
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: int = 50) -> Dict[str, Any]:
|
|
101
|
-
"""Runs a read-only git query."""
|
|
102
|
-
is_safe, err_msg, tokens = _is_git_command_safe(pattern)
|
|
103
|
-
if not is_safe:
|
|
104
|
-
return {"error": err_msg, "matches": [], "count": 0}
|
|
105
|
-
|
|
106
|
-
git_bin = shutil.which("git")
|
|
107
|
-
if not git_bin:
|
|
108
|
-
return {"error": "git executable not found in PATH", "matches": [], "count": 0}
|
|
109
|
-
|
|
110
|
-
# --no-textconv is a per-subcommand option (diff/log/show/blame), so it must
|
|
111
|
-
# follow the subcommand, not sit in the global option block.
|
|
112
|
-
if tokens and tokens[0].lower() in _TEXTCONV_SUBCOMMANDS:
|
|
113
|
-
cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, tokens[0], "--no-textconv", *tokens[1:]]
|
|
114
|
-
else:
|
|
115
|
-
cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
|
|
116
|
-
|
|
117
|
-
env = os.environ.copy()
|
|
118
|
-
env["GIT_TERMINAL_PROMPT"] = "0"
|
|
119
|
-
env["GIT_PAGER"] = "cat"
|
|
120
|
-
# Never let git consume the MCP server's own stdin (rev-parse --parseopt blocks on it).
|
|
121
|
-
stdin_devnull = subprocess.DEVNULL
|
|
122
|
-
|
|
123
|
-
try:
|
|
124
|
-
proc = subprocess.run(
|
|
125
|
-
cmd,
|
|
126
|
-
cwd=cwd,
|
|
127
|
-
stdin=stdin_devnull,
|
|
128
|
-
stdout=subprocess.PIPE,
|
|
129
|
-
stderr=subprocess.PIPE,
|
|
130
|
-
text=True,
|
|
131
|
-
timeout=timeout_sec,
|
|
132
|
-
env=env
|
|
133
|
-
)
|
|
134
|
-
if proc.returncode != 0:
|
|
135
|
-
err = proc.stderr.strip() or f"git exited with code {proc.returncode}"
|
|
136
|
-
return {"error": err, "matches": [], "count": 0}
|
|
137
|
-
|
|
138
|
-
raw_out = strip_ansi(proc.stdout or "").strip()
|
|
139
|
-
lines = [l for l in raw_out.splitlines() if l.strip()]
|
|
140
|
-
limited = lines[:max_results]
|
|
141
|
-
return {
|
|
142
|
-
"matches": limited,
|
|
143
|
-
# count is the true number of matching lines; matches may be truncated.
|
|
144
|
-
"count": len(lines),
|
|
145
|
-
"truncated": len(lines) > len(limited),
|
|
146
|
-
"raw": "\n".join(limited),
|
|
147
|
-
}
|
|
148
|
-
except subprocess.TimeoutExpired:
|
|
149
|
-
return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
|
|
150
|
-
except Exception as e:
|
|
151
|
-
return {"error": f"git execution error: {e}", "matches": [], "count": 0}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
def _run_rg_query(
|
|
155
|
-
pattern: str,
|
|
156
|
-
cwd: str,
|
|
157
|
-
path_filter: Optional[str] = None,
|
|
158
|
-
is_regex: bool = False,
|
|
159
|
-
case_sensitive: bool = False,
|
|
160
|
-
file_type: Optional[str] = None,
|
|
161
|
-
glob_filter: Optional[str] = None,
|
|
162
|
-
max_results: int = 25,
|
|
163
|
-
scope: str = "all"
|
|
164
|
-
) -> Optional[List[Dict[str, Any]]]:
|
|
165
|
-
"""Attempts fast search via ripgrep if available."""
|
|
166
|
-
rg_bin = shutil.which("rg")
|
|
167
|
-
if not rg_bin:
|
|
168
|
-
return None
|
|
169
|
-
|
|
170
|
-
# --with-filename is mandatory: for a single-file target ripgrep omits the
|
|
171
|
-
# path prefix, so every output line would be unparseable below (silent 0 hits).
|
|
172
|
-
cmd = [rg_bin, "--no-heading", "--with-filename", "--line-number", "--color=never", "--max-count", str(max_results)]
|
|
173
|
-
if not is_regex:
|
|
174
|
-
cmd.append("--fixed-strings")
|
|
175
|
-
if not case_sensitive:
|
|
176
|
-
cmd.append("--ignore-case")
|
|
177
|
-
else:
|
|
178
|
-
cmd.append("--case-sensitive")
|
|
179
|
-
|
|
180
|
-
if file_type:
|
|
181
|
-
cmd.extend(["--type", file_type])
|
|
182
|
-
if glob_filter:
|
|
183
|
-
cmd.extend(["--glob", glob_filter])
|
|
184
|
-
|
|
185
|
-
# Ignore default heavy folders
|
|
186
|
-
for d in ("node_modules", ".git", "dist", "build", ".venv", "__pycache__"):
|
|
187
|
-
cmd.extend(["--glob", f"!{d}/**"])
|
|
188
|
-
|
|
189
|
-
target_path = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
|
|
190
|
-
cmd.extend(["--", pattern, target_path])
|
|
191
|
-
|
|
192
|
-
try:
|
|
193
|
-
proc = subprocess.run(
|
|
194
|
-
cmd,
|
|
195
|
-
cwd=cwd,
|
|
196
|
-
stdin=subprocess.DEVNULL,
|
|
197
|
-
stdout=subprocess.PIPE,
|
|
198
|
-
stderr=subprocess.PIPE,
|
|
199
|
-
text=True,
|
|
200
|
-
timeout=5
|
|
201
|
-
)
|
|
202
|
-
err_text = (proc.stderr or "").strip()
|
|
203
|
-
# rg exits 1 for "no matches" (not an error) and 2 for real failures.
|
|
204
|
-
if proc.returncode not in (0, 1) and err_text:
|
|
205
|
-
raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
|
|
206
|
-
scope_all = str(scope or "all").lower() in ("", "all")
|
|
207
|
-
matches = []
|
|
208
|
-
_rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
|
|
209
|
-
for line in proc.stdout.splitlines():
|
|
210
|
-
if not line.strip():
|
|
211
|
-
continue
|
|
212
|
-
m_line = _rg_line_re.match(line)
|
|
213
|
-
if m_line:
|
|
214
|
-
raw_file, raw_lnum, raw_txt = m_line.groups()
|
|
215
|
-
f_path = os.path.relpath(raw_file, cwd)
|
|
216
|
-
# ripgrep has no notion of TokenSafe scopes: apply the same matcher
|
|
217
|
-
# the Python fallback uses so results do not change with rg presence.
|
|
218
|
-
if not scope_all:
|
|
219
|
-
try:
|
|
220
|
-
from src.scoped_search import ScopedSearch
|
|
221
|
-
if not ScopedSearch.is_match_file(f_path, f_path, str(scope).lower()):
|
|
222
|
-
continue
|
|
223
|
-
except Exception:
|
|
224
|
-
pass
|
|
225
|
-
try:
|
|
226
|
-
l_num = int(raw_lnum)
|
|
227
|
-
except ValueError:
|
|
228
|
-
l_num = 0
|
|
229
|
-
snippet = raw_txt.strip()[:180]
|
|
230
|
-
matches.append({"file": f_path, "line": l_num, "content": snippet})
|
|
231
|
-
if len(matches) >= max_results:
|
|
232
|
-
break
|
|
233
|
-
return matches
|
|
234
|
-
except Exception:
|
|
235
|
-
return None
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
def _iter_search_files(search_root: str, cwd: str):
|
|
239
|
-
"""Yields (full_path, rel_path) for an explicit file target or a directory tree."""
|
|
240
|
-
if os.path.isfile(search_root):
|
|
241
|
-
yield search_root, os.path.relpath(search_root, cwd)
|
|
242
|
-
return
|
|
243
|
-
for root, dirs, files in os.walk(search_root):
|
|
244
|
-
dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
|
|
245
|
-
for f in files:
|
|
246
|
-
full_path = os.path.join(root, f)
|
|
247
|
-
yield full_path, os.path.relpath(full_path, cwd)
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
# Approximation of ripgrep's --type map for the pure-Python fallback, so the
|
|
251
|
-
# file_type filter is not silently ignored when rg is unavailable.
|
|
252
|
-
FILE_TYPE_EXTENSIONS = {
|
|
253
|
-
"typescript": {".ts", ".tsx", ".mts", ".cts"},
|
|
254
|
-
"ts": {".ts", ".tsx", ".mts", ".cts"},
|
|
255
|
-
"javascript": {".js", ".jsx", ".mjs", ".cjs"},
|
|
256
|
-
"js": {".js", ".jsx", ".mjs", ".cjs"},
|
|
257
|
-
"python": {".py", ".pyi"},
|
|
258
|
-
"py": {".py", ".pyi"},
|
|
259
|
-
"rust": {".rs"},
|
|
260
|
-
"go": {".go"},
|
|
261
|
-
"java": {".java"},
|
|
262
|
-
"ruby": {".rb"},
|
|
263
|
-
"php": {".php"},
|
|
264
|
-
"c": {".c", ".h"},
|
|
265
|
-
"cpp": {".cpp", ".cc", ".cxx", ".hpp", ".hh"},
|
|
266
|
-
"csharp": {".cs"},
|
|
267
|
-
"markdown": {".md", ".markdown"},
|
|
268
|
-
"md": {".md", ".markdown"},
|
|
269
|
-
"json": {".json"},
|
|
270
|
-
"yaml": {".yaml", ".yml"},
|
|
271
|
-
"toml": {".toml"},
|
|
272
|
-
"html": {".html", ".htm"},
|
|
273
|
-
"css": {".css", ".scss", ".sass", ".less"},
|
|
274
|
-
"sql": {".sql"},
|
|
275
|
-
"shell": {".sh", ".bash", ".zsh"},
|
|
276
|
-
"swift": {".swift"},
|
|
277
|
-
"kotlin": {".kt", ".kts"},
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
def _run_python_text_search(
|
|
282
|
-
pattern: str,
|
|
283
|
-
cwd: str,
|
|
284
|
-
path_filter: Optional[str] = None,
|
|
285
|
-
is_regex: bool = False,
|
|
286
|
-
case_sensitive: bool = False,
|
|
287
|
-
scope: str = "all",
|
|
288
|
-
glob_filter: Optional[str] = None,
|
|
289
|
-
file_type: Optional[str] = None,
|
|
290
|
-
max_results: int = 25
|
|
291
|
-
) -> List[Dict[str, Any]]:
|
|
292
|
-
"""Pure Python search fallback. Raises ValueError for an unusable regex or file_type."""
|
|
293
|
-
search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
|
|
294
|
-
if not os.path.exists(search_root):
|
|
295
|
-
return []
|
|
296
|
-
|
|
297
|
-
type_exts = None
|
|
298
|
-
if file_type:
|
|
299
|
-
type_exts = FILE_TYPE_EXTENSIONS.get(str(file_type).lower().lstrip("."))
|
|
300
|
-
if type_exts is None:
|
|
301
|
-
raise ValueError(
|
|
302
|
-
f"unsupported file_type '{file_type}' (known: {', '.join(sorted(FILE_TYPE_EXTENSIONS))})"
|
|
303
|
-
)
|
|
304
|
-
|
|
305
|
-
regex = None
|
|
306
|
-
if is_regex:
|
|
307
|
-
flags = 0 if case_sensitive else re.IGNORECASE
|
|
308
|
-
try:
|
|
309
|
-
regex = re.compile(pattern, flags)
|
|
310
|
-
except re.error as e:
|
|
311
|
-
# Never degrade to a literal search: that silently returns bogus hits.
|
|
312
|
-
raise ValueError(f"invalid regular expression: {e}")
|
|
313
|
-
|
|
314
|
-
matches = []
|
|
315
|
-
target_lower = pattern if case_sensitive else pattern.lower()
|
|
316
|
-
explicit_file = os.path.isfile(search_root)
|
|
317
|
-
|
|
318
|
-
for full_path, rel_p in _iter_search_files(search_root, cwd):
|
|
319
|
-
# An explicitly named file is searched as-is: extension, scope, and glob
|
|
320
|
-
# filters only make sense when walking a directory tree.
|
|
321
|
-
if not explicit_file:
|
|
322
|
-
ext = os.path.splitext(full_path)[1].lower()
|
|
323
|
-
if ext in IGNORED_EXTENSIONS:
|
|
324
|
-
continue
|
|
325
|
-
# One matcher for every scope ("code", "config", extensions, globs):
|
|
326
|
-
# reusing ScopedSearch keeps the fallback identical to the rg path.
|
|
327
|
-
if str(scope or "all").lower() not in ("", "all"):
|
|
328
|
-
try:
|
|
329
|
-
from src.scoped_search import ScopedSearch
|
|
330
|
-
if not ScopedSearch.is_match_file(full_path, rel_p, str(scope).lower()):
|
|
331
|
-
continue
|
|
332
|
-
except Exception:
|
|
333
|
-
if scope == "code" and ext not in CODE_EXTENSIONS:
|
|
334
|
-
continue
|
|
335
|
-
if type_exts is not None and ext not in type_exts:
|
|
336
|
-
continue
|
|
337
|
-
if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
|
|
338
|
-
continue
|
|
339
|
-
|
|
340
|
-
try:
|
|
341
|
-
with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
|
|
342
|
-
for line_idx, line in enumerate(fp):
|
|
343
|
-
hit = False
|
|
344
|
-
if regex:
|
|
345
|
-
hit = bool(regex.search(line))
|
|
346
|
-
elif case_sensitive:
|
|
347
|
-
hit = pattern in line
|
|
348
|
-
else:
|
|
349
|
-
hit = target_lower in line.lower()
|
|
350
|
-
|
|
351
|
-
if hit:
|
|
352
|
-
matches.append({
|
|
353
|
-
"file": rel_p,
|
|
354
|
-
"line": line_idx + 1,
|
|
355
|
-
"content": line.strip()[:180]
|
|
356
|
-
})
|
|
357
|
-
if len(matches) >= max_results:
|
|
358
|
-
return matches
|
|
359
|
-
except Exception:
|
|
360
|
-
continue
|
|
361
|
-
|
|
362
|
-
return matches
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
def _run_glob_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 50) -> Tuple[List[str], int, int]:
|
|
366
|
-
"""Finds matching files by a brace-aware glob.
|
|
367
|
-
|
|
368
|
-
Returns (hits, scanned, total); the walk always completes so the caller can
|
|
369
|
-
report honest coverage even when the result list is capped.
|
|
370
|
-
"""
|
|
371
|
-
patterns = compile_patterns(pattern)
|
|
372
|
-
search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
|
|
373
|
-
if not os.path.exists(search_root):
|
|
374
|
-
raise FileNotFoundError(search_root)
|
|
375
|
-
|
|
376
|
-
if os.path.isfile(search_root):
|
|
377
|
-
rel_p = os.path.relpath(search_root, cwd).replace("\\", "/")
|
|
378
|
-
return ([rel_p] if matches_any(patterns, rel_p) else []), 1, 1
|
|
379
|
-
|
|
380
|
-
results: List[str] = []
|
|
381
|
-
scanned = 0
|
|
382
|
-
for full_path, rel_p in _iter_search_files(search_root, cwd):
|
|
383
|
-
scanned += 1
|
|
384
|
-
rel_p = rel_p.replace("\\", "/")
|
|
385
|
-
if matches_any(patterns, rel_p, os.path.basename(full_path)):
|
|
386
|
-
if len(results) < max_results:
|
|
387
|
-
results.append(rel_p)
|
|
388
|
-
return results, scanned, scanned
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
def _run_fuzzy_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 30) -> List[str]:
|
|
392
|
-
"""Case-insensitive fuzzy match across relative file paths."""
|
|
393
|
-
search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
|
|
394
|
-
if not os.path.exists(search_root):
|
|
395
|
-
return []
|
|
396
|
-
|
|
397
|
-
pat_lower = pattern.lower().replace(" ", "")
|
|
398
|
-
results = []
|
|
399
|
-
for _, rel_p in _iter_search_files(search_root, cwd):
|
|
400
|
-
name_lower = rel_p.lower()
|
|
401
|
-
# Subsequence match
|
|
402
|
-
it = iter(name_lower)
|
|
403
|
-
if all(ch in it for ch in pat_lower):
|
|
404
|
-
results.append(rel_p)
|
|
405
|
-
if len(results) >= max_results:
|
|
406
|
-
return results
|
|
407
|
-
return results
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any]:
|
|
411
|
-
"""Executes a single search query dict."""
|
|
412
|
-
pattern = str(query_dict.get("pattern") or query_dict.get("query") or "").strip()
|
|
413
|
-
q_type = str(query_dict.get("type") or "text").lower().strip()
|
|
414
|
-
path_filter = query_dict.get("path")
|
|
415
|
-
max_res = int(query_dict.get("max_results") or DEFAULT_QUERY_RESULTS)
|
|
416
|
-
case_sensitive = bool(query_dict.get("case_sensitive"))
|
|
417
|
-
output_mode = str(query_dict.get("output_mode") or "content").lower()
|
|
418
|
-
file_type = query_dict.get("file_type")
|
|
419
|
-
glob_filter = query_dict.get("glob")
|
|
420
|
-
scope = str(query_dict.get("scope") or "all").lower()
|
|
421
|
-
|
|
422
|
-
if not pattern and q_type != "git":
|
|
423
|
-
return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
|
|
424
|
-
|
|
425
|
-
# A path that does not exist must be an explicit error: an empty result list
|
|
426
|
-
# is indistinguishable from a genuine zero-hit search.
|
|
427
|
-
if path_filter:
|
|
428
|
-
search_root = os.path.normpath(os.path.join(cwd, str(path_filter)))
|
|
429
|
-
if not os.path.exists(search_root):
|
|
430
|
-
return {
|
|
431
|
-
"type": q_type,
|
|
432
|
-
"pattern": pattern,
|
|
433
|
-
"error": f"path does not exist: {path_filter}",
|
|
434
|
-
"matches": [],
|
|
435
|
-
"count": 0,
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
if q_type == "git":
|
|
439
|
-
git_cwd = os.path.normpath(os.path.join(cwd, str(path_filter))) if path_filter else cwd
|
|
440
|
-
res = _run_git_query(pattern, git_cwd, max_results=max_res)
|
|
441
|
-
return {"type": "git", "pattern": pattern, **res}
|
|
442
|
-
|
|
443
|
-
if q_type == "glob":
|
|
444
|
-
try:
|
|
445
|
-
matched_paths, scanned, total = _run_glob_search(
|
|
446
|
-
pattern, cwd, path_filter=path_filter, max_results=max_res
|
|
447
|
-
)
|
|
448
|
-
except GlobPatternError as e:
|
|
449
|
-
return {
|
|
450
|
-
"type": "glob", "pattern": pattern,
|
|
451
|
-
"error": f"invalid glob pattern: {e}",
|
|
452
|
-
"matches": [], "count": 0,
|
|
453
|
-
"scanned_files": 0, "total_files": None, "partial": False,
|
|
454
|
-
}
|
|
455
|
-
base = {
|
|
456
|
-
"type": "glob", "pattern": pattern,
|
|
457
|
-
"scanned_files": scanned, "total_files": total,
|
|
458
|
-
"partial": False, "truncated": len(matched_paths) >= max_res,
|
|
459
|
-
}
|
|
460
|
-
if not matched_paths:
|
|
461
|
-
base["note"] = "glob matched no files (braces are expanded; ** is accepted)"
|
|
462
|
-
if output_mode == "count":
|
|
463
|
-
return {**base, "count": len(matched_paths)}
|
|
464
|
-
return {**base, "matches": matched_paths, "count": len(matched_paths)}
|
|
465
|
-
|
|
466
|
-
if q_type == "fuzzy":
|
|
467
|
-
matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
|
|
468
|
-
if output_mode == "count":
|
|
469
|
-
return {"type": "fuzzy", "pattern": pattern, "count": len(matched_paths)}
|
|
470
|
-
return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
|
|
471
|
-
|
|
472
|
-
is_regex = (q_type == "regex")
|
|
473
|
-
# Try ripgrep first
|
|
474
|
-
rg_matches = _run_rg_query(
|
|
475
|
-
pattern=pattern,
|
|
476
|
-
cwd=cwd,
|
|
477
|
-
path_filter=path_filter,
|
|
478
|
-
is_regex=is_regex,
|
|
479
|
-
case_sensitive=case_sensitive,
|
|
480
|
-
file_type=file_type,
|
|
481
|
-
glob_filter=glob_filter,
|
|
482
|
-
max_results=max_res,
|
|
483
|
-
scope=scope
|
|
484
|
-
)
|
|
485
|
-
|
|
486
|
-
try:
|
|
487
|
-
matches = rg_matches if rg_matches is not None else _run_python_text_search(
|
|
488
|
-
pattern=pattern,
|
|
489
|
-
cwd=cwd,
|
|
490
|
-
path_filter=path_filter,
|
|
491
|
-
is_regex=is_regex,
|
|
492
|
-
case_sensitive=case_sensitive,
|
|
493
|
-
scope=scope,
|
|
494
|
-
glob_filter=glob_filter,
|
|
495
|
-
file_type=file_type,
|
|
496
|
-
max_results=max_res
|
|
497
|
-
)
|
|
498
|
-
except ValueError as e:
|
|
499
|
-
return {"type": q_type, "pattern": pattern, "error": str(e), "matches": [], "count": 0}
|
|
500
|
-
|
|
501
|
-
if output_mode == "files_with_matches":
|
|
502
|
-
unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
|
|
503
|
-
return {"type": q_type, "pattern": pattern, "matches": unique_files, "count": len(unique_files)}
|
|
504
|
-
elif output_mode == "count":
|
|
505
|
-
return {"type": q_type, "pattern": pattern, "count": len(matches)}
|
|
506
|
-
|
|
507
|
-
return {"type": q_type, "pattern": pattern, "matches": matches, "count": len(matches)}
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
def execute_batch_search(
|
|
511
|
-
queries: List[Dict[str, Any]],
|
|
512
|
-
cwd: Optional[str] = None
|
|
513
|
-
) -> Dict[str, Any]:
|
|
514
|
-
"""
|
|
515
|
-
Executes up to 20 mixed search queries concurrently and returns a consolidated report.
|
|
516
|
-
"""
|
|
517
|
-
if not isinstance(queries, list) or not queries:
|
|
518
|
-
return {
|
|
519
|
-
"success": False,
|
|
520
|
-
"error": "Queries must be a non-empty array of query specifications.",
|
|
521
|
-
"results": [],
|
|
522
|
-
"summary_md": "Error: queries array is empty."
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
if len(queries) > MAX_BATCH_QUERIES:
|
|
526
|
-
return {
|
|
527
|
-
"success": False,
|
|
528
|
-
"error": f"Batch search exceeds maximum of {MAX_BATCH_QUERIES} queries (got {len(queries)}).",
|
|
529
|
-
"results": [],
|
|
530
|
-
"summary_md": "Error: query count exceeds maximum."
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
base_dir = os.path.abspath(cwd or os.getcwd())
|
|
534
|
-
results: List[Dict[str, Any]] = [{} for _ in queries]
|
|
535
|
-
|
|
536
|
-
# Concurrent execution across queries
|
|
537
|
-
with ThreadPoolExecutor(max_workers=min(len(queries), 8)) as executor:
|
|
538
|
-
future_to_idx = {
|
|
539
|
-
executor.submit(_execute_single_query, q, base_dir): i
|
|
540
|
-
for i, q in enumerate(queries)
|
|
541
|
-
}
|
|
542
|
-
for future in as_completed(future_to_idx):
|
|
543
|
-
idx = future_to_idx[future]
|
|
544
|
-
try:
|
|
545
|
-
results[idx] = future.result()
|
|
546
|
-
except Exception as e:
|
|
547
|
-
results[idx] = {"error": str(e), "matches": [], "count": 0}
|
|
548
|
-
|
|
549
|
-
# Format into markdown summary
|
|
550
|
-
md_lines: List[str] = [f"## TokenSafe Batch Search Report ({len(queries)} queries)"]
|
|
551
|
-
for i, res in enumerate(results):
|
|
552
|
-
q_type = res.get("type", "search")
|
|
553
|
-
pattern = res.get("pattern", "")
|
|
554
|
-
count = res.get("count", 0)
|
|
555
|
-
err = res.get("error")
|
|
556
|
-
|
|
557
|
-
if err:
|
|
558
|
-
md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — Error: {err}")
|
|
559
|
-
continue
|
|
560
|
-
|
|
561
|
-
md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — {count} match(es)")
|
|
562
|
-
matches = res.get("matches") or []
|
|
563
|
-
|
|
564
|
-
if q_type == "git":
|
|
565
|
-
raw_git = res.get("raw")
|
|
566
|
-
if raw_git:
|
|
567
|
-
md_lines.append("```text\n" + raw_git + "\n```")
|
|
568
|
-
elif not matches:
|
|
569
|
-
md_lines.append("*(clean / no output)*")
|
|
570
|
-
elif isinstance(matches, list):
|
|
571
|
-
# Honor the caller's max_results instead of a fixed 15-item cap;
|
|
572
|
-
# the Zero-Spill Guard folds oversized payloads at the MCP boundary.
|
|
573
|
-
for m in matches:
|
|
574
|
-
if isinstance(m, dict):
|
|
575
|
-
f_name = m.get("file", "")
|
|
576
|
-
l_num = m.get("line", "")
|
|
577
|
-
content = m.get("content", "")
|
|
578
|
-
md_lines.append(f"- `{f_name}:{l_num}`: {content}")
|
|
579
|
-
elif isinstance(m, str):
|
|
580
|
-
md_lines.append(f"- `{m}`")
|
|
581
|
-
|
|
582
|
-
summary_md = "\n".join(md_lines)
|
|
583
|
-
errored = [r for r in results if isinstance(r, dict) and r.get("error")]
|
|
584
|
-
return {
|
|
585
|
-
"success": not (errored and len(errored) == len(results)),
|
|
586
|
-
"query_count": len(queries),
|
|
587
|
-
"results": results,
|
|
588
|
-
"summary_md": summary_md
|
|
589
|
-
}
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
TokenSafe Format Parsers & Reducers package.
|
|
3
|
-
"""
|
|
4
|
-
|
|
5
|
-
from src.format_parsers.compiler_errors import CompilerErrorCompactor
|
|
6
|
-
from src.format_parsers.lockfiles import LockfileReducer
|
|
7
|
-
from src.format_parsers.tabular import TabularReducer
|
|
8
|
-
from src.format_parsers.json_log import JSONLogReducer
|
|
9
|
-
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
10
|
-
from src.format_parsers.ansi import strip_ansi, has_ansi
|
|
11
|
-
|
|
12
|
-
__all__ = [
|
|
13
|
-
"CompilerErrorCompactor",
|
|
14
|
-
"LockfileReducer",
|
|
15
|
-
"TabularReducer",
|
|
16
|
-
"JSONLogReducer",
|
|
17
|
-
"ContainerAndK8sReducer",
|
|
18
|
-
"strip_ansi",
|
|
19
|
-
"has_ansi",
|
|
20
|
-
]
|