The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): park a Bot Chat delivery whose target owner is not running
Teknium6ed97629c5d3
diff --git a/cron/bot_chat_legacy.py b/cron/bot_chat_legacy.pyindex 5087f199175..e6ff689ec8f 100644--- a/cron/bot_chat_legacy.py+++ b/cron/bot_chat_legacy.py@@ -1,7 +1,7 @@-"""Upgrade path for ``cron/bot_chat_pending`` records the retired CLI lane left behind.+"""``cron/bot_chat_pending``: Bot Chat outputs whose target owner was not running yet.-The old lane parked never-started Bot Chat outputs there for a later tick to replay-through ``hermes chat``. That consumer is gone; each still-``queued`` record is handed,+``defer`` parks one (a cross-profile target whose gateway is down or still starting), and+the retired CLI lane left records of the same shape behind. Each still-``queued`` record is handed,under its own id, to the target profile's live owner through the canonical``tools.bot_live_delivery.deliver_to_live_owner`` door (idempotent per id). Records arenever deleted: they keep their final status as evidence, exactly as the old drain did.@@ -20,6 +20,18 @@ logger = logging.getLogger(__name__)_warned: set[Path] = set()+def defer(key: str, job: dict, content: str, home: Path, *, for_failure: bool) -> None:+ """Park one never-admitted output under its delivery id; a later tick hands it to the owner."""+ import time+ root = get_hermes_home().resolve() / "cron" / "bot_chat_pending"+ root.mkdir(parents=True, exist_ok=True, mode=0o700)+ path = root / f"{key}.json"+ if not path.exists(): # an existing record (queued or already transferred) keeps its status+ atomic_json_write(path, dict(+ id=key, status="queued", job={k: job[k] for k in ("id", "name") if k in job}, content=content,+ home=str(home), for_failure=for_failure, sequence=time.time_ns()), fsync_dir=True, mode=0o600)++def _queued(root: Path) -> list[tuple[Path, dict]]:found = []for path in root.glob("*.json"):diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex 3571e67ec2a..9a36f425286 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -729,7 +729,8 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *,``suppressed`` — a durable disposition, never a send — and flagged on the job); anythingelse is an explicit unverified status string so Optional[str] callers cannot misreportadmission as delivery. ``profile`` is ``""`` for the job's own profile. There is no- second-writer fallback: without a running authority the payload stays unverified for retry.+ second-writer fallback: a target whose authority is not ready gets the payload parked under+ the same delivery id (``cron.bot_chat_legacy.defer``) and admitted by a later tick."""import hashlibimport json@@ -772,7 +773,13 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *,job["_notification_all_targets_suppressed"] = Truereturn Noneif receipt is None:- owner = find_canonical_live_owner(home)+ try:+ owner = find_canonical_live_owner(home)+ except ValueError: # the target's gateway is down or starting: not a disposition+ from cron.bot_chat_legacy import defer+ defer(key, job, content, home, for_failure=for_failure)+ job.setdefault("_bot_chat_delivery_receipts", {})[target] = {"status": "queued", "delivery_id": key}+ return f"{target} queued (receipt {key}): target profile not running; admitted once it is"if owner is None:return f"bot-chat delivery to profile '{profile_label}' unverified: no canonical Bot Chat"# A failure notice rides as ``diagnostic`` so the target's reply stays muted.diff --git a/tests/cron/test_bot_chat_delivery_no_owner.py b/tests/cron/test_bot_chat_delivery_no_owner.pynew file mode 100644index 00000000000..052942f4a68--- /dev/null+++ b/tests/cron/test_bot_chat_delivery_no_owner.py@@ -0,0 +1,37 @@+"""A Bot Chat cron delivery whose target owner is not running is parked, never booked failed:+a later tick admits it to the owner once, under the same delivery id."""+from unittest.mock import Mock++from cron import scheduler_delivery as delivery+from tools import bot_live_delivery as mailbox+++def test_bot_chat_target_without_live_owner_is_parked_and_admitted_later(tmp_path, monkeypatch):+ from cron import jobs+ from cron.bot_chat_legacy import drain_legacy_pending+ from gateway import config++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.delenv("_HERMES_CRON_EXTERNAL_WORKER", raising=False)+ monkeypatch.setattr(delivery._sched, "load_config", dict)+ monkeypatch.setattr(config, "load_gateway_config", lambda: None)+ monkeypatch.setattr(jobs, "update_job", lambda key, values: None)+ (tmp_path / "state.db").write_text("")+ monkeypatch.setattr(mailbox, "find_canonical_live_owner",+ Mock(side_effect=ValueError("profile authority is not ready")))+ job = dict(id="digest", name="Digest", execution_id="run-1", deliver="bot-chat")+ assert delivery._deliver_result(job, "the report") is None # not a failed delivery+ drain_legacy_pending() # owner still down: stays parked++ admitted = []++ def deliver(home, owner, message, *, delivery_id, notification_category="result"):+ admitted.append((delivery_id, message))+ return {"status": "queued", "message": message, "delivery_id": delivery_id}++ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: {"session_id": "bot"})+ monkeypatch.setattr(mailbox, "deliver_to_live_owner", deliver)+ drain_legacy_pending()+ drain_legacy_pending()+ key = job["_bot_chat_delivery_receipts"]["bot-chat:(own)"]["delivery_id"]+ assert [(k, "the report" in m) for k, m in admitted] == [(key, True)]diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.pyindex c098abc3e2a..c7fb086c9e3 100644--- a/tests/cron/test_cron_bot_chat_delivery.py+++ b/tests/cron/test_cron_bot_chat_delivery.py@@ -143,8 +143,8 @@ def test_failure_notice_reaches_the_owner_as_a_diagnostic(tmp_path, monkeypatch)assert seen == ["diagnostic", "result"]-def test_deliver_without_authority_is_unverified_not_a_second_writer(tmp_path, monkeypatch):- """No running authority → explicit unverified status; never a local CLI turn."""+def test_deliver_without_authority_is_parked_not_a_second_writer(tmp_path, monkeypatch):+ """No running authority → parked for a later tick (explicit queued status); never a local CLI turn."""import subprocessfrom tools import bot_live_delivery as mailbox@@ -153,7 +153,7 @@ def test_deliver_without_authority_is_unverified_not_a_second_writer(tmp_path, mmonkeypatch.setattr(mailbox, "find_canonical_live_owner",mock.Mock(side_effect=ValueError("profile authority is not ready")))err = _deliver_to_bot_chat({"id": "j1", "name": "n", "execution_id": "r1"}, "out", "")- assert err is not None and "unverified" in err and "not ready" in err+ assert err is not None and "queued" in err and "not running" in errdef test_failure_notice_to_a_profile_hiding_warnings_is_suppressed_not_sent(tmp_path, monkeypatch):