The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cron): hermes cron cancel stops a job's live run
kokhlo8c228c5b895e
diff --git a/cron/cancellation.py b/cron/cancellation.pynew file mode 100644index 00000000000..d7537e8fce4--- /dev/null+++ b/cron/cancellation.py@@ -0,0 +1,124 @@+"""On-demand cancellation of an in-flight cron run (``hermes cron cancel``).++The request has to reach the process that owns the run, and that process is usually not+the one taking the request: ``run_one_job`` hands an attempt to a detached external worker+before anything executes in-process, so an in-memory ``Event`` can never be the transport.+The request is therefore a marker file per EXECUTION — the ledger already mints one id per+attempt — polled by the same cancel seam the fire-claim heartbeat uses, so a cancel reaches+script runs (tree-kill + TERM/KILL escalation) and agent runs (interrupt) through the code+those paths already own.++Keying by execution id is what makes a leftover marker harmless: only the run it was written+for can read it, so a cancel can never bleed into the job's next fire.+"""++from __future__ import annotations++import contextlib+import os+import time+from pathlib import Path+from typing import Any, Dict, Optional++from hermes_constants import get_hermes_home++from cron.executions import live_inflight_execution++# A marker whose run was SIGKILLed before it could clean up is unreadable garbage. Canceling a+# job is rare, so the prune rides along with the write instead of needing its own sweep.+_MARKER_TTL_SECONDS = 24 * 3600++_DEFAULT_REASON = "cancelled on request (hermes cron cancel)"+++def _cancels_dir() -> Path:+ """Resolved per call so a multiplexed gateway never writes into another profile's home."""+ return get_hermes_home().resolve() / "cron" / "cancels"+++def _marker_path(execution_id: str) -> Path:+ execution_id = str(execution_id or "").strip()+ if not execution_id or "/" in execution_id or "\\" in execution_id or execution_id in {".", ".."}:+ raise ValueError(f"Not a usable execution id: {execution_id!r}")+ return _cancels_dir() / f"{execution_id}.cancel"+++def _prune_stale_markers(now: Optional[float] = None) -> None:+ cutoff = (now if now is not None else time.time()) - _MARKER_TTL_SECONDS+ with contextlib.suppress(OSError):+ for entry in _cancels_dir().iterdir():+ with contextlib.suppress(OSError):+ if entry.stat().st_mtime < cutoff:+ entry.unlink()+++def request_cancel(execution_id: str, *, reason: Optional[str] = None) -> Path:+ """Record a cancel for one execution. Idempotent: the marker holds the first reason."""+ path = _marker_path(execution_id)+ path.parent.mkdir(parents=True, exist_ok=True)+ tmp = path.with_suffix(".cancel.tmp")+ tmp.write_text((reason or _DEFAULT_REASON).strip(), encoding="utf-8")+ os.replace(tmp, path)+ _prune_stale_markers()+ return path+++def cancel_requested(execution_id: str) -> bool:+ with contextlib.suppress(ValueError, OSError):+ return _marker_path(execution_id).exists()+ return False+++def clear_cancel(execution_id: str) -> None:+ """Called by the run itself once it has wound down, so a finished attempt leaves no marker."""+ with contextlib.suppress(ValueError, OSError):+ _marker_path(execution_id).unlink(missing_ok=True)+++class CancelRequest:+ """``_CancelEventLike`` view of one execution's cancel marker.++ Implements ``set()`` for the protocol but never latches: this source is owned by another+ process, so a local ``set()`` would claim a cancel nobody asked for.+ """++ def __init__(self, execution_id: str) -> None:+ self.execution_id = str(execution_id or "")+ self._reason: Optional[str] = None++ def is_set(self) -> bool:+ return cancel_requested(self.execution_id)++ def set(self) -> None: # pragma: no cover — protocol shape only+ raise NotImplementedError("a cancel request is set by the requesting process, not the run")++ @property+ def reason(self) -> str:+ if self._reason is None:+ with contextlib.suppress(ValueError, OSError):+ recorded = _marker_path(self.execution_id).read_text(encoding="utf-8").strip()+ if recorded:+ self._reason = recorded+ self._reason = self._reason or _DEFAULT_REASON+ return self._reason+++def cancel_run(job_id: str, *, reason: Optional[str] = None) -> Dict[str, Any]:+ """Request cancellation of the job's live run. A job with nothing in flight is a no-op."""+ record = live_inflight_execution(job_id)+ if record is None:+ return {+ "success": True,+ "cancelled": False,+ "execution_id": None,+ "detail": "No run of this job is in flight — nothing to cancel.",+ }+ request_cancel(record["id"], reason=reason)+ return {+ "success": True,+ "cancelled": True,+ "execution_id": record["id"],+ "status": record.get("status"),+ "pid": record.get("pid"),+ "detail": "Cancel requested; the run stops at its next cancel check.",+ }diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 70046c33eeb..afaf1494958 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -531,6 +531,7 @@ from cron.executions import (recover_interrupted_executions, settle_unstarted_execution, terminalize_dead_owner)from cron.scheduler_liveness import ExecutionProgressStamper, _inactivity_watchdog_loopfrom cron.scheduler_bookkeeping import _classify_delivery_outcome+from cron.cancellation import CancelRequest, clear_cancel# Response marker that suppresses delivery (output is still saved locally for audit).SILENT_MARKER = "[SILENT]"@@ -679,6 +680,20 @@ class _CombinedCancelEvent:for event in self._events:event.set()+ @property+ def reason(self) -> Optional[str]:+ """Why the run is being torn down, from whichever source fired — so a script or agent+ stop never reports "fire claim lost" for an operator cancel (or the reverse)."""+ for event in self._events:+ if event.is_set():+ return getattr(event, "reason", None)+ return None+++def cancel_reason(cancel_event: Optional[_CancelEventLike]) -> str:+ """Human-facing cause for a cancelled run; the legacy wording when no source carries one."""+ return getattr(cancel_event, "reason", None) or "cron fire ownership was lost"+def get_running_job_ids() -> frozenset[str]:"""Thread-safe snapshot of executing job IDs (dispatch until ``_process_job`` returns). Read by@@ -1979,9 +1994,10 @@ def _run_agent_with_watchdog(def _abort_if_fire_claim_lost() -> None:if cancel_event is None or not cancel_event.is_set():return+ reason = cancel_reason(cancel_event)if agent is not None and hasattr(agent, "interrupt"):- agent.interrupt("Cron fire claim ownership was lost")- raise RuntimeError(f"Cron job '{job_name}' lost its durable fire claim ownership")+ agent.interrupt(f"Cron run stopped: {reason}")+ raise RuntimeError(f"Cron job '{job_name}' was stopped: {reason}")def _heartbeat_run_claim_if_due():nonlocal _last_claim_heartbeat@@ -3002,6 +3018,7 @@ class _FireOwnership:def __init__(self, job: dict, claim_lost: Optional[_CancelEventLike] = None,transport_cancel: Optional[_CancelEventLike] = None,+ operator_cancel: Optional[_CancelEventLike] = None,):self.job = job# Two handles: the heartbeat's raw ``lost_ownership`` event and the caller's transport@@ -3009,10 +3026,13 @@ class _FireOwnership:# ``set()`` would propagate into the transport event this run does not own (#105861).self.claim_lost = claim_lostself.transport_cancel = transport_cancel- # What ``run_job`` receives as its ``cancel_event``: either source cancels the run.+ # ``operator_cancel`` (``hermes cron cancel``) is a THIRD source, deliberately not folded+ # into ``transport_cancel``: only a transport cancel counts as claim loss for bookkeeping,+ # while an operator cancel is a real outcome this run records itself.+ # What ``run_job`` receives as its ``cancel_event``: any source cancels the run.self.cancel_event: Optional[_CancelEventLike] = (- _CombinedCancelEvent(claim_lost, transport_cancel)- if claim_lost is not None or transport_cancel is not None+ _CombinedCancelEvent(claim_lost, transport_cancel, operator_cancel)+ if claim_lost is not None or transport_cancel is not None or operator_cancel is not Noneelse None)claim = job.get("fire_claim")self.owner = str(claim.get("by") or "") if isinstance(claim, dict) else None@@ -3288,16 +3308,18 @@ def _run_one_job_body(transport_cancel: Optional[_CancelEventLike] = None,execution_token: Optional[object] = None,) -> bool:- fence = _FireOwnership(job, claim_lost, transport_cancel)- fire_owner = fence.owner- _side_effect_fence = fence.side_effect_fence- _fire_claim_ownership_lost = fence.lost-execution_id = job.get("execution_id")if not execution_id:execution_id = create_execution(job["id"], source="direct", scheduled_instant=job.get("_scheduled_instant"))["id"]job = dict(job, execution_id=execution_id)+ # The execution id is resolved BEFORE the fence so ``hermes cron cancel`` can join the same+ # cancel seam: the marker it writes is polled by whichever process owns this attempt.+ fence = _FireOwnership(job, claim_lost, transport_cancel, CancelRequest(execution_id))+ fire_owner = fence.owner+ _side_effect_fence = fence.side_effect_fence+ _fire_claim_ownership_lost = fence.lost+delivery_attempted = Falsedelivery_error = None@@ -3493,6 +3515,9 @@ def _run_one_job_body(finally:# Function-level on purpose: must scope delivery, deferred teardown, claim-loss handling and# bookkeeping — not just run_job. Do not move into the run block's finally.+ # The attempt is over either way, so its cancel marker goes with it — an unread marker+ # would otherwise sit in the cancels dir until the TTL prune.+ clear_cancel(execution_id)exit_cron_execution(_identity_token)if _fire_scope_tokens is not None:_reset_fire_secret_scope(_fire_scope_tokens)diff --git a/cron/scheduler_script.py b/cron/scheduler_script.pyindex c0f529bca0c..bc9ecca2277 100644--- a/cron/scheduler_script.py+++ b/cron/scheduler_script.py@@ -495,7 +495,7 @@ def _run_job_script(if cancel_event is not None and cancel_event.is_set():_terminate_cron_script_tree(proc)_drain_script_pipes(proc)- return False, "Script cancelled because cron fire ownership was lost"+ return False, f"Script cancelled: {_sched.cancel_reason(cancel_event)}"remaining = deadline - time.monotonic()if remaining <= 0:_terminate_cron_script_tree(proc)diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex bccabd1c0dc..171702fdef8 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -991,6 +991,24 @@ def cron_notepad(args) -> int:return 1+def cron_cancel(args) -> int:+ """Stop a job's live run. The schedule is untouched — the next fire still happens."""+ result = _cron_api(action="cancel", job_id=args.job_id,+ reason=getattr(args, "reason", None))+ if not result.get("success"):+ print(color(f"Failed to cancel run: {result.get('error', 'unknown error')}", Colors.RED))+ return 1+ job = result.get("job") or {}+ label = f"{job.get('name', args.job_id)} ({args.job_id})"+ if not result.get("cancelled"):+ print(color(f"Nothing to cancel for {label}", Colors.YELLOW))+ return 0+ print(color(f"Cancel requested for {label}", Colors.GREEN))+ print(f" Execution: {result['execution_id']} (pid {result.get('pid')})")+ print(f" {result.get('detail', '')}")+ return 0++# Late-bound lambdas keep module-level monkeypatching working; list/status/runs return None -> 0._CRON_SUBCOMMANDS = {"list": lambda a: cron_list(getattr(a, "all", False)) or 0,@@ -1005,6 +1023,7 @@ _CRON_SUBCOMMANDS = {"pause": lambda a: _job_action("pause", a.job_id, "Paused"),"resume": lambda a: cron_resume(a),"run": lambda a: _job_action("run", a.job_id, "Triggered"),+ "cancel": lambda a: cron_cancel(a),"remove": lambda a: _job_action("remove", a.job_id, "Removed"),}_CRON_SUBCOMMANDS["history"] = _CRON_SUBCOMMANDS["runs"]@@ -1019,5 +1038,5 @@ def cron_command(args):if handler is not None:return handler(args)print(f"Unknown cron command: {subcmd}\n"- "Usage: hermes cron [list|create|edit|pause|resume|run|remove|status|runs|doctor|tick]")+ "Usage: hermes cron [list|create|edit|pause|resume|run|cancel|remove|status|runs|doctor|tick]")sys.exit(1)diff --git a/hermes_cli/subcommands/cron.py b/hermes_cli/subcommands/cron.pyindex e81df18d099..53707af8e3a 100644--- a/hermes_cli/subcommands/cron.py+++ b/hermes_cli/subcommands/cron.py@@ -179,6 +179,12 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:cron_run.add_argument("job_id", help="Job ID to trigger")add_accept_hooks_flag(cron_run)+ cron_cancel = cron_subparsers.add_parser(+ "cancel", help="Stop a job's live run (its schedule is untouched)")+ cron_cancel.add_argument("job_id", help="Job ID whose in-flight run to stop")+ cron_cancel.add_argument(+ "--reason", help="Optional note recorded with the cancelled run")+cron_remove = cron_subparsers.add_parser("remove", aliases=["rm", "delete"], help="Remove a scheduled job")cron_remove.add_argument("job_id", help="Job ID to remove")diff --git a/tests/cron/test_cron_cancel.py b/tests/cron/test_cron_cancel.pynew file mode 100644index 00000000000..a302f84be96--- /dev/null+++ b/tests/cron/test_cron_cancel.py@@ -0,0 +1,154 @@+"""Coverage for on-demand cancellation of an in-flight cron run (`hermes cron cancel`)."""++import threading+import time++import pytest++[email protected](autouse=True)+def _isolated_cancels(monkeypatch, tmp_path):+ """Point the marker store at a scratch home so a cancel can never see a real profile."""+ from cron import cancellation++ monkeypatch.setattr(cancellation, "_cancels_dir", lambda: tmp_path / "cancels")+ yield+++def _claim(job_id: str) -> dict:+ from cron.executions import create_execution, mark_execution_running++ record = create_execution(job_id, source="test")+ mark_execution_running(record["id"])+ return record+++def test_marker_drives_the_runs_cancel_view():+ from cron.cancellation import CancelRequest, cancel_requested, clear_cancel, request_cancel++ request = CancelRequest("exec-a")+ assert not request.is_set()++ request_cancel("exec-a", reason="operator asked")+ assert request.is_set()+ assert cancel_requested("exec-a")+ # The recorded reason is what the run reports — not a generic "cancelled".+ assert request.reason == "operator asked"++ clear_cancel("exec-a")+ assert not request.is_set()+++def test_a_marker_only_ever_reaches_its_own_execution():+ from cron.cancellation import CancelRequest++ finished, upcoming = CancelRequest("exec-old"), CancelRequest("exec-new")+ from cron.cancellation import request_cancel+ request_cancel("exec-old")++ assert finished.is_set()+ # Recurring jobs reuse the job id every fire, so a stale marker must not cancel the next run.+ assert not upcoming.is_set()+++def test_cancel_run_targets_the_live_execution():+ from cron.cancellation import CancelRequest, cancel_run++ record = _claim("job-live")+ result = cancel_run("job-live", reason="wedged")++ assert result["success"] and result["cancelled"]+ assert result["execution_id"] == record["id"]+ assert CancelRequest(record["id"]).is_set()+++def test_cancel_is_a_noop_when_nothing_is_in_flight():+ from cron.cancellation import cancel_run++ _claim("job-done")+ from cron.executions import finish_execution+ from cron.executions import latest_execution+ finish_execution(latest_execution("job-done")["id"], success=True)++ result = cancel_run("job-done")+ assert result["success"] and not result["cancelled"]+ assert result["execution_id"] is None+++def test_operator_cancel_is_not_treated_as_claim_loss():+ from cron import scheduler+ from cron.cancellation import CancelRequest, request_cancel++ job = {"id": "job-fence", "fire_claim": {"by": "someone-else"}}+ request_cancel("exec-fenced")+ fence = scheduler._FireOwnership(job, None, None, CancelRequest("exec-fenced"))++ # The run stops...+ assert fence.cancel_event.is_set()+ assert scheduler.cancel_reason(fence.cancel_event) == "cancelled on request (hermes cron cancel)"+ # ...but a cancel is a real outcome the run records itself, not a lost fire claim.+ assert not fence.transport_cancelled()+ assert fence.claim_lost is None++[email protected]("posix")[email protected]_system_guard_bypass+def test_cancelling_a_script_job_kills_it_and_names_the_reason(tmp_path, monkeypatch):+ import os++ import psutil+ from cron import scheduler, scheduler_script+ from cron.cancellation import CancelRequest, request_cancel++ # Script paths resolve under the firing profile's home; point it at the scratch dir.+ monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)+ monkeypatch.setattr(scheduler_script, "_get_script_timeout", lambda: 60)+ scripts = tmp_path / "scripts"+ scripts.mkdir()+ ready = tmp_path / "script.pid"+ script = scripts / "blocking.py"+ script.write_text(+ "import os, time\n"+ f"open({str(ready) + '.tmp'!r}, 'w').write(str(os.getpid()))\n"+ f"os.replace({str(ready) + '.tmp'!r}, {str(ready)!r})\n"+ "time.sleep(120)\n",+ encoding="utf-8")++ cancel = CancelRequest("exec-live-script")+ results: list = []+ thread = threading.Thread(+ target=lambda: results.append(+ scheduler_script._run_job_script(str(script), workdir=str(tmp_path), cancel_event=cancel)))+ thread.start()+ try:+ deadline = time.monotonic() + 10+ while not ready.exists() and thread.is_alive() and time.monotonic() < deadline:+ time.sleep(0.01)+ assert ready.exists(), f"script must start before it can be cancelled (results={results})"+ pid = int(ready.read_text(encoding="utf-8"))++ request_cancel("exec-live-script", reason="operator asked")+ thread.join(timeout=20)+ assert not thread.is_alive()+ assert results[0][0] is False+ assert "operator asked" in results[0][1]++ deadline = time.monotonic() + 5+ while _alive(pid) and time.monotonic() < deadline:+ time.sleep(0.05)+ assert not _alive(pid), "the cancelled script must not outlive the cancel"+ finally:+ if ready.exists():+ pid = int(ready.read_text(encoding="utf-8"))+ if _alive(pid):+ os.kill(pid, 9)+ thread.join(timeout=20)+++def _alive(pid: int) -> bool:+ import psutil++ try:+ return psutil.Process(pid).status() != psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return Falsediff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 2197f72c190..4814c3facf5 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -1003,11 +1003,22 @@ def _action_update(job: dict[str, Any], a: dict[str, Any]) -> str:_JOBLESS_ACTIONS = {"create": _action_create, "list": _action_list}+++def _action_cancel(job: Dict[str, Any], a: Dict[str, Any]) -> str:+ """Stop the job's LIVE run. Per-run, not per-schedule: the job keeps its next fire."""+ from cron.cancellation import cancel_run++ # The schedule is untouched, so no provider notification — nothing about future fires moved.+ return _dumps({"job": _format_job(job), **cancel_run(job["id"], reason=a.get("reason"))})++_JOB_ACTIONS = {"remove": _action_remove, "update": _action_update,"run": _action_run, "run_now": _action_run, "trigger": _action_run,"pause": lambda job, a: _job_state_result(pause_job(job["id"], reason=a["reason"])),"resume": lambda job, a: _job_state_result(resume_job(job["id"])),+ "cancel": _action_cancel,}@@ -1105,7 +1116,7 @@ def _cronjob_schema_overrides() -> dict:CRONJOB_SCHEMA = {"name": "cronjob_manage",- "description": """Schedule recurring or one-off agent tasks (cron jobs): create, list, edit, run. action='create' schedules a job from a prompt and/or skills; 'list' inspects jobs; 'update'/'pause'/'resume'/'remove' manage one by job_id (always list first — never guess job IDs); 'run' fires a job immediately in the BACKGROUND (returns a handle at once, outcome re-enters the conversation when done — do not wait or poll; optional 'prompt' adds transient context for that fire only).+ "description": """Schedule recurring or one-off agent tasks (cron jobs): create, list, edit, run. action='create' schedules a job from a prompt and/or skills; 'list' inspects jobs; 'update'/'pause'/'resume'/'remove' manage one by job_id (always list first — never guess job IDs); 'run' fires a job immediately in the BACKGROUND (returns a handle at once, outcome re-enters the conversation when done — do not wait or poll; optional 'prompt' adds transient context for that fire only); 'cancel' stops a job's LIVE run without touching its schedule (a no-op when nothing is in flight).Jobs run in a fresh session with no current-chat context, so prompts must be self-contained, and the agent's FINAL RESPONSE is what gets delivered — cron runs are autonomous and cannot ask questions. Jobs run on the main agent model (whatever `hermes model` is set to when they fire) unless the user pins one. Prefer updating an existing job over creating near-duplicates.""","parameters": {@@ -1115,11 +1126,11 @@ Jobs run in a fresh session with no current-chat context, so prompts must be sel"paused_reason": {"type": "string", "description": "Create only: auditable reason; requires paused=true."},"action": {"type": "string",- "description": "One of: create, list, update, pause, resume, remove, run. When action=create, the 'schedule' and 'prompt' fields are REQUIRED."+ "description": "One of: create, list, update, pause, resume, remove, run, cancel. When action=create, the 'schedule' and 'prompt' fields are REQUIRED."},"job_id": {"type": "string",- "description": "Required for update/pause/resume/remove/run."+ "description": "Required for update/pause/resume/remove/run/cancel."},"pinned": {"type": "boolean",diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 74bb4a150d6..203e308b6f9 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -14,6 +14,7 @@ Cron jobs can:- schedule one-shot or recurring tasks- pause, resume, edit, trigger, and remove jobs+- stop a run that is already in flight, without touching the job's schedule- attach zero, one, or multiple skills to a job- deliver results back to the origin chat, local files, or configured platform targets- run in fresh agent sessions with the normal static tool list@@ -293,6 +294,7 @@ hermes cron listhermes cron pause <job_id_or_name>hermes cron resume <job_id_or_name>hermes cron run <job_id_or_name>+hermes cron cancel <job_id_or_name>hermes cron remove <job_id_or_name>hermes cron edit <job_id_or_name> [...flags]hermes cron status@@ -304,6 +306,7 @@ What they do:- `pause` — keep the job but stop scheduling it- `resume` — re-enable the job. A recurring job whose slot came due while it was paused keeps that slot due, so the next tick fires one catch-up run (or logs the skip when `cron.catch_up_missed: false`) instead of silently jumping to the next occurrence; otherwise the next future run is computed- `run` — trigger the job on the next scheduler tick. A manual run is an extra fire: the scheduled run still happens and the `repeat` count is not spent, so test-firing an `in 30m` reminder keeps the real one (a run once the slot is already due is that scheduled run)+- `cancel` — stop the job's **current** run (see [Stopping a run in flight](#stopping-a-run-in-flight))- `remove` — delete it entirely- `edit` — modify schedule, prompt, delivery, etc.- `tick` — run one scheduler pass and exit (for a system crontab or other external@@ -312,12 +315,41 @@ What they do:(`hermes cron list` shows it) and fire on the next tick after `hermes gateway start`; theirschedule 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_manage` 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.+**Name-based lookup.** The mutating verbs (`pause`, `resume`, `run`, `cancel`, `remove`, `edit`) plus the agent's `cronjob_manage` 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.+### Stopping a run in flight: `hermes cron cancel`++`pause` only suppresses future fires — a run that is already executing keeps going until it+finishes or hits a timeout. When a run is wedged (a script blocked on network I/O, an agent+turn that will not end), stop just that run:++```bash+hermes cron cancel <job_id_or_name>+hermes cron cancel <job_id_or_name> --reason "wedged on the staging API"+```++The schedule is untouched: the job stays enabled and its next fire happens as planned. What+changes is the current run.++- **Script jobs** (`--script`, including [no-agent mode](#no-agent-mode-script-only-jobs)) get the+ whole process tree terminated — `SIGTERM` to the script's process group, escalating to+ `SIGKILL` after a grace period, and backgrounded grandchildren included. This is the same+ teardown a script timeout already performs, so nothing new is left running behind the job.+- **Agent jobs** have the in-flight turn interrupted at its next checkpoint.++The cancel is a *request*, not a kill: it is recorded against that run's execution id and picked+up at the run's next cancel check (well under a second for a script). The run then records why+it stopped, so `hermes cron runs <job_id>` shows the cancel reason instead of an unexplained+timeout or a bare failure.++Cancelling a job with nothing running is a safe no-op that says so, and a cancel that arrives+after the run has already finished changes nothing. A cancel cannot undo side effects the run+already performed — it stops the run, it does not roll it back.+### Creating a job paused (safe canary)Create a canary without a create-then-pause scheduling race: