Skip to content

The agent that grows with you

fix(bot-mode): only a live-admitted DM stays ambiguous when the runner cannot boot

kshitijk4poorbe0a4147aa21
diff --git a/tests/tools/test_bot_dm_activation_failure.py b/tests/tools/test_bot_dm_activation_failure.py
deleted file mode 100644
index 3a82d846f67..00000000000
--- a/tests/tools/test_bot_dm_activation_failure.py
+++ /dev/null
@@ -1,118 +0,0 @@
-"""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.stdout
diff --git a/tests/tools/test_bot_mode_dm_entry.py b/tests/tools/test_bot_mode_dm_entry.py
index c7dd3c50ae1..a15d6dbd170 100644
--- a/tests/tools/test_bot_mode_dm_entry.py
+++ b/tests/tools/test_bot_mode_dm_entry.py
@@ -22,6 +22,7 @@ import pytest
from pm.environments import install_state_dir, runtime_facts_path, site_packages
from tools import bot_relay
+from tools.bot_mode_dm import _dm_delivery_id
REPO = Path(__file__).resolve().parents[2]
RUNNER = REPO / "tools" / "bot_mode_dm.py"
@@ -109,50 +110,30 @@ def test_delivery_runner_that_cannot_activate_names_the_repair_remedy(tmp_path,
assert result.returncode == 1, result
assert "hermes pm repair" in result.stderr
assert "No module named" not in result.stdout + result.stderr
+ assert result.stdout == "" # nothing was handed over, so no "do not resend" outcome
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."""
+def test_delivery_runner_that_cannot_activate_after_live_admission_stays_ambiguous(tmp_path, uncommittable_home):
+ """The sender may already have admitted this DM to the live owner (its pinned intent exists)
+ and was told not to resend. A runner that then cannot activate must keep that outcome
+ unknown, with the same delivery id, instead of a bare repair hint that reads as a failure."""
_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)
+ dm_file.write_text("hello teammate", encoding="utf-8")
+ intent = Path(str(dm_file) + ".live.json")
+ intent.write_text("{}", encoding="utf-8")
+
+ result = _run([*BARE, str(RUNNER), "--run-delivery", "query-file", str(dm_file),
+ "--profile-home", str(tmp_path), 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()
+ assert payload["status"] == "ambiguous"
+ assert payload["delivery_id"] == _dm_delivery_id(str(dm_file))
+ assert "Do not resend" in payload["error"]
+ assert dm_file.exists() and intent.exists()
@pytest.mark.parametrize("home", ["committed_home", "uncommittable_home"])
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index 63f5e233e9e..a394dd8ef6b 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -540,6 +540,21 @@ def _local_delivery_home(argv: list[str]) -> Path | None:
return dict(_roster(_hermes_root(Path(_default_home())))).get(argv[2])
+def _live_outcome_unknown(dm_file: str, cause: object) -> str:
+ """The runner's stdout when a live admission may have happened but its outcome is unknown."""
+ return json.dumps({"status": "ambiguous", "delivery_id": _dm_delivery_id(dm_file),
+ "error": f"Live admission outcome unknown: {cause}. Do not resend.",
+ "evidence_file": dm_file})
+
+
+def _runner_dm_file(args: list[str]) -> Optional[str]:
+ """The DM file named by ``--run-delivery [--author <json>] <mode> <dm_file> …`` argv."""
+ rest = args[1:]
+ if rest[:1] == ["--author"]:
+ rest = rest[2:]
+ return rest[1] if len(rest) >= 2 and rest[0] in ("stdin", "query-file") else None
+
+
def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,
profile_home: Path | None = None, author: Optional[dict] = None) -> int:
"""Route to the live owner before attempting a CLI transport. Live deliveries
@@ -561,9 +576,7 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,
try:
record = _admit_live_dm(home, dm_file, author)
except Exception as exc:
- print(json.dumps({"status": "ambiguous", "delivery_id": _dm_delivery_id(dm_file),
- "error": f"Live admission outcome unknown: {exc}. Do not resend.",
- "evidence_file": dm_file}))
+ print(_live_outcome_unknown(dm_file, exc))
return 1
if record is not None:
return _wait_live_dm(record["profile_home"], record["delivery_id"], dm_file=dm_file)
@@ -825,80 +838,24 @@ 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
# entry point before the lazy Hermes imports. Run as a path, sys.path[0] is tools/.
sys.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.
+ # Only the delivery lane boots: 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.
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))
+ except (Exception, SystemExit) as exc:
+ # A pinned live intent means the sender may already have admitted this DM and was
+ # told not to resend; a bare repair hint would read as "NOT delivered". Without an
+ # intent nothing was handed over, so the plain failure is the truth.
+ dm_file = _runner_dm_file(sys.argv[1:])
+ failed = not isinstance(exc, SystemExit) or exc.code not in (None, 0)
+ if failed and dm_file and os.path.exists(dm_file + ".live.json"):
+ print(_live_outcome_unknown(dm_file, "the delivery runner could not activate "
+ "Hermes dependencies (see stderr)"))
raise
- except Exception as exc:
- print(json.dumps(_activation_failure_status(sys.argv[1:], str(exc))))
- raise SystemExit(1) from None
raise SystemExit(_delivery_main(sys.argv[1:]))