Files
hermes-agent/scripts/check_tool_discovery.py
alt-glitch 3bb8a40b45 refactor(tools): an explicit list of tool modules replaces the folder scan
discover_builtin_tools() imports the modules named in
tools.registry._TOOL_MODULES, in that order, each inside the same try as
before: a module that fails to import is logged and skipped, and the rest
still register. The safe worker still loads only its three modules. The list
is today's scan result in today's order, 38 modules.

Gone with the scan: the AST parse of every tools/*.py at startup, its verdict
cache in HERMES_HOME/cache/tool_discovery_cache.json (an existing file is left
alone and no longer read), the skip set NOT_TOOL_MODULES, which no release
shipped, and the tools_dir parameter, which only tests of the scan passed.

scripts/check_tool_discovery.py now compares the list with the tracked files
under tools/ that call registry.register() at their top level, and fails on
either difference. It reads the list from the text of tools/registry.py and
holds the predicate itself, so the guard imports no application code. A listed
module inside a package must be <pkg>/tool.py in a package with an __init__.py.

Adding a built-in tool is now three edits: the tool file, its name in
_TOOL_MODULES, and its toolset. `just check` names a tool file that is missing
from the list.
2026-11-30 23:20:42 +05:30

101 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""Fail when the list of built-in tool modules and the modules that register a tool differ.
Discovery imports exactly ``tools.registry._TOOL_MODULES``. A tracked module under ``tools/`` that
calls ``registry.register()`` at import and is not listed never loads, and its tools are missing with
no error. A listed module must exist and register a tool; inside a package it is ``<pkg>/tool.py``,
and the package has an ``__init__.py`` (setuptools drops a folder without one from the wheel).
The list is read from the text of ``tools/registry.py``, so the guard imports no application code.
Usage: python3 scripts/check_tool_discovery.py
"""
from __future__ import annotations
import ast
import subprocess
import sys
from collections.abc import Iterable
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.append(str(ROOT))
from hermes_agent.compat.paths import current_path
def _is_registry_register_call(node: ast.AST) -> bool:
"""True when *node* is a ``registry.register(...)`` call expression."""
if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call):
return False
func = node.value.func
return (
isinstance(func, ast.Attribute) and func.attr == "register"
and isinstance(func.value, ast.Name) and func.value.id == "registry")
def module_registers_tools(module_path: Path) -> bool:
"""True when the module body (or a module-level ``for``) calls ``registry.register(...)``.
Only module-body statements count, so helpers registering inside a function are skipped;
a text prefilter avoids ``ast.parse`` for files lacking both words."""
try:
source = module_path.read_text(encoding="utf-8-sig")
if "registry" not in source or "register" not in source:
return False
tree = ast.parse(source, filename=str(module_path))
except (OSError, SyntaxError):
return False
# Table-driven modules register several tools from one loop, still at import time.
return any(
_is_registry_register_call(stmt)
or (isinstance(stmt, ast.For) and any(_is_registry_register_call(s) for s in stmt.body))
for stmt in tree.body)
def listed_tool_modules(registry_source: Path) -> tuple[str, ...]:
"""``_TOOL_MODULES`` as ``tools/registry.py`` writes it."""
for node in ast.parse(registry_source.read_text(encoding="utf-8-sig")).body:
if isinstance(node, ast.AnnAssign) and getattr(node.target, "id", None) == "_TOOL_MODULES" and node.value:
return tuple(ast.literal_eval(node.value))
raise SystemExit(f"check_tool_discovery: {registry_source} assigns no _TOOL_MODULES")
def discovery_problems(tools_dir: Path, listed: Iterable[str]) -> list[str]:
"""One line per difference between *listed* (module names under the ``tools`` package) and the
tracked modules under *tools_dir* that register a tool at import."""
tracked = subprocess.run(
["git", "ls-files", "-z", "--", "*.py"],
cwd=tools_dir, capture_output=True, text=True, check=True, timeout=60,
).stdout
registering = {
".".join(("tools", *Path(rel).with_suffix("").parts)) for rel in tracked.split("\0")
if rel and module_registers_tools(tools_dir / rel)
}
listed = list(listed)
problems = [f"{module}: registers a tool at import but is not in tools.registry._TOOL_MODULES"
for module in sorted(registering - set(listed))]
for module in listed:
parts = module.split(".")[1:]
path = tools_dir.joinpath(*parts).with_suffix(".py")
if len(parts) > 1 and parts[-1] != "tool":
problems.append(f"{module}: a tool in a package registers from <pkg>/tool.py")
elif len(parts) > 1 and not (path.parent / "__init__.py").is_file():
problems.append(f"{module}: its package has no __init__.py, so the wheel would drop it")
elif module not in registering:
problems.append(f"{module}: listed in tools.registry._TOOL_MODULES but registers no tool at import")
return problems
def main() -> int:
tools_dir = ROOT / current_path("tools")
problems = discovery_problems(tools_dir, listed_tool_modules(tools_dir / "registry.py"))
if problems:
print("The built-in tool modules and tools.registry._TOOL_MODULES differ:", file=sys.stderr)
for line in problems:
print(f" {line}", file=sys.stderr)
return 1
print("check_tool_discovery: OK")
return 0
if __name__ == "__main__":
sys.exit(main())