The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: migrate adjacent bot tests off the retired local CLI turn and mailbox claim
Teknium5409d89a2df9
diff --git a/tests/cron/test_cron_live_bot_delivery.py b/tests/cron/test_cron_live_bot_delivery.pyindex 70fbd6ccc78..057db2224b1 100644--- a/tests/cron/test_cron_live_bot_delivery.py+++ b/tests/cron/test_cron_live_bot_delivery.py@@ -6,6 +6,32 @@ from cron import scheduler_delivery as deliveryfrom tools import bot_live_delivery as mailbox+class _FakeAuthority:+ """The profile authority's canonical deliver door: one admission per stable+ id, exact retries inspect the committed state, the owner may settle it."""++ def __init__(self):+ self.records = {}++ def __call__(self, home, 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="", error="", reason="")+ with mailbox._locked(home) as root:+ mailbox._write(root / f"{params['id']}.json", record)+ elif record["message"] != params["message"]:+ raise ValueError("admission_conflict")+ return dict(record)+++def _owner(home):+ return dict(profile_home=str(Path(home).resolve()), session_id="local-bot", canonical=True,+ lease_id="authority-1", live_session_id="local-bot")++def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypatch):monkeypatch.setattr(Path, "home", lambda: tmp_path)source = tmp_path / "custom-home"@@ -14,12 +40,13 @@ def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypatmonkeypatch.setattr(delivery.subprocess, "run", subprocess_run)from hermes_cli.profiles import get_profile_dir+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)for profile, home in [("", source), ("research", get_profile_dir("research"))]:- owner = dict(profile_home=str(home.resolve()), session_id="bot", lease_id="lease",- live_session_id="live")- discovery = Mock(return_value=owner)+ discovery = Mock(return_value=_owner(home))monkeypatch.setattr(mailbox, "find_canonical_live_owner", discovery)job = dict(id="digest", name="Digest", execution_id="first-run")+ admitted_before = len(authority.records)pending = delivery._deliver_to_bot_chat(job, "payload", profile)assert pending and "queued" in pendingrecords = list((home / "runtime/bot_live_delivery").glob("*.json"))@@ -27,12 +54,15 @@ def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypatkey = records[0].stemrecord = mailbox.read_delivery_result(home, key)assert record and record["message"].endswith("payload")+ # Same execution id -> same stable delivery id, no second admission.discovery.side_effect = AssertionError("receipt must precede discovery")assert delivery._deliver_to_bot_chat(dict(job), "payload", profile) == pending- mailbox.claim_pending_delivery(home, owner)- mailbox.complete_delivery(home, key, status="ambiguous", error="owner died")+ assert key in authority.records and len(authority.records) == admitted_before + 1+ # The owner dies mid-execution: the authority reports the admission ambiguous.+ authority.records[key].update(status="ambiguous", error="owner died")outcome = delivery._deliver_to_bot_chat(dict(job), "payload", profile)- assert outcome and "ambiguous" in outcome+ assert outcome and "ambiguous" in outcome and "owner died" in outcome+ # Only a NEW execution mints a new id.discovery.side_effect = Nonenext_job = dict(job, execution_id="next-run")outcome = delivery._deliver_to_bot_chat(next_job, "payload", profile)@@ -47,9 +77,9 @@ def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))monkeypatch.delenv("_HERMES_CRON_EXTERNAL_WORKER", raising=False)- owner = dict(profile_home=str(tmp_path.resolve()), session_id="bot", lease_id="lease",- live_session_id="live")- monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: owner)+ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: _owner(tmp_path))+ authority = _FakeAuthority()+ monkeypatch.setattr(mailbox, "authority_delivery", authority)monkeypatch.setattr(delivery._sched, "load_config", lambda: {})monkeypatch.setattr(config, "load_gateway_config", lambda: None)monkeypatch.setattr(delivery.subprocess, "run", Mock(side_effect=AssertionError("CLI")))@@ -63,8 +93,9 @@ def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):assert delivery._sched._classify_delivery_outcome(delivery_error=error, delivery_queued=queued, should_deliver=True, unresolved_origin=False,normalized_deliver="bot-chat", incident_acked=False, success=True) == "queued"- record = mailbox.claim_pending_delivery(tmp_path, owner)- assert record is not None- mailbox.complete_delivery(tmp_path, record["delivery_id"], status="settled", reply="done")+ (key,) = authority.records+ assert next(iter(queued.values()))["delivery_id"] == key+ authority.records[key].update(status="settled", reply="done")assert delivery._deliver_result(job, "payload") is Noneassert updates[-1]["last_delivery_queued"] is None+diff --git a/tests/tools/test_bot_mode_refusal_contract.py b/tests/tools/test_bot_mode_refusal_contract.pyindex ebd3e29b262..a3fb227e706 100644--- a/tests/tools/test_bot_mode_refusal_contract.py+++ b/tests/tools/test_bot_mode_refusal_contract.py@@ -1,25 +1,5 @@-import json-import sysfrom types import SimpleNamespace-from tools import bot_mode_dm---def test_delivery_uses_refusal_code_before_human_wording(tmp_path, capsys):- for code, message, busy in (- ("SESSION_NOT_OWNED", "Ce chat est occupé.", True),- ("SESSION_COORDINATION_UNAVAILABLE", "Cannot verify whether session already has a live owner", False),- ("SESSION_NOT_OWNED_EXTRA", "Different failure", False),- ):- dm = tmp_path / "message.txt"- dm.write_text("isolated probe", encoding="utf-8")- child = tmp_path / "child.py"- child.write_text(f"import sys\nprint({f'hermes-refusal-reason: {code}'!r}, file=sys.stderr)\nprint({message!r}, file=sys.stderr)\nraise SystemExit(1)\n", encoding="utf-8")- assert bot_mode_dm._run_delivery([sys.executable, str(child)], str(dm), stdin_file=False) == 1- output = capsys.readouterr()- assert (json.loads(output.out)["reason"] == "target_busy") if busy else not output.out- assert not dm.exists()-def test_one_shot_cli_preserves_refusal_reason(monkeypatch, capsys):from cli import HermesCLIdiff --git a/tests/tools/test_bot_turn_lock.py b/tests/tools/test_bot_turn_lock.pyindex 1b02ae6febf..9e942aead8d 100644--- a/tests/tools/test_bot_turn_lock.py+++ b/tests/tools/test_bot_turn_lock.py@@ -142,71 +142,9 @@ def test_turn_wait_seconds_reads_config(monkeypatch):assert bot_relay.turn_wait_seconds() == 7.0-# ── wiring: local teammate delivery (tools/bot_mode_dm.py) ──────────────────---def test_run_delivery_holds_profile_lock_during_turn(root, tmp_path, monkeypatch):- """The local `hermes -p <profile>` turn runs UNDER the profile lock."""- home = root / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- dm = tmp_path / "dm.txt"- dm.write_text("hi", encoding="utf-8")- observed = {}-- def _fake_run(argv, **kwargs):- # While the turn runs, a second acquire on the same profile must fail.- with pytest.raises(TurnBusyError):- with acquire_turn_lock(home, "ops", timeout_seconds=0.15):- pass # pragma: no cover- observed["argv"] = argv-- class _P:- returncode = 0- stdout = ""- stderr = ""-- return _P()-- monkeypatch.setattr(bot_mode_dm.subprocess, "run", _fake_run)- rc = bot_mode_dm._run_delivery(- ["hermes", "-p", "ops", "chat"], str(dm), stdin_file=False- )- assert rc == 0- assert observed["argv"][:3] == ["hermes", "-p", "ops"]- # …and after the turn, the lock is free again.- with acquire_turn_lock(home, "ops", timeout_seconds=0.5):- pass---def test_delivery_main_reports_target_busy_json(root, tmp_path, monkeypatch, capsys):- """A queued delivery that exceeds its budget surfaces the structured error."""- home = root / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(bot_relay, "turn_wait_seconds", lambda: 0.2)- dm = tmp_path / "dm.txt"- dm.write_text("hi", encoding="utf-8")-- held = threading.Event()- release = threading.Event()- t = threading.Thread(- target=_hold_flock, args=(turn_lock_path(home, "ops"), held, release)- )- t.start()- assert held.wait(timeout=5)- try:- rc = bot_mode_dm._delivery_main(- ["--run-delivery", "query-file", str(dm), "hermes", "-p", "ops", "chat"]- )- assert rc == 1- payload = json.loads(capsys.readouterr().out.strip())- assert payload["reason"] == "target_busy" # #93091 item-1 enum extension- assert "ops" in payload["error"]- finally:- release.set()- t.join(timeout=5)- assert not dm.exists(), "DM plaintext must be reclaimed even on refusal"+# ── wiring: peer transport (tools/bot_mode_dm.py) never contends locally ──────+# Retired: the local query-file CLI turn under the profile lock. Local Bot Chat+# delivery is admitted by the profile authority, which owns its own FIFO.def test_peer_stdin_delivery_skips_local_lock(root, tmp_path, monkeypatch):@@ -260,84 +198,3 @@ def test_local_delivery_command_never_reenters_the_lock():assert Path(argv[0]).name in ("hermes", "hermes.exe")assert "--run-delivery" not in argvassert not any("bot_mode_dm" in part for part in argv)---def test_relay_deliver_returns_target_busy_error(tmp_path, monkeypatch):- import tui_gateway.server as srv-- h = tmp_path / "h"- (h / "profiles" / "ops").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(h))- monkeypatch.setattr(bot_relay, "turn_wait_seconds", lambda: 0.2)-- spawned = {}-- # Deterministic spawn detection: sentinel argv from the exact factory the- # deliver handler uses. A global subprocess.run patch also intercepts- # unrelated gateway-init calls (git rev-parse / ls-remote in CI), so- # never fuzzy-match argv — mark the delivery command itself.- monkeypatch.setattr(- bot_relay, "local_delivery_command", lambda prof, tmp: ["__delivery__", prof]- )-- def _fake_run(argv, **kwargs):- argv = list(argv or [])- if argv and argv[0] == "__delivery__":- spawned["argv"] = argv-- class _Done:- returncode = 0- stdout = ""- stderr = ""-- return _Done()-- monkeypatch.setattr("subprocess.run", _fake_run)-- held = threading.Event()- release = threading.Event()- t = threading.Thread(- target=_hold_flock, args=(turn_lock_path(h, "ops"), held, release)- )- t.start()- assert held.wait(timeout=5)- try:- out = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "x"})- assert "error" in out- assert out["error"]["code"] == 5096- assert "target_busy" in out["error"]["message"]- assert not spawned, "turn must not spawn while the profile is busy"- finally:- release.set()- t.join(timeout=5)---def test_relay_deliver_serializes_then_succeeds(tmp_path, monkeypatch):- import tui_gateway.server as srv-- h = tmp_path / "h"- (h / "profiles" / "ops").mkdir(parents=True)- monkeypatch.setenv("HERMES_HOME", str(h))- monkeypatch.setattr(bot_relay, "turn_wait_seconds", lambda: 5.0)-- class _Proc:- returncode = 0- stdout = "pong"- stderr = ""-- monkeypatch.setattr("subprocess.run", lambda *a, **k: _Proc())-- held = threading.Event()- release = threading.Event()- t = threading.Thread(- target=_hold_flock, args=(turn_lock_path(h, "ops"), held, release)- )- t.start()- assert held.wait(timeout=5)- threading.Timer(0.3, release.set).start()- start = time.monotonic()- out = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "x"})- t.join(timeout=5)- assert "error" not in out, out- assert out["result"]["reply"] == "pong"- assert time.monotonic() - start >= 0.2, "deliver should have queued"