The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): stop lifecycle guard false-positives and crashes on .py/binary scripts
CriptoGusc98ed22e4250
diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.pyindex b09635c998b..a50d720f06f 100644--- a/cron/lifecycle_guard.py+++ b/cron/lifecycle_guard.py@@ -219,8 +219,14 @@ def _iter_referenced_shell_scripts(yield _resolve_terminal_script_path(arguments[arg_index], cwd)continue- if "/" in executable or executable.endswith((".sh", ".bash", ".zsh")):- yield _resolve_terminal_script_path(executable, cwd)+ # A bare "/" token is pathlib's division operator in Python sources+ # (e.g. `Path.home() / ".hermes"`), not an executable reference.+ # Resolving it walks to the filesystem root and fails the+ # regular-file check below, hard-blocking innocent .py scripts+ # (#77131). Skip pure-separator tokens.+ if executable.strip("/"):+ if "/" in executable or executable.endswith((".sh", ".bash", ".zsh")):+ yield _resolve_terminal_script_path(executable, cwd)def _iter_shell_command_payloads(command: str) -> Iterator[str]:@@ -267,6 +273,14 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:os.close(descriptor)if len(data) > _MAX_REFERENCED_SCRIPT_BYTES:return None, True+ # A NUL byte in the first chunk means this is a binary (ELF/Mach-O/+ # PE), not a shell script — scanning its decoded contents would+ # tokenize machine code and feed junk paths into the recursion+ # (including a `ValueError: embedded null byte` from Path.resolve,+ # #76762). Treat it as "nothing to scan" rather than unsafe: a binary+ # executed by the user is not a referenced *shell script*.+ if b"\x00" in data:+ return None, Falsereturn data.decode("utf-8", errors="replace"), False@@ -298,7 +312,10 @@ def _contains_unsafe_gateway_action(for script_path in _iter_referenced_shell_scripts(command, cwd=cwd):try:resolved = script_path.resolve(strict=False)- except OSError:+ except (OSError, ValueError):+ # OSError: unreadable/long paths. ValueError: embedded NUL byte+ # from a binary's decoded contents tokenized as a path — a+ # guarded path must never crash the guard (#76762).resolved = script_pathif resolved in visited:continue@@ -392,16 +409,31 @@ def check_gateway_lifecycle(surfaces this as a tool error; the CLI prints it in red and exits 1)."""combined = prompt or ""+ python_script = Falseif script:+ python_script = _resolve_script_path(script).suffix == ".py"script_text = _read_script_for_scanning(script)if script_text:combined = f"{combined}\n{script_text}"- script_dir = _resolve_script_directory(script) if script else None- if contains_gateway_lifecycle_command_or_referenced_script(- combined,- cwd=script_dir,- ):+ if python_script:+ # Python is executed by the interpreter, never through a POSIX+ # shell: the shell-script reference walk is a false-positive+ # generator on Python sources (pathlib's "/" operator resolves to+ # the filesystem root and trips the regular-file check, blocking+ # every innocent .py cron script, #77131). The direct command+ # regex below still scans the full text, so a literal+ # `hermes gateway restart` embedded in a .py script is still+ # blocked. Non-regular/oversized script files still fail closed+ # via the lifecycle-shaped sentinel in _read_script_for_scanning.+ unsafe = contains_gateway_lifecycle_command(combined)+ else:+ script_dir = _resolve_script_directory(script) if script else None+ unsafe = contains_gateway_lifecycle_command_or_referenced_script(+ combined,+ cwd=script_dir,+ )+ if unsafe:raise GatewayLifecycleBlocked("Blocked: cron job contains a gateway lifecycle command or persistent ""launchctl submit operation. This is blocked to prevent agent-driven "diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.pyindex 840e26a0dfa..bd90e991301 100644--- a/tests/hermes_cli/test_gateway_restart_loop.py+++ b/tests/hermes_cli/test_gateway_restart_loop.py@@ -643,6 +643,68 @@ class TestLifecycleGuardModule:with pytest.raises(GatewayLifecycleBlocked):check_gateway_lifecycle("daily", "restart.sh")+ def test_python_script_with_pathlib_division_not_blocked(self, tmp_path):+ """#77131: a .py cron script using pathlib division (Path.home() /+ ".hermes") must NOT be blocked.++ Before the fix, the shell-script reference walk tokenized Python+ sources and treated pathlib's bare "/" operator as an executable+ path resolving to the filesystem root, which fails the+ regular-file check and hard-blocks every innocent .py script.+ Python is executed by the interpreter, never through a POSIX shell,+ so the walk is skipped for .py and only the direct command regex+ runs.+ """+ from cron.lifecycle_guard import check_gateway_lifecycle+ script = tmp_path / "digest.py"+ script.write_text(+ "from pathlib import Path\n"+ 'ENV = Path.home() / ".hermes" / ".env"\n'+ 'print("digest ok")\n'+ )+ check_gateway_lifecycle("clean prompt", str(script))++ def test_python_script_with_literal_lifecycle_command_still_blocked(+ self, tmp_path+ ):+ """#77131: skipping the shell walk for .py must NOT weaken the guard —+ a literal lifecycle command embedded in a .py script is still caught+ by the direct regex scan."""+ from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle+ script = tmp_path / "evil.py"+ script.write_text('import os\nos.system("hermes gateway restart")\n')+ with pytest.raises(GatewayLifecycleBlocked):+ check_gateway_lifecycle("clean prompt", str(script))++ def test_absolute_path_binary_does_not_crash_guard(self):+ """#76762: a terminal command invoking a binary by absolute path+ (e.g. /usr/bin/python3) must not crash the guard with+ ValueError: embedded null byte.++ Before the fix, the walk read the binary's bytes, decoded them as+ text, and re-tokenized machine code containing NUL bytes; the+ recursion then called Path.resolve() on a path with an embedded NUL+ and only OSError was caught. Binaries are now skipped as+ "nothing to scan" and ValueError is tolerated at resolve time.+ """+ from cron.lifecycle_guard import (+ contains_gateway_lifecycle_command_or_referenced_script,+ )+ result = contains_gateway_lifecycle_command_or_referenced_script(+ '/usr/bin/python3 -c "print(1)"'+ )+ assert result is False++ def test_shell_script_reference_walk_still_works(self, tmp_path):+ """The referenced-script walk still applies to real shell scripts:+ a .sh script that itself invokes a lifecycle command is caught."""+ from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle+ script = tmp_path / "wrapper.sh"+ script.write_text("#!/bin/bash\n./deploy.sh\n")+ (tmp_path / "deploy.sh").write_text("#!/bin/bash\nhermes gateway stop\n")+ with pytest.raises(GatewayLifecycleBlocked):+ check_gateway_lifecycle("daily ops", str(script))+# ---------------------------------------------------------------------------# Defense 2 (chokepoint): cron.jobs.create_job blocks the AGENT model-tool path