Skip to content

The agent that grows with you

fix(cron): one bad legacy Bot Chat pending record no longer stops all cron

Teknium3b6138df0d39
diff --git a/cron/bot_chat_legacy.py b/cron/bot_chat_legacy.py
index 59ede7e52e6..7e1a56b85b2 100644
--- a/cron/bot_chat_legacy.py
+++ b/cron/bot_chat_legacy.py
@@ -37,42 +37,74 @@ def _queued(root: Path) -> list[tuple[Path, dict]]:
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."""
+def _malformed(record: dict) -> str:
+ """Why *record* can never be handed off (empty when its required fields are usable)."""
+ missing = [key for key in ("id", "home", "content")
+ if not isinstance(record.get(key), str) or not record.get(key)]
+ if missing:
+ return f"malformed legacy bot-chat record (missing {', '.join(missing)}); not delivered"
+ if not isinstance(record.get("job") or {}, dict):
+ return "malformed legacy bot-chat record (job is not an object); not delivered"
+ return ""
+
+
+def _dispose(path: Path, record: dict) -> bool:
+ """Decide one queued record in place; False leaves it queued 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
+ if reason := _malformed(record):
+ record.update(status="ambiguous", error=reason)
+ return True
+ 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:
+ return False # Owner not ready: discovery uncertainty is not a disposition.
+ if owner is None:
+ return False
+ 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)
+ return False
+ receipt_status = receipt.get("status") if isinstance(receipt, dict) else None
+ record.update(status="transferred", error=None, receipt_status=receipt_status)
+ return True
+
+
+def drain_legacy_pending() -> None:
+ """Admit queued legacy records to their live owner; an absent owner leaves them for a later tick.
+
+ Each record is isolated: a malformed one is kept as ``ambiguous`` evidence and an
+ unexpected failure leaves only that record queued, so one bad file never stops cron.
+ """
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)
+ try:
+ if not _dispose(path, record):
continue
- record.update(status="transferred", error=None, receipt_status=receipt["status"])
- atomic_json_write(path, record, fsync_dir=True, mode=0o600)
+ atomic_json_write(path, record, fsync_dir=True, mode=0o600)
+ except Exception as exc:
+ logger.log(logging.DEBUG if path in _warned else logging.WARNING,
+ "Legacy Bot Chat pending record %s left queued: %s", path, exc)
+ _warned.add(path)
+ continue
logger.info("Legacy Bot Chat pending record %s -> %s", path.name, record["status"])
diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.py
index a36bc0aed6a..a3f9878fe74 100644
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@ -57,8 +57,12 @@ def _tick_admitted(
reconcile_pending(allow_connect=False)
else:
reconcile_pending()
- from cron.bot_chat_legacy import drain_legacy_pending
- drain_legacy_pending()
+ # Upgrade drain for the retired CLI lane's records: never let it stop due jobs below.
+ try:
+ from cron.bot_chat_legacy import drain_legacy_pending
+ drain_legacy_pending()
+ except Exception as _legacy_exc:
+ _sched.logger.warning("Legacy Bot Chat pending drain failed: %s", _legacy_exc)
_sched._maybe_reap_dead_owners()
# Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.
try:
diff --git a/tests/cron/test_bot_chat_legacy_isolation.py b/tests/cron/test_bot_chat_legacy_isolation.py
new file mode 100644
index 00000000000..eeb11772e0a
--- /dev/null
+++ b/tests/cron/test_bot_chat_legacy_isolation.py
@@ -0,0 +1,44 @@
+"""One malformed legacy ``cron/bot_chat_pending`` record must not stop the profile's cron.
+
+``drain_legacy_pending`` runs on every tick before ``get_due_jobs()``. A record missing a
+field (or any per-record failure) is set aside as ``ambiguous`` evidence, and the tick
+still fires the due job beside it.
+"""
+import json
+from datetime import timedelta
+
+import cron.jobs as J
+import cron.scheduler as S
+from cron import scheduler_authority
+
+
+def test_corrupt_legacy_record_is_isolated_and_due_job_still_fires(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ (home / "scripts").mkdir(parents=True)
+ pending = home / "cron" / "bot_chat_pending"
+ pending.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ for name, value in (("HERMES_DIR", home), ("CRON_DIR", home / "cron"),
+ ("JOBS_FILE", home / "cron" / "jobs.json"),
+ ("OUTPUT_DIR", home / "cron" / "output")):
+ monkeypatch.setattr(J, name, value)
+ monkeypatch.setattr(S, "_hermes_home", home)
+ monkeypatch.setattr(S, "_sweep_mcp_orphans", lambda: None)
+ monkeypatch.setattr(scheduler_authority, "reconcile_pending", lambda *, allow_connect=True: None)
+ S._running_job_ids.clear()
+
+ corrupt = pending / "corrupt.json" # a queued record with no ``home``/``content``
+ corrupt.write_text(json.dumps({"id": "legacy-1", "status": "queued"}), encoding="utf-8")
+ script = home / "scripts" / "fire.sh"
+ script.write_text("#!/bin/sh\necho fired\n", encoding="utf-8")
+ script.chmod(0o755)
+ job = J.create_job(prompt=None, schedule="every 1h", name="script", script="fire.sh",
+ no_agent=True, deliver="local")
+ stored = J.load_jobs()
+ stored[0]["next_run_at"] = (J._hermes_now() - timedelta(minutes=1)).replace(microsecond=0).isoformat()
+ J.save_jobs(stored)
+
+ assert S.tick(verbose=False) == 1
+ assert J.get_job(job["id"])["last_status"] == "ok"
+ record = json.loads(corrupt.read_text(encoding="utf-8"))
+ assert record["status"] == "ambiguous" and record["error"]