The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): module-form worker carries the install root on PYTHONPATH (#122299, #122487, #122500, salvage #122420)
teknium15392a83ccd35
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex fae39081d23..5925689f6e7 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -910,6 +910,13 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Optf"profile's environment ({type(exc).__name__}: {exc}); do not resend")if home.parent.name != "profiles":argv += ["-p", "default"]+ if argv[1:3] == ["-m", "hermes_cli.main"]:+ # served_profile_child_env strips Hermes-owned PYTHONPATH entries; under a store-python+ # shim the bare interpreter then cannot import the package find_spec just proved (#122487).+ from pathlib import Path++ from cron.scheduler_worker_env import pin_hermes_tree_on_pythonpath+ pin_hermes_tree_on_pythonpath(env, Path(__file__).resolve().parents[1])query_file = Nonetry:diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 68037368a88..41adccc9fce 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -2481,17 +2481,16 @@ def _propagate_module_import_root(cmd: list[str], env: dict[str, str]) -> None:the spawned child runs the bare ``sys.executable`` from the task workspacewith a scrubbed ``PYTHONPATH`` and cannot import the package the parentjust proved importable — it dies before any work and the board- auto-blocks (#122299). Same-interpreter child, so the root is version-safe- to propagate: the entries the scrub removes are dangerous only for a- different interpreter's compiled modules. ``hermes_cli.main``'s own- bootstrap then owns dependency activation as usual.+ auto-blocks (#122299, #122487, #122500). Same-interpreter child, so the+ root is version-safe to propagate; ``hermes_cli.main``'s own bootstrap+ then owns dependency activation as usual. A resolved shim path owns its+ imports and is left alone. Same pin cron's external worker uses (#112729)."""if cmd[1:3] != ["-m", "hermes_cli.main"]:return- root = str(Path(__file__).resolve().parents[1])- parts = [p for p in env.get("PYTHONPATH", "").split(os.pathsep) if p]- if os.path.normcase(root) not in {os.path.normcase(p) for p in parts}:- env["PYTHONPATH"] = os.pathsep.join([root, *parts])+ from cron.scheduler_worker_env import pin_hermes_tree_on_pythonpath++ pin_hermes_tree_on_pythonpath(env, Path(__file__).resolve().parents[1])def _absolute_hermes_path(path: str) -> str:diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.pyindex 56387bcafa3..0734a74703b 100644--- a/tests/hermes_cli/test_kanban_db.py+++ b/tests/hermes_cli/test_kanban_db.py@@ -1619,16 +1619,16 @@ def test_resolve_hermes_argv_module_actually_runs():)-def test_worker_module_argv_puts_package_root_on_child_pythonpath():+def test_default_spawn_pins_repo_root_on_module_worker_pythonpath(tmp_path, monkeypatch):"""A module-form worker must carry the import context that selected it.``_resolve_hermes_argv`` proves ``hermes_cli`` importable in the gateway,where a store-python shim has the repo root on ``sys.path`` in-process;- the spawned bare ``sys.executable -m hermes_cli.main`` child cannot see- that injection and dies on import, auto-blocking the board (#122299).- The dispatcher must prepend the running install's package root to the- child's PYTHONPATH — never for a resolved shim path, which owns its own- imports.+ the worker env scrub strips Hermes-owned PYTHONPATH entries, so the bare+ ``sys.executable -m hermes_cli.main`` child died on import and the board+ auto-blocked (#122299, #122487, #122500). The spawned env must put the+ running install's root first on PYTHONPATH — and never for a resolved shim+ path, which owns its own imports."""import osimport sys@@ -1637,54 +1637,38 @@ def test_worker_module_argv_puts_package_root_on_child_pythonpath():from hermes_cli import kanban_db_dispatch as kbdroot = str(Path(kbd.__file__).resolve().parents[1])+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.delenv("HERMES_KANBAN_HOME", raising=False)+ monkeypatch.delenv("PYTHONPATH", raising=False)+ monkeypatch.delenv("HERMES_BIN", raising=False)- env: dict = {}- kbd._propagate_module_import_root([sys.executable, "-m", "hermes_cli.main"], env)- assert env["PYTHONPATH"].split(os.pathsep)[0] == root-- # Existing entries survive, the root lands first, and it is not duplicated.- env = {"PYTHONPATH": os.pathsep.join(("/opt/other", root))}- kbd._propagate_module_import_root([sys.executable, "-m", "hermes_cli.main"], env)- assert env["PYTHONPATH"].split(os.pathsep) == ["/opt/other", root]-- # A resolved shim path owns its own imports — no PYTHONPATH rewriting.- env = {}- kbd._propagate_module_import_root(["/usr/local/bin/hermes"], env)- assert "PYTHONPATH" not in env+ captured = {}+ class _FakePopen:+ def __init__(self, cmd, **kwargs):+ captured["cmd"] = cmd+ captured["env"] = kwargs.get("env", {})+ self.pid = 4242-def test_module_argv_importable_from_scrubbed_env_at_neutral_cwd(tmp_path):- """The propagated root is exactly what a bare child needs to import.+ monkeypatch.setattr("subprocess.Popen", _FakePopen)- Store-python repro shape (#122299): a bare interpreter launched from a- neutral cwd with no PYTHONPATH cannot import ``hermes_cli`` unless the- package root rides on PYTHONPATH. Execute the resolved module argv's- import question in a real subprocess to prove the propagated value works.- """- import os- import subprocess- import sys- from hermes_cli import kanban_db_dispatch as kbd+ task = kb.Task(+ id="t_import_root", title="x", body=None, assignee="coder", status="ready",+ priority=0, created_by=None, created_at=0, started_at=None, completed_at=None,+ workspace_kind="worktree", workspace_path=str(tmp_path / "ws"), claim_lock=None,+ claim_expires=None, tenant=None, branch_name=None,+ )- env: dict = {}- kbd._propagate_module_import_root([sys.executable, "-m", "hermes_cli.main"], env)- child_env = {"PYTHONPATH": env["PYTHONPATH"]}- if os.name == "nt":- # A Windows python.exe needs SystemRoot for crypto/DLL initialization.- child_env["SystemRoot"] = os.environ["SystemRoot"]+ monkeypatch.setattr(kbd, "_resolve_hermes_argv", lambda: [sys.executable, "-m", "hermes_cli.main"])+ kbd._default_spawn(task, str(tmp_path / "ws"))+ assert captured["env"]["PYTHONPATH"].split(os.pathsep)[0] == root- probe = (- "import importlib.util, sys; "- "sys.exit(0 if importlib.util.find_spec('hermes_cli') is not None else 1)"- )- r = subprocess.run(- [sys.executable, "-c", probe],- cwd=tmp_path, env=child_env, capture_output=True, text=True, timeout=30,- )- assert r.returncode == 0, (- f"bare {sys.executable} could not find hermes_cli from {tmp_path} "- f"with only PYTHONPATH={child_env['PYTHONPATH']!r}; stderr={r.stderr[:200]!r}"- )+ monkeypatch.setattr(kbd, "_resolve_hermes_argv", lambda: ["/opt/hermes/bin/hermes"])+ kbd._default_spawn(task, str(tmp_path / "ws"))+ assert root not in captured["env"].get("PYTHONPATH", "").split(os.pathsep)# ---------------------------------------------------------------------------