Skip to content

The agent that grows with you

fix(cron): hand legacy cron/bot_chat_pending records to the live Bot Chat owner

Tekniumadee13f092e8
diff --git a/cron/bot_chat_legacy.py b/cron/bot_chat_legacy.py
new file mode 100644
index 00000000000..59ede7e52e6
--- /dev/null
+++ b/cron/bot_chat_legacy.py
@@ -0,0 +1,78 @@
+"""Upgrade path for ``cron/bot_chat_pending`` records the retired CLI lane left behind.
+
+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,
+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 are
+never deleted: they keep their final status as evidence, exactly as the old drain did.
+A ``claimed`` record was an uncertain CLI turn and is never resent.
+"""
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+
+from hermes_constants import get_hermes_home
+from utils import atomic_json_write
+
+logger = logging.getLogger(__name__)
+_warned: set[Path] = set()
+
+
+def _queued(root: Path) -> list[tuple[Path, dict]]:
+ found = []
+ for path in root.glob("*.json"):
+ try:
+ record = json.loads(path.read_text(encoding="utf-8-sig"))
+ if not isinstance(record, dict):
+ raise ValueError(f"expected a JSON object, got {type(record).__name__}")
+ except (OSError, ValueError) as exc:
+ if path not in _warned:
+ _warned.add(path)
+ logger.error("Unreadable legacy Bot Chat pending record %s kept as evidence: %s", path, exc)
+ continue
+ if record.get("status") == "queued":
+ found.append((path, record))
+ return sorted(found, key=lambda item: (item[1].get("sequence", 0), item[0].name))
+
+
+def drain_legacy_pending() -> None:
+ """Admit queued legacy records to their live owner; an absent owner leaves them for a later tick."""
+ from cron.scheduler_delivery import BOT_CHAT_POLICY_PLATFORM, bot_chat_message
+ from gateway.warning_notifications import warning_notifications_enabled
+ from hermes_cli.config_effective import load_user_config_effective
+ from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner
+
+ root = get_hermes_home().resolve() / "cron" / "bot_chat_pending"
+ if not root.is_dir():
+ return
+ for path, record in _queued(root):
+ home = Path(record["home"]).resolve()
+ for_failure = bool(record.get("for_failure"))
+ if not (home / "state.db").is_file():
+ record.update(status="ambiguous", error=f"bot-chat delivery target no longer exists: {home}")
+ elif for_failure and not warning_notifications_enabled(
+ BOT_CHAT_POLICY_PLATFORM, load_user_config_effective(home / "config.yaml")):
+ record.update(status="suppressed", error=None)
+ else:
+ try:
+ owner = find_canonical_live_owner(home)
+ except ValueError:
+ continue # Owner not ready: discovery uncertainty is not a disposition.
+ if owner is None:
+ continue
+ try:
+ receipt = deliver_to_live_owner(
+ home, owner, bot_chat_message(record.get("job") or {}, record["content"]),
+ delivery_id=record["id"], notification_category="diagnostic" if for_failure else "result")
+ except Exception as exc:
+ # The door is idempotent per id (a replay returns the existing receipt), so the
+ # record stays queued for the next tick; log loudly once, quietly after.
+ logger.log(logging.DEBUG if path in _warned else logging.WARNING,
+ "Legacy Bot Chat pending record %s not handed off yet: %s", path, exc)
+ _warned.add(path)
+ continue
+ record.update(status="transferred", error=None, receipt_status=receipt["status"])
+ atomic_json_write(path, record, fsync_dir=True, mode=0o600)
+ logger.info("Legacy Bot Chat pending record %s -> %s", path.name, record["status"])
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index 25f23c0e066..0a2fc83b4f5 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -704,6 +704,23 @@ def _get_standalone_send_timeout() -> int:
return 60
+def bot_chat_message(job: dict, content: str) -> str:
+ """The inbound Bot Chat turn text for one cron output.
+
+ Outward lane: this text becomes an inbound turn in another profile's Bot Chat through the
+ live owner's durable admission record, so it gets the same fail-closed scrub as the chat
+ message and the session mirror; the admitted record carries the scrubbed copy, never the raw
+ output.
+ """
+ content = _redact_cron_payload(content, "bot-chat payload")
+ job_name = _redact_cron_payload(job.get("name", job.get("id", "?")), "job name")
+ return (
+ f'[Cronjob "{job_name}" output — '
+ f"scheduled job, not the user. Review it, act on anything that needs action, and "
+ f"summarize for the chat.]\n\n{content}"
+ )
+
+
def _deliver_to_bot_chat(job: dict, content: str, profile: str, *,
for_failure: bool = False) -> Optional[str]:
"""Admit job output to the target profile's authority as a real inbound Bot Chat turn.
@@ -725,17 +742,7 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *,
job_id = job.get("id", "?")
profile_label = profile or "(own)"
- # Outward lane: this text becomes an inbound turn in another profile's Bot Chat through the
- # live owner's durable admission record, so it gets the same fail-closed scrub as the chat
- # message and the session mirror. Rebind ``content`` itself so the admitted record carries
- # the scrubbed copy, not the raw output.
- content = _redact_cron_payload(content, "bot-chat payload")
- job_name = _redact_cron_payload(job.get("name", job_id), "job name")
- message = (
- f'[Cronjob "{job_name}" output — '
- f"scheduled job, not the user. Review it, act on anything that needs action, and "
- f"summarize for the chat.]\n\n{content}"
- )
+ message = bot_chat_message(job, content)
try:
source_home = get_hermes_home().resolve()
home = (get_profile_dir(profile) if profile else source_home).resolve()
diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.py
index 073d9d5bcb4..a36bc0aed6a 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -57,6 +57,8 @@ def _tick_admitted(
reconcile_pending(allow_connect=False)
else:
reconcile_pending()
+ from cron.bot_chat_legacy import drain_legacy_pending
+ drain_legacy_pending()
_sched._maybe_reap_dead_owners()
# Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.
try:
diff --git a/tests/cron/test_cron_bot_chat_delivery.py b/tests/cron/test_cron_bot_chat_delivery.py
index 7403668ea07..1e50dc84025 100644
--- a/tests/cron/test_cron_bot_chat_delivery.py
+++ b/tests/cron/test_cron_bot_chat_delivery.py
@@ -176,3 +176,50 @@ def test_delivery_targets_include_local_profiles():
bot_chat_entries = [t for t in targets if t["id"].startswith(BOT_CHAT_PLATFORM)]
# No gateway home channel needed for bot-chat targets.
assert all(t["home_target_set"] for t in bot_chat_entries)
+
+
+# ── legacy cron/bot_chat_pending upgrade path ────────────────────────────────
+
+def test_tick_hands_legacy_pending_records_to_the_live_owner_once(tmp_path, monkeypatch):
+ """Records the retired CLI lane left in cron/bot_chat_pending are never orphaned: a queued
+ (never-started) record is admitted to the live owner under its own id; a claimed one (an
+ uncertain CLI turn) is never resent; the files stay as evidence."""
+ import json
+
+ import cron.jobs as J
+ import cron.scheduler as S
+ from cron import scheduler_authority
+ from tools import bot_live_delivery as mailbox
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr(J, "HERMES_DIR", tmp_path)
+ monkeypatch.setattr(J, "CRON_DIR", tmp_path / "cron")
+ monkeypatch.setattr(J, "JOBS_FILE", tmp_path / "cron" / "jobs.json")
+ monkeypatch.setattr(J, "OUTPUT_DIR", tmp_path / "cron" / "output")
+ monkeypatch.setattr(S, "_hermes_home", tmp_path)
+ monkeypatch.setattr(S, "_sweep_mcp_orphans", lambda: None)
+ monkeypatch.setattr(scheduler_authority, "reconcile_pending", lambda *, allow_connect=True: None)
+ (tmp_path / "state.db").write_text("")
+ root = tmp_path / "cron" / "bot_chat_pending"
+ root.mkdir(parents=True)
+ queued, claimed = "a" * 64, "b" * 64
+ for key, status in ((queued, "queued"), (claimed, "claimed")):
+ (root / f"{key}.json").write_text(json.dumps(dict(
+ id=key, status=status, job={"id": "j1", "name": "Digest"}, content="the report",
+ profile="", home=str(tmp_path), sequence=1, for_failure=True)))
+ admitted = []
+
+ def fake_deliver(home, owner, message, *, delivery_id, notification_category="result"):
+ admitted.append((delivery_id, message, notification_category))
+ 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", fake_deliver)
+
+ S.tick(verbose=False)
+ S.tick(verbose=False)
+
+ assert [(key, category) for key, _, category in admitted] == [(queued, "diagnostic")]
+ assert 'Cronjob "Digest" output' in admitted[0][1] and "the report" in admitted[0][1]
+ assert json.loads((root / f"{queued}.json").read_text())["status"] == "transferred"
+ assert json.loads((root / f"{claimed}.json").read_text())["status"] == "claimed"