The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-mode): preserve delivery uncertainty on bootstrap exit
Neomail2875635bb1881
diff --git a/tests/tools/test_bot_dm_activation_failure.py b/tests/tools/test_bot_dm_activation_failure.pynew file mode 100644index 00000000000..3a82d846f67--- /dev/null+++ b/tests/tools/test_bot_dm_activation_failure.py@@ -0,0 +1,118 @@+"""Offline failure contract on top of the runner bootstrap in PR #123070.++The child may fail dependency activation AFTER the parent has durably admitted the DM.+No transport, live owner, external profile, or network is used here.+"""+import json+import os+from pathlib import Path+import shlex+import subprocess+import sys++from tools import bot_mode_dm as dm+++# Execute the actual script entrypoint; only the external activation boundary is sabotaged.+# An in-process runpy call would inherit the parent's already-activated package state.+_CHILD = """import builtins, runpy, sys+original = builtins.__import__+def blocked(name, *args, **kwargs):+ if name == 'hermes_bootstrap':+ raise RuntimeError('test: dependency generation unavailable')+ return original(name, *args, **kwargs)+builtins.__import__ = blocked+sys.argv = sys.argv[1:]+runpy.run_path(sys.argv[0], run_name='__main__')+"""+++def _failed_child(tmp_path, dm_file, profile_home, *, waiter=False, command=None):+ argv = (["--wait-reply", str(tmp_path / "reply.json"), "@peer", "1"] if waiter else+ ["--run-delivery", "query-file", str(dm_file), "--profile-home", str(profile_home),+ "/nonexistent/transport"])+ runner = shlex.split(command) if command else [sys.executable, str(Path(dm.__file__).resolve()), *argv]+ assert runner[1] == str(Path(dm.__file__).resolve())+ env = {k: v for k, v in os.environ.items() if k not in+ ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV", "HERMES_RUNTIME_DIR") and+ not (k.endswith("_KEY") or k.endswith("_TOKEN"))}+ env["HERMES_HOME"] = str(tmp_path / "isolated-hermes")+ env["HOME"] = str(tmp_path)+ env["TMPDIR"] = str(tmp_path)+ return subprocess.run([runner[0], "-c", _CHILD, *runner[1:]],+ cwd=str(Path(dm.__file__).resolve().parents[1]), env=env,+ capture_output=True, text=True, timeout=20)+++def test_parent_admission_then_child_activation_failure_remains_unknown(tmp_path, monkeypatch):+ profile_home = tmp_path / "recipient"+ profile_home.mkdir()+ dm_file = tmp_path / "dm.txt"+ monkeypatch.setattr(dm, "_write_dm_file", lambda content: (dm_file.write_text(content), str(dm_file))[1])+ observed = {}++ def admitted(home, path, author):+ assert home == profile_home and path == str(dm_file)+ delivery_id = dm._dm_delivery_id(path)+ Path(path + ".live.json").write_text(json.dumps({"delivery_id": delivery_id}))+ receipt = profile_home / "runtime" / "bot_live_delivery" / f"{delivery_id}.json"+ receipt.parent.mkdir(parents=True)+ receipt.write_text(json.dumps({"status": "queued"}))+ return {"status": "queued", "delivery_id": delivery_id}++ def spawn(command, label, *, task_id, agent):+ result = _failed_child(tmp_path, dm_file, profile_home, command=command)+ observed["child"] = result+ return json.dumps({"process_id": "offline-only"})++ monkeypatch.setattr(dm, "_admit_live_dm", admitted)+ monkeypatch.setattr(dm, "_spawn_delivery", spawn)+ parent = json.loads(dm._start_delivery(["/nonexistent/transport"], "offline-message", "@peer",+ stdin_file=False, task_id=None, agent=None,+ profile_home=profile_home))+ child = observed["child"]+ result = json.loads(child.stdout.strip())+ assert parent["status"] == "queued" and child.returncode == 1+ assert result["status"] == "ambiguous" and result["outcome"] == "UNKNOWN"+ assert result["delivery_id"] == parent["delivery_id"]+ assert "Do not resend" in result["detail"]+ assert dm_file.exists()+++def test_activation_fails_before_admission_only_with_strong_absence_evidence(tmp_path):+ profile_home = tmp_path / "recipient"+ profile_home.mkdir()+ dm_file = tmp_path / "dm.txt"+ dm_file.write_text("offline-message")+ child = _failed_child(tmp_path, dm_file, profile_home)+ result = json.loads(child.stdout.strip())+ assert child.returncode == 1 and result["status"] == "not_delivered"+ assert result["delivery_id"] == dm._dm_delivery_id(str(dm_file))+ assert dm_file.exists()++ # A receipt with no intent, or a truncated intent, still forbids a resend.+ receipt = profile_home / "runtime" / "bot_live_delivery" / f"{dm._dm_delivery_id(str(dm_file))}.json"+ receipt.parent.mkdir(parents=True)+ receipt.write_text(json.dumps({"status": "queued"}))+ child = _failed_child(tmp_path, dm_file, profile_home)+ result = json.loads(child.stdout.strip())+ assert child.returncode == 1 and result["status"] == "ambiguous"+ receipt.unlink()+ Path(str(dm_file) + ".live.json").write_text("")+ child = _failed_child(tmp_path, dm_file, profile_home)+ result = json.loads(child.stdout.strip())+ assert child.returncode == 1 and result["status"] == "ambiguous"++ Path(str(dm_file) + ".live.json").unlink()+ child = _failed_child(tmp_path, dm_file, profile_home,+ command=shlex.join([sys.executable, str(Path(dm.__file__).resolve()),+ "--run-delivery", "query-file", str(dm_file),+ "/nonexistent/transport"]))+ assert json.loads(child.stdout)["outcome"] == "UNKNOWN" # no pinned receipt home+ dm_file.unlink()+ child = _failed_child(tmp_path, dm_file, profile_home)+ assert json.loads(child.stdout)["outcome"] == "UNKNOWN" # payload vanished++ (tmp_path / "reply.json").write_text(json.dumps({"reply": "offline-pong"}))+ waiter = _failed_child(tmp_path, dm_file, profile_home, waiter=True)+ assert waiter.returncode == 0 and "offline-pong" in waiter.stdoutdiff --git a/tests/tools/test_bot_mode_dm_entry.py b/tests/tools/test_bot_mode_dm_entry.pyindex 91b31b03e58..c7dd3c50ae1 100644--- a/tests/tools/test_bot_mode_dm_entry.py+++ b/tests/tools/test_bot_mode_dm_entry.py@@ -112,6 +112,49 @@ def test_delivery_runner_that_cannot_activate_names_the_repair_remedy(tmp_path,assert dm_file.read_text(encoding="utf-8") == "hello teammate"[email protected]("evidence,expected", [+ ("none", "ambiguous"),+ ("intent", "ambiguous"),+ ("receipt", "ambiguous"),+ ("unreadable_intent", "ambiguous"),+ ("missing_dm", "ambiguous"),+ ("unpinned_home", "ambiguous"),+])+def test_real_bootstrap_failure_reports_admission_evidence(tmp_path, uncommittable_home, evidence, expected):+ """Exercise native activate_dependencies -> SystemExit, not an import replacement."""+ _home, env = uncommittable_home+ profile = tmp_path / "recipient"+ profile.mkdir()+ dm_file = tmp_path / "dm.txt"+ dm_file.write_text("offline-message", encoding="utf-8")+ from tools.bot_mode_dm import _dm_delivery_id+ delivery_id = _dm_delivery_id(str(dm_file))+ if evidence == "intent":+ Path(str(dm_file) + ".live.json").write_text('{"status":"queued"}')+ elif evidence == "unreadable_intent":+ Path(str(dm_file) + ".live.json").write_text("")+ elif evidence == "receipt":+ receipt = profile / "runtime" / "bot_live_delivery" / f"{delivery_id}.json"+ receipt.parent.mkdir(parents=True)+ receipt.write_text('{"status":"queued"}')+ elif evidence == "missing_dm":+ dm_file.unlink()+ argv = [*BARE, str(RUNNER), "--run-delivery", "query-file", str(dm_file)]+ if evidence != "unpinned_home":+ argv.extend(["--profile-home", str(profile)])+ result = _run([*argv, sys.executable, "-c", "pass"], env)+ assert result.returncode == 1, result+ assert "hermes pm repair" in result.stderr+ payload = json.loads(result.stdout)+ assert payload["status"] == expected+ assert payload["delivery_id"] == delivery_id+ if expected == "ambiguous":+ assert payload["outcome"] == "UNKNOWN"+ assert "Do not resend" in payload["detail"]+ else:+ assert dm_file.exists()++@pytest.mark.parametrize("home", ["committed_home", "uncommittable_home"])def test_reply_waiter_prints_the_reply_whatever_the_dependency_state(tmp_path, request, home):"""The relay's reply waiter shares the entry but is stdlib only, and its stdout is thediff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 3cb196a36f0..63f5e233e9e 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -825,6 +825,57 @@ def _session_title(agent: Any) -> str:return ""+def _activation_failure_status(args: list[str], error: str) -> dict:+ """Classify boot failure without mistaking a pre-admitted DM for non-delivery.++ This absence proof assumes the supported one-runner-per-unique-DM-file model:+ _write_dm_file creates a fresh file, the parent finishes _admit_live_dm before+ spawning its runner, and _admit_live_dm creates the intent with O_EXCL before+ delivery. If another process can concurrently admit this SAME file, lstat+ absence is not atomic evidence; that unsupported race must be UNKNOWN.+ """+ def absent(path: Path) -> bool:+ try:+ os.lstat(path)+ except FileNotFoundError:+ return True+ except OSError:+ return False+ return False++ rest = args[1:]+ if rest[:1] == ["--author"] and len(rest) >= 2:+ rest = rest[2:]+ dm_file = rest[1] if len(rest) >= 2 and rest[0] in ("stdin", "query-file") else None+ profile_home = rest[3] if len(rest) >= 4 and rest[2] == "--profile-home" else None+ delivery_id = ""+ evidence: dict[str, Any] = {}+ proven_no_effect = False+ if args[:1] == ["--run-delivery"] and dm_file:+ try:+ delivery_id = _dm_delivery_id(dm_file)+ dm_present = Path(dm_file).is_file() and not Path(dm_file).is_symlink()+ except OSError:+ dm_present = False+ intent_absent = absent(Path(dm_file + ".live.json"))+ evidence.update(dm_file_present=dm_present, live_intent_absent=intent_absent)+ receipt_absent = False+ if profile_home is not None:+ receipt = Path(profile_home) / "runtime" / "bot_live_delivery" / f"{delivery_id}.json"+ receipt_absent = absent(receipt)+ evidence["receipt_absent"] = receipt_absent+ # Only a pinned home and the single-runner contract make absence meaningful.+ proven_no_effect = dm_present and intent_absent and receipt_absent+ if proven_no_effect:+ return {"status": "not_delivered", "reason": "dependency_activation_failed",+ "delivery_id": delivery_id, "error": f"{error}; run `hermes pm repair`",+ "evidence": evidence, "detail": "No live intent or receipt was found; the runner stopped before transport. The DM file is kept."}+ return {"status": "ambiguous", "outcome": "UNKNOWN", "reason": "dependency_activation_failed",+ "delivery_id": delivery_id, "evidence_file": dm_file, "evidence": evidence,+ "error": f"{error}; run `hermes pm repair`",+ "detail": "The message may already be admitted to the live owner. Do not resend; reconcile the receipt and target transcript."}++if __name__ == "__main__": # pragma: no cover - exercised as a background process# Spawned as a script with the sender's sys.executable, which under PM is the bare store# interpreter (dependencies are activated in-process, never inherited), so boot like every@@ -832,6 +883,22 @@ if __name__ == "__main__": # pragma: no cover - exercised as a background procesys.path.insert(0, str(Path(__file__).resolve().parent.parent))# The reply waiter is stdlib only and its stdout is the sender's wake-up, so an activation# failure must never exit it before it can print the outcome.- if sys.argv[1:2] != ["--wait-reply"]:- import hermes_bootstrap # noqa: F401+ if sys.argv[1:2] == ["--run-delivery"]:+ try:+ import hermes_bootstrap # noqa: F401+ except SystemExit as exc:+ # Bootstrap can exit after failed activation, but also after a legacy handoff+ # or a Windows relaunch. An exit code alone cannot prove non-delivery.+ # Keep the original zero/non-error exits intact; never catch KeyboardInterrupt.+ if exc.code in (None, 0):+ raise+ status = _activation_failure_status(sys.argv[1:], "bootstrap exited before runner")+ status.update(status="ambiguous", outcome="UNKNOWN", reason="bootstrap_exit_unknown",+ error="Bootstrap exited before runner; see stderr for the original cause",+ detail="Bootstrap exited before delivery status was known. Do not resend; reconcile the receipt and target transcript.")+ print(json.dumps(status))+ raise+ except Exception as exc:+ print(json.dumps(_activation_failure_status(sys.argv[1:], str(exc))))+ raise SystemExit(1) from Noneraise SystemExit(_delivery_main(sys.argv[1:]))