The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: migrate message_agent local delivery tests to canonical admission
Tekniumd05be93f13a8
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex 50629a585ad..9f2e789a0c6 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -211,18 +211,59 @@ def _capture_spawn(monkeypatch):return calls+class _FakeAuthority:+ """The target profile's canonical ``bot_relay.deliver`` door: one admission per+ envelope id, exact retries inspect it, a changed payload conflicts."""++ def __init__(self):+ self.calls = []+ self.records = {}++ def __call__(self, home, params):+ from tools import bot_live_delivery as live++ self.calls.append((Path(home).resolve(), dict(params)))+ record = self.records.get(params["id"])+ if record is None:+ record = self.records[params["id"]] = dict(+ status="queued", delivery_id=params["id"], profile_home=str(Path(home).resolve()),+ session_id="local-bot", message=params["message"], admission_id="adm-" + params["id"][:8],+ reply="")+ with live._locked(home) as root:+ live._write(root / f"{params['id']}.json", record)+ elif record["message"] != params["message"]:+ raise ValueError("admission_conflict")+ return {k: record[k] for k in ("status", "delivery_id", "profile_home", "session_id", "reply")}+++def _canonical_target(monkeypatch, target: Path) -> _FakeAuthority:+ from tools import bot_live_delivery as live++ owner = dict(profile_home=str(target.resolve()), session_id="local-bot", canonical=True,+ lease_id="authority-1", live_session_id="local-bot")+ monkeypatch.setattr(live, "find_canonical_live_owner",+ lambda home: owner if Path(home).resolve() == target.resolve() else None)+ authority = _FakeAuthority()+ monkeypatch.setattr(live, "authority_delivery", authority)+ return authority++def _runner_parts(command):parts = shlex.split(command)marker = parts.index("--run-delivery")argv = parts[marker + 3 :]+ profile_home = Noneif argv[:1] == ["--profile-home"]:- argv = argv[2:]- return parts[marker + 1], parts[marker + 2], argv+ profile_home, argv = argv[1], argv[2:]+ return parts[marker + 1], parts[marker + 2], argv, profile_home-def test_local_delivery_command_and_ack(tmp_path, monkeypatch):+def test_local_delivery_admits_canonically_and_acks(tmp_path, monkeypatch):calls = _capture_spawn(monkeypatch)home = _managed_home(tmp_path, teammates=("researcher",))+ target = home / "profiles" / "researcher"+ authority = _canonical_target(monkeypatch, target)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)agent = _FakeAgent(home, title="Bot Chat")result = json.loads(@@ -235,11 +276,17 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):agent=agent,))- assert result["status"] == "sent"+ assert result["status"] == "queued"assert result["to"] == "@researcher"assert result["process_id"] == "proc_test1234"- assert "do NOT wait" in result["detail"]+ assert "Do NOT wait" in result["detail"]+ # Exactly one canonical admission, on the target profile's own authority.+ assert [h for h, _p in authority.calls] == [target.resolve()]+ _home, params = authority.calls[0]+ assert params["id"] == result["delivery_id"] and params["profile"] == "researcher"++ # The background process only waits for the receipt: no model turn argv.assert len(calls) == 1call = calls[0]assert call["background"] is True@@ -247,28 +294,19 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):assert call["_host_local"] is Trueassert Path(call["workdir"]) == Path(bot_mode_dm.__file__).resolve().parent.parentcommand = call["command"]- mode, dm_file, transport_argv = _runner_parts(command)+ mode, dm_file, transport_argv, profile_home = _runner_parts(command)assert mode == "query-file"- assert transport_argv == [- "hermes",- "-p",- "researcher",- "chat",- "--in",- "~",- "-c",- "Bot Chat",- "--create-if-missing",- "-Q",- ]+ assert Path(profile_home) == target.resolve()+ assert transport_argv[:3] == ["hermes", "-p", "researcher"]# message body rides the temp file, never the command lineassert "PAYLOAD_SENTINEL_7A91" not in commandassert "$(" not in command- # attribution prefix applied server-side; body verbatim inside the file+ # attribution prefix applied server-side; body verbatim in the admitted messagecontent = Path(dm_file).read_text(encoding="utf-8")assert content.startswith("Message from π€ hermes (@hermes): ")assert '$(and this is not shell)' in content+ assert params["message"] == contentdef test_peer_delivery_command_pins_registry_profile_for_secondary_bots(@@ -293,7 +331,7 @@ def test_peer_delivery_command_pins_registry_profile_for_secondary_bots(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))assert result["status"] == "sent"- mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[0]["command"])assert mode == "stdin"# The registry the tool validated against is the machine root's β the# default profile's home β so the CLI runs there, not in reviewer.@@ -310,7 +348,7 @@ def test_peer_delivery_command(tmp_path, monkeypatch):)assert result["status"] == "sent"assert "spark" in result["to"]- mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[0]["command"])assert mode == "stdin"assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark/researcher"]@@ -319,32 +357,58 @@ def test_peer_delivery_command(tmp_path, monkeypatch):bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))assert result2["status"] == "sent"- mode, _dm_file, transport_argv = _runner_parts(calls[1]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[1]["command"])assert mode == "stdin"assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark"]def test_named_profile_sender_prefix(tmp_path, monkeypatch):"""A named-profile bot signs with its own handle, not @hermes."""- calls = _capture_spawn(monkeypatch)+ _capture_spawn(monkeypatch)home = _managed_home(tmp_path, teammates=("researcher", "coder"))- profile_home = home / "profiles" / "coder"- agent = _FakeAgent(profile_home, title="Bot Chat")+ authority = _canonical_target(monkeypatch, home / "profiles" / "researcher")+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)+ agent = _FakeAgent(home / "profiles" / "coder", title="Bot Chat")result = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent))- assert result["status"] == "sent"- _mode, dm_file, _transport_argv = _runner_parts(calls[0]["command"])- assert Path(dm_file).read_text(encoding="utf-8").startswith(- "Message from π€ coder (@coder): "- )+ assert result["status"] == "queued"+ assert authority.calls[0][1]["message"].startswith("Message from π€ coder (@coder): ")-def test_spawn_failure_reports_error(tmp_path, monkeypatch):+def test_unavailable_authority_is_reported_never_worked_around(tmp_path, monkeypatch):+ """No canonical target: the sender learns the outcome is unknown and nothing+ else (no CLI, no background runner) is started."""home = _managed_home(tmp_path)agent = _FakeAgent(home, title="Bot Chat")+ from tools import bot_live_delivery as live++ def unavailable(home):+ raise ValueError("profile authority is not ready")+ monkeypatch.setattr(live, "find_canonical_live_owner", unavailable)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)+ import tools.terminal_tool as terminal_tool_module++ monkeypatch.setattr(terminal_tool_module, "terminal_tool",+ lambda *a, **k: pytest.fail("no runner may start without admission"))+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no CLI turn may start"))+ result = json.loads(+ bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent)+ )+ assert result["status"] == "ambiguous"+ assert "not ready" in result["error"] and "Do not resend" in result["error"]+ assert Path(result["evidence_file"]).read_text(encoding="utf-8").endswith("hi")+++def test_notification_spawn_failure_is_reported_after_admission(tmp_path, monkeypatch):+ """The receipt waiter failing to start is a notification problem, surfaced+ beside the (already committed) admission β never a reason to re-admit."""+ home = _managed_home(tmp_path)+ target = home / "profiles" / "researcher"+ authority = _canonical_target(monkeypatch, target)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)import tools.terminal_tool as terminal_tool_moduledef boom(command, **kwargs):@@ -352,10 +416,11 @@ def test_spawn_failure_reports_error(tmp_path, monkeypatch):monkeypatch.setattr(terminal_tool_module, "terminal_tool", boom)result = json.loads(- bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent)+ bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=_FakeAgent(home)))- assert "error" in result- assert "could not be started" in result["error"]+ assert result["status"] == "queued"+ assert "could not be started" in result["notification_error"]+ assert len(authority.records) == 1def test_live_dm_admitted_before_waiter_failure(tmp_path, monkeypatch):@@ -363,8 +428,7 @@ def test_live_dm_admitted_before_waiter_failure(tmp_path, monkeypatch):home = _managed_home(tmp_path)target = home / "profiles" / "researcher"- owner = dict(profile_home=str(target), session_id="bot", lease_id="lease", live_session_id="live")- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner if Path(h) == target else None)+ authority = _canonical_target(monkeypatch, target)monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)monkeypatch.setenv("HERMES_HOME", str(tmp_path / "wrong-home"))import tools.terminal_tool as terminal@@ -374,19 +438,17 @@ def test_live_dm_admitted_before_waiter_failure(tmp_path, monkeypatch):assert result["status"] == "queued"record = live.read_delivery_result(target, result["delivery_id"])assert record is not None- assert record["owner"] == owner- assert record["message"] == "Message from π€ hermes (@hermes): hello"+ assert record["delivery_id"] == result["delivery_id"]+ assert record["profile_home"] == str(target.resolve())+ assert authority.records[result["delivery_id"]]["message"] == "Message from π€ hermes (@hermes): hello"assert "notification_error" in result-def test_live_dm_runner_retry_never_reexecutes_failed_claim(tmp_path, monkeypatch, capsys):- from tools import bot_live_delivery as live-+def test_live_dm_runner_retry_never_reexecutes_failed_admission(tmp_path, monkeypatch, capsys):home = _managed_home(tmp_path)target = home / "profiles" / "researcher"monkeypatch.setenv("HERMES_HOME", str(home))- owner = dict(profile_home=str(target), session_id="bot", lease_id="lease", live_session_id="live")- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner)+ authority = _canonical_target(monkeypatch, target)monkeypatch.setattr(bot_mode_dm, "_LIVE_WAIT_SECONDS", 0)monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("must not launch a model turn"))dm_file = tmp_path / "message.txt"@@ -395,22 +457,23 @@ def test_live_dm_runner_retry_never_reexecutes_failed_claim(tmp_path, monkeypatcassert bot_mode_dm._run_delivery(argv, str(dm_file), stdin_file=False) == 0queued = json.loads(capsys.readouterr().out)assert queued["status"] == "queued"- claimed = live.claim_pending_delivery(target, owner)- assert claimed is not None- live.complete_delivery(target, claimed["delivery_id"], status="failed", error="HTTP 429 rate limit")- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: None)+ # The authority settles the admission as failed; a retry of the same runner+ # reads that exact receipt (same id) and never admits or executes again.+ authority.records[queued["delivery_id"]]["status"] = "failed"+ from tools import bot_live_delivery as live+ monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: pytest.fail("intent is pinned"))assert bot_mode_dm._run_delivery(argv, str(dm_file), stdin_file=False) == 1failed = json.loads(capsys.readouterr().out)assert failed["status"] == "failed"assert failed["delivery_id"] == queued["delivery_id"]+ assert len(authority.records) == 1assert dm_file.read_text(encoding="utf-8") == "hello"-# ββ plaintext tempfile lifecycle βββββββββββββββββββββββββββββββββββββββββββββ+# ββ plaintext tempfile lifecycle (peer stdin transport) βββββββββββββββββββββ[email protected]("stdin_file", [False, True])-def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file):+def test_peer_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path):dm_file = tmp_path / "message with spaces.txt"dm_file.write_text("secret $(not shell)", encoding="utf-8")observed = tmp_path / "observed.txt"@@ -421,19 +484,14 @@ def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file)import pathlibimport sys- source = sys.stdin if sys.argv[1] == "-" else open(sys.argv[1], encoding="utf-8")- with source:- pathlib.Path(sys.argv[2]).write_text(source.read(), encoding="utf-8")+ pathlib.Path(sys.argv[1]).write_text(sys.stdin.read(), encoding="utf-8")"""),encoding="utf-8",)- source_arg = "-" if stdin_file else str(dm_file)returncode = bot_mode_dm._run_delivery(- [sys.executable, str(child), source_arg, str(observed)],- str(dm_file),- stdin_file=stdin_file,+ [sys.executable, str(child), str(observed)], str(dm_file), stdin_file=True)assert returncode == 0@@ -441,7 +499,7 @@ def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file)assert not dm_file.exists()-def test_delivery_runner_unlinks_when_child_launch_raises(tmp_path, monkeypatch):+def test_peer_delivery_runner_unlinks_when_child_launch_raises(tmp_path, monkeypatch):dm_file = tmp_path / "message.txt"dm_file.write_text("secret", encoding="utf-8")@@ -450,80 +508,41 @@ def test_delivery_runner_unlinks_when_child_launch_raises(tmp_path, monkeypatch)monkeypatch.setattr(subprocess, "run", boom)with pytest.raises(RuntimeError, match="child launch failed"):- bot_mode_dm._run_delivery(["hermes"], str(dm_file), stdin_file=False)+ bot_mode_dm._run_delivery(["hermes"], str(dm_file), stdin_file=True)assert not dm_file.exists()-def test_delivery_runner_preserves_child_failure_and_unlinks(tmp_path):+def test_peer_delivery_runner_preserves_child_failure_and_unlinks(tmp_path):dm_file = tmp_path / "message.txt"dm_file.write_text("secret", encoding="utf-8")child = tmp_path / "fail.py"child.write_text(- "import pathlib, sys\n"- "assert pathlib.Path(sys.argv[-1]).read_text(encoding='utf-8') == 'secret'\n"+ "import sys\n"+ "assert sys.stdin.read() == 'secret'\n""raise SystemExit(7)\n",encoding="utf-8",)- returncode = bot_mode_dm._run_delivery(- [sys.executable, str(child)], str(dm_file), stdin_file=False- )+ returncode = bot_mode_dm._run_delivery([sys.executable, str(child)], str(dm_file), stdin_file=True)assert returncode == 7assert not dm_file.exists()-def test_delivery_runner_surfaces_live_owner_refusal(tmp_path, capsys):- """#100523: the CLI's single-owner lease refusal is a delivery FAILURE the- sender can read, not a raw exit-1 with the payload silently gone."""+def test_local_delivery_runner_surfaces_refusal_and_retains_payload(tmp_path, monkeypatch, capsys):+ """A local delivery with no canonical authority is a FAILURE the sender can+ read β typed reason, payload retained β never a CLI turn of its own."""dm_file = tmp_path / "message.txt"dm_file.write_text("hi", encoding="utf-8")- child = tmp_path / "owned.py"- child.write_text(- "import sys\n"- "print('Session abc already has a live owner (desktop, pid 1).', file=sys.stderr)\n"- "raise SystemExit(1)\n",- encoding="utf-8",- )+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no local inference fallback"))- returncode = bot_mode_dm._run_delivery(- [sys.executable, str(child), "-p", "ops"], str(dm_file), stdin_file=False- )+ returncode = bot_mode_dm._run_delivery(["hermes", "-p", "ops"], str(dm_file), stdin_file=False)assert returncode == 1payload = json.loads(capsys.readouterr().out)- assert payload["reason"] == "target_busy"- assert "NOT delivered" in payload["error"]---def test_query_file_delivery_closes_stdin_for_initial_attempt_and_retry(- tmp_path, monkeypatch-):- dm_file = tmp_path / "message.txt"- dm_file.write_text("secret", encoding="utf-8")- calls = []- responses = [- subprocess.CompletedProcess([], 1, stdout="", stderr="HTTP 429 rate limit"),- subprocess.CompletedProcess([], 0, stdout="", stderr=""),- ]-- def fake_run(argv, **kwargs):- calls.append((argv, kwargs))- return responses.pop(0)-- monkeypatch.setattr(subprocess, "run", fake_run)-- returncode = bot_mode_dm._run_delivery(- ["hermes", "-p", "researcher"], str(dm_file), stdin_file=False- )-- assert returncode == 0- assert len(calls) == 2- assert [kwargs["stdin"] for _argv, kwargs in calls] == [- subprocess.DEVNULL,- subprocess.DEVNULL,- ]- assert not dm_file.exists()+ assert payload["reason"] == "runtime_unavailable"+ assert "retained" in payload["error"]+ assert dm_file.read_text(encoding="utf-8") == "hi"@pytest.mark.parametrize("args", [[], ["--run-delivery"], ["--run-delivery", "bad", "x"]])@@ -531,31 +550,19 @@ 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):+def test_delivery_main_runs_peer_transport_and_unlinks(tmp_path):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",+ "pathlib.Path(sys.argv[1]).write_text(sys.stdin.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),- ]+ ["--run-delivery", "stdin", str(dm_file), sys.executable, str(child), str(observed)])assert returncode == 0@@ -573,31 +580,34 @@ def test_delivery_main_maps_launch_exception_to_one_and_unlinks(tmp_path, monkeymonkeypatch.setattr(subprocess, "run", boom)assert (bot_mode_dm._delivery_main(- ["--run-delivery", "query-file", str(dm_file), "missing-transport"]+ ["--run-delivery", "stdin", 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):+def test_delivery_main_local_refusal_retains_payload(tmp_path, monkeypatch, capsys):+ dm_file = tmp_path / "message.txt"+ dm_file.write_text("secret", encoding="utf-8")+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no local inference fallback"))+ assert bot_mode_dm._delivery_main(["--run-delivery", "query-file", str(dm_file), "hermes", "-p", "ghost"]) == 1+ assert json.loads(capsys.readouterr().out)["reason"] == "runtime_unavailable"+ assert dm_file.read_text(encoding="utf-8") == "secret"+++def test_real_peer_delivery_command_round_trip(tmp_path):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",+ "pathlib.Path(sys.argv[1]).write_text(sys.stdin.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,+ [sys.executable, str(child), str(observed)], str(dm_file), stdin_file=True)result = subprocess.run(shlex.split(command), check=False)