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.
This commit is contained in:
alt-glitch
2026-11-15 14:34:09 +05:30
committed by Siddharth Balyan
parent c3bd0bfc53
commit e6f7b6732d
4 changed files with 58 additions and 3 deletions

View File

@@ -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 <pkg>/tool.py:", file=sys.stderr)
" them. Inside a package, register from <pkg>/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

View File

@@ -37,7 +37,9 @@ METRIC_FIX = {
" `<stem>/` 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 `<stem>_<topic>.py`. A model tool"
" in a folder registers from `tools/<stem>/tool.py`, the only file tool discovery imports"
" there. New tests go in `tests/<area>/<stem>/test_<topic>.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/<area>/<stem>/test_<topic>.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"

View File

@@ -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"]

View File

@@ -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"
)