Skip to content

The agent that grows with you

fix(cron): spawn bot-chat delivery from a live cwd

686f6c61c89be4c52d38
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index afb9109d6c6..2a7dc5dafe4 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -742,6 +742,9 @@ def _run_bot_chat_turn(argv: list, env: dict, report_path: str, timeout: float)
"""
from hermes_cli.quiet_single_query import read_turn_report
+ # The scheduler may sit in a directory that no longer exists (a kanban worker whose
+ # scratch workspace was reaped): a child inheriting that cwd dies at CLI startup
+ # (#102941). The target home is the one directory this lane has already verified.
# Lossy decode everywhere; on Windows also decode as the UTF-8 the child writes.
# A stray non-UTF-8 byte (e.g. a grandchild sharing the pipe interleaving a
# partial multi-byte write) must not raise UnicodeDecodeError in the drain
@@ -760,7 +763,7 @@ def _run_bot_chat_turn(argv: list, env: dict, report_path: str, timeout: float)
popen_kwargs["encoding"] = "utf-8"
proc = subprocess.Popen(
argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
- env=env, creationflags=windows_hide_flags(), **popen_kwargs)
+ env=env, cwd=env.get("HERMES_HOME") or None, creationflags=windows_hide_flags(), **popen_kwargs)
streams: dict = {}
def _drain() -> None:
diff --git a/hermes_cli/_startup_fast.py b/hermes_cli/_startup_fast.py
index e72c5672292..74491fbf006 100644
--- a/hermes_cli/_startup_fast.py
+++ b/hermes_cli/_startup_fast.py
@@ -53,12 +53,26 @@ def normalize_hermes_home_env() -> None:
os.environ["HERMES_HOME"] = expanded
+def _realpath_or_self(path: str) -> str:
+ """``os.path.realpath`` that survives a deleted cwd.
+
+ A relative ``sys.path`` entry is resolved through ``os.getcwd()``, which raises
+ ``FileNotFoundError`` once the directory the process started in has been removed
+ (a cron delivery child spawned from a reaped scratch workspace, #102941); the CLI
+ then dies before it can parse argv.
+ """
+ try:
+ return os.path.realpath(path)
+ except OSError:
+ return path
+
+
def ensure_project_root_on_path() -> None:
"""Put the project root at sys.path[0], deduping realpath-equivalents."""
project_root = project_root_str()
- normalized_root = os.path.normcase(os.path.realpath(project_root))
+ normalized_root = os.path.normcase(_realpath_or_self(project_root))
sys.path[:] = [entry for entry in sys.path
- if not entry or os.path.normcase(os.path.realpath(entry)) != normalized_root]
+ if not entry or os.path.normcase(_realpath_or_self(entry)) != normalized_root]
sys.path.insert(0, project_root)
diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.py
index 69f8aa1afbe..e0f2c6a320d 100644
--- a/tests/cron/test_cron_bot_chat_delivery.py
+++ b/tests/cron/test_cron_bot_chat_delivery.py
@@ -277,6 +277,29 @@ def test_turn_report_books_the_delivery_while_the_child_still_lingers(tmp_path):
proc.wait(timeout=10)
[email protected](os.name == "nt", reason="Windows refuses to remove the process cwd; no such fixture there")
+def test_delivery_child_runs_in_the_target_home_not_the_schedulers_cwd(tmp_path, monkeypatch):
+ """The spawn pins ``cwd`` to the target home: a scheduler left in a reaped kanban scratch
+ workspace must not hand its dead cwd to the child, which then dies before argv (#102941)."""
+ home = tmp_path / "home"
+ home.mkdir()
+ report = tmp_path / "turn.json"
+ gone = tmp_path / "scratch"
+ gone.mkdir()
+ monkeypatch.chdir(gone)
+ gone.rmdir()
+ child = textwrap.dedent("""
+ import os, sys
+ from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV, write_turn_report
+ sys.stdout.write(os.getcwd())
+ write_turn_report(os.environ.pop(TURN_REPORT_FILE_ENV), exit_code=0)
+ """)
+ env = {**_child_env(), "HERMES_HOME": str(home), TURN_REPORT_FILE_ENV: str(report)}
+ result = sched_delivery._run_bot_chat_turn([sys.executable, "-c", child], env, str(report), timeout=30)
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == os.path.realpath(home)
+
+
def test_turn_that_never_ends_is_still_killed_at_the_cap(tmp_path):
"""Control: with no turn report the cap stays the guard it always was."""
started = time.monotonic()
diff --git a/tests/hermes_cli/test_startup_fast_guards.py b/tests/hermes_cli/test_startup_fast_guards.py
index 27aed5712f3..d583ac51813 100644
--- a/tests/hermes_cli/test_startup_fast_guards.py
+++ b/tests/hermes_cli/test_startup_fast_guards.py
@@ -22,6 +22,8 @@ import subprocess
import sys
from pathlib import Path
+import pytest
+
REPO_ROOT = Path(__file__).resolve().parents[2]
# Modules that must NEVER be imported by the fast path. Each one either
@@ -39,6 +41,35 @@ _FORBIDDEN_MODULES = (
)
[email protected](os.name == "nt", reason="Windows refuses to remove the process cwd; no such fixture there")
+def test_cli_starts_from_a_deleted_cwd(tmp_path):
+ """A child spawned into a directory that was removed since (a cron delivery from a reaped
+ kanban workspace) must still reach argv parsing: a relative ``sys.path`` entry made
+ ``ensure_project_root_on_path`` die in ``realpath`` → ``getcwd`` (#102941)."""
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ gone = tmp_path / "scratch"
+ gone.mkdir()
+ # The child needs the checkout on sys.path by absolute name; the cwd is exactly what is gone.
+ env = {**os.environ, "HERMES_HOME": str(home), "TERMUX_VERSION": "",
+ "PYTHONPATH": os.pathsep.join(p for p in (str(REPO_ROOT), os.environ.get("PYTHONPATH")) if p)}
+ env.pop("HERMES_DEV", None)
+ fd = os.open(gone, os.O_RDONLY)
+ try:
+ gone.rmdir()
+ # ``cwd=`` of a removed path is refused by Popen, so start in the dead dir via a
+ # preexec fchdir onto its still-open handle — the shape a reaped workspace leaves behind.
+ result = subprocess.run(
+ [sys.executable, "-m", "hermes_cli.main", "--version"],
+ capture_output=True, text=True, timeout=60, env=env,
+ cwd=REPO_ROOT, preexec_fn=lambda: os.fchdir(fd))
+ finally:
+ os.close(fd)
+ assert result.returncode == 0, result.stderr
+ assert "Hermes Agent v" in result.stdout
+ assert "FileNotFoundError" not in result.stderr
+
+
def test_startup_fast_import_weight():
"""Importing _startup_fast must not drag in any heavy module."""
probe = (