The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): make immediate execution race-safe
Evgeniiacaafcc6bba3
diff --git a/cron/executions.py b/cron/executions.pyindex 01437ab9847..40a9780700a 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -17,7 +17,10 @@ from typing import Any, Dict, Iterator, List, Optionalfrom hermes_constants import get_hermes_homefrom hermes_time import now as _hermes_now-EXECUTIONS_FILE = get_hermes_home().resolve() / "cron" / "executions.db"+# Optional test override. Production resolves the path at transaction time so+# dashboard operations that temporarily enter another profile cannot leak that+# profile's execution records into the import-time home.+EXECUTIONS_FILE: Optional[Path] = NoneMAX_TERMINAL_EXECUTIONS = 1000_TERMINAL_STATES = ("completed", "failed", "unknown")_lock = threading.RLock()@@ -25,8 +28,9 @@ _PROCESS_ID = uuid.uuid4().hexdef _connect() -> sqlite3.Connection:- EXECUTIONS_FILE.parent.mkdir(parents=True, exist_ok=True)- return sqlite3.connect(EXECUTIONS_FILE, timeout=5)+ path = EXECUTIONS_FILE or (get_hermes_home().resolve() / "cron" / "executions.db")+ path.parent.mkdir(parents=True, exist_ok=True)+ return sqlite3.connect(path, timeout=5)def _initialize_schema(conn: sqlite3.Connection) -> None:diff --git a/cron/jobs.py b/cron/jobs.pyindex d225fe4ec7c..766209148d4 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -103,6 +103,8 @@ TICKER_INTERVAL_SECONDS = 60# concurrent mark_job_run / advance_next_run calls can clobber each other._jobs_file_lock = threading.RLock()_jobs_lock_state = threading.local()+_fire_fence_locks: Dict[str, threading.RLock] = {}+_fire_fence_locks_guard = threading.Lock()# Upper bound on waiting for the cross-process .jobs.lock flock (#60703).# Every cron function in the process funnels through _jobs_lock(), and the@@ -371,6 +373,86 @@ def _jobs_lock():_jobs_lock_state.depth = 0_jobs_lock_state.load_stamp = None++def _fire_job_lock(job_id: str):+ """Serialize one job's owner mutations and external side effects.++ Unlike the global jobs lock, this lock may be held across network delivery.+ It is scoped to one profile + job, so unrelated cron jobs keep progressing.+ Fencing fails closed when cross-process locking is unavailable.+ """+ cron_dir = _current_cron_store().cron_dir+ lock_key = f"{cron_dir.resolve()}::{job_id}"+ with _fire_fence_locks_guard:+ local_lock = _fire_fence_locks.setdefault(lock_key, threading.RLock())++ with local_lock:+ ensure_dirs()+ lock_name = uuid.uuid5(uuid.NAMESPACE_URL, lock_key).hex+ lock_path = cron_dir / f".fire-{lock_name}.lock"+ lock_fd = None+ acquired = False+ try:+ lock_fd = open(lock_path, "a+", encoding="utf-8")+ lock_fd.seek(0)+ if fcntl is not None:+ deadline = time.monotonic() + _JOBS_LOCK_TIMEOUT_SECONDS+ while True:+ try:+ fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ acquired = True+ break+ except (OSError, IOError):+ if time.monotonic() >= deadline:+ logger.error(+ "Timed out waiting for fire fence %s; failing closed",+ lock_path,+ )+ break+ time.sleep(0.1)+ elif msvcrt is not None:+ getattr(msvcrt, "locking")(+ lock_fd.fileno(), getattr(msvcrt, "LK_LOCK"), 1+ )+ acquired = True+ else: # pragma: no cover - supported platforms provide one backend+ logger.error("No cross-process lock backend for cron fire fence")+ except (OSError, IOError) as exc:+ logger.error("Cron fire fence unavailable for %s: %s", job_id, exc)++ try:+ yield acquired+ finally:+ if lock_fd is not None:+ try:+ if acquired and fcntl is not None:+ fcntl.flock(lock_fd, fcntl.LOCK_UN)+ elif acquired and msvcrt is not None:+ getattr(msvcrt, "locking")(+ lock_fd.fileno(), getattr(msvcrt, "LK_UNLCK"), 1+ )+ except (OSError, IOError):+ pass+ finally:+ lock_fd.close()+++def fire_claim_fence(job_id: str, *, expected_owner: str):+ """Hold a per-job fence while an owner performs an external side effect."""+ with _fire_job_lock(job_id) as acquired:+ if not acquired:+ yield False+ return+ with _jobs_lock():+ job = next((item for item in load_jobs() if item.get("id") == job_id), None)+ claim = job.get("fire_claim") if isinstance(job, dict) else None+ owns_claim = (+ isinstance(claim, dict) and claim.get("by") == expected_owner+ )+ yield owns_claim+# Fields on a cron job that must never change after creation. ``id`` is used# as a filesystem path component under ``OUTPUT_DIR``; allowing it to be# updated lets an unsafe value (``../escape``, absolute path, nested) leak@@ -2069,10 +2151,37 @@ def remove_job(job_id: str) -> bool:"Failed to clear notepad for removed job %s",canonical_id, exc_info=True,)+ # Prune the per-job fire-fence lock entry so the registry does+ # not grow monotonically across create/remove cycles.+ _fence_key = f"{_current_cron_store().cron_dir.resolve()}::{canonical_id}"+ with _fire_fence_locks_guard:+ _fire_fence_locks.pop(_fence_key, None)return Truereturn False+def mark_job_run(+ job_id: str,+ success: bool,+ error: Optional[str] = None,+ delivery_error: Optional[str] = None,+ status: Optional[str] = None,+ *,+ expected_fire_owner: Optional[str] = None,+) -> bool:+ with _fire_job_lock(job_id) as acquired:+ if not acquired:+ return False+ return _mark_job_run_locked(+ job_id,+ success,+ error,+ delivery_error,+ status=status,+ expected_fire_owner=expected_fire_owner,+ )++def _set_alert_flag(job_id: str, field: str, value: bool) -> bool:"""Set/clear a persisted alert-dedup marker; return the PRIOR value.@@ -2124,9 +2233,15 @@ def clear_drift_alerted(job_id: str) -> None:_set_alert_flag(job_id, "drift_alerted", False)-def mark_job_run(job_id: str, success: bool, error: Optional[str] = None,- delivery_error: Optional[str] = None,- status: Optional[str] = None):+def _mark_job_run_locked(+ job_id: str,+ success: bool,+ error: Optional[str] = None,+ delivery_error: Optional[str] = None,+ *,+ status: Optional[str] = None,+ expected_fire_owner: Optional[str] = None,+) -> bool:"""Mark a job as having been run.@@ -2146,6 +2261,15 @@ def mark_job_run(job_id: str, success: bool, error: Optional[str] = None,jobs = load_jobs()for i, job in enumerate(jobs):if job["id"] == job_id:+ if expected_fire_owner is not None:+ claim = job.get("fire_claim")+ if not isinstance(claim, dict) or claim.get("by") != expected_fire_owner:+ logger.warning(+ "mark_job_run: job_id %s fire claim owner changed; "+ "discarding stale completion",+ job_id,+ )+ return Falsenow = _hermes_now().isoformat()job["last_run_at"] = nowjob["last_status"] = status or ("ok" if success else "error")@@ -2205,7 +2329,7 @@ def mark_job_run(job_id: str, success: bool, error: Optional[str] = None,job["state"] = "completed"job["next_run_at"] = Nonesave_jobs(jobs)- return+ return True# Compute next runjob["next_run_at"] = compute_next_run(job["schedule"], now)@@ -2240,9 +2364,10 @@ def mark_job_run(job_id: str, success: bool, error: Optional[str] = None,job["state"] = "scheduled"save_jobs(jobs)- return+ return Truelogger.warning("mark_job_run: job_id %s not found, skipping save", job_id)+ return Falsedef _write_wedged_oneshot_diagnostic(job: Dict[str, Any]) -> None:@@ -2474,7 +2599,31 @@ def _machine_id() -> str:return f"{host}:{os.getpid()}"-def claim_job_for_fire(job_id: str, *, claim_ttl_seconds: int = 300) -> bool:+def claim_job_for_fire(+ job_id: str,+ *,+ claim_ttl_seconds: int = 300,+ force: bool = False,+ return_job: bool = False,+) -> Union[bool, Dict[str, Any]]:+ with _fire_job_lock(job_id) as acquired:+ if not acquired:+ return False+ return _claim_job_for_fire_locked(+ job_id,+ claim_ttl_seconds=claim_ttl_seconds,+ force=force,+ return_job=return_job,+ )+++def _claim_job_for_fire_locked(+ job_id: str,+ *,+ claim_ttl_seconds: int = 300,+ force: bool = False,+ return_job: bool = False,+) -> Union[bool, Dict[str, Any]]:"""Atomically claim a job for a single external 'fire' (multi-machineat-most-once). Returns True iff THIS caller won the claim.@@ -2482,7 +2631,10 @@ def claim_job_for_fire(job_id: str, *, claim_ttl_seconds: int = 300) -> bool:external scheduler (Chronos) signals a job is due across N gateway replicas:exactly one wins. Single-machine deployments always win.- Under the file lock: reject if the job is missing/disabled/paused. If a+ Under the file lock: reject if the job is missing/disabled/paused. An+ explicit manual fire may pass ``force=True`` to atomically enable and+ resume the job as part of the claim; external scheduler callbacks must+ leave it false so a stale callback cannot resurrect a paused job. If afresh claim (younger than ``claim_ttl_seconds``) already exists, lose.Otherwise stamp a ``fire_claim`` and, for recurring jobs, advance``next_run_at`` (mirrors ``advance_next_run``'s at-most-once bump so a stale@@ -2501,8 +2653,10 @@ def claim_job_for_fire(job_id: str, *, claim_ttl_seconds: int = 300) -> bool:if job["id"] != job_id:continue# enabled + pause markers must both clear — a half-paused record- # (enabled=true, state=paused/paused_at set) must not claim.- if not is_job_runnable(job):+ # (enabled=true, state=paused/paused_at set) must not claim. An+ # explicit ``force`` (Trigger-now on a paused job) bypasses the+ # gate and atomically resumes the job below.+ if not force and not is_job_runnable(job):return Falsenow = _hermes_now()existing = job.get("fire_claim")@@ -2520,14 +2674,23 @@ def claim_job_for_fire(job_id: str, *, claim_ttl_seconds: int = 300) -> bool:return False # someone holds a fresh claimexcept Exception:pass # malformed claim → overwrite- job["fire_claim"] = {"at": now.isoformat(), "by": _machine_id()}+ if force:+ job["enabled"] = True+ job["state"] = "scheduled"+ job["paused_at"] = None+ job["paused_reason"] = None+ # Per-acquisition token: a process may legitimately reclaim its own+ # stale lease, and the previous runner must not heartbeat the new+ # claim merely because hostname + PID are unchanged.+ owner = f"{_machine_id()}:{uuid.uuid4().hex}"+ job["fire_claim"] = {"at": now.isoformat(), "by": owner}kind = job.get("schedule", {}).get("kind")if kind in {"cron", "interval"}:nxt = compute_next_run(job["schedule"], now.isoformat())if nxt:job["next_run_at"] = nxtsave_jobs(jobs)- return True+ return copy.deepcopy(job) if return_job else Truereturn False@@ -2617,6 +2780,39 @@ def _sweep_completed_oneshots(return removed+def heartbeat_fire_claim(job_id: str, *, expected_owner: str) -> bool:+ with _fire_job_lock(job_id) as acquired:+ if not acquired:+ return False+ return _heartbeat_fire_claim_locked(+ job_id,+ expected_owner=expected_owner,+ )+++def _heartbeat_fire_claim_locked(job_id: str, *, expected_owner: str) -> bool:+ """Refresh an active ``fire_claim`` without extending another owner's lease.++ A cron execution can legitimately outlive the fire-claim TTL. The shared+ run wrapper calls this periodically so another scheduler process cannot+ treat a live execution as abandoned and dispatch it again. Comparing the+ owner copied at dispatch prevents a stale runner from refreshing a claim+ that has since been recovered by another process.+ """+ with _jobs_lock():+ jobs = load_jobs()+ for job in jobs:+ if job.get("id") != job_id:+ continue+ claim = job.get("fire_claim")+ if not isinstance(claim, dict) or claim.get("by") != expected_owner:+ return False+ claim["at"] = _hermes_now().isoformat()+ save_jobs(jobs)+ return True+ return False++def get_due_jobs() -> List[Dict[str, Any]]:"""Get all jobs that are due to run now.diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 345a098b96d..bc3f5e71828 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -11,12 +11,14 @@ runs at a time if multiple processes overlap.import asyncioimport atexitimport concurrent.futures+import contextlibimport contextvarsimport jsonimport loggingimport osimport reimport shutil+import signalimport subprocessimport sysimport threading@@ -34,7 +36,7 @@ except ImportError:except ImportError:msvcrt = Nonefrom pathlib import Path-from typing import Any, List, Optional+from typing import Any, List, Optional, Protocol# Add parent directory to path for imports BEFORE repo-level imports.# Without this, standalone invocations (e.g. after `hermes update` reloads@@ -427,7 +429,18 @@ _LEGACY_HOME_TARGET_ENV_VARS = {"QQBOT_HOME_CHANNEL": "QQ_HOME_CHANNEL",}-from cron.jobs import get_due_jobs, mark_job_run, save_job_output, advance_next_runs, claim_dispatch, heartbeat_run_claim+from cron.jobs import (+ advance_next_runs,+ claim_dispatch,+ claim_job_for_fire,+ fire_claim_fence,+ get_due_jobs,+ heartbeat_fire_claim,+ heartbeat_run_claim,+ mark_job_run,+ save_job_output,+ use_cron_store,+)from cron.executions import create_execution, finish_execution, mark_execution_running# Sentinel: when a cron agent has nothing new to report, it can start its@@ -471,6 +484,7 @@ def _is_cron_silence_response(text: str) -> bool:_parallel_pool: Optional[concurrent.futures.ThreadPoolExecutor] = None_parallel_pool_max_workers: Optional[int] = None_running_job_ids: set = set()+_running_fire_owners: dict[str, dict[object, tuple[Optional[str], Path]]] = {}_running_lock = threading.Lock()# Wall-clock (time.time()) instant each in-flight job id was claimed by@@ -507,16 +521,48 @@ _FORCED_RELEASE_HISTORY = 20_INFLIGHT_MIN_ALLOWANCE_MINUTES = 30.0-# Job IDs the gateway shutdown path force-killed the tool subprocess of-# while still in ``_running_job_ids`` (see ``mark_running_jobs_interrupted``-# below). ``run_one_job``'s own completion path checks this set before-# writing its own ``last_status`` so a cron agent thread that keeps running-# in-process after its tool was killed out from under it — and produces a-# plausible-looking final response from truncated output — can never-# overwrite the interrupted status with a false "ok" (#60432).+# Execution tokens (``object()`` identity keys from ``_running_fire_owners``)+# of runs the shutdown path force-interrupted — see+# ``mark_running_jobs_interrupted`` below. ``run_one_job``'s own completion+# path checks its OWN token before writing ``last_status`` so a cron agent+# thread that keeps running in-process after its tool was killed out from+# under it — and produces a plausible-looking final response from truncated+# output — can never overwrite the interrupted status with a false "ok"+# (#60432). Token keying keeps an interruption scoped to that exact+# execution: a later run of the same job ID (recurring jobs reuse the ID+# every fire) must not inherit the stale flag. Legacy dispatch paths without+# a registered fire owner fall back to storing the bare job ID._interrupted_job_ids: set = set()+class _CancelEventLike(Protocol):+ """Structural type for cancellation sources (``threading.Event`` and+ ``_CombinedCancelEvent`` both satisfy it)."""++ def is_set(self) -> bool: ...+ def set(self) -> None: ...+++class _CombinedCancelEvent:+ """Duck-typed ``threading.Event`` that ORs several cancellation sources.++ ``run_one_job`` already derives a ``lost_ownership`` event from the+ fire-claim heartbeat; transports (dashboard webhook drain, API server+ shutdown) contribute their own per-task event. The worker only ever+ calls ``is_set()`` / ``set()``, so a tiny wrapper beats a pump thread.+ """++ def __init__(self, *events: Optional["_CancelEventLike"]) -> None:+ self._events = [event for event in events if event is not None]++ def is_set(self) -> bool:+ return any(event.is_set() for event in self._events)++ def set(self) -> None:+ for event in self._events:+ event.set()++def get_running_job_ids() -> "frozenset[str]":"""Thread-safe snapshot of cron job IDs currently executing.@@ -533,7 +579,7 @@ def get_running_job_ids() -> "frozenset[str]":blind to them (#60432)."""with _running_lock:- return frozenset(_running_job_ids)+ return frozenset(_running_job_ids | _running_fire_owners.keys())def try_register_running_job(job_id: str) -> bool:@@ -829,7 +875,11 @@ def sweep_stale_inflight(due_jobs: Optional[list] = None) -> list:return [s[0] for s in stale]-def mark_running_jobs_interrupted(reason: str) -> list:+def mark_running_jobs_interrupted(+ reason: str,+ *,+ only_owners: Optional[set] = None,+) -> list:"""Best-effort: mark every currently in-flight cron job interrupted.Called by the gateway shutdown path immediately after it force-kills@@ -851,24 +901,62 @@ def mark_running_jobs_interrupted(reason: str) -> list:every entry in ``_running_agents`` on a drain timeout withoutper-agent correlation either.+ ``only_owners``: optional set of ``(job_id, fire_owner)`` pairs. When+ given (dashboard webhook drain), ONLY those exact executions are+ marked — unrelated runs sharing the process (e.g. the desktop ticker's+ own jobs) are left untouched. Interruption flags are recorded per+ execution token, so a later run of the same job ID never consumes a+ stale flag that targeted its dead predecessor.+Returns the list of job IDs marked, for the caller to log."""with _running_lock:- job_ids = list(_running_job_ids)- _interrupted_job_ids.update(job_ids)+ active_fires = [+ (token, job_id, owner, profile_home)+ for job_id, executions in _running_fire_owners.items()+ for token, (owner, profile_home) in executions.items()+ ]+ if only_owners is not None:+ active_fires = [+ fire for fire in active_fires+ if (fire[1], fire[2]) in only_owners+ ]+ registered_ids = {job_id for _t, job_id, _o, _p in active_fires}+ if only_owners is None:+ active_fires.extend(+ (None, job_id, None, _get_hermes_home())+ for job_id in _running_job_ids - registered_ids+ )+ _interrupted_job_ids.update(+ token if token is not None else job_id+ for token, job_id, _owner, _profile_home in active_fires+ )marked = []- for job_id in job_ids:+ for _token, job_id, fire_owner, profile_home in active_fires:+ if not fire_owner:+ logger.warning(+ "Job '%s' interrupted before its durable fire owner was registered; "+ "leaving persisted state untouched",+ job_id,+ )+ continuetry:- mark_job_run(job_id, False, reason)- marked.append(job_id)+ with use_cron_store(profile_home):+ if mark_job_run(+ job_id,+ False,+ reason,+ expected_fire_owner=fire_owner,+ ):+ marked.append(job_id)except Exception as e:logger.warning("Failed to mark job %s interrupted: %s", job_id, e)return marked-def _is_interrupted(job_id: str) -> bool:- """Non-destructive peek at whether the shutdown path has marked- ``job_id`` interrupted (see ``mark_running_jobs_interrupted``).+def _is_interrupted(job_id: str, token: Optional[object] = None) -> bool:+ """Non-destructive peek at whether the shutdown path has marked THIS+ execution interrupted (see ``mark_running_jobs_interrupted``).Called by ``run_one_job`` BEFORE it decides what to deliver — a jobwhose tool subprocess was killed mid-flight may still produce a@@ -876,24 +964,35 @@ def _is_interrupted(job_id: str) -> bool:that must not go out to the user as if it were a normal result.Unlike ``_consume_interrupted_flag`` below, this does not clear theflag: the later, authoritative check (right before ``last_status`` is- written) still needs to see it."""+ written) still needs to see it. ``token`` scopes the check to one+ exact execution: owner-registered runs are matched by token, so a+ fresh run reusing the same job ID is not poisoned by a flag that+ targeted its dead predecessor. The bare job ID is only ever stored+ for legacy dispatch paths with no registered fire owner.+ """with _running_lock:+ if token is not None and token in _interrupted_job_ids:+ return Truereturn job_id in _interrupted_job_ids-def _consume_interrupted_flag(job_id: str) -> bool:+def _consume_interrupted_flag(job_id: str, token: Optional[object] = None) -> bool:"""Return True and clear the flag if the shutdown path already marked- ``job_id`` interrupted (see ``mark_running_jobs_interrupted``).+ THIS execution interrupted (see ``mark_running_jobs_interrupted``).Called by ``run_one_job`` right before it would otherwise write its own``last_status``. Consuming (discarding) rather than just checking keepsthe flag from leaking across a later, unrelated run of the same job ID(recurring jobs reuse their ID every fire)."""with _running_lock:+ hit = False+ if token is not None and token in _interrupted_job_ids:+ _interrupted_job_ids.discard(token)+ hit = Trueif job_id in _interrupted_job_ids:_interrupted_job_ids.discard(job_id)- return True- return False+ hit = True+ return hit# Sequential (env-mutating) cron jobs — workdir jobs that touch@@ -2808,6 +2907,7 @@ _DEFAULT_SCRIPT_TIMEOUT = 3600 # seconds (1 hour)# Backward-compatible module override used by tests and emergency monkeypatches._SCRIPT_TIMEOUT = _DEFAULT_SCRIPT_TIMEOUT_RUN_CLAIM_HEARTBEAT_SECONDS = 60.0+_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS = _RUN_CLAIM_HEARTBEAT_SECONDS * 3def _get_script_timeout() -> int:@@ -2901,9 +3001,91 @@ def _windows_cron_python_invocation(python_exe: str) -> tuple[str, dict[str, strreturn str(interpreter), env_overlay+def _terminate_cron_script_process(proc: subprocess.Popen) -> None:+ """Best-effort hard stop of a cron script and every child it spawned."""+ if proc.poll() is not None:+ return+ if sys.platform == "win32":+ try:+ subprocess.run(+ ["taskkill", "/PID", str(proc.pid), "/T", "/F"],+ capture_output=True,+ timeout=10,+ creationflags=windows_hide_flags(),+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired):+ proc.kill()+ else:+ try:+ process_group: Optional[int] = os.getpgid(proc.pid)+ except (ProcessLookupError, OSError):+ process_group = None+ if process_group is not None:+ try:+ os.killpg(process_group, signal.SIGTERM) # windows-footgun: ok — POSIX-only branch (win32 handled above)+ except (ProcessLookupError, PermissionError, OSError):+ process_group = None+ if process_group is not None:+ try:+ proc.wait(timeout=1.0)+ except subprocess.TimeoutExpired:+ pass+ # Escalate whenever ANY group member survived the TERM: a+ # TERM-ignoring descendant keeps the stdio pipe write ends+ # open, and the caller's communicate() would then block on+ # EOF forever. killpg(pgid, 0) probes group liveness.+ try:+ os.killpg(process_group, 0) # windows-footgun: ok — POSIX-only branch+ except (ProcessLookupError, OSError):+ process_group = None+ if process_group is not None:+ try:+ os.killpg(process_group, getattr(signal, "SIGKILL", signal.SIGTERM))+ except (ProcessLookupError, PermissionError, OSError):+ pass+ try:+ proc.wait(timeout=1.0)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait(timeout=1.0)+++def _drain_script_pipes(proc: subprocess.Popen) -> None:+ """Reap a terminated script process without ever blocking indefinitely.++ A descendant that survived the tree kill can hold the pipe write ends+ open, so a bare ``communicate()`` would wait for EOF forever. Bound the+ drain, then abandon the pipes — the caller only needs the process reaped+ and the worker thread unblocked, not the output.+ """+ try:+ proc.communicate(timeout=5.0)+ return+ except subprocess.TimeoutExpired:+ pass+ try:+ proc.kill()+ except OSError:+ pass+ for stream in (proc.stdout, proc.stderr):+ try:+ if stream is not None:+ stream.close()+ except OSError:+ pass+ try:+ proc.wait(timeout=5.0)+ except subprocess.TimeoutExpired:+ # Truly wedged — leave the zombie to the OS reaper rather than+ # blocking the cron worker thread forever.+ pass++def _run_job_script(script_path: str,workdir: Optional[str] = None,+ cancel_event: Optional[_CancelEventLike] = None,) -> tuple[bool, str]:"""Execute a cron job's data-collection script and capture its output.@@ -3006,10 +3188,11 @@ def _run_job_script(try:from tools.environments.local import build_subprocess_env- popen_kwargs = {}+ popen_kwargs: dict[str, Any] = {"start_new_session": True}if sys.platform == "win32":popen_kwargs = {- "creationflags": windows_hide_flags(),+ "creationflags": windows_hide_flags()+ | getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),"encoding": "utf-8","errors": "replace",}@@ -3020,17 +3203,34 @@ def _run_job_script(# NEVER mutate the Python process cwd — that would leak into# concurrent gateway sessions (#69396)._script_cwd = workdir or str(path.parent)- result = subprocess.run(+ proc = subprocess.Popen(argv,- capture_output=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,text=True,- timeout=script_timeout,cwd=_script_cwd,env=env,**popen_kwargs,)- stdout = (result.stdout or "").strip()- stderr = (result.stderr or "").strip()+ deadline = time.monotonic() + script_timeout+ while True:+ if cancel_event is not None and cancel_event.is_set():+ _terminate_cron_script_process(proc)+ _drain_script_pipes(proc)+ return False, "Script cancelled because cron fire ownership was lost"+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ _terminate_cron_script_process(proc)+ _drain_script_pipes(proc)+ return False, f"Script timed out after {script_timeout}s: {path}"+ try:+ stdout_raw, stderr_raw = proc.communicate(timeout=min(0.1, remaining))+ break+ except subprocess.TimeoutExpired:+ continue++ stdout = (stdout_raw or "").strip()+ stderr = (stderr_raw or "").strip()# Redact secrets from both stdout and stderr before any return path.try:@@ -3042,8 +3242,8 @@ def _run_job_script(stdout = "[REDACTED - redaction failed]"stderr = "[REDACTED - redaction failed]"- if result.returncode != 0:- parts = [f"Script exited with code {result.returncode}"]+ if proc.returncode != 0:+ parts = [f"Script exited with code {proc.returncode}"]if stderr:parts.append(f"stderr:\n{stderr}")if stdout:@@ -3052,14 +3252,15 @@ def _run_job_script(return True, stdout- except subprocess.TimeoutExpired:- return False, f"Script timed out after {script_timeout}s: {path}"except Exception as exc:return False, f"Script execution failed: {exc}"def _run_job_script_with_claim_heartbeat(- job: dict, script_path: str, workdir: Optional[str] = None,+ job: dict,+ script_path: str,+ workdir: Optional[str] = None,+ cancel_event: Optional[_CancelEventLike] = None,) -> tuple[bool, str]:"""Run a cron script while keeping its owned one-shot claim fresh.@@ -3081,7 +3282,7 @@ def _run_job_script_with_claim_heartbeat(and schedule.get("kind") == "once"and owner):- return _run_job_script(script_path, workdir=workdir)+ return _run_job_script(script_path, workdir=workdir, cancel_event=cancel_event)job_id = str(job.get("id") or "")stop = threading.Event()@@ -3112,10 +3313,10 @@ def _run_job_script_with_claim_heartbeat(job_id,exc_info=True,)- return _run_job_script(script_path, workdir=workdir)+ return _run_job_script(script_path, workdir=workdir, cancel_event=cancel_event)try:- return _run_job_script(script_path, workdir=workdir)+ return _run_job_script(script_path, workdir=workdir, cancel_event=cancel_event)finally:stop.set()# Event.wait() wakes immediately. Keep completion bounded if the@@ -3726,8 +3927,11 @@ def _preflight_job_config(job: dict, cfg: dict) -> Optional[str]:def run_job(- job: dict, *, defer_agent_teardown: Optional[list] = None,+ job: dict,+ *,+ defer_agent_teardown: Optional[list] = None,extra_prompt: Optional[str] = None,+ cancel_event: Optional[_CancelEventLike] = None,) -> tuple[bool, str, str, Optional[str]]:"""Execute a single cron job.@@ -3807,7 +4011,7 @@ def run_job(try:ok, output = _run_job_script_with_claim_heartbeat(- job, script_path, workdir=_job_workdir,+ job, script_path, workdir=_job_workdir, cancel_event=cancel_event,)except Exception as exc:logger.exception(@@ -4009,7 +4213,9 @@ def run_job(prerun_script = Nonescript_path = job.get("script")if script_path:- prerun_script = _run_job_script_with_claim_heartbeat(job, script_path)+ prerun_script = _run_job_script_with_claim_heartbeat(+ job, script_path, cancel_event=cancel_event,+ )_ran_ok, _script_output = prerun_scriptif _ran_ok and not _parse_wake_gate(_script_output):logger.info(@@ -4725,6 +4931,15 @@ def run_job()_last_claim_heartbeat = time.monotonic()+ def _abort_if_fire_claim_lost() -> None:+ if cancel_event is None or not cancel_event.is_set():+ return+ 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"+ )+def _heartbeat_run_claim_if_due():nonlocal _last_claim_heartbeatif not _is_oneshot or not _run_claim_owner:@@ -4754,15 +4969,17 @@ def run_job(if _cron_inactivity_limit is None:# Unlimited — no inactivity watchdog, but a one-shot still# needs its run_claim heartbeat, so poll instead of blocking.- if _is_oneshot:+ if _is_oneshot or cancel_event is not None:result = Nonewhile True:done, _ = concurrent.futures.wait({_cron_future}, timeout=_POLL_INTERVAL,)if done:+ _abort_if_fire_claim_lost()result = _cron_future.result()break+ _abort_if_fire_claim_lost()_heartbeat_run_claim_if_due()else:result = _cron_future.result()@@ -4773,8 +4990,10 @@ def run_job({_cron_future}, timeout=_POLL_INTERVAL,)if done:+ _abort_if_fire_claim_lost()result = _cron_future.result()break+ _abort_if_fire_claim_lost()_heartbeat_run_claim_if_due()# Agent still running — check inactivity._idle_secs = 0.0@@ -5120,9 +5339,117 @@ def _teardown_cron_agent(agent, job_id: str) -> None:logger.debug("Job '%s': failed to reap stale auxiliary clients: %s", job_id, e)+def _run_with_fire_claim_heartbeat(job: dict, run) -> bool:+ """Run ``run`` while keeping this job's owned durable fire claim fresh."""+ claim = job.get("fire_claim")+ owner = str(claim.get("by") or "") if isinstance(claim, dict) else ""+ if not owner:+ return run(None)++ job_id = str(job.get("id") or "")+ stop = threading.Event()+ lost_ownership = threading.Event()+ heartbeat_context = contextvars.copy_context()++ def _finish_unstarted(error: str) -> None:+ execution_id = job.get("execution_id")+ if not execution_id:+ return+ try:+ finish_execution(execution_id, success=False, error=error)+ except Exception:+ logger.warning(+ "Job '%s': failed to close unstarted execution ledger row",+ job_id,+ exc_info=True,+ )++ try:+ owns_fire_claim = heartbeat_fire_claim(job_id, expected_owner=owner)+ except Exception:+ logger.warning(+ "Job '%s': initial fire_claim validation failed",+ job_id,+ exc_info=True,+ )+ _finish_unstarted(+ "Fire claim ownership could not be validated before execution started."+ )+ return True++ if owns_fire_claim is False:+ logger.warning(+ "Job '%s': fire claim ownership was already lost before execution",+ job_id,+ )+ _finish_unstarted("Fire claim ownership lost before execution started.")+ return True++ def _heartbeat_loop() -> None:+ last_confirmed = time.monotonic()+ while not stop.wait(_RUN_CLAIM_HEARTBEAT_SECONDS):+ try:+ if not heartbeat_fire_claim(job_id, expected_owner=owner):+ lost_ownership.set()+ logger.warning(+ "Job '%s': fire claim ownership lost; interrupting stale run",+ job_id,+ )+ return+ last_confirmed = time.monotonic()+ except Exception:+ logger.debug(+ "Job '%s': fire_claim heartbeat failed",+ job_id,+ exc_info=True,+ )+ if (+ time.monotonic() - last_confirmed+ >= _FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS+ ):+ lost_ownership.set()+ logger.warning(+ "Job '%s': fire_claim could not be renewed within %.1fs; "+ "interrupting uncertain run",+ job_id,+ _FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS,+ )+ return++ heartbeat_thread = threading.Thread(+ target=heartbeat_context.run,+ args=(_heartbeat_loop,),+ name="cron-fire-claim-heartbeat",+ daemon=True,+ )+ try:+ heartbeat_thread.start()+ except Exception:+ logger.warning(+ "Job '%s': could not start fire_claim heartbeat",+ job_id,+ exc_info=True,+ )+ _finish_unstarted(+ "Fire claim heartbeat could not be started; execution was not run."+ )+ return True++ try:+ return run(lost_ownership)+ finally:+ stop.set()+ heartbeat_thread.join(timeout=1.0)++def run_one_job(- job: dict, *, adapters=None, loop=None, verbose: bool = False,+ job: dict,+ *,+ adapters=None,+ loop=None,+ verbose: bool = False,extra_prompt: Optional[str] = None,+ cancel_event: Optional[_CancelEventLike] = None,) -> bool:"""Run ONE due job end-to-end: execute → save output → deliver → mark.@@ -5130,14 +5457,94 @@ def run_one_job(that BOTH the built-in ticker and an external provider's ``fire_due`` (e.g.Chronos) run the identical sequence — no duplicated correctness.- It does NOT decide whether the job is due, claim it, or compute the next- run — those are the caller's concern (``tick`` advances ``next_run_at``- under the file lock before dispatch; an external provider claims via the- store CAS). This function only fires the given job once.+ It does NOT decide whether the job is due or acquire the initial claim —+ both the ticker and external providers use the same store CAS before+ calling it. It does keep an acquired claim alive for the full execution.Returns True if the job was processed (even if the job itself failed —failure is recorded via ``mark_job_run``), False only if processing raised.++ ``cancel_event``: optional transport-level cancellation source (dashboard+ webhook drain, API server shutdown). It is OR-combined with the internal+ fire-claim heartbeat's lost-ownership event, so either trigger stops the+ run cooperatively — agent interruption AND script process-tree kill —+ through the single fenced completion path."""+ claim = job.get("fire_claim")+ fire_owner = str(claim.get("by") or "") if isinstance(claim, dict) else ""+ execution_token = object()+ profile_home = _get_hermes_home().resolve()+ with _running_lock:+ _running_fire_owners.setdefault(job["id"], {})[execution_token] = (+ fire_owner or None,+ profile_home,+ )+ try:+ return _run_with_fire_claim_heartbeat(+ job,+ lambda lost_ownership: _run_one_job_body(+ job,+ adapters=adapters,+ loop=loop,+ verbose=verbose,+ extra_prompt=extra_prompt,+ fire_claim_lost=(+ _CombinedCancelEvent(lost_ownership, cancel_event)+ if cancel_event is not None+ else lost_ownership+ ),+ execution_token=execution_token,+ ),+ )+ finally:+ with _running_lock:+ executions = _running_fire_owners.get(job["id"])+ if executions is not None:+ executions.pop(execution_token, None)+ if not executions:+ _running_fire_owners.pop(job["id"], None)+++def _run_one_job_body(+ job: dict,+ *,+ adapters=None,+ loop=None,+ verbose: bool = False,+ extra_prompt: Optional[str] = None,+ fire_claim_lost: Optional[_CancelEventLike] = None,+ execution_token: Optional[object] = None,+) -> bool:+ claim = job.get("fire_claim")+ fire_owner = str(claim.get("by") or "") if isinstance(claim, dict) else None++ class _FireClaimLostDuringSideEffect(Exception):+ pass++ def _side_effect_fence():+ if fire_owner is None:+ return contextlib.nullcontext(True)+ return fire_claim_fence(job["id"], expected_owner=fire_owner)++ def _fire_claim_ownership_lost() -> bool:+ if fire_claim_lost is not None and fire_claim_lost.is_set():+ return True+ if fire_owner is None:+ return False+ try:+ if heartbeat_fire_claim(job["id"], expected_owner=fire_owner):+ return False+ except Exception:+ logger.debug(+ "Job '%s': fire_claim ownership validation failed",+ job["id"],+ exc_info=True,+ )+ return False+ if fire_claim_lost is not None:+ fire_claim_lost.set()+ return True+execution_id = job.get("execution_id")if not execution_id:execution_id = create_execution(job["id"], source="direct")["id"]@@ -5190,10 +5597,19 @@ def run_one_job(# interpreter-shutdown guard in _deliver_result._deferred_agents: list = []try:- success, output, final_response, error = run_job(- job, defer_agent_teardown=_deferred_agents,- extra_prompt=extra_prompt,- )+ if fire_claim_lost is None:+ success, output, final_response, error = run_job(+ job,+ defer_agent_teardown=_deferred_agents,+ extra_prompt=extra_prompt,+ )+ else:+ success, output, final_response, error = run_job(+ job,+ defer_agent_teardown=_deferred_agents,+ extra_prompt=extra_prompt,+ cancel_event=fire_claim_lost,+ )except BaseException:# run_job's finally still hands back the agent when it raises; tear# it down here so a failed run never leaks its async resources@@ -5206,6 +5622,37 @@ def run_one_job(finally:reset_secret_scope(_scope_token)+ if _fire_claim_ownership_lost():+ for _deferred_agent in _deferred_agents:+ _teardown_cron_agent(_deferred_agent, job["id"])+ # Distinguish a real ownership loss (TTL expiry / replacement+ # claim) from a transport-level cancel (dashboard drain): in the+ # latter case WE still own the claim, and silently discarding+ # would leave fire_claim lingering until TTL and last_status+ # stale. Probe ownership once; if still ours, record the+ # interruption through the owner-fenced terminal write.+ if fire_owner is not None and heartbeat_fire_claim(+ job["id"], expected_owner=fire_owner,+ ):+ mark_job_run(+ job["id"],+ False,+ "Interrupted by shutdown before terminal completion.",+ expected_fire_owner=fire_owner,+ )+ finish_execution(+ execution_id,+ success=False,+ error="Interrupted by shutdown before terminal completion.",+ )+ else:+ finish_execution(+ execution_id,+ success=False,+ error="Fire claim ownership lost; stale result was discarded.",+ )+ return True+# Everything from here through delivery runs with the agent still live# (deferred teardown). Wrap it ALL in a try/finally so that if any step# between run_job returning and delivery — save_job_output, the [SILENT]@@ -5214,8 +5661,12 @@ def run_one_job(# swallow the error and leak the agent's subprocesses/clients (#10200).delivery_error = Noneblocked_config = False+ side_effect_ownership_lost = Falsetry:- output_file = save_job_output(job["id"], output)+ with _side_effect_fence() as owns_output:+ if not owns_output:+ raise _FireClaimLostDuringSideEffect+ output_file = save_job_output(job["id"], output)if verbose:logger.info("Output saved to: %s", output_file)@@ -5226,7 +5677,7 @@ def run_one_job(# "this run was interrupted" summary instead of that response.# Peek-only: the flag stays set for the authoritative check# right before mark_job_run below.- if success and _is_interrupted(job["id"]):+ if success and _is_interrupted(job["id"], execution_token):success = Falseerror = ("Interrupted by gateway shutdown before the run finished "@@ -5303,16 +5754,35 @@ def run_one_job(logger.info("Job '%s': agent returned %s — skipping delivery", job["id"], SILENT_MARKER)should_deliver = False+ if should_deliver and _fire_claim_ownership_lost():+ should_deliver = False+ logger.warning(+ "Job '%s': skipping delivery after fire claim ownership loss",+ job["id"],+ )+if should_deliver:unresolved_origin = (_normalize_deliver_value(job.get("deliver", "local")) == "origin"and not _resolve_delivery_targets(job))try:- delivery_error = _deliver_result(job, deliver_content, adapters=adapters, loop=loop)+ with _side_effect_fence() as owns_delivery:+ if not owns_delivery:+ raise _FireClaimLostDuringSideEffect+ delivery_error = _deliver_result(+ job,+ deliver_content,+ adapters=adapters,+ loop=loop,+ )except Exception as de:+ if isinstance(de, _FireClaimLostDuringSideEffect):+ raisedelivery_error = str(de)logger.error("Delivery failed for job %s: %s", job["id"], de)+ except _FireClaimLostDuringSideEffect:+ side_effect_ownership_lost = Truefinally:# Tear down the deferred agent(s) now that save + delivery have run# (or raised). Must happen on every path so cron agents never leak@@ -5320,6 +5790,32 @@ def run_one_job(for _deferred_agent in _deferred_agents:_teardown_cron_agent(_deferred_agent, job["id"])+ if side_effect_ownership_lost or _fire_claim_ownership_lost():+ # Same transport-cancel distinction as the pre-side-effect path:+ # if WE still own the claim, record the interruption instead of+ # discarding silently (lingering claim + stale last_status).+ if fire_owner is not None and heartbeat_fire_claim(+ job["id"], expected_owner=fire_owner,+ ):+ mark_job_run(+ job["id"],+ False,+ "Interrupted by shutdown before terminal completion.",+ expected_fire_owner=fire_owner,+ )+ finish_execution(+ execution_id,+ success=False,+ error="Interrupted by shutdown before terminal completion.",+ )+ else:+ finish_execution(+ execution_id,+ success=False,+ error="Fire claim ownership lost; stale result was discarded.",+ )+ return True+# Treat empty final_response as a soft failure so last_status# is not "ok" — the agent ran but produced nothing useful.# (issue #8585)@@ -5327,14 +5823,28 @@ def run_one_job(success = Falseerror = "Agent completed but produced empty response (model error, timeout, or misconfiguration)"- if not _consume_interrupted_flag(job["id"]):- if blocked_config:- mark_job_run(- job["id"], success, error, delivery_error=delivery_error,- status="blocked_config",- )- else:- mark_job_run(job["id"], success, error, delivery_error=delivery_error)+ interrupted = _consume_interrupted_flag(job["id"], execution_token)+ if interrupted:+ finish_execution(+ execution_id,+ success=False,+ error="Interrupted by gateway shutdown before terminal completion.",+ )+ return True++ mark_kwargs = {"delivery_error": delivery_error}+ if fire_owner is not None:+ mark_kwargs["expected_fire_owner"] = fire_owner+ if blocked_config:+ mark_kwargs["status"] = "blocked_config"+ marked = mark_job_run(job["id"], success, error, **mark_kwargs)+ if fire_owner is not None and not marked:+ finish_execution(+ execution_id,+ success=False,+ error="Fire claim ownership lost before terminal completion.",+ )+ return Truenormalized_deliver = _normalize_deliver_value(job.get("deliver", "local"))if delivery_error:delivery_outcome = "failed"@@ -5361,12 +5871,16 @@ def run_one_job(# is never written, so the job sits in state "scheduled" until the# run-claim TTL expires and the dispatch-limit guard removes it with# no output and no error. Record the failure first, then re-raise- # anything that isn't a plain Exception.+ # anything that isn't a plain Exception. Owner fencing still applies:+ # a stale worker must not record over a replacement claim owner._err_text = str(e) or type(e).__name__logger.error("Error processing job %s: %s", job['id'], _err_text)try:- if not _consume_interrupted_flag(job["id"]):- mark_job_run(job["id"], False, _err_text)+ if not _consume_interrupted_flag(job["id"], execution_token):+ mark_kwargs = {}+ if fire_owner is not None:+ mark_kwargs["expected_fire_owner"] = fire_owner+ mark_job_run(job["id"], False, _err_text, **mark_kwargs)except Exception as record_err:# Never let bookkeeping mask the original interruption.logger.error(@@ -5555,6 +6069,10 @@ def tick(# bumping next_run_at forward so the grace window never expires.# mark_job_run() overwrites next_run_at on completion.# Batched: one load + one save for the whole due set, not one per job.+ # Composes with the claim-time advance in claim_job_for_fire: for+ # cron-kind jobs both compute the same next occurrence; interval jobs+ # re-anchor from their own "now" at claim time (harmless for+ # at-most-once — mark_job_run re-anchors at completion regardless).advance_next_runs([job["id"] for job in due_jobs])# Resolve max parallel workers: env var > config.yaml > unbounded.@@ -5589,7 +6107,28 @@ def tick(module-level ``run_one_job`` so ``tick`` and external providers(Chronos ``fire_due``) use the identical execute→save→deliver→markbody."""- return run_one_job(job, adapters=adapters, loop=loop, verbose=verbose)+ # Acquire the durable claim only when this worker actually starts,+ # not while it may wait behind other work in an executor queue.+ # This prevents a queued lease from expiring before execution.+ claimed = claim_job_for_fire(job["id"], return_job=True)+ if not claimed:+ finish_execution(+ job["execution_id"],+ success=False,+ error="Fire claim lost; execution was not started.",+ )+ return True+ # Production CAS returns the exact persisted record with its unique+ # owner. Bool fallback keeps older test doubles/API overrides+ # compatible; real callers using return_job=True never take it.+ claimed_job = dict(claimed) if isinstance(claimed, dict) else dict(job)+ claimed_job["execution_id"] = job["execution_id"]+ return run_one_job(+ claimed_job,+ adapters=adapters,+ loop=loop,+ verbose=verbose,+ )# Partition due jobs: those with a per-job workdir mutate# os.environ["TERMINAL_CWD"] inside run_job, which is process-global, sodiff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.pyindex db3641a8c96..e5923d5ed03 100644--- a/cron/scheduler_provider.py+++ b/cron/scheduler_provider.py@@ -19,6 +19,7 @@ selected via the `cron.provider` config key (empty = built-in)."""from __future__ import annotations+import inspectimport threadingfrom abc import ABC, abstractmethodfrom typing import Any@@ -98,7 +99,23 @@ class CronScheduler(ABC):return recover_interrupted_executions()- def fire_due(self, job_id: str, *, adapters: Any = None, loop: Any = None) -> bool:+ @property+ def supports_force_fire(self) -> bool:+ """Whether ``fire_due`` accepts the additive ``force`` keyword.++ Signature detection keeps providers written before ``force`` was added+ source-compatible. Providers accepting ``**kwargs`` are compatible.+ """+ return provider_supports_force_fire(self)++ def fire_due(+ self,+ job_id: str,+ *,+ adapters: Any = None,+ loop: Any = None,+ force: bool = False,+ ) -> bool:"""Run a single job NOW via the shared orchestrator. Called by theinbound fire webhook when an external scheduler signals a job is due.@@ -107,20 +124,72 @@ class CronScheduler(ABC):``run_one_job`` body. Built-in never calls this (it has its own tickloop); an external provider routes its inbound fire here.- Returns True if THIS caller claimed and ran the job, False if the claim- was lost (another machine/retry won it) or the job no longer exists.+ Returns True if THIS caller claimed and processed the attempt, even if+ the job itself failed. Returns False only if the claim was lost+ (another machine/retry won it) or the job no longer exists.+ """+ claimed_job = self.claim_fire(job_id, force=force)+ if claimed_job is None:+ return False+ return self.fire_claimed(claimed_job, adapters=adapters, loop=loop)++ def claim_fire(self, job_id: str, *, force: bool = False) -> dict | None:+ """Durably claim one fire and create its audit attempt before dispatch.++ Webhook transports call this synchronously before acknowledging the+ external scheduler, then pass the exact owner-bearing snapshot to+ ``fire_claimed`` in tracked background work.+ """+ from cron.executions import create_execution, finish_execution+ from cron.jobs import claim_job_for_fire++ execution = create_execution(job_id, source=self.name)+ claim_kwargs = {"return_job": True}+ if force:+ claim_kwargs["force"] = True+ try:+ claimed_job = claim_job_for_fire(job_id, **claim_kwargs)+ except BaseException as exc:+ finish_execution(+ execution["id"],+ success=False,+ error=f"Fire claim failed before dispatch: {type(exc).__name__}: {exc}",+ )+ raise+ if not isinstance(claimed_job, dict):+ finish_execution(+ execution["id"],+ success=False,+ error="Fire claim was not acquired",+ )+ return None+ claimed_job["execution_id"] = execution["id"]+ return claimed_job++ def fire_claimed(+ self,+ claimed_job: dict,+ *,+ adapters: Any = None,+ loop: Any = None,+ cancel_event: Any = None,+ ) -> bool:+ """Run an exact snapshot returned by ``claim_fire``.++ ``cancel_event``: optional transport-owned ``threading.Event`` (or+ compatible) that lets the caller stop this execution cooperatively+ — e.g. the dashboard lifespan drain signalling pending webhook+ fires before the event loop shuts down."""- from cron.jobs import claim_job_for_fire, get_job- from cron.executions import create_executionfrom cron.scheduler import run_one_job- if not claim_job_for_fire(job_id):- return False # another machine already claimed this fire- job = get_job(job_id)- if job is None:- return False # job removed (e.g. repeat-N exhausted) between arm and fire- job["execution_id"] = create_execution(job_id, source=self.name)["id"]- return run_one_job(job, adapters=adapters, loop=loop)+ run_one_job(+ claimed_job,+ adapters=adapters,+ loop=loop,+ cancel_event=cancel_event,+ )+ return Truedef reconcile(self) -> None:"""Converge the external registry toward jobs.json (the desired state):@@ -129,6 +198,68 @@ class CronScheduler(ABC):return None+def provider_supports_force_fire(provider: Any) -> bool:+ """Return whether a provider can safely receive ``fire_due(force=...)``."""+ try:+ parameters = inspect.signature(provider.fire_due).parameters.values()+ except (TypeError, ValueError):+ return False+ return any(+ parameter.kind is inspect.Parameter.VAR_KEYWORD+ or (+ parameter.name == "force"+ and parameter.kind+ in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)+ )+ for parameter in parameters+ )+++def provider_supports_split_fire(provider: Any) -> bool:+ """Return whether a provider implements the two-phase fire contract.++ The webhook admission path uses ``claim_fire`` + ``fire_claimed`` so the+ 202 response is backed by a durable, owner-fenced claim. A legacy+ third-party provider that overrides the documented single-phase+ ``fire_due`` hook (custom claim/re-arm/telemetry behavior) but inherits+ the base ``claim_fire`` must keep being driven through its own+ ``fire_due`` — silently routing around its override would drop that+ behavior. Providers that customize ``claim_fire`` itself are already+ split-aware and keep the two-phase path.+ """+ cls = type(provider)+ fire_due_impl = getattr(cls, "fire_due", None)+ claim_fire_impl = getattr(cls, "claim_fire", None)+ fire_claimed_impl = getattr(cls, "fire_claimed", None)+ if claim_fire_impl is not None and claim_fire_impl is not CronScheduler.claim_fire:+ return True+ # Overriding the second phase is also proof of split-awareness (the+ # provider composes with the inherited claim path) — e.g. Chronos keeps+ # its re-arm logic in ``fire_claimed`` only.+ if fire_claimed_impl is not None and fire_claimed_impl is not CronScheduler.fire_claimed:+ return True+ if fire_due_impl is None or fire_due_impl is CronScheduler.fire_due:+ return True+ return False+++def provider_supports_fire_cancel(provider: Any) -> bool:+ """Return whether ``fire_claimed`` accepts a ``cancel_event`` kwarg."""+ try:+ parameters = inspect.signature(provider.fire_claimed).parameters.values()+ except (TypeError, ValueError):+ return False+ return any(+ parameter.kind is inspect.Parameter.VAR_KEYWORD+ or (+ parameter.name == "cancel_event"+ and parameter.kind+ in (inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY)+ )+ for parameter in parameters+ )++def resolve_cron_scheduler() -> "CronScheduler":"""Return the active cron scheduler provider.@@ -169,6 +300,28 @@ def resolve_cron_scheduler() -> "CronScheduler":return InProcessCronScheduler()+def scheduler_for_profile_mode(+ provider: "CronScheduler", *, multiplex_profiles: bool+) -> "CronScheduler":+ """Return a scheduler that can safely serve the gateway's profile mode.++ External providers currently own one unscoped remote registry/client and+ therefore cannot safely reconcile several profile stores from one process.+ Fail closed to the built-in multiplex ticker until the provider API carries+ explicit profile identity through lifecycle and webhook calls.+ """+ if not multiplex_profiles or isinstance(provider, InProcessCronScheduler):+ return provider++ import logging++ logging.getLogger("cron.scheduler_provider").warning(+ "cron.provider '%s' does not support multiplex_profiles; using built-in ticker",+ provider.name,+ )+ return InProcessCronScheduler()++class InProcessCronScheduler(CronScheduler):"""Default provider: the historical in-process 60s ticker.diff --git a/gateway/run.py b/gateway/run.pyindex 1dd0e9e7c34..081af9f49b3 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -29630,9 +29630,17 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =# historical in-process 60s ticker; an external provider (e.g. chronos)# may arm a schedule and return. Pass the event loop so cron delivery can# use live adapters (E2EE support).- from cron.scheduler_provider import InProcessCronScheduler, resolve_cron_scheduler+ from cron.scheduler_provider import (+ InProcessCronScheduler,+ resolve_cron_scheduler,+ scheduler_for_profile_mode,+ )cron_stop = threading.Event()- cron_provider = resolve_cron_scheduler()+ multiplex_cron = bool(getattr(runner.config, "multiplex_profiles", False))+ cron_provider = scheduler_for_profile_mode(+ resolve_cron_scheduler(),+ multiplex_profiles=multiplex_cron,+ )cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}# Multiplex profiles: tell the built-in ticker which profile homes to@@ -29643,7 +29651,7 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =# never execute because no ticker owns that store.if (isinstance(cron_provider, InProcessCronScheduler)- and getattr(runner.config, "multiplex_profiles", False)+ and multiplex_cron):try:profile_homes = _multiplex_profile_homes(runner.config)diff --git a/tests/cron/test_claim_job_for_fire.py b/tests/cron/test_claim_job_for_fire.pyindex 16c827972e4..fa0f7b39b34 100644--- a/tests/cron/test_claim_job_for_fire.py+++ b/tests/cron/test_claim_job_for_fire.py@@ -7,6 +7,9 @@ claim for a given fire. Single-machine deployments always win (unaffected).These exercise the real store against a temp HERMES_HOME (no mocks) per theE2E-over-mocks discipline for file-touching code."""+import threading+import time+import pytest@@ -32,6 +35,47 @@ def test_claim_succeeds_once_then_blocks(temp_home):assert get_job(jid)["next_run_at"] != before+def test_claim_oneshot_cannot_be_double_claimed(temp_home):+ """A one-shot can't be double-claimed (the fresh claim blocks the retry)."""+ from cron.jobs import create_job, claim_job_for_fire++ job = create_job(prompt="x", schedule="30m", name="o")+ assert claim_job_for_fire(job["id"]) is True+ assert claim_job_for_fire(job["id"]) is False+++def test_claim_unknown_job_returns_false(temp_home):+ from cron.jobs import claim_job_for_fire++ assert claim_job_for_fire("nope-does-not-exist") is False+++def test_claim_paused_job_returns_false(temp_home):+ """A paused job can't be claimed."""+ from cron.jobs import create_job, claim_job_for_fire, pause_job++ job = create_job(prompt="x", schedule="every 5m", name="p")+ pause_job(job["id"])+ assert claim_job_for_fire(job["id"]) is False+++def test_forced_claim_atomically_resumes_paused_job(temp_home):+ """Explicit manual fire may resume a paused job without exposing a due+ intermediate state to the ticker."""+ from cron.jobs import create_job, claim_job_for_fire, get_job, pause_job++ job = create_job(prompt="x", schedule="every 5m", name="manual")+ pause_job(job["id"])++ assert claim_job_for_fire(job["id"], force=True) is True+ claimed = get_job(job["id"])+ assert claimed["enabled"] is True+ assert claimed["state"] == "scheduled"+ assert claimed["paused_at"] is None+ assert claimed["paused_reason"] is None+ assert claimed["fire_claim"] is not None++def test_stale_claim_is_reclaimable(temp_home, monkeypatch):"""A claim older than the TTL is overwritten — the fire isn't stuck foreverif the winning machine crashed before mark_job_run cleared the claim."""@@ -58,3 +102,116 @@ def test_mark_job_run_clears_claim(temp_home):assert get_job(jid).get("fire_claim") is None# …and the re-armed recurring job is claimable again.assert claim_job_for_fire(jid) is True+++def test_fire_claim_heartbeat_refreshes_only_expected_owner(temp_home, monkeypatch):+ from datetime import datetime, timedelta++ import cron.jobs as jobs++ job = jobs.create_job(prompt="x", schedule="every 5m", name="heartbeat")+ assert jobs.claim_job_for_fire(job["id"]) is True+ claimed = jobs.get_job(job["id"])["fire_claim"]+ claimed_at = datetime.fromisoformat(claimed["at"])+ monkeypatch.setattr(+ jobs,+ "_hermes_now",+ lambda: claimed_at + timedelta(seconds=30),+ )++ assert jobs.heartbeat_fire_claim(+ job["id"],+ expected_owner=claimed["by"],+ ) is True+ refreshed = jobs.get_job(job["id"])["fire_claim"]+ assert refreshed["at"] != claimed["at"]+ assert refreshed["by"] == claimed["by"]+ assert jobs.heartbeat_fire_claim(+ job["id"],+ expected_owner="replacement-owner",+ ) is False+++def test_reclaimed_fire_uses_new_owner_token(temp_home, monkeypatch):+ from datetime import datetime, timedelta++ import cron.jobs as jobs++ job = jobs.create_job(prompt="x", schedule="every 5m", name="reclaim")+ assert jobs.claim_job_for_fire(job["id"]) is True+ original = dict(jobs.get_job(job["id"])["fire_claim"])+ original_at = datetime.fromisoformat(original["at"])+ monkeypatch.setattr(+ jobs,+ "_hermes_now",+ lambda: original_at + timedelta(seconds=301),+ )++ assert jobs.claim_job_for_fire(job["id"]) is True+ replacement = dict(jobs.get_job(job["id"])["fire_claim"])+ assert replacement["by"] != original["by"]+ assert jobs.heartbeat_fire_claim(+ job["id"],+ expected_owner=original["by"],+ ) is False+ assert jobs.get_job(job["id"])["fire_claim"] == replacement+++def test_stale_fire_owner_cannot_mark_replacement_run(temp_home):+ import cron.jobs as jobs++ job = jobs.create_job(prompt="x", schedule="every 5m", name="fenced")+ assert jobs.claim_job_for_fire(job["id"]) is True+ original = dict(jobs.get_job(job["id"])["fire_claim"])+ records = jobs.load_jobs()+ records[0]["fire_claim"] = {"at": original["at"], "by": "replacement"}+ jobs.save_jobs(records)++ assert jobs.mark_job_run(+ job["id"],+ success=True,+ expected_fire_owner=original["by"],+ ) is False+ persisted = jobs.get_job(job["id"])+ assert persisted["fire_claim"]["by"] == "replacement"+ assert persisted.get("last_run_at") is None+++def test_fire_claim_fence_serializes_terminal_revocation(temp_home):+ """A side effect authorized by owner linearizes before terminal revocation."""+ from cron.jobs import (+ claim_job_for_fire,+ create_job,+ fire_claim_fence,+ mark_job_run,+ )++ job = create_job(prompt="x", schedule="every 5m", name="fenced-side-effect")+ claimed = claim_job_for_fire(job["id"], return_job=True)+ assert isinstance(claimed, dict)+ owner = claimed["fire_claim"]["by"]+ terminal_done = threading.Event()++ def finish_run():+ mark_job_run(job["id"], True, expected_fire_owner=owner)+ terminal_done.set()++ with fire_claim_fence(job["id"], expected_owner=owner) as owns_claim:+ assert owns_claim is True+ thread = threading.Thread(target=finish_run)+ thread.start()+ time.sleep(0.05)+ assert terminal_done.is_set() is False++ thread.join(timeout=1)+ assert terminal_done.is_set() is True+++def test_fire_claim_fence_rejects_stale_owner(temp_home):+ from cron.jobs import claim_job_for_fire, create_job, fire_claim_fence++ job = create_job(prompt="x", schedule="every 5m", name="stale-fence")+ claim_job_for_fire(job["id"])++ with fire_claim_fence(job["id"], expected_owner="stale") as owns_claim:+ assert owns_claim is Falsediff --git a/tests/cron/test_cron_no_agent.py b/tests/cron/test_cron_no_agent.pyindex 6378e4bde62..52f51ba3038 100644--- a/tests/cron/test_cron_no_agent.py+++ b/tests/cron/test_cron_no_agent.py@@ -158,10 +158,37 @@ def test_timed_out_no_agent_script_delivery_is_not_mislabeled_as_provider_failur)delivered = []- def _timeout(*_args, **kwargs):- raise subprocess.TimeoutExpired(cmd="slow.py", timeout=kwargs["timeout"])+ # The script runner uses Popen + a polling loop (cancel/timeout aware),+ # so simulate a process that never finishes: communicate() always times+ # out and the script deadline is shrunk to keep the test fast.+ class _NeverFinishes:+ returncode = None+ pid = 0+ stdout = None+ stderr = None- monkeypatch.setattr(scheduler.subprocess, "run", _timeout)+ def __init__(self, *_args, **_kwargs):+ pass++ def poll(self):+ return None++ def communicate(self, timeout=None):+ raise subprocess.TimeoutExpired(cmd="slow.py", timeout=timeout)++ def wait(self, timeout=None):+ raise subprocess.TimeoutExpired(cmd="slow.py", timeout=timeout)++ def kill(self):+ self.returncode = -9++ monkeypatch.setattr(scheduler.subprocess, "Popen", _NeverFinishes)+ monkeypatch.setattr(scheduler, "_get_script_timeout", lambda: 1)+ monkeypatch.setattr(+ scheduler,+ "_terminate_cron_script_process",+ lambda proc: setattr(proc, "returncode", -15),+ )monkeypatch.setattr(scheduler,"_deliver_result",diff --git a/tests/cron/test_cron_script.py b/tests/cron/test_cron_script.pyindex 32642e0341b..311140c3e95 100644--- a/tests/cron/test_cron_script.py+++ b/tests/cron/test_cron_script.py@@ -156,20 +156,39 @@ class TestRunJobScript:captured = {}- def fake_run(argv, **kwargs):- captured["argv"] = argv- captured["kwargs"] = kwargs- return SimpleNamespace(returncode=0, stdout="ok\n", stderr="")+ class FakeProc:+ def __init__(self, argv, **kwargs):+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ self.returncode = 0++ def poll(self):+ return self.returncode++ def communicate(self, timeout=None):+ return ("ok\n", "")++ def wait(self, timeout=None):+ return self.returncode++ fake_run = FakeProcmonkeypatch.setattr(sched_mod.sys, "executable", str(venv_python))- monkeypatch.setattr(sched_mod.subprocess, "run", fake_run)+ monkeypatch.setattr(sched_mod, "windows_hide_flags", lambda: 0x08000000)+ monkeypatch.setattr(sched_mod.subprocess, "Popen", fake_run)success, output = _run_job_script("probe.py")assert success is Trueassert output == "ok"assert captured["argv"] == [str(base_python), str(script.resolve())]- assert captured["kwargs"]["creationflags"] == sched_mod.windows_hide_flags()+ # The script runner always adds CREATE_NEW_PROCESS_GROUP on win32 so a+ # cancel can taskkill the whole tree; on POSIX the getattr default is+ # 0 and the flag set is exactly windows_hide_flags().+ expected_flags = sched_mod.windows_hide_flags() | getattr(+ sched_mod.subprocess, "CREATE_NEW_PROCESS_GROUP", 0+ )+ assert captured["kwargs"]["creationflags"] == expected_flagsenv = captured["kwargs"]["env"]assert env["VIRTUAL_ENV"] == str(venv)assert str(site_packages) in env["PYTHONPATH"]@@ -185,12 +204,25 @@ class TestRunJobScript:captured = {}- def fake_run(argv, **kwargs):- captured["argv"] = argv- captured["kwargs"] = kwargs- return SimpleNamespace(returncode=0, stdout="ok\n", stderr="")+ class FakeProc:+ def __init__(self, argv, **kwargs):+ captured["argv"] = argv+ captured["kwargs"] = kwargs+ self.returncode = 0++ def poll(self):+ return self.returncode++ def communicate(self, timeout=None):+ return ("ok\n", "")++ def wait(self, timeout=None):+ return self.returncode++ fake_run = FakeProc- monkeypatch.setattr(sched_mod.subprocess, "run", fake_run)+ monkeypatch.setattr(sched_mod.sys, "platform", "linux")+ monkeypatch.setattr(sched_mod.subprocess, "Popen", fake_run)success, output = _run_job_script("probe.py")diff --git a/tests/cron/test_cron_workdir.py b/tests/cron/test_cron_workdir.pyindex be2c2aced20..284675de892 100644--- a/tests/cron/test_cron_workdir.py+++ b/tests/cron/test_cron_workdir.py@@ -145,6 +145,53 @@ class TestTickWorkdirPartition:pieces tick() calls."""+ def test_workdir_jobs_run_sequentially(self, tmp_path, monkeypatch):+ import cron.scheduler as sched++ # Two workdir jobs (both sequential) + one parallel job.+ workdir_a = {"id": "a", "name": "A", "workdir": str(tmp_path)}+ workdir_b = {"id": "b", "name": "B", "workdir": str(tmp_path)}+ parallel_job = {"id": "c", "name": "C", "workdir": None}++ monkeypatch.setattr(sched, "get_due_jobs", lambda: [workdir_a, workdir_b, parallel_job])+ monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)++ # Record call order / thread context.+ import threading+ calls: list[tuple[str, str]] = []+ order_lock = threading.Lock()++ def fake_run_job(job, *, defer_agent_teardown=None, **_kw):+ # Return a minimal tuple matching run_job's signature.+ with order_lock:+ calls.append((job["id"], threading.current_thread().name))+ return True, "output", "response", None++ monkeypatch.setattr(sched, "run_job", fake_run_job)+ monkeypatch.setattr(sched, "save_job_output", lambda _jid, _o: None)+ monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)+ monkeypatch.setattr(+ sched, "_deliver_result", lambda *_a, **_kw: None+ )++ n = sched.tick(verbose=False)+ assert n == 3++ ids = [c[0] for c in calls]+ # Sequential workdir jobs preserve submission order relative to each+ # other (single-thread pool).+ assert ids.index("a") < ids.index("b")++ # Workdir jobs run on the persistent single-thread cron-seq pool —+ # NOT the main thread — so a long workdir job never blocks the ticker.+ main_thread_name = threading.current_thread().name+ for jid in ("a", "b"):+ workdir_thread_name = next(t for j, t in calls if j == jid)+ assert workdir_thread_name != main_thread_name+ assert workdir_thread_name.startswith("cron-seq"), workdir_thread_name+ par_thread_name = next(t for j, t in calls if j == "c")+ assert par_thread_name.startswith("cron-parallel"), par_thread_name+# ---------------------------------------------------------------------------# scheduler.run_job: TERMINAL_CWD + skip_context_files wiringdiff --git a/tests/cron/test_execution_ledger.py b/tests/cron/test_execution_ledger.pyindex 5f268c64192..5c02b6eea8e 100644--- a/tests/cron/test_execution_ledger.py+++ b/tests/cron/test_execution_ledger.py@@ -39,6 +39,24 @@ def test_execution_transitions_are_durable(monkeypatch, tmp_path):assert persisted == [completed]+def test_execution_ledger_follows_the_current_profile_home(monkeypatch, tmp_path):+ import cron.executions as executions++ current_home = {"path": tmp_path / "default"}+ monkeypatch.setattr(executions, "EXECUTIONS_FILE", None)+ monkeypatch.setattr(executions, "get_hermes_home", lambda: current_home["path"])++ default_row = executions.create_execution("default-job", source="builtin")+ current_home["path"] = tmp_path / "worker"+ worker_row = executions.create_execution("worker-job", source="builtin")++ assert executions.list_executions() == [worker_row]+ current_home["path"] = tmp_path / "default"+ assert executions.list_executions() == [default_row]+ assert (tmp_path / "default" / "cron" / "executions.db").is_file()+ assert (tmp_path / "worker" / "cron" / "executions.db").is_file()++def test_terminal_execution_cannot_be_rewritten(monkeypatch, tmp_path):executions = _point_ledger(monkeypatch, tmp_path)record = executions.create_execution("immutable", source="builtin")@@ -182,7 +200,7 @@ def test_generic_submit_failure_finishes_attempt_and_releases_guard(monkeypatch)lambda execution_id, **kwargs: finished.append((execution_id, kwargs)),)monkeypatch.setattr(scheduler, "get_due_jobs", lambda: [{"id": "submit-fail"}])- monkeypatch.setattr(scheduler, "advance_next_runs", lambda _ids: 0)+ monkeypatch.setattr(scheduler, "claim_job_for_fire", lambda _job_id: True)monkeypatch.setattr(scheduler, "_get_parallel_pool", lambda _workers: BrokenPool())assert scheduler.tick(verbose=False, sync=False) == 0diff --git a/tests/cron/test_parallel_pool.py b/tests/cron/test_parallel_pool.pyindex 4eca57463ea..41d3cff547e 100644--- a/tests/cron/test_parallel_pool.py+++ b/tests/cron/test_parallel_pool.py@@ -71,7 +71,7 @@ class TestRunningJobGuard:dispatched = []monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])- monkeypatch.setattr(sched, "advance_next_runs", lambda *_a, **_kw: 0)+ monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)monkeypatch.setattr(sched, "run_job", lambda j, **_kw: dispatched.append(j["id"]) or (True, "out", "resp", None))monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: None)monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)@@ -85,6 +85,56 @@ class TestRunningJobGuard:sched._shutdown_parallel_pool()+ def test_fire_claim_is_acquired_only_when_executor_worker_starts(self, monkeypatch):+ """Queue wait must not consume the durable claim TTL."""+ import cron.scheduler as sched++ sched._running_job_ids.clear()+ job = {+ "id": "queued-job",+ "name": "queued",+ "prompt": "test",+ "schedule": "every 5m",+ "enabled": True,+ "next_run_at": "2020-01-01T00:00:00",+ "deliver": "local",+ }+ submitted = []+ claim_calls = []++ class DeferredPool:+ def submit(self, callback):+ future = concurrent.futures.Future()+ submitted.append((callback, future))+ return future++ monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])+ monkeypatch.setattr(sched, "_get_parallel_pool", lambda _workers: DeferredPool())+ monkeypatch.setattr(+ sched,+ "create_execution",+ lambda *_a, **_kw: {"id": "execution-1"},+ )+ monkeypatch.setattr(+ sched,+ "claim_job_for_fire",+ lambda job_id, **kwargs: claim_calls.append((job_id, kwargs))+ or {**job, "fire_claim": {"by": "worker-owner", "at": "now"}},+ )+ monkeypatch.setattr(sched, "run_one_job", lambda *_a, **_kw: True)++ assert sched.tick(verbose=False, sync=False) == 1+ assert claim_calls == []+ assert len(submitted) == 1++ callback, future = submitted[0]+ result = callback()+ future.set_result(result)++ assert claim_calls == [("queued-job", {"return_job": True})]+ assert "queued-job" not in sched._running_job_ids++class TestSyncMode:"""tick() blocks by default (sync=True); tick(sync=False) returns immediately."""@@ -104,7 +154,7 @@ class TestSyncMode:]monkeypatch.setattr(sched, "get_due_jobs", lambda: jobs)- monkeypatch.setattr(sched, "advance_next_runs", lambda *_a, **_kw: 0)+ monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)monkeypatch.setattr(sched, "run_job", lambda j, **_kw: (True, "out", "resp", None))monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out")monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)@@ -115,6 +165,49 @@ class TestSyncMode:sched._shutdown_parallel_pool()+ def test_sync_false_returns_immediately(self, tmp_path, monkeypatch):+ """sync=False returns before parallel jobs finish (optimistic count)."""+ import cron.scheduler as sched++ sched._parallel_pool = None+ sched._parallel_pool_max_workers = None+ sched._running_job_ids.clear()++ job = {+ "id": "slow-job",+ "name": "slow",+ "prompt": "test",+ "schedule": "every 5m",+ "enabled": True,+ "next_run_at": "2020-01-01T00:00:00",+ "deliver": "local",+ }++ barrier = threading.Barrier(2, timeout=5)++ def slow_run(j, *, defer_agent_teardown=None, **_kw):+ barrier.wait() # blocks until test thread also waits+ return True, "out", "resp", None++ monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])+ monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)+ monkeypatch.setattr(sched, "run_job", slow_run)+ monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out")+ monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)+ monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)++ start = time.monotonic()+ n = sched.tick(verbose=False, sync=False) # opt-in: non-blocking+ elapsed = time.monotonic() - start++ assert n == 1 # optimistic count+ assert elapsed < 1.0 # returned immediately, didn't wait for slow_run++ # Let the job finish so cleanup works.+ barrier.wait()+ time.sleep(0.1)+ sched._shutdown_parallel_pool()+class TestSequentialPool:"""Sequential (workdir) jobs use the persistent cron-seq pool.@@ -151,7 +244,7 @@ class TestSequentialPool:return True, "out", "resp", Nonemonkeypatch.setattr(sched, "get_due_jobs", lambda: [job])- monkeypatch.setattr(sched, "advance_next_runs", lambda *_a, **_kw: 0)+ monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)monkeypatch.setattr(sched, "run_job", slow_run)monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: "/tmp/out")monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)@@ -168,6 +261,43 @@ class TestSequentialPool:time.sleep(0.1)sched._shutdown_parallel_pool()+ def test_sequential_running_guard_prevents_double_dispatch(self, tmp_path, monkeypatch):+ """A workdir job already in _running_job_ids is skipped on next tick."""+ import cron.scheduler as sched++ sched._parallel_pool = None+ sched._parallel_pool_max_workers = None+ sched._sequential_pool = None+ sched._running_job_ids.clear()++ job = {+ "id": "guard-seq",+ "name": "guard-seq",+ "prompt": "test",+ "schedule": "every 5m",+ "enabled": True,+ "next_run_at": "2020-01-01T00:00:00",+ "deliver": "local",+ "workdir": str(tmp_path),+ }++ # Simulate the job already running.+ sched._running_job_ids.add("guard-seq")++ dispatched = []+ monkeypatch.setattr(sched, "get_due_jobs", lambda: [job])+ monkeypatch.setattr(sched, "claim_job_for_fire", lambda *_a, **_kw: True)+ monkeypatch.setattr(sched, "run_job", lambda j, **_kw: dispatched.append(j["id"]) or (True, "out", "resp", None))+ monkeypatch.setattr(sched, "save_job_output", lambda *_a, **_kw: None)+ monkeypatch.setattr(sched, "mark_job_run", lambda *_a, **_kw: None)+ monkeypatch.setattr(sched, "_deliver_result", lambda *_a, **_kw: None)++ n = sched.tick(verbose=False)+ assert n == 0 # skipped, not dispatched+ assert dispatched == []++ sched._running_job_ids.discard("guard-seq")+ sched._shutdown_parallel_pool()def test_get_sequential_pool_is_persistent(self):"""_get_sequential_pool returns the same single-thread pool."""diff --git a/tests/cron/test_recurring_eagain_redispatch.py b/tests/cron/test_recurring_eagain_redispatch.pyindex 74a28eb32ff..5e9d499541f 100644--- a/tests/cron/test_recurring_eagain_redispatch.py+++ b/tests/cron/test_recurring_eagain_redispatch.py@@ -68,18 +68,34 @@ def wedge_env(tmp_path, monkeypatch):class TestEAGAINRecurringRedispatches:def _make_script_eagain(self, env, monkeypatch):- """Make the next subprocess.run raise EAGAIN once, then pass."""+ """Make the next subprocess.Popen raise EAGAIN once, then pass.++ The script runner spawns via Popen (polling loop for cancel/timeout),+ so the substrate-failure injection point is the Popen constructor.+ """import cron.scheduler as sched_mod- real_run = sched_mod.subprocess.runstate = {"n": 0}- def fake_run(argv, **kwargs):+ class _OkProc:+ def __init__(self, argv, **kwargs):+ self.returncode = 0++ def poll(self):+ return self.returncode++ def communicate(self, timeout=None):+ return ("ok\n", "")++ def wait(self, timeout=None):+ return 0++ def fake_popen(argv, **kwargs):state["n"] += 1if state["n"] == 1:raise OSError(11, "Resource temporarily unavailable")- return subprocess.CompletedProcess(argv, 0, stdout="ok\n", stderr="")+ return _OkProc(argv, **kwargs)- monkeypatch.setattr(sched_mod.subprocess, "run", fake_run)+ monkeypatch.setattr(sched_mod.subprocess, "Popen", fake_popen)return statedef test_eagain_then_redispatched_on_next_tick(self, wedge_env, monkeypatch, tmp_path):diff --git a/tests/cron/test_run_one_job.py b/tests/cron/test_run_one_job.pyindex a61866c5441..462416fe1b3 100644--- a/tests/cron/test_run_one_job.py+++ b/tests/cron/test_run_one_job.py@@ -46,7 +46,7 @@ def test_tick_process_job_sequence(monkeypatch):sequence run_job → save → deliver → mark, in that order."""calls = _patch_pipeline(monkeypatch)monkeypatch.setattr(s, "get_due_jobs", lambda: [{"id": "j1", "name": "t"}])- monkeypatch.setattr(s, "advance_next_runs", lambda ids: 1)+ monkeypatch.setattr(s, "claim_job_for_fire", lambda _job_id, **_kwargs: True)s.tick(verbose=False, sync=True)@@ -54,6 +54,16 @@ def test_tick_process_job_sequence(monkeypatch):assert calls[-1] == ("mark", "j1", True)+def test_tick_skips_job_when_durable_fire_claim_is_lost(monkeypatch):+ """A manual/external fire that wins the shared CAS must exclude ticker."""+ calls = _patch_pipeline(monkeypatch)+ monkeypatch.setattr(s, "get_due_jobs", lambda: [{"id": "j1", "name": "t"}])+ monkeypatch.setattr(s, "claim_job_for_fire", lambda _job_id: False)++ assert s.tick(verbose=False, sync=True) == 0+ assert calls == []++def test_run_one_job_success_sequence(monkeypatch):"""The extracted helper runs the same execute→save→deliver→mark sequencefor a successful job."""diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.pyindex b8e5cce6526..007da444a46 100644--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@ -662,13 +662,345 @@ class TestRunJobSessionPersistence:"enabled": True,}with patch("cron.scheduler.get_due_jobs", return_value=[job]), patch(- "cron.scheduler.advance_next_runs"- ) as advance, patch("cron.scheduler.run_one_job") as run_one:+ "cron.scheduler.claim_job_for_fire", return_value=True+ ) as claim, patch("cron.scheduler.run_one_job") as run_one:assert tick(verbose=False, sync=True, can_dispatch=lambda: False) == 0- advance.assert_not_called()+ claim.assert_not_called()run_one.assert_not_called()+ def test_tick_marks_empty_response_as_error(self, tmp_path):+ """When run_job returns success=True but final_response is empty,+ tick() should mark the job as error so last_status != 'ok'.+ (issue #8585)+ """+ from cron.scheduler import tick++ job = {+ "id": "empty-job",+ "name": "empty-test",+ "prompt": "do something",+ "schedule": "every 1h",+ "enabled": True,+ "next_run_at": "2020-01-01T00:00:00",+ "deliver": "local",+ "last_status": None,+ }++ fake_db = MagicMock()++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler.get_due_jobs", return_value=[job]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.mark_job_run") as mock_mark, \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._resolve_origin", return_value=None), \+ patch("cron.scheduler.run_job", return_value=(True, "output", "", None)):+ tick(verbose=False)++ # Should be called with success=False because final_response is empty+ mock_mark.assert_called_once()+ call_args = mock_mark.call_args+ assert call_args[0][0] == "empty-job"+ assert call_args[0][1] is False # success should be False+ assert "empty" in call_args[0][2].lower() # error should mention empty++ def test_run_job_sets_auto_delivery_env_from_dotenv_home_channel(self, tmp_path, monkeypatch):+ job = {+ "id": "test-job",+ "name": "test",+ "prompt": "hello",+ "deliver": "telegram",+ }+ fake_db = MagicMock()+ seen = {}++ (tmp_path / ".env").write_text("TELEGRAM_HOME_CHANNEL=-2002\n")+ monkeypatch.delenv("TELEGRAM_HOME_CHANNEL", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_PLATFORM", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_CHAT_ID", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_THREAD_ID", raising=False)++ class FakeAgent:+ def __init__(self, *args, **kwargs):+ pass++ def run_conversation(self, *args, **kwargs):+ from gateway.session_context import get_session_env+ seen["platform"] = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM") or None+ seen["chat_id"] = get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID") or None+ seen["thread_id"] = get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID") or None+ return {"final_response": "ok"}++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._preflight_job_config", return_value=None), \+ patch("hermes_state.SessionDB", return_value=fake_db), \+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "***",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ), \+ patch("run_agent.AIAgent", FakeAgent):+ success, output, final_response, error = run_job(job)++ assert success is True+ assert error is None+ assert final_response == "ok"+ assert "ok" in output+ assert seen == {+ "platform": "telegram",+ "chat_id": "-2002",+ "thread_id": None,+ }+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_PLATFORM") is None+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_CHAT_ID") is None+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_THREAD_ID") is None+ fake_db.close.assert_called_once()++ def test_run_job_preserves_slack_origin_thread_for_same_explicit_channel(self, tmp_path, monkeypatch):+ job = {+ "id": "slack-thread-job",+ "name": "slack-thread",+ "prompt": "hello",+ "deliver": "slack:C0B3KEP3SD6",+ "origin": {+ "platform": "slack",+ "chat_id": "C0B3KEP3SD6",+ "thread_id": "1778485067.844139",+ },+ }+ fake_db = MagicMock()+ seen = {}++ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_PLATFORM", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_CHAT_ID", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_THREAD_ID", raising=False)++ class FakeAgent:+ def __init__(self, *args, **kwargs):+ pass++ def run_conversation(self, *args, **kwargs):+ from gateway.session_context import get_session_env++ seen["platform"] = get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM") or None+ seen["chat_id"] = get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID") or None+ seen["thread_id"] = get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID") or None+ return {"final_response": "ok"}++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._preflight_job_config", return_value=None), \+ patch("hermes_state.SessionDB", return_value=fake_db), \+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "***",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ), \+ patch("run_agent.AIAgent", FakeAgent):+ success, output, final_response, error = run_job(job)++ assert success is True+ assert error is None+ assert final_response == "ok"+ assert "ok" in output+ assert seen == {+ "platform": "slack",+ "chat_id": "C0B3KEP3SD6",+ "thread_id": "1778485067.844139",+ }+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_PLATFORM") is None+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_CHAT_ID") is None+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_THREAD_ID") is None+ fake_db.close.assert_called_once()++ @pytest.mark.parametrize("timeout_value", ["600", "0"])+ def test_run_job_heartbeats_oneshot_claim_in_both_wait_modes(+ self, tmp_path, monkeypatch, timeout_value+ ):+ """Timed and unlimited one-shot monitors both refresh their owned claim."""+ job = {+ "id": "heartbeat-job",+ "name": "heartbeat",+ "prompt": "hello",+ "schedule": {"kind": "once", "run_at": "2026-07-10T12:00:00Z"},+ "run_claim": {"at": "2026-07-10T12:00:00Z", "by": "owner-token"},+ }+ fake_db = MagicMock()++ class FakeAgent:+ def __init__(self, *args, **kwargs):+ pass++ def run_conversation(self, *args, **kwargs):+ return {"final_response": "ok"}++ class FakeFuture:+ def result(self):+ return {"final_response": "ok"}++ fake_future = FakeFuture()+ fake_pool = MagicMock()+ fake_pool.submit.return_value = fake_future+ wait_results = [(set(), set()), ({fake_future}, set())]+ monotonic_ticks = itertools.count(step=61.0)+ monkeypatch.setenv("HERMES_CRON_TIMEOUT", timeout_value)++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._preflight_job_config", return_value=None), \+ patch("hermes_state.SessionDB", return_value=fake_db), \+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "***",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ), \+ patch("run_agent.AIAgent", FakeAgent), \+ patch("cron.scheduler.concurrent.futures.ThreadPoolExecutor", return_value=fake_pool), \+ patch("cron.scheduler.concurrent.futures.wait", side_effect=wait_results), \+ patch("cron.scheduler.time.monotonic", side_effect=monotonic_ticks.__next__), \+ patch("cron.scheduler.heartbeat_run_claim", return_value=True) as heartbeat:+ success, _output, final_response, error = run_job(job)++ assert success is True+ assert error is None+ assert final_response == "ok"+ heartbeat.assert_called_once_with(+ "heartbeat-job", expected_owner="owner-token"+ )++ def test_run_job_resets_secret_source_cache_before_reload(self, tmp_path, monkeypatch):+ """Each run must clear the secret-source cache before re-reading the+ env, so a long-running gateway re-resolves Bitwarden/BSM-backed secrets+ instead of leaving the startup .env placeholder in place (#33465).++ A bare ``load_dotenv`` re-load can't do this: startup already recorded+ this HERMES_HOME in ``_APPLIED_HOMES``, so the external-secret pull+ no-ops and only the placeholder is re-applied. The scheduler must call+ ``reset_secret_source_cache()`` (forcing the re-pull) and route through+ ``load_hermes_dotenv`` (which then re-applies external secret sources).+ """+ job = {"id": "bsm-job", "name": "bsm", "prompt": "hello"}+ fake_db = MagicMock()+ call_order = []++ def _record_reset():+ call_order.append("reset")++ def _record_load(*args, **kwargs):+ call_order.append("load")+ return []++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._resolve_origin", return_value=None), \+ patch("hermes_cli.env_loader.reset_secret_source_cache", _record_reset), \+ patch("hermes_cli.env_loader.load_hermes_dotenv", _record_load), \+ patch("hermes_state.SessionDB", return_value=fake_db), \+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "***",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ), \+ patch("run_agent.AIAgent") as mock_agent_cls:+ mock_agent = MagicMock()+ mock_agent.run_conversation.return_value = {"final_response": "ok"}+ mock_agent_cls.return_value = mock_agent+ success, _output, _final, error = run_job(job)++ assert success is True+ assert error is None+ # reset MUST precede the reload, else _APPLIED_HOMES no-ops the re-pull.+ assert call_order[:2] == ["reset", "load"], call_order++ def test_run_job_clears_stale_auto_delivery_thread_id_between_jobs(self, tmp_path, monkeypatch):+ jobs = [+ {+ "id": "threaded-job",+ "name": "threaded",+ "prompt": "hello",+ "deliver": "telegram:-1001:42",+ },+ {+ "id": "threadless-job",+ "name": "threadless",+ "prompt": "hello again",+ "deliver": "telegram:-2002",+ },+ ]+ fake_db = MagicMock()+ seen = []++ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_PLATFORM", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_CHAT_ID", raising=False)+ monkeypatch.delenv("HERMES_CRON_AUTO_DELIVER_THREAD_ID", raising=False)++ class FakeAgent:+ def __init__(self, *args, **kwargs):+ pass++ def run_conversation(self, *args, **kwargs):+ from gateway.session_context import get_session_env++ seen.append(+ {+ "platform": get_session_env("HERMES_CRON_AUTO_DELIVER_PLATFORM") or None,+ "chat_id": get_session_env("HERMES_CRON_AUTO_DELIVER_CHAT_ID") or None,+ "thread_id": get_session_env("HERMES_CRON_AUTO_DELIVER_THREAD_ID") or None,+ }+ )+ return {"final_response": "ok"}++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._preflight_job_config", return_value=None), \+ patch("hermes_state.SessionDB", return_value=fake_db), \+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "***",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ), \+ patch("run_agent.AIAgent", FakeAgent):+ for job in jobs:+ success, output, final_response, error = run_job(job)+ assert success is True+ assert error is None+ assert final_response == "ok"+ assert "ok" in output++ assert seen == [+ {+ "platform": "telegram",+ "chat_id": "-1001",+ "thread_id": "42",+ },+ {+ "platform": "telegram",+ "chat_id": "-2002",+ "thread_id": None,+ },+ ]+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_PLATFORM") is None+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_CHAT_ID") is None+ assert os.getenv("HERMES_CRON_AUTO_DELIVER_THREAD_ID") is None+ assert fake_db.close.call_count == 2+class TestRunJobConfigLogging:"""Verify that config.yaml parse failures are logged, not silently swallowed."""@@ -1028,6 +1360,7 @@ class TestSilentDelivery:def test_silent_response_suppresses_delivery(self, caplog):with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT]", None)), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \patch("cron.scheduler._deliver_result") as deliver_mock, \@@ -1038,12 +1371,61 @@ class TestSilentDelivery:deliver_mock.assert_not_called()assert any(SILENT_MARKER in r.message for r in caplog.records)+ def test_silent_with_note_suppresses_delivery(self):+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.run_job", return_value=(True, "# output", "[SILENT] No changes detected", None)), \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._deliver_result") as deliver_mock, \+ patch("cron.scheduler.mark_job_run"):+ from cron.scheduler import tick+ tick(verbose=False)+ deliver_mock.assert_not_called()++ def test_silent_trailing_suppresses_delivery(self):+ """Agent appended [SILENT] after explanation text — must still suppress."""+ response = "2 deals filtered out (like<10, reply<15).\n\n[SILENT]"+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.run_job", return_value=(True, "# output", response, None)), \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._deliver_result") as deliver_mock, \+ patch("cron.scheduler.mark_job_run"):+ from cron.scheduler import tick+ tick(verbose=False)+ deliver_mock.assert_not_called()++ def test_silent_is_case_insensitive(self):+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.run_job", return_value=(True, "# output", "[silent] nothing new", None)), \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._deliver_result") as deliver_mock, \+ patch("cron.scheduler.mark_job_run"):+ from cron.scheduler import tick+ tick(verbose=False)+ deliver_mock.assert_not_called()++ def test_bracketless_silent_variants_suppress(self):+ """Bracketless near-markers the model emits when it drops brackets+ must still suppress delivery (#51438, #46917)."""+ from cron.scheduler import tick+ for marker in ("SILENT", "NO_REPLY", "NO REPLY", "no_reply"):+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.run_job", return_value=(True, "# output", marker, None)), \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._deliver_result") as deliver_mock, \+ patch("cron.scheduler.mark_job_run"):+ tick(verbose=False)+ deliver_mock.assert_not_called()def test_report_quoting_marker_mid_sentence_still_delivers(self):"""A genuine report that merely mentions the token mid-sentence mustbe delivered — the old substring check wrongly swallowed it."""response = "I considered staying [SILENT] but here is the summary: 3 items merged."with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", return_value=(True, "# output", response, None)), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \patch("cron.scheduler._deliver_result") as deliver_mock, \@@ -1056,6 +1438,7 @@ class TestSilentDelivery:def test_failed_job_always_delivers(self):"""Failed jobs deliver regardless of [SILENT] in output."""with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", return_value=(False, "# output", "", "some error")), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \patch("cron.scheduler._deliver_result") as deliver_mock, \@@ -1064,10 +1447,23 @@ class TestSilentDelivery:tick(verbose=False)deliver_mock.assert_called_once()+ def test_output_saved_even_when_delivery_suppressed(self):+ with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.run_job", return_value=(True, "# full output", "[SILENT]", None)), \+ patch("cron.scheduler.save_job_output") as save_mock, \+ patch("cron.scheduler._deliver_result") as deliver_mock, \+ patch("cron.scheduler.mark_job_run"):+ save_mock.return_value = "/tmp/out.md"+ from cron.scheduler import tick+ tick(verbose=False)+ save_mock.assert_called_once_with("monitor-job", "# full output")+ deliver_mock.assert_not_called()def test_whitespace_only_response_is_marked_failed_not_delivered(self):"""Whitespace-only final responses should behave like empty responses."""with patch("cron.scheduler.get_due_jobs", return_value=[self._make_job()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", return_value=(True, "# output", " \n\t ", None)), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \patch("cron.scheduler._deliver_result") as deliver_mock, \@@ -1101,6 +1497,7 @@ class TestOneShotDispatchClaim:def test_claim_runs_before_run_job(self):order = []with patch("cron.scheduler.get_due_jobs", return_value=[self._oneshot()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.claim_dispatch", side_effect=lambda _id: order.append("claim") or True), \patch("cron.scheduler.run_job", side_effect=lambda _j, **_kw: order.append("run") or (True, "# out", "ok", None)), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \@@ -1110,6 +1507,20 @@ class TestOneShotDispatchClaim:tick(verbose=False)assert order == ["claim", "run"] # claim strictly before side effect+ def test_refused_claim_skips_run_job(self):+ with patch("cron.scheduler.get_due_jobs", return_value=[self._oneshot()]), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.claim_dispatch", return_value=False), \+ patch("cron.scheduler.run_job") as run_mock, \+ patch("cron.scheduler.save_job_output"), \+ patch("cron.scheduler._deliver_result") as deliver_mock, \+ patch("cron.scheduler.mark_job_run") as mark_mock:+ from cron.scheduler import tick+ tick(verbose=False)+ run_mock.assert_not_called()+ deliver_mock.assert_not_called()+ mark_mock.assert_not_called()+class TestBuildJobPromptSilentHint:"""Verify _build_job_prompt always injects [SILENT] guidance."""@@ -1355,7 +1766,7 @@ class TestParallelTick:]with patch("cron.scheduler.get_due_jobs", return_value=jobs), \- patch("cron.scheduler.advance_next_runs"), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", side_effect=mock_run_job), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \patch("cron.scheduler._deliver_result", return_value=None), \@@ -1400,7 +1811,7 @@ class TestParallelTick:]with patch("cron.scheduler.get_due_jobs", return_value=jobs), \- patch("cron.scheduler.advance_next_runs"), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \patch("cron.scheduler.run_job", side_effect=mock_run_job), \patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \patch("cron.scheduler._deliver_result", return_value=None), \@@ -1411,6 +1822,38 @@ class TestParallelTick:assert seen["tg-job"] == {"platform": "telegram", "chat_id": "111"}assert seen["dc-job"] == {"platform": "discord", "chat_id": "222"}+ def test_max_parallel_env_var(self, monkeypatch):+ """HERMES_CRON_MAX_PARALLEL=1 should restore serial behaviour."""+ monkeypatch.setenv("HERMES_CRON_MAX_PARALLEL", "1")+ call_times = []++ def mock_run_job(job, *, defer_agent_teardown=None, **_kw):+ import time+ call_times.append(("start", job["id"], time.monotonic()))+ time.sleep(0.05)+ call_times.append(("end", job["id"], time.monotonic()))+ return (True, "output", "response", None)++ jobs = [+ {"id": "s1", "name": "s1", "deliver": "local"},+ {"id": "s2", "name": "s2", "deliver": "local"},+ ]++ with patch("cron.scheduler.get_due_jobs", return_value=jobs), \+ patch("cron.scheduler.claim_job_for_fire", return_value=True), \+ patch("cron.scheduler.run_job", side_effect=mock_run_job), \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._deliver_result", return_value=None), \+ patch("cron.scheduler.mark_job_run"):+ from cron.scheduler import tick+ result = tick(verbose=False)++ assert result == 2+ # With max_workers=1, second job starts after first ends+ end_s1 = [t for action, jid, t in call_times if action == "end" and jid == "s1"][0]+ start_s2 = [t for action, jid, t in call_times if action == "start" and jid == "s2"][0]+ assert start_s2 >= end_s1, "Jobs ran concurrently despite max_parallel=1"+class TestDeliverResultTimeoutCancelsFuture:"""When future.result(timeout=60) raises TimeoutError in the live adapterdiff --git a/tests/cron/test_scheduler_provider.py b/tests/cron/test_scheduler_provider.pyindex 0229d8dd48c..552fbdf5a11 100644--- a/tests/cron/test_scheduler_provider.py+++ b/tests/cron/test_scheduler_provider.py@@ -129,6 +129,39 @@ def test_abc_growth_stays_additive():)+def test_force_fire_capability_detects_legacy_override():+ from cron.scheduler_provider import CronScheduler++ class Current(CronScheduler):+ @property+ def name(self):+ return "current"++ def start(self, stop_event, **kw):+ pass++ class Legacy(Current):+ def fire_due( # type: ignore[invalid-method-override]+ self, job_id, *, adapters=None, loop=None+ ):+ return True++ class PositionalOnly(Current):+ def fire_due( # type: ignore[invalid-method-override]+ self, job_id, force=False, /+ ):+ return True++ class KeywordSink(Current):+ def fire_due(self, job_id, **kwargs):+ return True++ assert Current().supports_force_fire is True+ assert Legacy().supports_force_fire is False+ assert PositionalOnly().supports_force_fire is False+ assert KeywordSink().supports_force_fire is True++def test_inprocess_provider_ticks_and_stops():"""The built-in provider drives cron.scheduler.tick(sync=False) on a loopand exits promptly when stop_event is set — same contract as the raw@@ -214,6 +247,98 @@ def test_resolve_defaults_to_builtin(monkeypatch):assert prov.name == "builtin"+def test_resolve_no_cron_section_falls_back_to_builtin(monkeypatch):+ """Config with no cron section at all → built-in (cfg_get returns default)."""+ import hermes_cli.config as cfg+ from cron import scheduler_provider as sp++ monkeypatch.setattr(cfg, "load_config", lambda: {})+ prov = sp.resolve_cron_scheduler()+ assert prov.name == "builtin"+++def test_resolve_unknown_provider_falls_back_to_builtin(monkeypatch):+ """A named provider that doesn't exist → built-in (cron never dies)."""+ import hermes_cli.config as cfg+ from cron import scheduler_provider as sp++ monkeypatch.setattr(cfg, "load_config", lambda: {"cron": {"provider": "nope-not-real"}})+ prov = sp.resolve_cron_scheduler()+ assert prov.name == "builtin"+++def test_resolve_unavailable_provider_falls_back(monkeypatch):+ """A provider that loads but reports is_available()==False → built-in."""+ import hermes_cli.config as cfg+ import plugins.cron_providers as pc+ from cron import scheduler_provider as sp+ from cron.scheduler_provider import CronScheduler++ class Unavailable(CronScheduler):+ @property+ def name(self):+ return "unavailable"++ def is_available(self):+ return False++ def start(self, stop_event, **kw):+ pass++ monkeypatch.setattr(cfg, "load_config", lambda: {"cron": {"provider": "unavailable"}})+ monkeypatch.setattr(pc, "load_cron_scheduler", lambda n: Unavailable())+ prov = sp.resolve_cron_scheduler()+ assert prov.name == "builtin"+++def test_resolve_available_provider_is_used(monkeypatch):+ """A provider that loads and is available is returned (not the fallback)."""+ import hermes_cli.config as cfg+ import plugins.cron_providers as pc+ from cron import scheduler_provider as sp+ from cron.scheduler_provider import CronScheduler++ class Fake(CronScheduler):+ @property+ def name(self):+ return "fake"++ def is_available(self):+ return True++ def start(self, stop_event, **kw):+ pass++ monkeypatch.setattr(cfg, "load_config", lambda: {"cron": {"provider": "fake"}})+ monkeypatch.setattr(pc, "load_cron_scheduler", lambda n: Fake())+ prov = sp.resolve_cron_scheduler()+ assert prov.name == "fake"+++def test_external_provider_falls_back_to_builtin_under_multiplex():+ from cron.scheduler_provider import (+ CronScheduler,+ InProcessCronScheduler,+ scheduler_for_profile_mode,+ )++ class External(CronScheduler):+ @property+ def name(self):+ return "external"++ def start(self, stop_event, **kwargs):+ return None++ external = External()++ assert scheduler_for_profile_mode(external, multiplex_profiles=False) is external+ assert isinstance(+ scheduler_for_profile_mode(external, multiplex_profiles=True),+ InProcessCronScheduler,+ )++# ── Phase 4B: additive hooks (on_jobs_changed / fire_due / reconcile) ────────@@ -238,19 +363,120 @@ def test_builtin_inherits_hook_defaults():def test_fire_due_default_claims_then_runs(monkeypatch):- """The default fire_due claims via the store CAS, fetches the job, and runs- it through the shared run_one_job body."""+ """The default fire_due runs the exact owner-bearing CAS snapshot."""import cron.jobs as jobsimport cron.scheduler as schedfrom cron.scheduler_provider import InProcessCronSchedulerran = []- monkeypatch.setattr(jobs, "claim_job_for_fire", lambda jid: True, raising=False)- monkeypatch.setattr(jobs, "get_job", lambda jid: {"id": jid, "name": "t"})- monkeypatch.setattr(sched, "run_one_job", lambda job, **kw: ran.append(job["id"]) or True)+ claims = []+ monkeypatch.setattr(+ jobs,+ "claim_job_for_fire",+ lambda jid, **kw: claims.append((jid, kw))+ or {"id": jid, "name": "t", "fire_claim": {"by": "exact-owner"}},+ raising=False,+ )+ monkeypatch.setattr(+ sched,+ "run_one_job",+ lambda job, **kw: ran.append((job["id"], job["fire_claim"]["by"])) or True,+ )assert InProcessCronScheduler().fire_due("j1") is True- assert ran == ["j1"]+ assert claims == [("j1", {"return_job": True})]+ assert ran == [("j1", "exact-owner")]+++def test_claim_fire_persists_attempt_before_fire_claimed(monkeypatch):+ import cron.executions as executions+ import cron.jobs as jobs+ import cron.scheduler as sched+ from cron.scheduler_provider import InProcessCronScheduler++ events = []+ monkeypatch.setattr(+ jobs,+ "claim_job_for_fire",+ lambda jid, **kwargs: events.append("claim")+ or {"id": jid, "fire_claim": {"by": "owner"}},+ )+ monkeypatch.setattr(+ executions,+ "create_execution",+ lambda jid, source: events.append("ledger") or {"id": "exec-1"},+ )+ monkeypatch.setattr(+ sched,+ "run_one_job",+ lambda job, **kwargs: events.append(("run", job["execution_id"])) or True,+ )++ provider = InProcessCronScheduler()+ claimed = provider.claim_fire("j1")++ assert events == ["ledger", "claim"]+ assert claimed is not None+ assert claimed["execution_id"] == "exec-1"+ assert provider.fire_claimed(claimed) is True+ assert events == ["ledger", "claim", ("run", "exec-1")]+++def test_fire_due_forwards_manual_force_to_store_claim(monkeypatch):+ import cron.jobs as jobs+ import cron.scheduler as sched+ from cron.scheduler_provider import InProcessCronScheduler++ claims = []+ monkeypatch.setattr(+ jobs,+ "claim_job_for_fire",+ lambda jid, **kw: claims.append((jid, kw))+ or {"id": jid, "name": "t", "fire_claim": {"by": "manual-owner"}},+ )+ monkeypatch.setattr(sched, "run_one_job", lambda job, **kw: True)++ assert InProcessCronScheduler().fire_due("j1", force=True) is True+ assert claims == [("j1", {"force": True, "return_job": True})]+++def test_fire_due_lost_claim_does_not_run(monkeypatch):+ """If the CAS claim is lost (another machine/retry won), fire_due returns+ False and never runs the job."""+ import cron.jobs as jobs+ import cron.scheduler as sched+ from cron.scheduler_provider import InProcessCronScheduler++ ran = []+ monkeypatch.setattr(+ jobs,+ "claim_job_for_fire",+ lambda jid, **kw: False,+ raising=False,+ )+ monkeypatch.setattr(sched, "run_one_job", lambda job, **kw: ran.append(job["id"]) or True)++ assert InProcessCronScheduler().fire_due("j1") is False+ assert ran == []+++def test_fire_due_missing_job_does_not_run(monkeypatch):+ """If the job vanished before atomic claim, fire_due does not run it."""+ import cron.jobs as jobs+ import cron.scheduler as sched+ from cron.scheduler_provider import InProcessCronScheduler++ ran = []+ monkeypatch.setattr(+ jobs,+ "claim_job_for_fire",+ lambda jid, **kw: False,+ raising=False,+ )+ monkeypatch.setattr(sched, "run_one_job", lambda job, **kw: ran.append(job["id"]) or True)++ assert InProcessCronScheduler().fire_due("gone") is False+ assert ran == []# ── F2a: ticker liveness — survival, heartbeat, honest status (#32612, #32895) ──diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.pyindex 0caa7a95554..da393b3ee35 100644--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@ -1,12 +1,163 @@"""Regression coverage for one-shot claims during blocking cron scripts."""from datetime import datetime, timedelta, timezone+import contextlib+import sysimport threading+import timefrom unittest.mock import MagicMock, patchimport pytest+def test_cancel_event_terminates_script_process_tree(tmp_path, monkeypatch):+ """Losing a fire claim must stop both the script and its descendants."""+ import cron.scheduler as scheduler++ monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)+ scripts_dir = tmp_path / "scripts"+ scripts_dir.mkdir()+ started = tmp_path / "started"+ child_done = tmp_path / "child-done"+ script = scripts_dir / "blocking.py"+ child_code = (+ "import time; from pathlib import Path; "+ f"time.sleep(1); Path({str(child_done)!r}).write_text('done')"+ )+ script.write_text(+ "import subprocess, sys, time\n"+ f"subprocess.Popen([sys.executable, '-c', {child_code!r}])\n"+ f"open({str(started)!r}, 'w').close()\n"+ "time.sleep(30)\n",+ encoding="utf-8",+ )++ cancel = threading.Event()+ result = []+ errors = []++ def _run() -> None:+ try:+ result.append(+ scheduler._run_job_script(+ str(script),+ workdir=str(tmp_path),+ cancel_event=cancel,+ )+ )+ except Exception as exc:+ errors.append(exc)++ thread = threading.Thread(target=_run)+ thread.start()+ deadline = time.monotonic() + 5+ while not started.exists() and not errors and time.monotonic() < deadline:+ time.sleep(0.01)+ assert errors == []+ assert started.exists(), "script did not start"++ cancel.set()+ thread.join(timeout=3)++ assert errors == []+ assert not thread.is_alive(), "script ignored cancellation"+ assert result and result[0][0] is False+ assert "cancel" in result[0][1].lower()+ time.sleep(1.2)+ assert not child_done.exists(), "script descendant survived cancellation"++[email protected](sys.platform == "win32", reason="POSIX process-group semantics")+def test_cancel_event_kills_sigterm_ignoring_descendant(tmp_path, monkeypatch):+ """A SIGTERM-ignoring grandchild must not wedge the cancellation path:+ the tree kill escalates to SIGKILL for surviving group members, and the+ pipe drain is bounded even if a descendant still holds the write ends."""+ import cron.scheduler as scheduler++ monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: tmp_path)+ scripts_dir = tmp_path / "scripts"+ scripts_dir.mkdir()+ started = tmp_path / "started"+ script = scripts_dir / "stubborn.py"+ child_code = (+ "import signal, time; "+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "+ f"open({str(started)!r}, 'w').close(); "+ "time.sleep(60)"+ )+ script.write_text(+ "import subprocess, sys, time\n"+ f"subprocess.Popen([sys.executable, '-c', {child_code!r}])\n"+ "time.sleep(60)\n",+ encoding="utf-8",+ )++ cancel = threading.Event()+ result = []+ errors = []++ def _run() -> None:+ try:+ result.append(+ scheduler._run_job_script(+ str(script),+ workdir=str(tmp_path),+ cancel_event=cancel,+ )+ )+ except Exception as exc:+ errors.append(exc)++ thread = threading.Thread(target=_run)+ thread.start()+ deadline = time.monotonic() + 5+ while not started.exists() and not errors and time.monotonic() < deadline:+ time.sleep(0.01)+ assert errors == []+ assert started.exists(), "script did not spawn its descendant"++ cancel.set()+ # TERM grace (1s) + KILL + bounded drain (5s) + margin: must return well+ # before the unbounded-communicate hang this regresses against.+ thread.join(timeout=10)++ assert errors == []+ assert not thread.is_alive(), "cancellation wedged on a SIGTERM-ignoring descendant"+ assert result and result[0][0] is False+ assert "cancel" in result[0][1].lower()+++def test_no_agent_forwards_cancel_event_to_script_runner(monkeypatch):+ import cron.scheduler as scheduler++ cancel = threading.Event()+ observed = []++ def _script_runner(job, script_path, workdir=None, cancel_event=None):+ observed.append(cancel_event)+ return True, ""++ monkeypatch.setattr(+ scheduler,+ "_run_job_script_with_claim_heartbeat",+ _script_runner,+ )++ success, _output, _response, error = scheduler.run_job(+ {+ "id": "cancel-aware-script",+ "name": "cancel aware",+ "script": "watchdog.py",+ "no_agent": True,+ },+ cancel_event=cancel,+ )++ assert success is True+ assert error is None+ assert observed == [cancel]++@pytest.mark.parametrize(("no_agent", "script_output"),[@@ -163,3 +314,267 @@ def test_script_heartbeat_uses_captured_claim_owner(tmp_path, monkeypatch):"at": replacement_timestamp,"by": "replacement-owner",}+++def test_run_one_job_refreshes_fire_claim_in_profile_store(tmp_path, monkeypatch):+ """The shared execute/save/deliver body keeps its durable fire claim alive."""+ import cron.jobs as jobs+ import cron.scheduler as scheduler++ profile_home = tmp_path / "profile"+ profile_home.mkdir()+ with jobs.use_cron_store(profile_home):+ job = jobs.create_job(prompt="x", schedule="every 5m", name="agent-run")+ assert jobs.claim_job_for_fire(job["id"]) is True+ claimed_job = jobs.get_job(job["id"])+ original_claim = dict(claimed_job["fire_claim"])++ heartbeat_seen = threading.Event()+ real_heartbeat = jobs.heartbeat_fire_claim++ def _observed_heartbeat(job_id: str, *, expected_owner: str) -> bool:+ updated = real_heartbeat(job_id, expected_owner=expected_owner)+ heartbeat_seen.set()+ return updated++ def _blocking_body(job, **kwargs):+ assert heartbeat_seen.wait(timeout=2)+ return True++ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", _observed_heartbeat)+ monkeypatch.setattr(scheduler, "_run_one_job_body", _blocking_body)++ with jobs.use_cron_store(profile_home):+ assert isinstance(claimed_job, dict)+ assert scheduler.run_one_job(claimed_job) is True+ refreshed = jobs.get_job(job["id"])["fire_claim"]++ assert refreshed["at"] != original_claim["at"]+ assert refreshed["by"] == original_claim["by"]+++def test_lost_fire_claim_stops_stale_delivery(monkeypatch):+ """A runner that loses its durable owner must not deliver its stale result."""+ import cron.scheduler as scheduler++ lost_seen = threading.Event()+ heartbeat_calls = 0++ def _heartbeat(job_id: str, *, expected_owner: str) -> bool:+ nonlocal heartbeat_calls+ heartbeat_calls += 1+ if heartbeat_calls == 1:+ return True+ lost_seen.set()+ return False++ def _run_job(job, *, defer_agent_teardown=None, extra_prompt=None, cancel_event=None):+ assert lost_seen.wait(timeout=2)+ return True, "stale output", "stale response", None++ job = {+ "id": "reclaimed-agent",+ "name": "reclaimed agent",+ "prompt": "work",+ "execution_id": "stale-execution",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "stale-owner"},+ }+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", _heartbeat)+ monkeypatch.setattr(scheduler, "run_job", _run_job)+ monkeypatch.setattr(scheduler, "claim_dispatch", lambda job_id: True)+ monkeypatch.setattr(scheduler, "mark_execution_running", lambda execution_id: None)+ monkeypatch.setattr(scheduler, "finish_execution", lambda *args, **kwargs: None)+ save_output = MagicMock()+ deliver_result = MagicMock()+ mark_run = MagicMock()+ monkeypatch.setattr(scheduler, "save_job_output", save_output)+ monkeypatch.setattr(scheduler, "_deliver_result", deliver_result)+ monkeypatch.setattr(scheduler, "mark_job_run", mark_run)++ with patch("agent.secret_scope.set_secret_scope", return_value=None), \+ patch("agent.secret_scope.build_profile_secret_scope", return_value=None), \+ patch("agent.secret_scope.reset_secret_scope"):+ assert scheduler.run_one_job(job) is True++ save_output.assert_not_called()+ deliver_result.assert_not_called()+ mark_run.assert_not_called()+++def test_initially_lost_fire_claim_finishes_execution_without_running(monkeypatch):+ """A stale claimed snapshot rejected before body entry must close its ledger row."""+ import cron.scheduler as scheduler++ run_body = MagicMock(return_value=True)+ finish = MagicMock()+ job = {+ "id": "already-reclaimed",+ "execution_id": "stale-execution",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "stale-owner"},+ }+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", lambda *args, **kwargs: False)+ monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)+ monkeypatch.setattr(scheduler, "finish_execution", finish)++ assert scheduler.run_one_job(job) is True++ run_body.assert_not_called()+ finish.assert_called_once_with(+ "stale-execution",+ success=False,+ error="Fire claim ownership lost before execution started.",+ )+++def test_initially_lost_claim_does_not_run_when_ledger_write_fails(monkeypatch):+ """A ledger I/O error cannot turn a confirmed ownership loss into execution."""+ import cron.scheduler as scheduler++ run_body = MagicMock(return_value=True)+ job = {+ "id": "already-reclaimed",+ "execution_id": "stale-execution",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "stale-owner"},+ }+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", lambda *args, **kwargs: False)+ monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)+ monkeypatch.setattr(+ scheduler,+ "finish_execution",+ MagicMock(side_effect=OSError("ledger unavailable")),+ )++ assert scheduler.run_one_job(job) is True+ run_body.assert_not_called()+++def test_initial_heartbeat_exception_does_not_start_execution(monkeypatch):+ """Unconfirmed initial ownership must fail closed before any side effect."""+ import cron.scheduler as scheduler++ run_body = MagicMock(return_value=True)+ finish = MagicMock()+ job = {+ "id": "validation-error",+ "execution_id": "validation-execution",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "owner"},+ }+ monkeypatch.setattr(+ scheduler,+ "heartbeat_fire_claim",+ MagicMock(side_effect=OSError("store unavailable")),+ )+ monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)+ monkeypatch.setattr(scheduler, "finish_execution", finish)++ assert scheduler.run_one_job(job) is True++ run_body.assert_not_called()+ finish.assert_called_once_with(+ "validation-execution",+ success=False,+ error="Fire claim ownership could not be validated before execution started.",+ )+++def test_heartbeat_thread_start_failure_does_not_start_execution(monkeypatch):+ """A claimed job cannot run when no renewal monitor protects its lease."""+ import cron.scheduler as scheduler++ run_body = MagicMock(return_value=True)+ finish = MagicMock()+ job = {+ "id": "thread-start-error",+ "execution_id": "thread-execution",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "owner"},+ }+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", lambda *args, **kwargs: True)+ monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)+ monkeypatch.setattr(scheduler, "finish_execution", finish)+ monkeypatch.setattr(+ scheduler.threading.Thread,+ "start",+ MagicMock(side_effect=RuntimeError("cannot start thread")),+ )++ assert scheduler.run_one_job(job) is True++ run_body.assert_not_called()+ finish.assert_called_once_with(+ "thread-execution",+ success=False,+ error="Fire claim heartbeat could not be started; execution was not run.",+ )+++def test_repeated_heartbeat_errors_cancel_after_bounded_grace(monkeypatch):+ """Store uncertainty cannot let a run outlive its last confirmed lease forever."""+ import cron.scheduler as scheduler++ calls = 0++ def heartbeat(*_args, **_kwargs):+ nonlocal calls+ calls += 1+ if calls == 1:+ return True+ raise OSError("store unavailable")++ def run_body(_job, **kwargs):+ assert kwargs["fire_claim_lost"].wait(timeout=0.5)+ return True++ job = {+ "id": "heartbeat-errors",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "owner"},+ }+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", heartbeat)+ monkeypatch.setattr(scheduler, "_run_one_job_body", run_body)+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)+ monkeypatch.setattr(scheduler, "_FIRE_CLAIM_HEARTBEAT_GRACE_SECONDS", 0.03)++ assert scheduler.run_one_job(job) is True+ assert calls >= 3+++def test_terminal_owner_cas_failure_marks_ledger_ownership_lost(monkeypatch):+ """A replacement owner cannot leave the stale ledger recorded as success."""+ import cron.scheduler as scheduler++ @contextlib.contextmanager+ def owned_fence(*_args, **_kwargs):+ yield True++ job = {+ "id": "terminal-cas",+ "execution_id": "execution-cas",+ "name": "terminal-cas",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "owner"},+ }+ finish = MagicMock()+ monkeypatch.setattr(scheduler, "heartbeat_fire_claim", lambda *args, **kwargs: True)+ monkeypatch.setattr(scheduler, "claim_dispatch", lambda *_args, **_kwargs: True)+ monkeypatch.setattr(scheduler, "mark_execution_running", lambda *_args: None)+ monkeypatch.setattr(+ scheduler,+ "run_job",+ lambda *_args, **_kwargs: (True, "output", "response", None),+ )+ monkeypatch.setattr(scheduler, "fire_claim_fence", owned_fence, raising=False)+ monkeypatch.setattr(scheduler, "save_job_output", lambda *_args: "output.md")+ monkeypatch.setattr(scheduler, "_deliver_result", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(scheduler, "mark_job_run", lambda *_args, **_kwargs: False)+ monkeypatch.setattr(scheduler, "finish_execution", finish)++ with patch("agent.secret_scope.set_secret_scope", return_value=None), \+ patch("agent.secret_scope.build_profile_secret_scope", return_value=None), \+ patch("agent.secret_scope.reset_secret_scope"):+ assert scheduler.run_one_job(job) is True++ finish.assert_called_once_with(+ "execution-cas",+ success=False,+ error="Fire claim ownership lost before terminal completion.",+ )diff --git a/tests/cron/test_sessiondb_init_hang.py b/tests/cron/test_sessiondb_init_hang.pyindex 9f89574309b..ce959325c5f 100644--- a/tests/cron/test_sessiondb_init_hang.py+++ b/tests/cron/test_sessiondb_init_hang.py@@ -222,7 +222,7 @@ class TestDispatchGuardReleasedAfterHang:side_effect=_session_db_executor(timeouts),), \patch.object(sched, "get_due_jobs", return_value=[job]), \- patch.object(sched, "advance_next_runs"), \+ patch.object(sched, "claim_job_for_fire", return_value=True), \patch.object(sched, "save_job_output", return_value="/tmp/out"), \patch.object(sched, "mark_job_run"), \patch.object(sched, "_deliver_result", return_value=None):diff --git a/tests/cron/test_shutdown_interrupt.py b/tests/cron/test_shutdown_interrupt.pyindex edafdb741ac..a8bb3bf28f1 100644--- a/tests/cron/test_shutdown_interrupt.py+++ b/tests/cron/test_shutdown_interrupt.py@@ -11,6 +11,7 @@ Covers the cron/scheduler.py primitives directly:result AFTER its tool was already killed out from under it"""+import threadingfrom unittest.mock import patchimport pytest@@ -23,9 +24,11 @@ def _reset_scheduler_state():import cron.scheduler as schedsched._running_job_ids.clear()+ sched._running_fire_owners.clear()sched._interrupted_job_ids.clear()yieldsched._running_job_ids.clear()+ sched._running_fire_owners.clear()sched._interrupted_job_ids.clear()@@ -72,8 +75,15 @@ class TestMarkRunningJobsInterrupted:import cron.scheduler as schedsched._running_job_ids.update({"job-1", "job-2"})-- with patch("cron.scheduler.mark_job_run") as mock_mark:+ profile_home = sched._get_hermes_home().resolve()+ sched._running_fire_owners.update(+ {+ "job-1": {object(): ("owner-1", profile_home)},+ "job-2": {object(): ("owner-2", profile_home)},+ }+ )++ with patch("cron.scheduler.mark_job_run", return_value=True) as mock_mark:marked = sched.mark_running_jobs_interrupted("gateway shutdown (final-cleanup)")assert sorted(marked) == ["job-1", "job-2"]@@ -84,6 +94,7 @@ class TestMarkRunningJobsInterrupted:# success must be False -- an interrupted run is never "ok".assert c.args[1] is Falseassert "gateway shutdown" in c.args[2]+ assert c.kwargs["expected_fire_owner"] in {"owner-1", "owner-2"}def test_sets_interrupted_flag_for_consumption_by_run_one_job(self):import cron.scheduler as sched@@ -102,16 +113,146 @@ class TestMarkRunningJobsInterrupted:import cron.scheduler as schedsched._running_job_ids.update({"job-1", "job-2"})+ profile_home = sched._get_hermes_home().resolve()+ sched._running_fire_owners.update(+ {+ "job-1": {object(): ("owner-1", profile_home)},+ "job-2": {object(): ("owner-2", profile_home)},+ }+ )def _side_effect(job_id, success, reason, **kwargs):if job_id == "job-1":raise OSError("disk full")+ return Truewith patch("cron.scheduler.mark_job_run", side_effect=_side_effect):marked = sched.mark_running_jobs_interrupted("shutdown")assert marked == ["job-2"]+ def test_stale_shutdown_cannot_clear_replacement_owner(self, tmp_path):+ import cron.jobs as jobs+ import cron.scheduler as sched++ profile_home = tmp_path / "profile"+ profile_home.mkdir()+ with jobs.use_cron_store(profile_home):+ created = jobs.create_job(prompt="x", schedule="every 5m", name="owned")+ claimed = jobs.claim_job_for_fire(created["id"], force=True, return_job=True)+ assert isinstance(claimed, dict)+ stale_owner = claimed["fire_claim"]["by"]+ original_status = claimed["last_status"]+ replacement_claim = {+ "at": "2026-07-12T12:30:00+00:00",+ "by": "replacement-owner",+ }+ replacement = {**claimed, "fire_claim": replacement_claim}+ jobs.save_jobs([replacement])++ sched._running_job_ids.add(created["id"])+ sched._running_fire_owners[created["id"]] = {+ object(): (stale_owner, profile_home)+ }+ marked = sched.mark_running_jobs_interrupted("shutdown")+ refreshed = jobs.get_job(created["id"])++ assert marked == []+ assert isinstance(refreshed, dict)+ assert refreshed["fire_claim"] == replacement_claim+ assert refreshed["last_status"] == original_status+++class TestRunningFireOwnerRegistry:+ def test_run_one_job_registers_owner_only_while_active(self):+ import cron.scheduler as sched++ job = {+ "id": "owned-job",+ "fire_claim": {"at": "2026-07-12T12:00:00+00:00", "by": "owner-1"},+ }++ def _observe_registry(current_job, run):+ assert list(sched._running_fire_owners[current_job["id"]].values()) == [+ ("owner-1", sched._get_hermes_home().resolve())+ ]+ return True++ with patch("cron.scheduler._run_with_fire_claim_heartbeat", side_effect=_observe_registry):+ assert sched.run_one_job(job) is True++ assert job["id"] not in sched._running_fire_owners++ def test_shutdown_sees_all_concurrent_direct_fire_owners(self, monkeypatch):+ """Direct entry points and replacement owners share one token registry."""+ import cron.scheduler as sched++ entered = threading.Barrier(3)+ release = threading.Event()+ marked_owners: list[str] = []++ def hold_run(_job, _run):+ entered.wait(timeout=2)+ release.wait(timeout=2)+ return True++ def mark(_job_id, _success, _reason, *, expected_fire_owner):+ marked_owners.append(expected_fire_owner)+ return True++ monkeypatch.setattr(sched, "_run_with_fire_claim_heartbeat", hold_run)+ monkeypatch.setattr(sched, "mark_job_run", mark)++ jobs = [+ {"id": "same-job", "fire_claim": {"by": "old-owner"}},+ {"id": "same-job", "fire_claim": {"by": "replacement-owner"}},+ ]+ threads = [threading.Thread(target=sched.run_one_job, args=(job,)) for job in jobs]+ for thread in threads:+ thread.start()+ entered.wait(timeout=2)++ assert sched.get_running_job_ids() == frozenset({"same-job"})+ assert sched.mark_running_jobs_interrupted("shutdown") == ["same-job", "same-job"]+ assert set(marked_owners) == {"old-owner", "replacement-owner"}++ release.set()+ for thread in threads:+ thread.join(timeout=2)+ assert not thread.is_alive()+ assert "same-job" not in sched.get_running_job_ids()++ def test_shutdown_marks_each_owner_in_its_profile_store(self, monkeypatch, tmp_path):+ import cron.jobs as cron_jobs+ import cron.scheduler as sched++ profile_a = tmp_path / "a"+ profile_b = tmp_path / "b"+ observed = []+ sched._running_fire_owners["same-job"] = {+ object(): ("owner-a", profile_a),+ object(): ("owner-b", profile_b),+ }++ def mark(job_id, success, reason, *, expected_fire_owner):+ observed.append(+ (+ job_id,+ success,+ expected_fire_owner,+ cron_jobs._current_cron_store().jobs_file,+ )+ )+ return True++ monkeypatch.setattr(sched, "mark_job_run", mark)++ assert sched.mark_running_jobs_interrupted("shutdown") == ["same-job", "same-job"]+ assert set(observed) == {+ ("same-job", False, "owner-a", profile_a / "cron" / "jobs.json"),+ ("same-job", False, "owner-b", profile_b / "cron" / "jobs.json"),+ }+class TestIsInterrupted:"""Peek-only check used at the delivery gate -- must NOT clear the@@ -155,6 +296,247 @@ class TestConsumeInterruptedFlag:assert sched._consume_interrupted_flag("job-1") is False+class TestExecutionScopedInterruption:+ """Interruption flags must target ONE execution, not the job ID.++ Owner-registered executions are recorded by their unique execution+ token, so a fresh run that reuses the same job ID (recurring fire,+ replacement claim owner) never consumes a flag that targeted its+ dead predecessor.+ """++ def test_interruption_targets_only_the_interrupted_execution(self):+ import cron.scheduler as sched++ profile_home = sched._get_hermes_home().resolve()+ old_token = object()+ sched._running_fire_owners["job-1"] = {+ old_token: ("owner-1", profile_home),+ }++ with patch("cron.scheduler.mark_job_run", return_value=True):+ sched.mark_running_jobs_interrupted("shutdown")++ assert sched._is_interrupted("job-1", old_token) is True+ new_token = object()+ assert sched._is_interrupted("job-1", new_token) is False+ # A new execution must not steal (and thereby clear) the old flag.+ assert sched._consume_interrupted_flag("job-1", new_token) is False+ assert sched._consume_interrupted_flag("job-1", old_token) is True+ assert sched._is_interrupted("job-1", old_token) is False++ def test_only_owners_marks_only_targeted_executions(self):+ import cron.scheduler as sched++ profile_home = sched._get_hermes_home().resolve()+ token_a, token_b = object(), object()+ sched._running_fire_owners["job-a"] = {token_a: ("owner-a", profile_home)}+ sched._running_fire_owners["job-b"] = {token_b: ("owner-b", profile_home)}++ with patch("cron.scheduler.mark_job_run", return_value=True) as mock_mark:+ marked = sched.mark_running_jobs_interrupted(+ "dashboard shutdown",+ only_owners={("job-a", "owner-a")},+ )++ assert marked == ["job-a"]+ assert mock_mark.call_count == 1+ assert mock_mark.call_args.kwargs["expected_fire_owner"] == "owner-a"+ assert sched._is_interrupted("job-a", token_a) is True+ assert sched._is_interrupted("job-b", token_b) is False++ def test_replacement_execution_of_same_job_is_not_poisoned(self):+ """A replacement owner starting while the stale flag exists must+ complete through the normal mark path, not the interrupted one."""+ import cron.scheduler as sched++ profile_home = sched._get_hermes_home().resolve()+ stale_token = object()+ sched._running_fire_owners["job-1"] = {+ stale_token: ("stale-owner", profile_home),+ }+ with patch("cron.scheduler.mark_job_run", return_value=True):+ sched.mark_running_jobs_interrupted("shutdown")+ sched._running_fire_owners.clear()++ job = {+ "id": "job-1",+ "name": "test job",+ "prompt": "do work",+ "fire_claim": {"by": "replacement-owner"},+ }+ with patch("cron.scheduler.claim_dispatch", return_value=True), \+ patch("agent.secret_scope.set_secret_scope", return_value=None), \+ patch("agent.secret_scope.build_profile_secret_scope", return_value=None), \+ patch("agent.secret_scope.reset_secret_scope"), \+ patch(+ "cron.scheduler.run_job",+ return_value=(True, "full output", "final response", None),+ ), \+ patch("cron.scheduler.save_job_output", return_value="/tmp/out.md"), \+ patch("cron.scheduler._is_cron_silence_response", return_value=False), \+ patch("cron.scheduler._deliver_result", return_value=None), \+ patch("cron.scheduler.fire_claim_fence"), \+ patch("cron.scheduler.heartbeat_fire_claim", return_value=True), \+ patch("cron.scheduler.mark_job_run", return_value=True) as mock_mark:+ result = sched.run_one_job(job)++ assert result is True+ mock_mark.assert_called_once()+++class TestCombinedCancelEvent:+ def test_or_semantics(self):+ import cron.scheduler as sched++ a, b = threading.Event(), threading.Event()+ combined = sched._CombinedCancelEvent(a, b)+ assert combined.is_set() is False+ b.set()+ assert combined.is_set() is True++ def test_set_propagates_to_all(self):+ import cron.scheduler as sched++ a, b = threading.Event(), threading.Event()+ combined = sched._CombinedCancelEvent(a, b)+ combined.set()+ assert a.is_set() and b.is_set()++ def test_run_one_job_forwards_external_cancel_event(self):+ import cron.scheduler as sched++ external = threading.Event()+ job = {"id": "job-x", "name": "x", "prompt": "p"}++ with patch.object(+ sched,+ "_run_with_fire_claim_heartbeat",+ side_effect=lambda job_arg, run: run(threading.Event()),+ ), patch.object(sched, "_run_one_job_body", return_value=True) as body:+ assert sched.run_one_job(job, cancel_event=external) is True++ combined = body.call_args.kwargs["fire_claim_lost"]+ assert combined.is_set() is False+ external.set()+ assert combined.is_set() is True+++class TestBaseExceptionThroughOwnerFencedFlow:+ """#73973 (sweeper review on #70638): a BaseException escaping run_job+ must still record a failed run through the owner-fenced terminal path —+ and a stale worker must not record over a replacement claim owner."""++ def _job(self):+ return {+ "id": "job-be",+ "name": "base exc",+ "prompt": "p",+ "fire_claim": {"by": "owner-be"},+ }++ def _patches(self, run_side_effect):+ return (+ patch("cron.scheduler.claim_dispatch", return_value=True),+ patch("agent.secret_scope.set_secret_scope", return_value=None),+ patch("agent.secret_scope.build_profile_secret_scope", return_value=None),+ patch("agent.secret_scope.reset_secret_scope"),+ patch("cron.scheduler.run_job", side_effect=run_side_effect),+ patch("cron.scheduler.heartbeat_fire_claim", return_value=True),+ )++ def test_cancelled_error_records_failure_and_reraises(self):+ import asyncio++ import cron.scheduler as sched++ p1, p2, p3, p4, p5, p6 = self._patches(asyncio.CancelledError())+ with p1, p2, p3, p4, p5, p6, \+ patch("cron.scheduler.mark_job_run", return_value=True) as mock_mark, \+ patch("cron.scheduler.finish_execution") as mock_finish:+ try:+ sched.run_one_job(self._job())+ raised = False+ except asyncio.CancelledError:+ raised = True++ assert raised, "non-Exception BaseException must propagate"+ mock_mark.assert_called_once()+ assert mock_mark.call_args.args[:3] == ("job-be", False, "CancelledError")+ assert mock_mark.call_args.kwargs["expected_fire_owner"] == "owner-be"+ assert mock_finish.call_args.kwargs["success"] is False++ def test_keyboard_interrupt_records_failure_and_reraises(self):+ import cron.scheduler as sched++ p1, p2, p3, p4, p5, p6 = self._patches(KeyboardInterrupt())+ with p1, p2, p3, p4, p5, p6, \+ patch("cron.scheduler.mark_job_run", return_value=True) as mock_mark, \+ patch("cron.scheduler.finish_execution"):+ try:+ sched.run_one_job(self._job())+ raised = False+ except KeyboardInterrupt:+ raised = True++ assert raised+ mock_mark.assert_called_once()+ assert mock_mark.call_args.kwargs["expected_fire_owner"] == "owner-be"++ def test_base_exception_from_stale_owner_is_fenced_out(self):+ """A replacement owner reclaimed the job: the stale worker's+ BaseException path must NOT write terminal state over it."""+ import asyncio++ import cron.scheduler as sched++ p1, p2, p3, p4, p5, p6 = self._patches(asyncio.CancelledError())+ with p1, p2, p3, p4, p5, p6, \+ patch("cron.scheduler.mark_job_run", return_value=False) as mock_mark, \+ patch("cron.scheduler.finish_execution"):+ try:+ sched.run_one_job(self._job())+ except asyncio.CancelledError:+ pass++ mock_mark.assert_called_once()+ # fenced write was attempted with the stale owner and discarded by+ # the store (return False) — and the code accepted that verdict+ # without retrying or writing anything else.+ assert mock_mark.call_args.kwargs["expected_fire_owner"] == "owner-be"+++class TestCallerLossAfterClaimAcquisition:+ """cirwel's integration assertion on #70638: if the HTTP/CLI caller is+ lost AFTER the claim was acquired, the gateway owner must produce at+ most one terminal ledger/artifact/delivery, clear only its own claim,+ and block retries while that ownership is live."""++ def test_second_fire_cannot_claim_while_first_ownership_live(self, tmp_path):+ import cron.jobs as jobs++ with jobs.use_cron_store(tmp_path):+ job = jobs.create_job(prompt="x", schedule="every 5m", name="owned")+ claimed = jobs.claim_job_for_fire(job["id"], force=True, return_job=True)+ assert isinstance(claimed, dict)++ # Caller died here — the claim outlives it. A retry (NAS/webhook+ # or manual) must be refused while the lease is fresh.+ retry = jobs.claim_job_for_fire(job["id"], return_job=True)+ assert retry is False or not isinstance(retry, dict)++ # The live owner still heartbeats and terminally marks — exactly+ # one terminal write, and only its own claim is cleared.+ owner = claimed["fire_claim"]["by"]+ assert jobs.heartbeat_fire_claim(job["id"], expected_owner=owner) is True+ assert jobs.mark_job_run(+ job["id"], True, expected_fire_owner=owner,+ ) is True+ refreshed = jobs.get_job(job["id"])+ assert refreshed["fire_claim"] is None+ assert refreshed["last_status"] == "ok"++class TestRunOneJobHonoursInterruptedFlag:"""run_one_job() must not let a job's own completion overwrite astatus the shutdown path already wrote for the same run."""