feat(tools): use installed ripgrep for native file search (#5948)

* feat(tools): expose installed ripgrep through exec

* refactor(tools): launch ripgrep with native argument vectors

* refactor(tools): reuse the fresh exec parameter schema

* fix(tools): select search backend in loader and display rg arguments

* fix(ui): simplify rg previews and localize search completion

* docs: simplify ripgrep configuration note

* docs: keep ripgrep note on one line
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-28 13:44:51 +08:00
1 parent b8893aba56
commit e0b8efa0be
33 files changed
+514 -204

No files matched your search

+6 -18
View File
@@ -207,33 +207,23 @@ class TestIsTemplateContent:
class TestBundledToolContract:
def test_tool_contract_balances_general_and_coding_workflows(self):
def test_tool_contract_contains_shared_execution_policy(self):
from importlib.resources import files as pkg_files
tpl = pkg_files("nanobot") / "templates" / "agent" / "tool_contract.md"
content = tpl.read_text(encoding="utf-8")
assert "## General Tool Contract" in content
assert "Use the narrowest structured tool" in content
assert "Do not use `exec` as a universal workaround" in content
assert "## File and Coding Workflows" in content
assert "`grep` returns matches with five context lines by default" in content
assert "apply_patch" in content
assert "acceptance criteria into concrete checks" in content
assert "visual evidence reaches the model" in content
assert "clear user request as authorization" in content
assert "Never invent missing records or measurements" in content
assert "## Web and External Information" in content
assert "## Messaging and Media" in content
assert "## Scheduling and Background Work" in content
assert "execution and verification" in content
assert "irreversible action" in content
assert "Wait for tool results" in content
def test_tool_contract_is_injected_without_workspace_file(self, tmp_path):
builder = _builder(tmp_path)
prompt = builder.build_system_prompt()
assert "# Tool Usage Notes" in prompt
assert "## General Tool Contract" in prompt
assert "Do not use `exec` as a universal workaround" in prompt
assert "clear user request as authorization" in prompt
# ---------------------------------------------------------------------------
@@ -305,7 +295,6 @@ class TestBuildSystemPrompt:
def test_default_identity_uses_relative_agent_paths(self, tmp_path):
result = ContextBuilder(tmp_path)._get_identity()
assert str(tmp_path.resolve()) not in result
assert "Agent profile: SOUL.md and USER.md" in result
assert "History log: memory/history.jsonl" in result
assert "Custom skills: skills/{skill-name}/SKILL.md" in result
@@ -318,10 +307,9 @@ class TestBuildSystemPrompt:
result = ContextBuilder(agent_home)._get_identity(workspace=project)
assert str(project.resolve()) not in result
assert f"agent workspace is at: {agent_home.resolve()}" in result
assert f"{agent_home.resolve()}/SOUL.md" in result
assert f"{project.resolve()}/SOUL.md" not in result
assert f"Custom skills: {agent_home.resolve()}/skills/" in result
def test_includes_bootstrap_files(self, tmp_path):
(tmp_path / "AGENTS.md").write_text("Be helpful and concise.", encoding="utf-8")
+6 -21
View File
@@ -118,9 +118,7 @@ def test_execution_rules_in_system_prompt(tmp_path) -> None:
prompt = builder.build_system_prompt()
assert "clear user request" in prompt
assert "multi-step tasks" in prompt
assert "read-only discovery before writes" in prompt
assert "verify the result" in prompt
assert "execution and verification" in prompt
def test_execution_rules_reach_existing_workspace_soul(tmp_path) -> None:
@@ -152,8 +150,8 @@ def test_default_soul_template_keeps_execution_policy_in_tool_contract() -> None
assert "## Execution Rules" not in soul
assert "clear user request" not in soul
assert "clear user request" in contract
assert "multi-step tasks" in contract
assert "irreversible action needs confirmation" in contract
assert "execution and verification" in contract
assert "Ask for confirmation when an irreversible action requires it" in contract
def test_channel_format_hint_telegram(tmp_path) -> None:
@@ -202,18 +200,6 @@ def test_build_messages_passes_channel_to_system_prompt(tmp_path) -> None:
assert "messaging app" in system
def test_system_prompt_keeps_message_tool_out_of_current_chat_replies(tmp_path) -> None:
workspace = _make_workspace(tmp_path)
builder = ContextBuilder(workspace)
prompt = builder.build_system_prompt(channel="slack")
assert "Do not use the 'message' tool for normal replies in the current chat" in prompt
assert "When 'generate_image' creates images" in prompt
assert "call 'message' with the artifact paths in the 'media' parameter" in prompt
assert "Wait for the tool results, then answer once" in prompt
def test_memory_skill_is_lazy_loaded_from_skills_index(tmp_path) -> None:
"""Memory search guidance should be discoverable without loading its full body."""
workspace = _make_workspace(tmp_path)
@@ -239,11 +225,10 @@ def test_fresh_workspace_omits_default_prompt_scaffolding(tmp_path) -> None:
assert "## USER.md" not in prompt
assert "8281248569" not in prompt
assert "(your name)" not in prompt
assert prompt.count("Do not use the 'message' tool for normal replies") == 1
def test_template_memory_md_is_skipped(tmp_path) -> None:
"""MEMORY.md matching the bundled template should not inject the Memory section."""
"""Template content is omitted while memory locations remain available."""
workspace = _make_workspace(tmp_path)
from nanobot.utils.helpers import sync_workspace_templates
sync_workspace_templates(workspace, silent=True)
@@ -251,8 +236,8 @@ def test_template_memory_md_is_skipped(tmp_path) -> None:
builder = ContextBuilder(workspace)
prompt = builder.build_system_prompt()
# This block is produced only when populated long-term memory is injected.
assert "# Memory\n\n## Long-term Memory" not in prompt
assert "## Long-term Memory" not in prompt
assert "History log: memory/history.jsonl" in prompt
assert "This file is automatically updated by nanobot" not in prompt
+1 -2
View File
@@ -350,8 +350,7 @@ def test_bundled_skills_use_agent_owned_paths(tmp_path: Path) -> None:
update_setup = loader.load_skill("update-setup")
assert memory is not None
assert "<history-log-path>" in memory
assert 'path="memory/history.jsonl"' not in memory
assert "`History log` path from the system prompt" in memory
assert update_setup is not None
assert "<agent-workspace>/skills/update/SKILL.md" in update_setup
assert "Never substitute a project-relative" in update_setup
+11
View File
@@ -16,6 +16,17 @@ def _hint(calls, max_length=40):
class TestToolHintKnownTools:
"""Test registered tool types produce correct formatted output."""
def test_rg_shows_argument_boundaries(self):
assert _hint([_tc("rg", {"args": ["-n", "hello world", "src"]})]) == 'rg -n "hello world" src'
def test_rg_shows_regex_and_empty_argument(self):
assert _hint([_tc("rg", {"args": [r"resolve\(", ""]})]) == 'rg resolve\\( ""'
def test_rg_truncates_long_arguments(self):
result = _hint([_tc("rg", {"args": ["x" * 100]})])
assert result.endswith("…")
assert len(result) == 43
def test_read_file_short_path(self):
result = _hint([_tc("read_file", {"path": "foo.txt"})])
assert result == 'read foo.txt'
+1
View File
@@ -12,6 +12,7 @@ FILE_TOOL_NAMES = {
"edit_file",
"find_files",
"grep",
"rg",
"list_dir",
"read_file",
"write_file",
+235
View File
@@ -0,0 +1,235 @@
"""Registration and exec delegation for ripgrep."""
import asyncio
import os
import re
import shlex
import shutil
import sys
from unittest.mock import AsyncMock
import pytest
from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.rg import RgTool
from nanobot.agent.tools.search import FindFilesTool, GrepTool
from nanobot.agent.tools.shell import ExecTool, _PreparedCommand
from nanobot.config.schema import ToolsConfig
@pytest.mark.parametrize("installed", [True, False])
@pytest.mark.parametrize("exec_enabled", [True, False])
@pytest.mark.parametrize("file_enabled", [True, False])
@pytest.mark.parametrize("scope", ["core", "subagent"])
@pytest.mark.parametrize("classes", [
[RgTool, GrepTool, FindFilesTool], [GrepTool, FindFilesTool, RgTool],
])
def test_loader_selects_one_search_backend(tmp_path, monkeypatch, installed, exec_enabled, file_enabled, scope, classes):
monkeypatch.setattr("nanobot.agent.tools.rg.shutil.which", lambda *a, **kw: "rg" if installed else None)
config = ToolsConfig()
config.exec.enable = exec_enabled
config.file.enable = file_enabled
ctx = ToolContext(config=config, workspace=str(tmp_path))
registry = ToolRegistry()
registered = ToolLoader(test_classes=classes).load(ctx, registry, scope=scope)
expected = {"rg"} if installed and exec_enabled else {"grep", "find_files"}
assert set(registry.tool_names) == (expected if file_enabled else set())
assert set(registered) == set(registry.tool_names)
def test_loader_keeps_builtin_search_when_rg_creation_fails(tmp_path, monkeypatch):
monkeypatch.setattr(RgTool, "enabled", classmethod(lambda cls, ctx: True))
def fail_create(cls, ctx):
raise RuntimeError("rg initialization failed")
monkeypatch.setattr(RgTool, "create", classmethod(fail_create))
registry = ToolRegistry()
registered = ToolLoader(test_classes=[RgTool, GrepTool, FindFilesTool]).load(
ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry,
)
assert set(registered) == {"grep", "find_files"}
assert set(registry.tool_names) == {"grep", "find_files"}
def test_loader_can_load_builtin_search_independently(tmp_path, monkeypatch):
monkeypatch.setattr(RgTool, "enabled", classmethod(lambda cls, ctx: True))
registry = ToolRegistry()
registered = ToolLoader(test_classes=[GrepTool, FindFilesTool]).load(
ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry,
)
assert set(registered) == {"grep", "find_files"}
assert set(registry.tool_names) == {"grep", "find_files"}
def test_loader_preserves_plugin_search_tool(tmp_path, monkeypatch):
monkeypatch.setattr(RgTool, "enabled", classmethod(lambda cls, ctx: True))
loader = ToolLoader(test_classes=[RgTool, GrepTool, FindFilesTool])
monkeypatch.setattr(loader, "_discover_plugins", lambda: {"external_grep": GrepTool})
registry = ToolRegistry()
registered = loader.load(ToolContext(config=ToolsConfig(), workspace=str(tmp_path)), registry)
assert registered == ["rg", "grep"]
assert set(registry.tool_names) == {"rg", "grep"}
def test_detection_uses_exec_path_configuration(tmp_path, monkeypatch):
config = ToolsConfig()
config.exec.path_prepend = str(tmp_path / "before")
config.exec.path_append = str(tmp_path / "after")
captured = {}
def which(command, *, path):
captured.update(command=command, path=path)
return "rg"
monkeypatch.setattr("nanobot.agent.tools.rg.shutil.which", which)
assert RgTool.enabled(ToolContext(config=config, workspace=str(tmp_path)))
assert captured["path"] == os.pathsep.join([
config.exec.path_prepend, os.environ.get("PATH", ""), config.exec.path_append,
])
async def test_rg_forwards_native_arguments_and_exec_options(monkeypatch):
execute = AsyncMock(return_value="native output")
monkeypatch.setattr(ExecTool, "execute", execute)
arguments = ["--engine=pcre2", "--sort", "path", "--json", "(?<=hello)world", "."]
result = await RgTool().execute(
args=arguments, working_dir="project", timeout=12,
yield_time_ms=25, max_output_chars=1500,
)
assert result == "native output"
execute.assert_awaited_once_with(
command=["rg", *arguments], working_dir="project", timeout=12,
yield_time_ms=25, max_output_chars=1500,
)
assert RgTool().read_only is False
def test_schema_exposes_arguments_and_exec_controls():
schema = RgTool().parameters
assert schema["properties"]["args"]["type"] == "array"
assert schema["properties"]["args"]["items"] == {"type": "string"}
assert schema["required"] == ["args"]
assert {"working_dir", "timeout", "yield_time_ms"} <= schema["properties"].keys()
assert "command" in ExecTool().parameters["properties"]
@pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")
async def test_native_search_and_file_discovery_via_exec(tmp_path):
(tmp_path / "source.py").write_text("before\nneedle\nafter\n", encoding="utf-8")
(tmp_path / "other.txt").write_text("unrelated\n", encoding="utf-8")
tool = RgTool(working_dir=str(tmp_path), restrict_to_workspace=True)
result = await tool.execute(args=["-n", "-C1", "-g", "*.py", "needle", "."])
assert "2:needle" in result
assert "before" in result and "after" in result
assert "Exit code: 0" in result
files = await tool.execute(args=["--files", "-g", "*.py", "."])
assert "source.py" in files
absent = await tool.execute(args=["absent", "."])
assert "Exit code: 1" in absent
async def test_exec_workspace_policy_applies(tmp_path):
result = await RgTool(working_dir=str(tmp_path), restrict_to_workspace=True).execute(
args=["--files"], working_dir=str(tmp_path.parent),
)
assert "outside the configured workspace" in result
@pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")
async def test_native_arguments_preserve_spaces_and_shell_characters(tmp_path):
text = 'hello world | $HOME > output; "quoted" & $(echo hi)'
(tmp_path / "space name.txt").write_text(text + "\n", encoding="utf-8")
tool = RgTool(working_dir=str(tmp_path))
result = await tool.execute(args=["-n", "-F", "--", text, "space name.txt"])
assert f"1:{text}" in result
assert "Exit code: 0" in result
@pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")
async def test_native_search_session(tmp_path):
(tmp_path / "source.txt").write_text("needle\n", encoding="utf-8")
manager = ExecSessionManager()
tool = RgTool(working_dir=str(tmp_path), session_manager=manager)
try:
result = await tool.execute(args=["-n", "needle", "."], yield_time_ms=0)
session = re.search(r"session_id:\s*([0-9a-f]+)", result)
if session:
poll = await manager.write(
session_id=session.group(1), chars=None, close_stdin=False, terminate=False,
yield_time_ms=10000, max_output_chars=1000,
)
result += poll.output
assert poll.exit_code == 0
assert "1:needle" in result
finally:
await manager.close_all()
async def test_direct_process_preserves_arguments_and_output_limit(tmp_path):
tool = ExecTool(working_dir=str(tmp_path))
result = await tool.execute(
command=[sys.executable, "-c", "print('x' * 4000)"], max_output_chars=1000,
)
assert "chars truncated" in result
assert "Exit code: 0" in result
async def test_direct_process_timeout(tmp_path):
result = await ExecTool(working_dir=str(tmp_path)).execute(
command=[sys.executable, "-c", "import time; time.sleep(20)"], timeout=1,
)
assert "timed out after 1 seconds" in result
async def test_direct_process_cancellation_reaps_child(tmp_path, monkeypatch):
spawned = asyncio.Event()
processes = []
original_spawn = ExecTool._spawn
async def capture(*args, **kwargs):
process = await original_spawn(*args, **kwargs)
processes.append(process)
spawned.set()
return process
monkeypatch.setattr(ExecTool, "_spawn", staticmethod(capture))
task = asyncio.create_task(ExecTool(working_dir=str(tmp_path)).execute(
command=[sys.executable, "-c", "import time; time.sleep(20)"],
))
await asyncio.wait_for(spawned.wait(), timeout=5)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert isinstance(processes[0].returncode, int)
@pytest.mark.skipif(shutil.which("rg") is None, reason="ripgrep not installed")
async def test_direct_search_uses_configured_path(tmp_path, monkeypatch):
installed = shutil.which("rg")
assert installed
bin_dir = tmp_path / "custom bin"
bin_dir.mkdir()
shutil.copy2(installed, bin_dir / ("rg.exe" if sys.platform == "win32" else "rg"))
monkeypatch.setenv("PATH", "")
result = await RgTool(working_dir=str(tmp_path), path_prepend=str(bin_dir)).execute(
args=["--version"],
)
assert "ripgrep" in result
assert "Exit code: 0" in result
@pytest.mark.parametrize("backend", ["bwrap", "seatbelt"])
def test_direct_search_preserves_sandbox_and_arguments(tmp_path, monkeypatch, backend):
monkeypatch.setattr("nanobot.agent.tools.shell._IS_WINDOWS", False)
args = ["rg", "-F", "hello | $HOME; 'world'", "."]
prepared = RgTool(working_dir=str(tmp_path), sandbox=backend)._prepare_command(args)
assert isinstance(prepared, _PreparedCommand)
assert isinstance(prepared.command, list)
assert prepared.command[0] == ("bwrap" if backend == "bwrap" else "/usr/bin/sandbox-exec")
assert prepared.command[-2] == "-c"
inner_command = prepared.command[-1].split("\n")[-1]
assert shlex.split(inner_command) == args
+12 -6
View File
@@ -758,19 +758,24 @@ async def test_search_tools_reject_paths_outside_workspace(tmp_path: Path) -> No
assert grep_result.startswith("Error:")
def test_agent_loop_registers_grep(tmp_path: Path) -> None:
@pytest.mark.parametrize("use_rg", [True, False])
def test_agent_loop_registers_search_backend(tmp_path: Path, monkeypatch, use_rg) -> None:
monkeypatch.setattr("nanobot.agent.tools.rg.RgTool.enabled", lambda ctx: use_rg)
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
loop = AgentLoop(bus=bus, provider=provider, workspace=tmp_path, model="test-model")
assert "find_files" in loop.tools.tool_names
assert "grep" in loop.tools.tool_names
assert ("rg" in loop.tools.tool_names) == use_rg
assert ("find_files" in loop.tools.tool_names) == (not use_rg)
assert ("grep" in loop.tools.tool_names) == (not use_rg)
@pytest.mark.asyncio
async def test_subagent_registers_grep(tmp_path: Path) -> None:
@pytest.mark.parametrize("use_rg", [True, False])
async def test_subagent_registers_search_backend(tmp_path: Path, monkeypatch, use_rg) -> None:
monkeypatch.setattr("nanobot.agent.tools.rg.RgTool.enabled", lambda ctx: use_rg)
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
@@ -804,8 +809,9 @@ async def test_subagent_registers_grep(tmp_path: Path) -> None:
LLMRuntime.capture(provider, "test-model", context_window_tokens=128_000),
)
assert "find_files" in captured["tool_names"]
assert "grep" in captured["tool_names"]
assert ("rg" in captured["tool_names"]) == use_rg
assert ("find_files" in captured["tool_names"]) == (not use_rg)
assert ("grep" in captured["tool_names"]) == (not use_rg)
def test_subagent_prompt_respects_disabled_skills(tmp_path: Path) -> None:
+3 -1
View File
@@ -1,6 +1,7 @@
"""Tests for tool plugin architecture: ToolLoader, ToolContext, metadata."""
from __future__ import annotations
import shutil
from dataclasses import fields
from pathlib import Path
from typing import Any
@@ -445,10 +446,11 @@ def test_loader_registers_same_tools_as_old_hardcoded():
expected = {
"read_file", "write_file", "edit_file", "list_dir",
"find_files", "grep", "exec", "exec_session", "list_exec_sessions",
"exec", "exec_session", "list_exec_sessions",
"web_search", "web_fetch",
"message", "spawn", "cron",
"my",
}
actual = set(registered)
expected.update({"rg"} if shutil.which("rg") else {"find_files", "grep"})
assert expected <= actual, f"Missing tools: {expected - actual}"