The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(bot-mode): cover delivery runner and sweep orphans
tachyon-r0ae18cdae022
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex 8d7ee933100..5cda3002857 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -10,6 +10,7 @@ import shleximport subprocessimport sysimport textwrap+import timefrom pathlib import Pathimport pytest@@ -386,6 +387,87 @@ def test_delivery_runner_preserves_child_failure_and_unlinks(tmp_path):assert not dm_file.exists()[email protected]("args", [[], ["--run-delivery"], ["--run-delivery", "bad", "x"]])+def test_delivery_main_rejects_invalid_cli(args):+ assert bot_mode_dm._delivery_main(args) == 2++[email protected]("mode", ["stdin", "query-file"])+def test_delivery_main_runs_valid_cli_and_unlinks(tmp_path, mode):+ dm_file = tmp_path / "message.txt"+ dm_file.write_text("secret", encoding="utf-8")+ observed = tmp_path / "observed.txt"+ child = tmp_path / "child.py"+ child.write_text(+ "import pathlib, sys\n"+ "source = sys.stdin if sys.argv[1] == '-' else open(sys.argv[1], encoding='utf-8')\n"+ "with source:\n"+ " pathlib.Path(sys.argv[2]).write_text(source.read(), encoding='utf-8')\n",+ encoding="utf-8",+ )+ source_arg = "-" if mode == "stdin" else str(dm_file)++ returncode = bot_mode_dm._delivery_main(+ [+ "--run-delivery",+ mode,+ str(dm_file),+ sys.executable,+ str(child),+ source_arg,+ str(observed),+ ]+ )++ assert returncode == 0+ assert observed.read_text(encoding="utf-8") == "secret"+ assert not dm_file.exists()+++def test_delivery_main_maps_launch_exception_to_one_and_unlinks(tmp_path, monkeypatch):+ dm_file = tmp_path / "message.txt"+ dm_file.write_text("secret", encoding="utf-8")++ def boom(*args, **kwargs):+ raise RuntimeError("child launch failed")++ monkeypatch.setattr(subprocess, "run", boom)+ assert (+ bot_mode_dm._delivery_main(+ ["--run-delivery", "query-file", str(dm_file), "missing-transport"]+ )+ == 1+ )+ assert not dm_file.exists()++[email protected]("stdin_file", [False, True])+def test_real_delivery_command_round_trip(tmp_path, stdin_file):+ dm_file = tmp_path / "message with spaces.txt"+ dm_file.write_text("secret λ\nsecond line", encoding="utf-8")+ observed = tmp_path / "observed with spaces.txt"+ child = tmp_path / "child with spaces.py"+ child.write_text(+ "import pathlib, sys\n"+ "source = sys.stdin if sys.argv[1] == '-' else open(sys.argv[1], encoding='utf-8')\n"+ "with source:\n"+ " pathlib.Path(sys.argv[2]).write_text(source.read(), encoding='utf-8')\n",+ encoding="utf-8",+ )+ source_arg = "-" if stdin_file else str(dm_file)+ command = bot_mode_dm._delivery_command(+ [sys.executable, str(child), source_arg, str(observed)],+ str(dm_file),+ stdin_file=stdin_file,+ )++ result = subprocess.run(shlex.split(command), check=False)++ assert result.returncode == 0+ assert observed.read_text(encoding="utf-8") == "secret λ\nsecond line"+ assert not dm_file.exists()++@pytest.mark.parametrize(("terminal_result", "raises"),[@@ -445,7 +527,8 @@ def test_write_dm_file_unlinks_partial_file_on_write_exception(tmp_path, monkeypreal_mkstemp = bot_mode_dm.tempfile.mkstempdef fixed_mkstemp(**kwargs):- return real_mkstemp(dir=tmp_path, **kwargs)+ kwargs["dir"] = tmp_path+ return real_mkstemp(**kwargs)class BrokenWriter:def __enter__(self):@@ -462,4 +545,29 @@ def test_write_dm_file_unlinks_partial_file_on_write_exception(tmp_path, monkeypwith pytest.raises(OSError, match="disk full"):bot_mode_dm._write_dm_file("secret")- assert list(tmp_path.glob("hermes-dm-*.txt")) == []+ assert list(tmp_path.glob("dm-*.txt")) == []+++def test_sweeper_removes_only_stale_dm_files(tmp_path, monkeypatch):+ dm_dir = tmp_path / bot_mode_dm._DM_DIR_NAME+ dm_dir.mkdir()+ legacy_stale = tmp_path / "hermes-dm-stale.txt"+ stale = dm_dir / "dm-stale.txt"+ fresh = dm_dir / "dm-fresh.txt"+ unrelated = tmp_path / "other.txt"+ for path in (legacy_stale, stale, fresh, unrelated):+ path.write_text("secret", encoding="utf-8")+ now = time.time()+ old = now - bot_mode_dm._DM_STALE_SECONDS - 1+ import os++ os.utime(legacy_stale, (old, old))+ os.utime(stale, (old, old))+ monkeypatch.setattr(bot_mode_dm.tempfile, "gettempdir", lambda: str(tmp_path))++ bot_mode_dm._sweep_stale_dm_files(now=now)++ assert not legacy_stale.exists()+ assert not stale.exists()+ assert fresh.exists()+ assert unrelated.exists()diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex dbacb11e3c8..7092ed5e88b 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -60,6 +60,12 @@ MESSAGE_AGENT_TOOL_NAME = "message_agent"# runaway paste can't turn one DM into a context bomb on the recipient.MESSAGE_MAX_CHARS = 16000+# A runner normally owns and removes each file. This bounds the residual+# plaintext lifetime if the machine dies after background-spawn acknowledgement+# but before the runner reaches its ``finally`` block.+_DM_DIR_NAME = "hermes-dm"+_DM_STALE_SECONDS = 24 * 60 * 60+_PEER_TARGET_RE = re.compile(r"^([a-z0-9][a-z0-9_-]{0,63})/([a-zA-Z0-9][a-zA-Z0-9_-]{0,63})$")_LOCAL_TARGET_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")@@ -413,9 +419,34 @@ def _try_relay_delivery(return None+def _dm_dir() -> Path:+ path = Path(tempfile.gettempdir()) / _DM_DIR_NAME+ path.mkdir(mode=0o700, parents=True, exist_ok=True)+ return path+++def _sweep_stale_dm_files(*, now: float | None = None) -> None:+ """Best-effort cleanup for files orphaned before their runner started."""+ cutoff = (time.time() if now is None else now) - _DM_STALE_SECONDS+ # Include the legacy temp-root location so upgrades clean files created by+ # versions predating the dedicated directory.+ locations = ((Path(tempfile.gettempdir()), "hermes-dm-*.txt"), (_dm_dir(), "*.txt"))+ for directory, pattern in locations:+ try:+ for candidate in directory.glob(pattern):+ try:+ if candidate.is_file() and candidate.stat().st_mtime < cutoff:+ candidate.unlink()+ except OSError:+ pass+ except OSError:+ pass++def _write_dm_file(content: str) -> str:"""The message rides a temp file — never inline shell text."""- fd, path = tempfile.mkstemp(prefix="hermes-dm-", suffix=".txt", text=True)+ _sweep_stale_dm_files()+ fd, path = tempfile.mkstemp(prefix="dm-", suffix=".txt", dir=_dm_dir(), text=True)try:with os.fdopen(fd, "w", encoding="utf-8") as f:f.write(content)@@ -442,6 +473,8 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool) -> int:"""Run one DM transport and remove its plaintext file after consumption."""try:if stdin_file:+ # Keep the file open until the transport exits; cleanup occurs+ # after subprocess.run returns, not merely after stdin reaches EOF.with open(dm_file, "r", encoding="utf-8") as stream:return subprocess.run(argv, stdin=stream, check=False).returncodereturn subprocess.run(@@ -494,11 +527,16 @@ def _spawn_delivery(command: str,label: str,*,- dm_file: str,+ dm_file: Optional[str] = None,task_id: Optional[str],agent: Any,) -> str:- """Launch the cleanup-owning runner and transfer file ownership on ack."""+ """Launch the cleanup-owning runner and transfer file ownership on ack.++ ``dm_file`` is None for relay deliveries: the waiter command watches a+ reply file, and the envelope artifacts are owned and swept by+ ``tools/bot_relay.py`` — there is no plaintext DM tempfile to reclaim.+ """transferred = Falsetry:from tools.terminal_tool import terminal_tool@@ -539,7 +577,7 @@ def _spawn_delivery(logger.error("message_agent delivery spawn failed: %s", exc, exc_info=True)return _err(f"Delivery to {label} could not be started: {exc}")finally:- if not transferred:+ if dm_file and not transferred:_unlink_dm_file(dm_file)