The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(review): ticker heartbeat proves liveness only while its writer is alive; routed hand-off never trusts an unknown probe; satellite manual runs get the ticker's routed grant
teknium117957f5014b2
diff --git a/cron/jobs.py b/cron/jobs.pyindex ebc659733ff..de6121443aa 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -1245,20 +1245,39 @@ def record_ticker_heartbeat(success: bool = False) -> None:Resolution uses ``_current_cron_store()`` so the heartbeat is correctly scoped to the active profile'sstore — critical under multiplex_profiles where each profile needs its own liveness signal (#69377)."""- _write_marker("ticker_heartbeat", str(time.time()), ".hb_")+ # ``<epoch> <pid>``: a killed ticker's last stamp reads fresh for ~3 minutes, so a reader with no+ # other proof of the scheduler (the in-process serve/Desktop ticker) checks the writer is alive.+ _write_marker("ticker_heartbeat", f"{time.time()} {os.getpid()}", ".hb_")if success:_write_marker("ticker_last_success", str(time.time()), ".hb_")+def _read_marker_fields(name: str) -> List[str]:+ try:+ return (_current_cron_store().cron_dir / name).read_text(encoding="utf-8-sig").split()+ except Exception:+ return []++def _epoch_file_age(name: str) -> Optional[float]:"""Seconds since the epoch stamp stored in ``<cron_dir>/<name>``; None = missing/unreadable."""try:- raw = (_current_cron_store().cron_dir / name).read_text(encoding="utf-8-sig").strip()- return max(0.0, time.time() - float(raw))+ return max(0.0, time.time() - float(_read_marker_fields(name)[0]))except Exception:return None+def ticker_heartbeat_writer_alive() -> bool:+ """True when the process that wrote this store's ticker heartbeat is still running. A legacy+ bare-epoch stamp names no writer and is NOT proof of a live scheduler by itself."""+ fields = _read_marker_fields("ticker_heartbeat")+ try:+ from hermes_cli._subprocess_compat import pid_exists_stdlib+ return len(fields) >= 2 and pid_exists_stdlib(int(fields[1]))+ except Exception:+ return False++def get_ticker_heartbeat_age() -> Optional[float]:"""Seconds since the ticker loop last iterated; None = missing/unreadable ("cannot determine",not "dead").diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex a2803a2ed29..6dbf6b7e884 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -58,11 +58,17 @@ def _builtin_gateway_liveness() -> Optional[bool]:from gateway.status import is_gateway_runtime_lock_activeif is_gateway_runtime_lock_active():return True- from hermes_cli.gateway import find_gateway_pids+ from hermes_cli.gateway import find_gateway_pids, named_profile_served_by_running_multiplexerif find_gateway_pids():return True- from cron.jobs import get_ticker_heartbeat_age- return _ticker_age_is_fresh(get_ticker_heartbeat_age())+ from cron.jobs import get_ticker_heartbeat_age, ticker_heartbeat_writer_alive+ if not _ticker_age_is_fresh(get_ticker_heartbeat_age()):+ return False+ # A served named profile's heartbeat is the host multiplexer's, whose process the served+ # record already proves. Any other writer (the in-process ticker, a shared gateway whose+ # record omits this profile) must itself still be running: a killed ticker's last stamp+ # reads fresh for ~3 minutes and would queue manual runs nobody picks up.+ return named_profile_served_by_running_multiplexer() or ticker_heartbeat_writer_alive()except Exception:return None@@ -499,8 +505,9 @@ def cron_status():# `hermes serve` / the Desktop backend ticks every local profile in-process: no# gateway argv, lock or host record — only the heartbeat it writes here (#121881).with contextlib.suppress(Exception):- from cron.jobs import get_ticker_heartbeat_age- in_process_ticker = _ticker_age_is_fresh(get_ticker_heartbeat_age())+ from cron.jobs import get_ticker_heartbeat_age, ticker_heartbeat_writer_alive+ in_process_ticker = (_ticker_age_is_fresh(get_ticker_heartbeat_age())+ and ticker_heartbeat_writer_alive())if host is not None:print(f" Scheduler host: {host.describe()}")# `hermes gateway restart` exits 78 for a served NAMED profilediff --git a/tests/hermes_cli/test_cron_satellite_diagnostics.py b/tests/hermes_cli/test_cron_satellite_diagnostics.pyindex d2f8295adc7..f9f2f515906 100644--- a/tests/hermes_cli/test_cron_satellite_diagnostics.py+++ b/tests/hermes_cli/test_cron_satellite_diagnostics.py@@ -191,6 +191,35 @@ def test_desktop_serve_ticker_is_not_reported_as_no_gateway(tmp_path, monkeypatcassert "gateway install" in stale+def test_in_process_ticker_heartbeat_counts_only_while_its_writer_lives(tmp_path, monkeypatch):+ """A killed serve/Desktop ticker leaves a stamp that reads fresh for ~3 minutes; without a lock,+ pid or served record the heartbeat proves a scheduler only while the process that wrote it is+ alive. A legacy bare-epoch stamp names no writer and is not proof by itself."""+ import subprocess+ import sys++ from cron import jobs+ from hermes_cli import cron++ home = tmp_path / "home"+ (home / "cron").mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(jobs, "CRON_DIR", home / "cron")+ monkeypatch.setattr("hermes_cli.gateway.find_gateway_pids", lambda: [])+ monkeypatch.setattr("gateway.status.is_gateway_runtime_lock_active", lambda lock_path=None: False)+ monkeypatch.setattr("hermes_cli.gateway.named_profile_served_by_running_multiplexer", lambda: False)+ monkeypatch.setattr(cron, "_active_cron_provider_name", lambda: "builtin")+ dead = subprocess.Popen([sys.executable, "-c", ""], stdin=subprocess.DEVNULL)+ dead.wait()++ (jobs.CRON_DIR / "ticker_heartbeat").write_text(f"{time.time()} {dead.pid}", encoding="utf-8")+ assert cron._builtin_gateway_liveness() is False+ (jobs.CRON_DIR / "ticker_heartbeat").write_text(str(time.time()), encoding="utf-8")+ assert cron._builtin_gateway_liveness() is False+ jobs.record_ticker_heartbeat(success=True)+ assert cron._builtin_gateway_liveness() is True++def test_named_profile_output_names_the_profile_and_trusts_its_own_ticker(served_root, capsys, monkeypatch):"""`hermes -p probe cron list/status` names the inspected profile on every verdict (#99579) andanswers "is a scheduler ticking THIS home": a fresh heartbeat written into probe's store countsdiff --git a/tests/tools/test_cronjob_run_immediate.py b/tests/tools/test_cronjob_run_immediate.pyindex b04bd1ac203..b3f220a943f 100644--- a/tests/tools/test_cronjob_run_immediate.py+++ b/tests/tools/test_cronjob_run_immediate.py@@ -158,6 +158,40 @@ class TestCronjobRunExecutesImmediately:assert res["success"] is Trueassert m_run.call_args.kwargs["adapters"] is work_adapters+ def test_execute_job_now_grants_a_shared_bot_satellite_only_its_routed_targets(self):+ """A credentialless satellite that posts through the primary's bot gets the ticker's+ route-restricted view (``SharedRouteAdapters``), never the whole primary adapter map: an+ unrouted target is a miss (fail closed), the routed one resolves the primary adapter."""+ from pathlib import Path++ from cron.scheduler_preflight import SharedRouteAdapters+ from gateway.profile_routing import ProfileRoute++ primary_bot = object()+ default_adapters = {"telegram": primary_bot}+ runner = SimpleNamespace(+ adapters=default_adapters, _gateway_loop=object(),+ _adapters_for_profile=lambda profile: default_adapters, # what authz hands a shared-bot satellite+ _is_shared_bot_satellite=lambda profile: profile == "keeper",+ )+ route = ProfileRoute(name="ops", platform="telegram", profile="keeper", chat_id="-100")+ completed = {"id": "job-run-1", "last_status": "ok", "last_error": None}++ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \+ patch("gateway.run._gateway_runner_ref", return_value=runner), \+ patch("hermes_constants.get_hermes_home", return_value=Path("/srv/hermes/profiles/keeper")), \+ patch("cron.scheduler_preflight._primary_profile_routes_for_current_home", return_value=[route]), \+ patch("cron.scheduler.run_one_job", return_value=True) as m_run, \+ patch("tools.cronjob_tools.get_job", return_value=completed):+ res = _execute_job_now(dict(_JOB))++ assert res["success"] is True+ adapters = m_run.call_args.kwargs["adapters"]+ assert isinstance(adapters, SharedRouteAdapters)+ assert adapters.get("telegram", {"chat_id": "-100"}) is primary_bot+ assert adapters.get("telegram", {"chat_id": "-999"}) is None+ assert adapters.get("telegram") is None+def test_execute_job_now_fails_instead_of_falling_back_when_owner_resolution_raises(self):"""Fail closed: if the owner profile cannot be resolved, the run is marked failed with theerror surfaced — it must NOT silently fall back to ``runner.adapters`` (the default bot)."""diff --git a/tests/tools/test_cronjob_run_primary_routed.py b/tests/tools/test_cronjob_run_primary_routed.pyindex 2cb31f22491..4b2d4f1c457 100644--- a/tests/tools/test_cronjob_run_primary_routed.py+++ b/tests/tools/test_cronjob_run_primary_routed.py@@ -59,12 +59,16 @@ def test_routed_run_is_queued_for_the_gateway_that_serves_the_profile(keeper_jobm_run.assert_called_once()-def test_routed_run_without_a_serving_gateway_fails_before_the_turn(keeper_job):[email protected]("gateway_serves_profile", [False, None])+def test_routed_run_without_a_serving_gateway_fails_before_the_turn(keeper_job, gateway_serves_profile):+ """False = no scheduler; None = the probe could not tell. Neither may queue a run that nothing+ would pick up."""from cron.jobs import get_job- out, m_run = _run(keeper_job["id"], gateway_serves_profile=False)+ out, m_run = _run(keeper_job["id"], gateway_serves_profile=gateway_serves_profile)assert out["success"] is Falseassert "profile route" in out["error"]+ assert ("Could not determine" in out["error"]) is (gateway_serves_profile is None)m_run.assert_not_called()stored = get_job(keeper_job["id"])assert stored["next_run_at"] == keeper_job["next_run_at"]diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 064ff952a7e..fbe200d4201 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -186,13 +186,18 @@ def _hand_off_primary_routed_run(job: Dict[str, Any], extra_prompt: Optional[strif not routed:return Nonefrom hermes_cli.cron import _builtin_gateway_liveness- if _builtin_gateway_liveness() is False:+ alive = _builtin_gateway_liveness()+ if alive is not True:+ # None = the probe could not tell; a run queued for a ticker that may not exist is worse+ # than an honest refusal (nothing would ever pick it up).+ cause = ("Start the gateway — its ticker will deliver the job on schedule." if alive is False+ else "Could not determine whether a gateway serves this profile; check "+ "`hermes cron status` and re-run.")return _dumps({"success": False,"error": (f"This job delivers to {', '.join(sorted(routed))} through the primary "- "gateway's profile route, which has no standalone sender. Start the "- "gateway — its ticker will deliver the job on schedule."),+ f"gateway's profile route, which has no standalone sender. {cause}"),})updated = trigger_job(job["id"], extra_prompt=extra_prompt)_notify_provider_jobs_changed_safe()@@ -353,7 +358,15 @@ def _run_claimed_job(job: Dict[str, Any], extra_prompt: Optional[str] = None) ->if runner is not None and hasattr(runner, "_adapters_for_profile"):from hermes_constants import get_hermes_home, profile_name_for_home- adapters = runner._adapters_for_profile(profile_name_for_home(get_hermes_home()))+ profile = profile_name_for_home(get_hermes_home())+ adapters = runner._adapters_for_profile(profile)+ # A credentialless shared-bot satellite borrows the primary's bot for ROUTED targets+ # only — the same grant the ticker's ``tick_adapters_for`` makes, never the full map.+ if getattr(runner, "_is_shared_bot_satellite", lambda _p: False)(profile):+ from cron.scheduler_preflight import (+ SharedRouteAdapters, _primary_profile_routes_for_current_home)++ adapters = SharedRouteAdapters(adapters, _primary_profile_routes_for_current_home())gateway_loop = getattr(runner, "_gateway_loop", None) if runner is not None else Nonetry:# run_one_job records last_run_at/last_status via mark_job_run; `job` is the