Skip to content

The agent that grows with you

fix(cron): a headless tick refuses agent jobs with no gateway instead of spawning one

teknium183417552b8f9
diff --git a/cron/AGENTS.md b/cron/AGENTS.md
index 8c55a501bcf..0729303272f 100644
--- a/cron/AGENTS.md
+++ b/cron/AGENTS.md
@@ -24,6 +24,12 @@ Hardening invariants — each guards a real failure; don't weaken without answer
executions ledger's `scheduled_instant` blocks a second fire, `cron.catch_up_missed: false`
skips past-grace misses with a logged reason. Never drop a slot silently (#107485).
- File lock `~/.hermes/cron/.tick.lock` prevents duplicate ticks across processes.
+- **Headless ticks refuse, never spawn.** `hermes cron tick` (system crontab / external scheduler)
+ calls `tick(headless=True)`; `cron/scheduler_gateway_gate.py` skips agent jobs when discovery
+ says no gateway owns the home (`last_fire_error` stamped, one warning per tick, due instant
+ untouched) instead of letting `run_canonical_job → connect_gateway → ensure_gateway_runtime`
+ spawn an unmanaged daemon. Same policy as approvals (headless/cron = refuse). The in-process
+ ticker and `hermes cron run` are not headless.
- Cron sessions pass `skip_memory=True`; memory providers intentionally do not run during cron.
- Cron execution has its own session. Eligible continuable deliveries may mirror or seed the
reply-facing conversation: origin, origin-less home fallback, user-written bare-platform home,
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 7c94242aef3..6e27a3101c4 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -3802,10 +3802,13 @@ def _sweep_mcp_orphans_when_all_done(futures: list) -> None:
def tick(
- verbose: bool = True, adapters=None, loop=None, sync: bool = True, *, can_dispatch=None):
+ verbose: bool = True, adapters=None, loop=None, sync: bool = True, *, can_dispatch=None,
+ headless: bool = False):
"""Check and run all due jobs. File-locked so only one tick runs at a time (gateway ticker vs
standalone daemon / manual tick). ``can_dispatch``: optional gate; false leaves due jobs for the
- next allowed tick. Returns the number of jobs executed (0 if another tick holds the lock)."""
+ next allowed tick. ``headless``: the tick runs outside any gateway (system crontab, ``hermes
+ cron tick``) and must refuse agent jobs rather than spawn one. Returns the number of jobs
+ executed (0 if another tick holds the lock)."""
# Stale-code yield gate — BEFORE the lock race. A process whose checkout was updated under it
# serves mixed sys.modules (jobs die on ImportErrors); if a fresher gateway holds the runtime
# lock, ITS ticker dispatches. With no fresh holder (desktop-standalone) the tick proceeds.
@@ -3842,6 +3845,9 @@ def tick(
due_jobs = get_due_jobs()
_sweep_stale_inflight_for_tick(due_jobs)
+ if headless:
+ from cron.scheduler_gateway_gate import refuse_agent_jobs_without_gateway
+ due_jobs = refuse_agent_jobs_without_gateway(due_jobs)
if not due_jobs:
# Idle tick: skip config load + pool setup, but still reap crashed jobs' MCP orphans.
@@ -3943,7 +3949,7 @@ if __name__ == "__main__":
raise SystemExit(
0 if _run_external_worker_payload(args.external_worker_file, args.ack_file) else 1
)
- tick(verbose=True)
+ tick(verbose=True, headless=True)
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
diff --git a/cron/scheduler_gateway_gate.py b/cron/scheduler_gateway_gate.py
new file mode 100644
index 00000000000..02fafb70004
--- /dev/null
+++ b/cron/scheduler_gateway_gate.py
@@ -0,0 +1,67 @@
+"""Headless tick gate: agent jobs need a live gateway; a headless tick never starts one.
+
+``run_canonical_job`` reaches the owner through ``connect_gateway`` → ``ensure_gateway_runtime``,
+which spawns an unmanaged daemon when nothing owns the profile. That is right for an interactive
+caller (``hermes cron run``) and wrong for ``hermes cron tick`` from a system crontab: every tick
+would leave a stray gateway behind. Headless surfaces refuse rather than spawn (same policy as
+approvals), so a headless tick skips its agent jobs while the gateway is down and lets them fire
+on the next tick once it is up — no run is recorded and the due instant does not move. The
+in-process ticker never reaches this gate: it runs inside the gateway by definition.
+"""
+import logging
+import os
+
+logger = logging.getLogger(__name__)
+
+GATEWAY_DOWN_HINT = (
+ "the gateway is not running, so agent jobs cannot fire; they run at the next tick once it is "
+ "up. Start it with `hermes gateway start` (or `hermes gateway install` for a service)."
+)
+
+
+def _gateway_absent(home) -> bool:
+ """True in exactly the state where ``ensure_gateway_runtime`` would spawn a daemon. Every
+ other state (starting, ready, draining, incompatible, ...) is left to ``connect_gateway``,
+ which awaits or reports it without spawning."""
+ from hermes_cli.gateway_runtime import discover_gateway_endpoint
+
+ if os.environ.get("HERMES_TUI_GATEWAY_URL", "").strip():
+ return False # explicit remote gateway: connect_gateway never spawns for it
+ return discover_gateway_endpoint(home).state == "absent"
+
+
+def _note_fire_refused(job_ids, detail: str) -> None:
+ """Stamp ``last_fire_error`` (shown by ``hermes cron list``) and drop the dispatch marks the
+ due scan just wrote: the slot was never handed over, so nothing must "restore" or "reclaim" it."""
+ from cron.jobs import _hermes_now, _jobs_lock, load_jobs, save_jobs
+
+ ids = set(job_ids)
+ with _jobs_lock():
+ jobs = load_jobs()
+ for job in jobs:
+ if job["id"] not in ids:
+ continue
+ job["last_fire_error"] = {"at": _hermes_now().isoformat(), "detail": detail[:500]}
+ job.pop("pending_slot", None)
+ if job.get("run_claim") is not None:
+ job["run_claim"] = None
+ save_jobs(jobs)
+
+
+def refuse_agent_jobs_without_gateway(due_jobs: list) -> list:
+ """Return the due jobs a headless tick may dispatch; agent jobs are held back (skipped, not
+ failed) when no gateway serves this home. Logs once per tick, not once per job."""
+ from hermes_constants import get_hermes_home
+
+ agent_jobs = [job for job in due_jobs if not job.get("no_agent")]
+ if not agent_jobs:
+ return due_jobs
+ home = get_hermes_home().resolve()
+ if not _gateway_absent(home):
+ return due_jobs
+ ids = [str(job["id"]) for job in agent_jobs]
+ _note_fire_refused(ids, f"Skipped: {GATEWAY_DOWN_HINT}")
+ logger.warning(
+ "Cron tick for %s skipped %d agent job(s) (%s): %s",
+ home, len(ids), ", ".join(ids), GATEWAY_DOWN_HINT)
+ return [job for job in due_jobs if job.get("no_agent")]
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index 628ef2434e3..0502e4303db 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -235,10 +235,13 @@ def _job_warnings(job: Dict[str, Any]) -> List[str]:
def cron_tick():
- """Run due jobs once and exit."""
+ """Run due jobs once and exit (external-scheduler mode: a system crontab calls this).
+
+ No gateway runs here by definition, and none is started: agent jobs are skipped with a logged
+ reason until the gateway is up (headless surfaces refuse rather than spawn)."""
from cron.scheduler import CronTickYielded, tick
try:
- tick(verbose=True)
+ tick(verbose=True, headless=True)
except CronTickYielded as exc:
# Inert for a one-shot CLI (no boot fingerprint); report cleanly rather than traceback.
print(color(f"✗ {exc}", Colors.YELLOW))
diff --git a/tests/cron/test_tick_without_gateway.py b/tests/cron/test_tick_without_gateway.py
new file mode 100644
index 00000000000..674519265b1
--- /dev/null
+++ b/tests/cron/test_tick_without_gateway.py
@@ -0,0 +1,83 @@
+"""``hermes cron tick`` with no live gateway refuses agent jobs instead of spawning one.
+
+The external-scheduler mode (system crontab calling ``hermes cron tick``) used to reach
+``run_canonical_job`` -> ``connect_gateway`` -> ``ensure_gateway_runtime``, which spawns an
+unmanaged daemon when nothing owns the profile. Headless surfaces refuse rather than spawn:
+the agent job is skipped (not failed), keeps its due instant, and one warning names the fix.
+"""
+from datetime import timedelta
+
+import pytest
+
+import cron.jobs as J
+import cron.scheduler as S
+from cron import scheduler_authority
+
+
+def cron_home(tmp_path, monkeypatch):
+ home = tmp_path / "home"
+ (home / "cron").mkdir(parents=True)
+ (home / "scripts").mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(J, "HERMES_DIR", home)
+ monkeypatch.setattr(J, "CRON_DIR", home / "cron")
+ monkeypatch.setattr(J, "JOBS_FILE", home / "cron" / "jobs.json")
+ monkeypatch.setattr(J, "OUTPUT_DIR", home / "cron" / "output")
+ monkeypatch.setattr(S, "_hermes_home", home)
+ monkeypatch.setattr(S, "_sweep_mcp_orphans", lambda: None)
+ S._running_job_ids.clear()
+ return home
+
+
+def _make_due(job_id: str) -> None:
+ stored = J.load_jobs()
+ slot = (J._hermes_now() - timedelta(minutes=1)).replace(microsecond=0).isoformat()
+ next(r for r in stored if r["id"] == job_id)["next_run_at"] = slot
+ J.save_jobs(stored)
+
+
+def test_tick_without_gateway_skips_agent_jobs_without_spawning_or_drift(cron_home, monkeypatch, caplog):
+ from hermes_cli import gateway_runtime, gateway_runtime_start
+
+ spawned = []
+ monkeypatch.setattr(gateway_runtime_start, "spawn_unmanaged_gateway",
+ lambda *a, **k: spawned.append(a))
+ monkeypatch.setattr(gateway_runtime, "ensure_gateway_runtime",
+ lambda *a, **k: pytest.fail("a headless tick must never ensure-or-spawn"))
+
+ agent = J.create_job(prompt="summarise inbox", schedule="every 1h", name="agent", deliver="local")
+ other = J.create_job(prompt="digest", schedule="every 1h", name="agent-2", deliver="local")
+ _make_due(agent["id"])
+ _make_due(other["id"])
+ due_before = {j["id"]: j["next_run_at"] for j in J.load_jobs()}
+
+ with caplog.at_level("WARNING", logger="cron.scheduler_authority"):
+ ran = S.tick(verbose=False, headless=True)
+
+ assert ran == 0 and spawned == []
+ stored = {j["id"]: j for j in J.load_jobs()}
+ for job_id in (agent["id"], other["id"]):
+ # Skipped, not failed: no run recorded, the due instant is untouched (no drift), no
+ # orphaned dispatch stamp for the next tick to "restore", and the reason is visible.
+ assert stored[job_id]["last_run_at"] is None
+ assert stored[job_id]["next_run_at"] == due_before[job_id]
+ assert "pending_slot" not in stored[job_id]
+ assert "hermes gateway start" in stored[job_id]["last_fire_error"]["detail"]
+ refusals = [r for r in caplog.records if "not running" in r.getMessage()]
+ assert len(refusals) == 1, "one log line per tick, not one per job"
+ assert agent["id"] in refusals[0].getMessage() and "hermes gateway start" in refusals[0].getMessage()
+
+
+def test_no_agent_jobs_still_fire_without_a_gateway(cron_home, monkeypatch):
+ counter = cron_home / "fires.txt"
+ script = cron_home / "scripts" / "fire.sh"
+ script.write_text(f"#!/bin/sh\necho fired >> {counter}\necho fired\n", encoding="utf-8")
+ script.chmod(0o755)
+ monkeypatch.setattr(scheduler_authority, "reconcile_pending", lambda: None)
+ job = J.create_job(prompt=None, schedule="every 1h", name="script", script="fire.sh",
+ no_agent=True, deliver="local")
+ _make_due(job["id"])
+
+ assert S.tick(verbose=False, headless=True) == 1
+ assert counter.read_text(encoding="utf-8").count("fired") == 1
diff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.py
index dc82450e0e2..f25bb629373 100644
--- a/tests/hermes_cli/test_cron.py
+++ b/tests/hermes_cli/test_cron.py
@@ -395,13 +395,16 @@ def test_cron_list_warns_when_gateway_not_running(monkeypatch, capsys):
assert "Nightly docs" in out
-def test_cron_tick_invokes_scheduler_tick_with_verbose(monkeypatch):
+def test_cron_tick_invokes_scheduler_tick_verbose_and_headless(monkeypatch):
+ """The CLI tick runs outside any gateway: it must declare itself headless so agent jobs are
+ refused, never spawned for."""
calls = []
- monkeypatch.setattr("cron.scheduler.tick", lambda verbose=False: calls.append(verbose))
+ monkeypatch.setattr("cron.scheduler.tick",
+ lambda verbose=False, headless=False: calls.append((verbose, headless)))
cron_cli.cron_tick()
- assert calls == [True]
+ assert calls == [(True, True)]
def test_cron_create_failure_returns_nonzero(monkeypatch, capsys):
diff --git a/website/docs/guides/cron-troubleshooting.md b/website/docs/guides/cron-troubleshooting.md
index b58d60d67d8..3e53d64ab0c 100644
--- a/website/docs/guides/cron-troubleshooting.md
+++ b/website/docs/guides/cron-troubleshooting.md
@@ -38,7 +38,7 @@ If the job fires once and then disappears from the list, it's a one-shot schedul
Cron jobs are fired by the gateway's background ticker thread, which ticks every 60 seconds. A regular CLI chat session does **not** automatically fire cron jobs.
-If you're expecting jobs to fire automatically, you need a running gateway (`hermes gateway` for foreground, or `hermes gateway start` for the installed service). For one-off debugging, you can manually trigger a tick with `hermes cron tick`.
+If you're expecting jobs to fire automatically, you need a running gateway (`hermes gateway` for foreground, or `hermes gateway start` for the installed service). For one-off debugging, you can manually trigger a tick with `hermes cron tick` — but that tick still needs the gateway: it never starts one, and with no gateway running it skips agent jobs (logged, shown in `hermes cron list`) until the next tick after `hermes gateway start`.
**Desktop app:** the desktop's primary backend runs its own ticker, and it ticks **every local profile's** cron store — so jobs on a secondary profile keep firing even while that profile's backend is asleep (the desktop puts idle profile backends to sleep after ~10 minutes). You do not need to keep a profile open for its scheduled jobs to run.
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 08e848104c3..9a98b458e7a 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -272,6 +272,11 @@ What they do:
- `run` — trigger the job on the next scheduler tick
- `remove` — delete it entirely
- `edit` — modify schedule, prompt, delivery, etc.
+- `tick` — run one scheduler pass and exit (for a system crontab or other external
+ scheduler). **The gateway must be running:** agent jobs execute inside the gateway, and a
+ tick never starts one. With no gateway up, agent jobs are skipped with a logged reason
+ (`hermes cron list` shows it) and fire on the next tick after `hermes gateway start`; their
+ schedule is not advanced or penalised. `no_agent` script jobs still run from a bare tick.
**Name-based lookup.** All four mutating verbs (`pause`, `resume`, `run`, `remove`, `edit`) plus the agent's `cronjob` tool now accept a job **name** (case-insensitive) in place of the hex ID. The agent and CLI both prefer an exact ID match if one exists; ambiguous name matches (multiple jobs sharing the same name) are refused with the full list of candidate IDs so you can pick one explicitly. Names are not unique, so this guard is load-bearing — it prevents silently mutating the wrong job when two share a name.