From e6f7b6732d7c00a75fd823e440ca47176bf81cb6 Mon Sep 17 00:00:00 2001 From: alt-glitch Date: Sun, 15 Nov 2026 14:34:09 +0530 Subject: [PATCH] fix(code-health): a folder made from a root module ships, and the guard needs __init__.py Two review findings on the folder rule: - A root module or an acp_adapter/ module turned into a folder drops out of setup.py's _root_py_modules and ships only if [tool.setuptools.packages.find] include matches it. The FILE_LINES fix text now names that step, and test_every_package_packaged_code_imports_is_found fails when packaged code imports a regular package the wheel would not ship (moving toolsets.py to toolsets/__init__.py fails it with ['toolsets']). - Discovery skips a tool package without __init__.py, so check_tool_discovery counts only candidates whose package has one, and its message says so. An intent-added tools/newpkg/tool.py with no __init__.py now fails the guard. Both changes are the reviewer's patches as suggested. --- scripts/check_tool_discovery.py | 8 +++- scripts/code_health/config.py | 4 +- tests/scripts/test_check_tool_discovery.py | 5 +++ tests/test_packaging_py_modules.py | 44 ++++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/scripts/check_tool_discovery.py b/scripts/check_tool_discovery.py index d97621bf30..f7f67dfa0a 100644 --- a/scripts/check_tool_discovery.py +++ b/scripts/check_tool_discovery.py @@ -29,14 +29,18 @@ def unreached_registrations(tools_dir: Path) -> list[Path]: tools_dir / rel for rel in listed.split("\0") if rel and _module_registers_tools(tools_dir / rel) } - return sorted(registering - set(_tool_module_candidates(tools_dir))) + # Discovery also skips a package without __init__.py (setuptools would drop it from the wheel). + discovered = {p for p in _tool_module_candidates(tools_dir) + if p.parent == tools_dir or (p.parent / "__init__.py").is_file()} + return sorted(registering - discovered) def main() -> int: missed = unreached_registrations(ROOT / current_path("tools")) if missed: print("These modules call registry.register() at import, but tool discovery never imports" - " them. Inside a package, register from /tool.py:", file=sys.stderr) + " them. Inside a package, register from /tool.py and give the package an" + " __init__.py:", file=sys.stderr) for path in missed: print(f" {path.relative_to(ROOT).as_posix()}", file=sys.stderr) return 1 diff --git a/scripts/code_health/config.py b/scripts/code_health/config.py index dc6317ca09..33db99c4d5 100644 --- a/scripts/code_health/config.py +++ b/scripts/code_health/config.py @@ -37,7 +37,9 @@ METRIC_FIX = { " `/` package (with `__init__.py`) and move an existing function or class into a topic" " module there (moved code keeps its cap); never a new flat `_.py`. A model tool" " in a folder registers from `tools//tool.py`, the only file tool discovery imports" - " there. New tests go in `tests///test_.py` (with `__init__.py`);" + " there. A root module or an `acp_adapter/` one also lists its new package in pyproject's" + " `[tool.setuptools.packages.find] include`, or the wheel drops it. New tests go in" + " `tests///test_.py` (with `__init__.py`);" " new behaviour never goes into a facade. Folder shape: root AGENTS.md ยง Packages and" " Python shape", "MEASURE": "the file must parse and measure (a file that cannot be measured cannot be" diff --git a/tests/scripts/test_check_tool_discovery.py b/tests/scripts/test_check_tool_discovery.py index c43c3c7926..9e4f568ade 100644 --- a/tests/scripts/test_check_tool_discovery.py +++ b/tests/scripts/test_check_tool_discovery.py @@ -41,3 +41,8 @@ def test_flat_modules_and_package_tool_py_pass(tmp_path): "pkg/helpers.py": "def helper():\n return 1\n", }) assert unreached_registrations(tools_dir) == [] + + +def test_package_tool_py_without_init_is_flagged(tmp_path): + tools_dir = _tracked_tools(tmp_path, {"__init__.py": "", "pkg/tool.py": _REGISTERS}) + assert unreached_registrations(tools_dir) == [tools_dir / "pkg/tool.py"] diff --git a/tests/test_packaging_py_modules.py b/tests/test_packaging_py_modules.py index 6249e4a5bf..2c96453385 100644 --- a/tests/test_packaging_py_modules.py +++ b/tests/test_packaging_py_modules.py @@ -16,6 +16,8 @@ import sys import tomllib from pathlib import Path +import setuptools + from hermes_agent.compat.paths import current_path REPO_ROOT = Path(__file__).resolve().parent.parent @@ -77,3 +79,45 @@ def test_every_root_module_imported_by_packaged_code_is_shipped(): assert not missing, f"packaged code imports root modules the wheel would not ship: {missing}" on_disk = {p.stem for p in REPO_ROOT.glob("*.py") if not p.stem.startswith("_test_")} - {"setup"} assert on_disk and on_disk <= shipped and "setup" not in shipped + + +def _imported_dotted_names(path: Path) -> set[str]: + """Absolute module names *path* imports, relative imports resolved against its package.""" + package = path.relative_to(REPO_ROOT).parent.parts + try: + tree = ast.parse(path.read_text(encoding="utf-8", errors="ignore")) + except (SyntaxError, OSError): + return set() + names: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names.update(a.name for a in node.names) + elif isinstance(node, ast.ImportFrom): + base = package[: len(package) - node.level + 1] if node.level else () + names.add(".".join((*base, *(node.module or "").split("."))).strip(".")) + return names + + +def test_every_package_packaged_code_imports_is_found(): + """A module turned into a folder (``toolsets.py`` -> ``toolsets/``, ``acp_adapter/server.py`` + -> ``acp_adapter/server/``) drops out of ``_root_py_modules`` and ships only if + ``packages.find`` matches it; the wheel would raise ``ModuleNotFoundError`` otherwise.""" + cfg = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text(encoding="utf-8")) + include = cfg["tool"]["setuptools"]["packages"]["find"]["include"] + found = set(setuptools.find_packages(where=str(REPO_ROOT), include=include)) + paths = [REPO_ROOT / f"{n}.py" for n in _root_py_modules()] + paths += [p for pkg in found for p in (REPO_ROOT / pkg.replace(".", "/")).glob("*.py")] + missing = set() + for path in paths: + for name in _imported_dotted_names(path): + parts = name.split(".") + for i in range(1, len(parts) + 1): + pkg, parent = ".".join(parts[:i]), ".".join(parts[: i - 1]) + # A regular package at the root or inside a shipped one; namespace dirs ship otherwise. + if (parent == "" or parent in found) and pkg not in found \ + and (REPO_ROOT.joinpath(*parts[:i]) / "__init__.py").is_file(): + missing.add(pkg) + assert not missing, ( + f"packaged code imports packages the wheel would not ship: {sorted(missing)}; add each to" + " [tool.setuptools.packages.find] include in pyproject.toml" + )