183 lines
5.8 KiB
Python
183 lines
5.8 KiB
Python
"""
|
||||
|
|
搜索定位工具(grep / 文件查找)
|
|||
|
|
=============================
|
|||
|
|
|
|||
|
|
【功能说明】
|
|||
|
|
自研工具链的代码定位能力:正则内容搜索(grep)与文件名模糊查找。
|
|||
|
|
对应《核心诉求》「代码定位」环节,决策点 6 定为「代码走符号检索不进向量库」。
|
|||
|
|
|
|||
|
|
【技术选型理由】
|
|||
|
|
1. 选 ripgrep 风格的纯 Python 实现(re + pathlib):
|
|||
|
|
不依赖外部 rg 二进制,跨平台一致、可单测、可控。
|
|||
|
|
2. grep 而非向量检索:代码定位要的是**精确符号匹配**,
|
|||
|
|
向量检索在代码上召回不准(决策点 6 已论证)。
|
|||
|
|
3. 输出结构化(文件+行号+内容片段):Agent 能直接定位到行级修改点。
|
|||
|
|
|
|||
|
|
【实现思路】
|
|||
|
|
- grep_files:按正则搜索,支持 glob 过滤、大小写开关、结果上限;
|
|||
|
|
- find_files:按文件名模式查找(支持 * 通配);
|
|||
|
|
- 两者都经路径守卫校验,结果上限防止刷爆上下文。
|
|||
|
|
|
|||
|
|
【潜在风险与应对】
|
|||
|
|
风险1:正则写错导致全库扫描耗时。
|
|||
|
|
应对:结果上限 100 条 + 扫描文件数上限 5000,超时保护。
|
|||
|
|
风险2:搜索到二进制文件产生乱码。
|
|||
|
|
应对:跳过常见二进制扩展名(.png/.zip/.class/.jar 等)。
|
|||
|
|
风险3:结果过多撑爆 Agent 上下文。
|
|||
|
|
应对:每条结果截断到 200 字符,总数硬上限。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import logging
|
|||
|
|
import re
|
|||
|
|
from pathlib import Path
|
|||
|
|
from typing import Any
|
|||
|
|
|
|||
|
|
from app.tools.audit import log_action
|
|||
|
|
from app.tools.path_guard import ensure_under_root
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.tools.search")
|
|||
|
|
|
|||
|
|
# 结果上限(防止刷爆 Agent 上下文)
|
|||
|
|
MAX_RESULTS = 100
|
|||
|
|
MAX_SCAN_FILES = 5000
|
|||
|
|
MAX_LINE_LENGTH = 200
|
|||
|
|
|
|||
|
|
# 跳过的二进制/无意义扩展名
|
|||
|
|
SKIP_EXTENSIONS = {
|
|||
|
|
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico",
|
|||
|
|
".zip", ".jar", ".war", ".class", ".pyc", ".pyd",
|
|||
|
|
".pdf", ".docx", ".xlsx", ".pptx",
|
|||
|
|
".exe", ".dll", ".so", ".dylib",
|
|||
|
|
".db", ".sqlite", ".sqlite3",
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
class SearchToolError(RuntimeError):
|
|||
|
|
"""搜索工具异常(中文可读)"""
|
|||
|
|
|
|||
|
|
def __init__(self, message: str, *, error_type: str = "SearchToolError") -> None:
|
|||
|
|
super().__init__(message)
|
|||
|
|
self.error_type = error_type
|
|||
|
|
|
|||
|
|
|
|||
|
|
def grep_files(
|
|||
|
|
pattern: str,
|
|||
|
|
search_path: str | Path,
|
|||
|
|
glob_filter: str = "*",
|
|||
|
|
case_sensitive: bool = False,
|
|||
|
|
max_results: int = MAX_RESULTS,
|
|||
|
|
) -> dict[str, Any]:
|
|||
|
|
"""
|
|||
|
|
正则内容搜索(grep)。
|
|||
|
|
|
|||
|
|
【参数】
|
|||
|
|
pattern:正则表达式
|
|||
|
|
search_path:搜索根目录
|
|||
|
|
glob_filter:文件名过滤(如 *.java)
|
|||
|
|
case_sensitive:是否区分大小写
|
|||
|
|
max_results:结果上限
|
|||
|
|
【返回】{pattern, total_matches, results: [{file, line_no, line}]}
|
|||
|
|
"""
|
|||
|
|
root = ensure_under_root(Path(search_path), action="搜索", readonly=True)
|
|||
|
|
if not root.exists():
|
|||
|
|
raise SearchToolError(f"搜索路径不存在:{root}", error_type="PathNotFound")
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
regex = re.compile(pattern, 0 if case_sensitive else re.IGNORECASE)
|
|||
|
|
except re.error as exc:
|
|||
|
|
raise SearchToolError(f"正则表达式无效:{pattern},原因:{exc}", error_type="InvalidRegex")
|
|||
|
|
|
|||
|
|
results: list[dict[str, Any]] = []
|
|||
|
|
scanned = 0
|
|||
|
|
|
|||
|
|
for file_path in root.rglob(glob_filter):
|
|||
|
|
if scanned >= MAX_SCAN_FILES:
|
|||
|
|
logger.warning("扫描文件数超限 %d,提前终止", MAX_SCAN_FILES)
|
|||
|
|
break
|
|||
|
|
if not file_path.is_file():
|
|||
|
|
continue
|
|||
|
|
if file_path.suffix.lower() in SKIP_EXTENSIONS:
|
|||
|
|
continue
|
|||
|
|
scanned += 1
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
text = file_path.read_text(encoding="utf-8", errors="replace")
|
|||
|
|
except Exception:
|
|||
|
|
continue
|
|||
|
|
|
|||
|
|
for line_no, line in enumerate(text.splitlines(), start=1):
|
|||
|
|
if regex.search(line):
|
|||
|
|
results.append(
|
|||
|
|
{
|
|||
|
|
"file": str(file_path),
|
|||
|
|
"line_no": line_no,
|
|||
|
|
"line": line[:MAX_LINE_LENGTH],
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
if len(results) >= max_results:
|
|||
|
|
break
|
|||
|
|
if len(results) >= max_results:
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
log_action(
|
|||
|
|
action="grep_files",
|
|||
|
|
target=str(root),
|
|||
|
|
result="success",
|
|||
|
|
details={"pattern": pattern, "matches": len(results), "scanned": scanned},
|
|||
|
|
)
|
|||
|
|
return {
|
|||
|
|
"pattern": pattern,
|
|||
|
|
"search_path": str(root),
|
|||
|
|
"total_matches": len(results),
|
|||
|
|
"scanned_files": scanned,
|
|||
|
|
"results": results,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def find_files(
|
|||
|
|
name_pattern: str,
|
|||
|
|
search_path: str | Path,
|
|||
|
|
max_results: int = MAX_RESULTS,
|
|||
|
|
) -> dict[str, Any]:
|
|||
|
|
"""
|
|||
|
|
按文件名模式查找文件。
|
|||
|
|
|
|||
|
|
【参数】name_pattern:支持 * 通配(如 *Controller.java)或纯名片段
|
|||
|
|
【返回】{pattern, total, files: [...]}
|
|||
|
|
"""
|
|||
|
|
root = ensure_under_root(Path(search_path), action="查找", readonly=True)
|
|||
|
|
if not root.exists():
|
|||
|
|
raise SearchToolError(f"查找路径不存在:{root}", error_type="PathNotFound")
|
|||
|
|
|
|||
|
|
# 纯名片段转通配模式
|
|||
|
|
pattern = name_pattern if "*" in name_pattern else f"*{name_pattern}*"
|
|||
|
|
|
|||
|
|
files: list[str] = []
|
|||
|
|
scanned = 0
|
|||
|
|
for file_path in root.rglob(pattern):
|
|||
|
|
if scanned >= MAX_SCAN_FILES:
|
|||
|
|
break
|
|||
|
|
if not file_path.is_file():
|
|||
|
|
continue
|
|||
|
|
if file_path.suffix.lower() in SKIP_EXTENSIONS:
|
|||
|
|
continue
|
|||
|
|
scanned += 1
|
|||
|
|
files.append(str(file_path))
|
|||
|
|
if len(files) >= max_results:
|
|||
|
|
break
|
|||
|
|
|
|||
|
|
log_action(
|
|||
|
|
action="find_files",
|
|||
|
|
target=str(root),
|
|||
|
|
result="success",
|
|||
|
|
details={"pattern": pattern, "found": len(files)},
|
|||
|
|
)
|
|||
|
|
return {
|
|||
|
|
"pattern": pattern,
|
|||
|
|
"search_path": str(root),
|
|||
|
|
"total": len(files),
|
|||
|
|
"files": files,
|
|||
|
|
}
|