The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(cron): two invariant ESTOP tests for the fire webhook and misfire backstop; docs
teknium1931387dd4270
diff --git a/tests/cron/test_misfire_catchup.py b/tests/cron/test_misfire_catchup.pyindex b3322bc8167..3ad5aef3ea5 100644--- a/tests/cron/test_misfire_catchup.py+++ b/tests/cron/test_misfire_catchup.py@@ -10,7 +10,6 @@ gateway housekeeping, claims and fires those jobs after a grace window.import threadingimport timefrom datetime import timedelta-from unittest.mock import patchimport pytest@@ -163,66 +162,27 @@ class TestFireOverdueJobs:assert provider.wait_fired(timeout=10)assert provider.fired == [job["id"]]- def test_estop_engaged_skips_backstop(self, tmp_cron_dir, tmp_path, monkeypatch):- """Engaged ESTOP → backstop returns 0 and spawns no fire threads.-- Matches the contract at ``agent/estop.py:1-9``: cron skips work,- in-flight work is untouched. The misfire sweep is the backstop; it- must yield to operator pause, then resume naturally on disengage.- """- from agent import estop-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- estop._logged_components.clear()-- job = create_job(prompt="p", schedule="every 1h")- _park_in_past(job["id"], minutes=30)- provider = RecordingProvider()-- estop.engage(reason="ops window")- try:- with patch.object(- provider, "claim_fire", wraps=provider.claim_fire- ) as claim, patch(- "cron.scheduler_provider.threading.Thread"- ) as thread:- assert fire_overdue_jobs(provider) == 0- # No claim attempted, no worker thread constructed — proves- # the ESTOP gate is the actual short-circuit (not a deferred- # admission that races the test).- claim.assert_not_called()- thread.assert_not_called()- assert provider.fired == []- finally:- estop.disengage()-- def test_estop_release_restores_backstop(self, tmp_cron_dir, tmp_path, monkeypatch):- """ESTOP release → next sweep catches up via the existing claim_fire path.-- No state to unwind — the sweep's job is already "fire things whose- scheduled fire never arrived," so a paused sweep just extends that- window until resume.- """+ def test_estop_skips_sweep_and_next_sweep_after_resume_catches_up(+ self, tmp_cron_dir, tmp_path, monkeypatch+ ):+ """`hermes pause` must silence the backstop too — otherwise it force-fires every job+ that ESTOP held back. Nothing to unwind: the first sweep after `hermes resume`+ catches up through the ordinary claim_fire path."""from agent import estopmonkeypatch.setenv("HERMES_HOME", str(tmp_path))estop._logged_components.clear()-job = create_job(prompt="p", schedule="every 1h")_park_in_past(job["id"], minutes=30)+ parked_at = get_job(job["id"])["next_run_at"]provider = RecordingProvider()- estop.engage(reason="ops window")- assert fire_overdue_jobs(provider) == 0 # paused — no fire+ estop.engage(reason="runaway fan-out")+ assert fire_overdue_jobs(provider) == 0+ assert provider.fired == []+ assert get_job(job["id"])["next_run_at"] == parked_at # nothing claimed or re-armedestop.disengage()- with patch.object(- provider, "claim_fire", wraps=provider.claim_fire- ) as claim:- assert fire_overdue_jobs(provider) == 1- # Recovery re-enters via the existing claim_fire path —- # explicit positive assertion proves the path is exercised,- # not just that *something* fired.- claim.assert_called_once()+ assert fire_overdue_jobs(provider) == 1assert provider.wait_fired()assert provider.fired == [job["id"]]diff --git a/tests/gateway/test_api_server_jobs.py b/tests/gateway/test_api_server_jobs.pyindex 457d877afe0..c9d483075ce 100644--- a/tests/gateway/test_api_server_jobs.py+++ b/tests/gateway/test_api_server_jobs.py@@ -12,7 +12,7 @@ Covers:import loggingfrom types import SimpleNamespace-from unittest.mock import AsyncMock, MagicMock, patch+from unittest.mock import MagicMock, patchimport pytestfrom aiohttp import web@@ -557,97 +557,3 @@ class TestCronPromptScanParity:assert "Blocked" in data["error"] or "threat" in data["error"].lower()mock_create.assert_not_called()--# ----------------------------------------------------------------------------# 19. test_cron_fire_estop-# -----------------------------------------------------------------------------class TestCronFireEstop:- """ESTOP must halt the NAS-managed cron fire webhook (Door 2 of the bug report).-- See ``agent/estop.py:1-9`` contract: "the cron scheduler ... skips work;- in-flight work is never killed." The webhook path was the gap — a managed-cron- operator running ``hermes pause`` previously kept getting fires through.- """-- @pytest.mark.asyncio- async def test_fire_webhook_returns_503_when_estop_engaged(- self, adapter, tmp_path, monkeypatch- ):- """Engaged ESTOP → 503 + Retry-After; claim_fire never reached."""- from agent import estop-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- estop._logged_components.clear()- estop.engage(reason="ops window")-- try:- app = web.Application(middlewares=[cors_middleware])- app["api_server_adapter"] = adapter- app.router.add_post("/api/cron/fire", adapter._handle_cron_fire)-- claims = {"sub": "chronos", "aud": "test"}- async with TestClient(TestServer(app)) as cli:- with patch(f"{_MOD}._CRON_AVAILABLE", True), patch(- f"{_MOD}._call_verifier", AsyncMock(return_value=claims)- ), patch(- "cron.scheduler_provider.resolve_cron_scheduler"- ) as resolve:- resp = await cli.post(- "/api/cron/fire",- json={"job_id": "aabbccddeeff"},- headers={"Authorization": "Bearer test-token"},- )- assert resp.status == 503- assert resp.headers.get("Retry-After") == "60"- data = await resp.json()- assert "paused" in data["error"].lower()- assert data["job_id"] == "aabbccddeeff"- # ESTOP check happens before admission — none of the- # provider's claim/execute entry points may run.- resolve.return_value.claim_fire.assert_not_called()- resolve.return_value.fire_claimed.assert_not_called()- resolve.return_value.fire_due.assert_not_called()- finally:- estop.disengage()-- @pytest.mark.asyncio- async def test_fire_webhook_401_when_verifier_crashes(- self, adapter, tmp_path, monkeypatch- ):- """Crashing verifier → 401 without consulting ESTOP.-- Auth runs before the ESTOP check, so a broken verifier never- learns the sentinel state. Prevents leaking pause state to- unauthenticated callers and proves the ordering invariant.- """- from agent import estop-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- estop._logged_components.clear()- estop.engage(reason="ops window")-- try:- app = web.Application(middlewares=[cors_middleware])- app["api_server_adapter"] = adapter- app.router.add_post("/api/cron/fire", adapter._handle_cron_fire)-- async def _verifier_raises(*args, **kwargs):- raise RuntimeError("JWKS endpoint unreachable")-- async with TestClient(TestServer(app)) as cli:- with patch(f"{_MOD}._CRON_AVAILABLE", True), patch(- f"{_MOD}._call_verifier",- AsyncMock(side_effect=_verifier_raises),- ):- resp = await cli.post(- "/api/cron/fire",- json={"job_id": "aabbccddeeff"},- headers={"Authorization": "Bearer test-token"},- )- assert resp.status == 401- data = await resp.json()- assert "token" in data["error"].lower() or "auth" in data["error"].lower()- finally:- estop.disengage()-diff --git a/tests/gateway/test_cron_fire_webhook.py b/tests/gateway/test_cron_fire_webhook.pyindex e315030a300..bf91f370ab6 100644--- a/tests/gateway/test_cron_fire_webhook.py+++ b/tests/gateway/test_cron_fire_webhook.py@@ -408,3 +408,47 @@ async def test_fire_without_runner_passes_none_adapters(adapter, monkeypatch):assert seen.get("job_id") == "no-runner"assert seen.get("adapters") is None+++async def test_estop_refuses_fire_before_admission_and_lifts_on_resume(adapter, monkeypatch, tmp_path):+ """`hermes pause` must stop the NAS-driven door too: 503 + Retry-After (NAS redelivers+ after `hermes resume`) and no ``claim_fire`` — a claim followed by a 503 would leave a+ claimed job that the retry and the misfire backstop both race for."""+ from agent import estop++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ estop._logged_components.clear()+ provider = _SpyProvider()+ monkeypatch.setattr("cron.scheduler_provider.resolve_cron_scheduler", lambda: provider)+ monkeypatch.setattr(+ "plugins.cron_providers.chronos.verify.get_fire_verifier",+ lambda: (lambda **kw: {"purpose": "cron_fire"}),+ )++ app = _create_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ estop.engage(reason="runaway fan-out")+ response = await cli.post(+ "/api/cron/fire",+ headers={"Authorization": "Bearer good"},+ json={"job_id": "abc123"},+ )+ assert response.status == 503+ assert response.headers.get("Retry-After") == "60"+ assert (await response.json())["job_id"] == "abc123"+ assert provider.claimed == [] and provider.fired == []+ assert adapter.active_agent_work_count() == 0++ estop.disengage()+ response = await cli.post(+ "/api/cron/fire",+ headers={"Authorization": "Bearer good"},+ json={"job_id": "abc123"},+ )+ assert response.status == 202+ for _ in range(50):+ if provider.fired:+ break+ await asyncio.sleep(0.01)+ assert provider.claimed == ["abc123"] and provider.fired == ["abc123"]diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 1eca44ed404..709218d3827 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -58,6 +58,7 @@ hermes [global-options] <command> [subcommand/options]| `hermes migrate` | Diagnose and (optionally) rewrite `config.yaml` to replace references to retired models or deprecated settings (e.g. `migrate xai`). || `hermes status` | Show agent, auth, and platform status. || `hermes cron` | Inspect and tick the cron scheduler. |+| `hermes pause` / `hermes resume` | Global emergency stop: no new cron fires (built-in ticker, managed-cron webhook, misfire catch-up), kanban dispatch or gateway turns start until resumed; in-flight work is never killed. || `hermes kanban` | Multi-profile collaboration board (tasks, links, dispatcher). || `hermes project` | Manage named, multi-folder workspaces (projects). Anchors desktop session grouping and, when bound to a kanban board, gives tasks a deterministic worktree + branch convention. State is per-profile. || `hermes webhook` | Manage dynamic webhook subscriptions for event-driven activation. |diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex c9f691deb85..04cf78df211 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -263,6 +263,10 @@ What they do:**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.+### Pausing everything: `hermes pause`++`hermes pause [--reason ...]` is the global emergency stop (`hermes resume` lifts it). While it is engaged no scheduled cron fire starts, whichever door it arrives through: the built-in ticker skips its dispatch, the managed-cron (hosted scheduler) fire webhook answers `503` with `Retry-After: 60` so the scheduler redelivers the fire after you resume, and the [misfire catch-up](#misfire-catch-up) sweep stays idle instead of force-firing everything that was held back. Runs already in flight are never killed, and nothing is lost: due work catches up on the first tick or sweep after `hermes resume`. Explicit manual runs (`hermes cron run`, the dashboard's Trigger button) are an operator override and still execute while paused.+### Creating a job paused (safe canary)Create a canary without a create-then-pause scheduling race: