The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cron): simplify jobs.py store and lifecycle_guard
Tekniume4711620a147
diff --git a/cron/jobs.py b/cron/jobs.pyindex 385d747619e..91e1ab67a04 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -1,14 +1,9 @@-"""-Cron job storage and management.--Jobs are stored in ~/.hermes/cron/jobs.json-Output is saved to ~/.hermes/cron/output/{job_id}/{timestamp}.md-"""+"""Cron job storage: ~/.hermes/cron/jobs.json; output in ~/.hermes/cron/output/{job_id}/{timestamp}.md"""import contextlibimport copyfrom contextvars import ContextVar-from dataclasses import dataclass+from dataclasses import dataclass, fieldimport jsonimport loggingimport shutil@@ -19,10 +14,8 @@ import osimport reimport uuid-# Cross-process advisory file locking for jobs.json critical sections.-# fcntl is Unix-only; on Windows fall back to msvcrt. Either may be absent,-# in which case _jobs_lock() degrades to in-process locking only (the old-# behaviour) rather than failing.+# Cross-process advisory locking for jobs.json: fcntl (Unix) or msvcrt (Windows). If both are+# absent, _jobs_lock() degrades to in-process locking rather than failing.try:import fcntlexcept ImportError: # pragma: no cover - non-Unix@@ -34,17 +27,15 @@ except ImportError: # pragma: no cover - non-Windowsfrom datetime import datetime, timedeltafrom pathlib import Pathfrom hermes_constants import get_hermes_home-from typing import Optional, Dict, List, Any, Set, Tuple, Union, Collection+from typing import Optional, Dict, List, Any, Callable, Set, Tuple, Union, Collectionlogger = logging.getLogger(__name__)from hermes_time import now as _hermes_nowfrom utils import atomic_replace, atomic_write_text-# ``croniter`` compiles ~15 ms of regexes at import and only matters for-# 5-field cron expressions. Resolve lazily; ``HAS_CRONITER`` stays a module-# attribute (tests monkeypatch it, and a monkeypatched value wins because-# ``_ensure_croniter`` only probes while it's still None).+# croniter is imported lazily (slow import, only needed for cron exprs). HAS_CRONITER stays a+# module attribute: a monkeypatched value wins because _ensure_croniter only probes while None.croniter = NoneHAS_CRONITER: Optional[bool] = None@@ -65,55 +56,34 @@ def _ensure_croniter() -> bool:# Configuration# =============================================================================-# Cron is per-profile by design (issue #4707). Each profile owns its own cron-# store under its own HERMES_HOME, and a profile-scoped gateway runs that-# profile's jobs under that same HERMES_HOME — so a job authored in profile-# `coder` lives in `~/.hermes/profiles/coder/cron/jobs.json` and executes with-# `coder`'s `.env`, `config.yaml`, and skills. We deliberately anchor on-# `get_hermes_home()` (the active profile home), NOT `get_default_hermes_root()`-# (the shared root). Anchoring at the root would funnel every profile's jobs-# into one shared `jobs.json` and run them under whatever HERMES_HOME the-# ticker process happens to have — leaking config/credentials/skills across-# profiles (the security boundary #4707 was filed for). Do NOT change this to-# the default root: that re-breaks per-profile isolation. See also the dynamic-# `_get_hermes_home()` / `_get_lock_paths()` resolution in cron/scheduler.py.+# Cron is per-profile by design: anchor at get_hermes_home() (active profile home), NOT+# get_default_hermes_root() — the shared root would funnel every profile's jobs into one jobs.json+# and run them under the ticker's HERMES_HOME, leaking config/credentials/skills across profiles.HERMES_DIR = get_hermes_home().resolve()-# These constants remain the default-profile fallback and a compatibility-# surface for existing callers/tests. Cross-profile callers must scope paths-# with use_cron_store() instead of mutating them process-wide.+# Default-profile fallback and compatibility surface for callers/tests. Cross-profile callers must+# scope paths with use_cron_store() instead of mutating these process-wide.CRON_DIR = HERMES_DIR / "cron"JOBS_FILE = CRON_DIR / "jobs.json"-# Heartbeat file the in-process ticker touches on every loop iteration. The-# gateway process and the (separate) ``hermes cron status`` process share it-# so status can tell whether the ticker THREAD is alive, not just whether the-# gateway PROCESS exists — a ticker that dies silently inside a live gateway-# would otherwise report healthy (#32612, #32895).+# Touched by the ticker every loop so `hermes cron status` can tell the ticker THREAD is alive,+# not just the gateway PROCESS (a silently dead ticker would otherwise report healthy).TICKER_HEARTBEAT_FILE = CRON_DIR / "ticker_heartbeat"-# Last tick that completed WITHOUT raising. Distinguishing this from the plain-# heartbeat lets status detect a ticker that is alive but failing every tick.+# Last tick that completed WITHOUT raising — lets status detect a ticker alive but failing every tick.TICKER_SUCCESS_FILE = CRON_DIR / "ticker_last_success"-# Default ticker loop interval (seconds). The single source of truth shared by-# the in-process ticker (cron/scheduler_provider.py) and the staleness-# threshold in `hermes cron status` (hermes_cli/cron.py), so the two never-# drift apart.+# Single source of truth for the ticker interval (scheduler_provider.py) and the staleness+# threshold in `hermes cron status` (hermes_cli/cron.py), so they never drift apart.TICKER_INTERVAL_SECONDS = 60-# In-process lock protecting load_jobs→modify→save_jobs cycles.-# Required when tick() runs jobs in parallel threads — without this,-# concurrent mark_job_run / advance_next_run calls can clobber each other.+# In-process lock for load_jobs→modify→save_jobs cycles; without it, parallel tick threads'+# mark_job_run / advance_next_run calls 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()_fire_fence_lock_state = threading.local()-# Upper bound on waiting for the cross-process .jobs.lock flock (#60703).-# Every cron function in the process funnels through _jobs_lock(), and the-# flock is taken while holding the process-wide RLock — so an unbounded wait-# on a lock held by a wedged sibling process silently freezes the ticker-# heartbeat and every job forever. 30s is orders of magnitude above any-# legitimate critical section (field updates only) while keeping the ticker's-# worst-case stall well under one status-alarm threshold.+# Upper bound on waiting for the cross-process .jobs.lock. Every cron function funnels through+# _jobs_lock(), so blocking forever on a wedged sibling process would freeze the ticker and every+# job. 30s is far above any legitimate critical section yet under one status-alarm threshold._JOBS_LOCK_TIMEOUT_SECONDS = 30.0OUTPUT_DIR = CRON_DIR / "output"ONESHOT_GRACE_SECONDS = 120@@ -125,6 +95,10 @@ class _CronStorePaths:jobs_file: Pathoutput_dir: Path+ @classmethod+ def for_dir(cls, cron_dir: Path) -> "_CronStorePaths":+ return cls(cron_dir, cron_dir / "jobs.json", cron_dir / "output")+_cron_store_override: ContextVar[Optional[_CronStorePaths]] = ContextVar("cron_store_override",@@ -132,30 +106,18 @@ _cron_store_override: ContextVar[Optional[_CronStorePaths]] = ContextVar()-# Import-time snapshot of the compatibility constants, so deliberate-# re-pointing of the module surface (monkeypatched CRON_DIR/JOBS_FILE/-# OUTPUT_DIR — the documented escape hatch existing tests/embedders use)-# is distinguishable from the constants merely being stale.+# Import-time snapshot so deliberate re-pointing of CRON_DIR/JOBS_FILE/OUTPUT_DIR (the documented+# escape hatch for tests/embedders) is distinguishable from the constants merely being stale._IMPORT_STORE = _CronStorePaths(CRON_DIR, JOBS_FILE, OUTPUT_DIR)def _current_cron_store() -> _CronStorePaths:"""Return paths pinned to this execution context's profile.- Precedence, most explicit first:-- 1. an active use_cron_store() override (ContextVar);- 2. deliberately re-pointed module constants — if CRON_DIR/JOBS_FILE/- OUTPUT_DIR no longer match their import-time values, someone chose- the documented process-wide compatibility surface; honor it;- 3. the ACTIVE profile home, resolved fresh via get_hermes_home()- (context-local override, then the HERMES_HOME env var) — so a test- or embedder that re-points HERMES_HOME after this module was- imported reads/writes ITS OWN store, not whatever jobs.json the- import happened to freeze (the filed incident: fixtures that patched- the env too late silently rewrote the user's real jobs file);- 4. the import-time constants (home unchanged since import — the common- path, returned unchanged).+ Precedence: (1) active use_cron_store() override; (2) deliberately re-pointed module constants+ (differ from import-time values → honor the compatibility surface); (3) the ACTIVE profile home+ resolved fresh via get_hermes_home(), so re-pointing HERMES_HOME after import reads/writes ITS+ OWN store rather than the user's real jobs.json frozen at import; (4) the import-time constants."""override = _cron_store_override.get()if override is not None:@@ -166,21 +128,13 @@ def _current_cron_store() -> _CronStorePaths:home = get_hermes_home().resolve()if home == HERMES_DIR:return live_constants- cron_dir = home / "cron"- return _CronStorePaths(cron_dir, cron_dir / "jobs.json", cron_dir / "output")+ return _CronStorePaths.for_dir(home / "cron")@contextlib.contextmanagerdef use_cron_store(home: Union[str, Path]):"""Route cron storage to ``home`` without mutating process globals."""- cron_dir = Path(home).expanduser().resolve() / "cron"- token = _cron_store_override.set(- _CronStorePaths(- cron_dir=cron_dir,- jobs_file=cron_dir / "jobs.json",- output_dir=cron_dir / "output",- )- )+ token = _cron_store_override.set(_CronStorePaths.for_dir(Path(home).expanduser().resolve() / "cron"))try:yieldfinally:@@ -192,36 +146,24 @@ def get_cron_output_dir() -> Path:return _current_cron_store().output_dir-# Fallback stale-recovery window for a one-shot's running-claim (#59229) when-# the cron inactivity timeout is disabled (HERMES_CRON_TIMEOUT=0 → unlimited),-# in which case no finite run bound exists to derive from. Also acts as the-# floor for the derived value so a very short configured timeout can't make the-# claim expire mid-run.+# Fallback stale-recovery window for a one-shot's running-claim when HERMES_CRON_TIMEOUT=0+# (unlimited, no bound to derive from); also the floor so a tiny timeout can't expire a claim mid-run.ONESHOT_RUN_CLAIM_TTL_SECONDS = 1800-# The derived TTL is the cron inactivity timeout times this headroom multiplier.-# A healthy run clears its claim via mark_job_run() long before the TTL; the-# TTL only recovers a claim left by a tick that DIED mid-run. HERMES_CRON_TIMEOUT-# is an *inactivity* limit, not a wall-clock cap — a job that keeps producing-# output legitimately runs past it — so the multiplier gives comfortable-# headroom over any healthy run before we treat a claim as stale.+# Derived TTL = inactivity timeout × this headroom. The TTL only recovers a claim left by a tick that+# DIED mid-run; the timeout is an *inactivity* limit, not a wall-clock cap, so healthy runs may+# legitimately exceed it — hence the headroom._ONESHOT_RUN_CLAIM_TTL_HEADROOM = 3_DEFAULT_CRON_INACTIVITY_TIMEOUT = 600.0def _oneshot_run_claim_ttl_seconds() -> float:- """Resolve the one-shot running-claim stale-recovery TTL.+ """Resolve the one-shot running-claim TTL from ``HERMES_CRON_TIMEOUT``.- Derived from ``HERMES_CRON_TIMEOUT`` (the cron inactivity timeout the- scheduler enforces on each run) so the safety valve tracks how long a run- is actually allowed to go quiet, instead of a magic constant:-- - unset / invalid → default 600s inactivity limit → TTL = 1800s- - ``0`` (unlimited runs) → no finite bound to derive from → fall back to- ``ONESHOT_RUN_CLAIM_TTL_SECONDS``- - positive N → ``max(N * headroom, ONESHOT_RUN_CLAIM_TTL_SECONDS)`` so a- tiny configured timeout can never expire a claim mid-run.+ unset/invalid → 600s → 1800s; ``0`` (unlimited) → ``ONESHOT_RUN_CLAIM_TTL_SECONDS``;+ positive N → ``max(N * headroom, ONESHOT_RUN_CLAIM_TTL_SECONDS)`` so a tiny timeout never+ expires a claim mid-run."""raw = os.getenv("HERMES_CRON_TIMEOUT", "").strip()timeout = _DEFAULT_CRON_INACTIVITY_TIMEOUT@@ -242,15 +184,9 @@ def _oneshot_run_claim_ttl_seconds() -> float:def _job_running_in_this_process(job_id: str) -> bool:"""Return True when the scheduler in THIS process is still running ``job_id``.- Direct liveness signal for stale-entry recovery (#62002): the run_claim- TTL alone cannot distinguish "the claiming tick died" from "the run is- alive but slow" — a run stalled on network I/O (or a laptop that slept- mid-run) legitimately outlives the TTL. The in-process ticker and the run- share this process, so the scheduler's running set settles the common- single-gateway case without any claim-age guesswork.-- Imported lazily: the scheduler imports this module at load, so a- module-level import here would be circular.+ The run_claim TTL alone cannot distinguish "claiming tick died" from "alive but slow" (a run+ stalled on I/O or a slept laptop legitimately outlives it); the in-process running set settles+ the single-gateway case. Lazy import: the scheduler imports this module, so top-level would be circular."""try:from cron.scheduler import get_running_job_ids@@ -270,25 +206,51 @@ def _jobs_lock_file() -> Path:return _current_cron_store().cron_dir / ".jobs.lock"+def _acquire_flock(lock_fd, timeout: float) -> Optional[bool]:+ """Bounded exclusive lock: True when acquired, False on timeout, None when no backend exists.++ A blocking flock(LOCK_EX) has NO timeout and is taken while holding the in-process lock, so a+ wedged sibling process would freeze EVERY cron function here forever. Poll LOCK_NB against a+ deadline instead; the caller decides the degraded mode on timeout.+ """+ if fcntl is not None:+ deadline = time.monotonic() + timeout+ while True:+ try:+ fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ return True+ except (OSError, IOError):+ if time.monotonic() >= deadline:+ return False+ time.sleep(0.1)+ if msvcrt is not None:+ getattr(msvcrt, "locking")(lock_fd.fileno(), getattr(msvcrt, "LK_LOCK"), 1)+ return True+ return None+++def _release_flock(lock_fd) -> None:+ """Unlock (best effort) and close a lock file opened for ``_acquire_flock``."""+ try:+ if fcntl is not None:+ fcntl.flock(lock_fd, fcntl.LOCK_UN)+ elif msvcrt is not None:+ getattr(msvcrt, "locking")(lock_fd.fileno(), getattr(msvcrt, "LK_UNLCK"), 1)+ except (OSError, IOError):+ pass+ finally:+ lock_fd.close()++@contextlib.contextmanagerdef _jobs_lock():"""Serialize a load_jobs→modify→save_jobs critical section.- Combines the in-process threading lock (cheap mutual exclusion between- the gateway's parallel tick threads) with a cross-process advisory file- lock on ``<cron dir>/.jobs.lock`` (mutual exclusion between the gateway process- and standalone ``hermes`` CLI invocations, which previously shared no lock- at all — a `cron pause` could be silently clobbered by a concurrent- gateway write, leaving a "paused" job still firing).-- The flock is blocking, but every critical section that uses it is short- (field updates only — no agent execution), so contention resolves in- milliseconds. If neither fcntl nor msvcrt is available the manager still- provides in-process locking, matching the historical behaviour.-- Nested calls in the same thread reuse the held lock so legacy callers that- invoke save_jobs() inside a broader mutation section don't deadlock or try- to reacquire the advisory file lock.+ In-process RLock (parallel tick threads) plus a cross-process flock on ``<cron dir>/.jobs.lock``+ (gateway vs. CLI writes — otherwise a `cron pause` could be clobbered and keep firing). Sections+ are short (field updates only). Nested calls in one thread reuse the held lock. Without a flock+ backend, or on flock timeout (logged loudly), it degrades to in-process-only locking: a briefly+ torn cross-process write beats a dead scheduler."""depth = getattr(_jobs_lock_state, "depth", 0)if depth:@@ -301,11 +263,9 @@ def _jobs_lock():with _jobs_file_lock:_jobs_lock_state.depth = 1- # Stamp of jobs.json as of this section's load_jobs() (#80703's- # fast-path, credit @JoaoMarcos44): lets _save_jobs_unlocked skip the- # shrink-merge parse when the file provably hasn't changed since this- # section read it. Reset on entry/exit so stale stamps from unlocked- # loads or prior sections can never suppress a needed merge.+ # jobs.json stamp as of this section's load_jobs(): lets _save_jobs_unlocked skip the+ # shrink-merge parse when the file provably hasn't changed. Reset on entry/exit so stale+ # stamps from unlocked loads or prior sections can never suppress a needed merge._jobs_lock_state.load_stamp = Nonelock_fd = Nonetry:@@ -313,63 +273,29 @@ def _jobs_lock():ensure_dirs()lock_fd = open(_jobs_lock_file(), "a+", encoding="utf-8")lock_fd.seek(0)- if fcntl is not None:- # Bounded acquisition (#60703): a plain blocking- # fcntl.flock(LOCK_EX) here has NO timeout, and it is- # taken while holding the process-wide _jobs_file_lock- # RLock above. If another process wedges while holding- # .jobs.lock (e.g. an old gateway draining through a- # restart), a single blocked acquirer freezes EVERY cron- # function in this process — including the ticker's- # get_due_jobs() — silently and forever: the heartbeat- # file stops updating and all jobs stop firing with no- # error logged. Poll LOCK_NB against a deadline instead;- # on timeout, log loudly and fall through to the same- # in-process-only degraded mode used when locking is- # unavailable. A briefly-torn cross-process write is- # strictly better than a permanently dead scheduler.- _deadline = time.monotonic() + _JOBS_LOCK_TIMEOUT_SECONDS- while True:- try:- fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)- break- except (OSError, IOError):- if time.monotonic() >= _deadline:- logger.error(- "Timed out after %.0fs waiting for the cron "- "jobs lock (%s) — another process is holding "- "it. Proceeding with in-process locking only "- "so the scheduler stays alive (#60703).",- _JOBS_LOCK_TIMEOUT_SECONDS,- _jobs_lock_file(),- )- try:- lock_fd.close()- except OSError:- pass- lock_fd = None- break- time.sleep(0.1)- elif msvcrt is not None:- getattr(msvcrt, "locking")(lock_fd.fileno(), getattr(msvcrt, "LK_LOCK"), 1)+ if _acquire_flock(lock_fd, _JOBS_LOCK_TIMEOUT_SECONDS) is False:+ logger.error(+ "Timed out after %.0fs waiting for the cron "+ "jobs lock (%s) — another process is holding "+ "it. Proceeding with in-process locking only "+ "so the scheduler stays alive (#60703).",+ _JOBS_LOCK_TIMEOUT_SECONDS,+ _jobs_lock_file(),+ )+ try:+ lock_fd.close()+ except OSError:+ pass+ lock_fd = Noneexcept (OSError, IOError) as e:- # Never let a locking failure take down cron writes — fall back to- # in-process-only protection (still held via _jobs_file_lock).+ # A locking failure must never take down cron writes — in-process lock still held.logger.warning("jobs.json cross-process lock unavailable (%s); ""proceeding with in-process lock only", e)try:yieldfinally:if lock_fd is not None:- try:- if fcntl is not None:- fcntl.flock(lock_fd, fcntl.LOCK_UN)- elif msvcrt is not None:- getattr(msvcrt, "locking")(lock_fd.fileno(), getattr(msvcrt, "LK_UNLCK"), 1)- except (OSError, IOError):- pass- finally:- lock_fd.close()+ _release_flock(lock_fd)finally:_jobs_lock_state.depth = 0_jobs_lock_state.load_stamp = None@@ -379,9 +305,8 @@ def _jobs_lock():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.+ Unlike the global jobs lock this may be held across network delivery; scoped to one profile ++ job so unrelated jobs keep progressing. Fails closed when cross-process locking is unavailable."""cron_dir = _current_cron_store().cron_dirlock_key = f"{cron_dir.resolve()}::{job_id}"@@ -413,28 +338,12 @@ def _fire_job_lock(job_id: str):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+ result = _acquire_flock(lock_fd, _JOBS_LOCK_TIMEOUT_SECONDS)+ if result is None: # pragma: no cover - supported platforms provide one backendlogger.error("No cross-process lock backend for cron fire fence")+ elif not result:+ logger.error("Timed out waiting for fire fence %s; failing closed", lock_path)+ acquired = bool(result)except (OSError, IOError) as exc:logger.error("Cron fire fence unavailable for %s: %s", job_id, exc)@@ -444,16 +353,9 @@ def _fire_job_lock(job_id: str):finally:held_locks.pop(lock_key, None)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:+ if acquired:+ _release_flock(lock_fd)+ else:lock_fd.close()finally:local_lock.release()@@ -474,20 +376,16 @@ def fire_claim_fence(job_id: str, *, expected_owner: str):)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-# into output writes/deletes.+# Fields that must never change after creation: ``id`` is a path component under OUTPUT_DIR, so an+# update could leak ``../escape``/absolute/nested values into output writes/deletes._IMMUTABLE_JOB_FIELDS = frozenset({"id"})def _job_output_dir(job_id: str) -> Path:"""Resolve a job's output directory, rejecting any path-escape attempt.- Job IDs are filesystem path components under ``OUTPUT_DIR``. A legacy or- crafted ID containing ``..``, absolute paths, or nested separators would- allow output writes/deletes to escape the cron output sandbox. Reject- anything that isn't a single safe path component.+ IDs containing ``..``, absolute paths, or separators would let output writes/deletes escape the+ sandbox; only a single safe path component is accepted."""text = str(job_id or "").strip()if not text or text in {".", ".."} or "/" in text or "\\" in text:@@ -545,11 +443,9 @@ NO_AGENT_WITHOUT_SCRIPT_ERROR = (def job_payload_is_empty(job: Dict[str, Any]) -> bool:- """True when a job record has nothing runnable at all.+ """True when a job record has nothing runnable (blank prompt, no script, no skills).- A blank/whitespace prompt with no script and no skills would hand the- agent an empty instruction on every fire (incident a5e29e688dc0).- ``no_agent`` needs no special case here — it already requires a script.+ ``no_agent`` needs no special case — it already requires a script."""if _coerce_job_text(job.get("prompt")).strip():return False@@ -558,9 +454,7 @@ def job_payload_is_empty(job: Dict[str, Any]) -> bool:if _normalize_skill_list(job.get("skill"), job.get("skills")):return False# Only flag if at least one payload field is explicitly present in the record- if "prompt" in job or "script" in job or "skill" in job or "skills" in job:- return True- return False+ return any(k in job for k in ("prompt", "script", "skill", "skills"))def _schedule_display_for_job(job: Dict[str, Any]) -> str:@@ -581,12 +475,8 @@ def _schedule_display_for_job(job: Dict[str, Any]) -> str:def _normalize_job_record(job: Dict[str, Any]) -> Dict[str, Any]:- """Return a read-safe cron job shape for UI/API/tool/scheduler consumers.-- Older or hand-edited jobs can have nullable fields like ``prompt``,- ``name``, or ``schedule_display``. Keep storage untouched on read, but- ensure consumers never crash while formatting or running those records.- """+ """Return a read-safe job shape: legacy/hand-edited records may have nullable ``prompt``,+ ``name``, ``schedule_display``. Storage is untouched; consumers never crash on formatting."""normalized = _apply_skill_fields(job)job_id = _coerce_job_text(normalized.get("id"), "unknown")prompt = _coerce_job_text(normalized.get("prompt"))@@ -607,9 +497,8 @@ def _normalize_job_record(job: Dict[str, Any]) -> Dict[str, Any]:normalized["name"] = namenormalized["schedule_display"] = _schedule_display_for_job(normalized)- # Display state is derived from the scheduler-honoured ``enabled`` flag so a- # half-paused record (enabled=true + state/paused_at) cannot render as- # "paused" while the fleet is still live. See effective_job_state().+ # Derived from the scheduler-honoured ``enabled`` flag so a half-paused record cannot render+ # "paused" while still firing. See effective_job_state().normalized["state"] = effective_job_state(normalized)return normalized@@ -623,26 +512,16 @@ def _has_pause_marker(job: Dict[str, Any]) -> bool:def is_job_runnable(job: Dict[str, Any]) -> bool:- """True iff the scheduler may fire this job.-- ``enabled`` is the scheduler-honoured flag. Pause markers (``state`` /- ``paused_at``) are a second gate so a contradictory half-paused record- never fires even before self-heal runs.- """+ """True iff the scheduler may fire this job: ``enabled`` plus pause markers as a second gate so+ a contradictory half-paused record never fires even before self-heal runs."""if not job.get("enabled", True):return False- if _has_pause_marker(job):- return False- return True+ return not _has_pause_marker(job)def effective_job_state(job: Dict[str, Any]) -> str:- """Operator-facing state derived from the scheduler-honoured flag.-- A job with ``enabled=true`` must never display as paused — that was the- 07-30 outage failure mode (list looked frozen, fleet kept merging).- Terminal states (completed/error) are preserved regardless of enabled.- """+ """Operator-facing state derived from ``enabled``: an enabled job must never display as paused+ (list looked frozen while jobs kept firing). Terminal states are preserved regardless."""stored = _coerce_job_text(job.get("state")).strip()if stored in {"completed", "error"}:return stored@@ -664,27 +543,12 @@ def is_terminal_job(job: Dict[str, Any]) -> bool:def _is_recoverable_error_job(job: Dict[str, Any]) -> bool:"""True for a recurring job stuck in ``state=error``.- ``state=error`` is set ONLY on a cron/interval job when- ``compute_next_run()`` fails to produce a next occurrence (e.g. the- ``croniter`` package is missing, or a malformed schedule) — see- ``_mark_job_run_locked``'s issue #16265 comment: recurring jobs must- NEVER be silently disabled. Unlike ``state=completed`` (a one-shot- that genuinely has no more occurrences, ever), an error-state- recurring job still has a schedule with future occurrences once the- underlying issue resolves — it is stuck pending a ``next_run_at``- recompute, not truly done.-- ``is_terminal_job()`` treats both states identically, which is correct- for blocking bare reactivation through ``update_job`` on a genuinely- completed job, but wrong here: it also blocks the due-scan's own- ``next_run_at`` self-heal (``_get_due_jobs_locked`` already recomputes- it for ``cron``/``interval`` jobs, but never reaches that code), the- at-most-once pre-advance (``advance_next_runs``), the dispatch claim- (``_claim_job_for_fire_locked``), and manual recovery (``resume_job``)- — wedging the job forever with no exit except deleting and recreating- it. Callers that need "is this job truly done" should keep using- ``is_terminal_job()`` alone; callers that need "can this job still- reach a future occurrence" should exclude this case.+ ``state=error`` is set ONLY when ``compute_next_run()`` fails for a cron/interval job (croniter+ missing, malformed schedule); recurring jobs must NEVER be silently disabled, and unlike+ ``completed`` such a job still has future occurrences once the issue resolves. Treating it as+ terminal would block the due-scan self-heal, at-most-once pre-advance, dispatch claim, and+ ``resume_job`` — wedging it forever. Use ``is_terminal_job()`` for "truly done"; exclude this+ case for "can still reach a future occurrence"."""return (job.get("state") == "error"@@ -710,20 +574,11 @@ def _secure_file(path: Path):def _preserve_file_ownership(path: Path, before: Optional[os.stat_result]) -> None:- """Restore a rewritten file's previous owner (POSIX, privileged writer only).-- The atomic-write pattern (mkstemp + replace) makes the rewritten file owned- by the *writer's* euid. When a root shell runs a state-writing cron CLI- command (``docker exec hermes hermes cron create ...`` — ``docker exec``- defaults to root) against a store owned by the unprivileged gateway user,- the replace flips ``jobs.json`` to ``root:root`` mode 600 and the gateway's- ticker (uid 1000) is silently locked out of every subsequent tick (#68483).-- Root can always hand ownership back, so do exactly that: when the euid is 0- and the pre-replace owner differs, chown the new file to the previous- uid/gid. Unprivileged writers are a no-op (their own rewrite already heals- a root-owned file back to their uid, and they couldn't chown anyway).- No-op on Windows. Best-effort: a failure must never break the save.+ """Restore a rewritten file's previous owner (POSIX, root writer only).++ Atomic replace makes the file owned by the writer's euid; a root CLI write (e.g. ``docker exec``)+ against the unprivileged gateway's store would flip jobs.json to root:root 0600 and lock the+ ticker out of every later tick. Root can hand ownership back, so chown when the owner differed."""if before is None or os.name != "posix":return@@ -748,14 +603,9 @@ def _preserve_file_ownership(path: Path, before: Optional[os.stat_result]) -> Nodef _is_named_profile_path(path: Path) -> bool:- """Return True if *path* is inside a named profile home.-- Named profiles live under ``<hermes_home>/profiles/<name>/``. The- default profile lives at ``<hermes_home>`` directly (no ``profiles``- parent), as do custom ``HERMES_HOME`` paths outside ``~/.hermes``.+ """True if *path* is under ``<hermes_home>/profiles/<name>/`` (default/custom homes are not).- Checks both the resolved path (handles symlinks in the parent chain)- and the raw path (catches symlinked profile homes whose resolve()+ Checks the resolved path (symlinked parents) and the raw path (symlinked profile homes whosetarget no longer contains ``profiles``)."""try:@@ -769,12 +619,9 @@ def _is_named_profile_path(path: Path) -> bool:def _ensure_cron_dir(cron_dir: Path) -> None:"""Create a cron directory without resurrecting a deleted profile home.- Named profiles are created by the profile lifecycle, not cron. A stale- multiplex scheduler may still hold a path to a deleted profile after the- user removes it; ``parents=False`` makes that race fail closed- (FileNotFoundError) instead of silently restoring the directory tree.- Default and custom Hermes homes keep ``parents=True`` so first-run- directory creation still works.+ A stale multiplex scheduler may still hold a deleted profile's path; ``parents=False`` makes+ that race fail closed instead of restoring the tree. Default/custom homes keep ``parents=True``+ so first-run creation works."""if _is_named_profile_path(cron_dir):cron_dir.mkdir(exist_ok=True)@@ -796,16 +643,10 @@ def ensure_dirs():# =============================================================================def normalize_repeat_value(repeat: Any) -> Optional[int]:- """Coerce a repeat value from any entry point into ``Optional[int]``.-- The tool schema exposes ``repeat`` as an integer, but agents and users- legitimately pass the user-facing strings ``'forever'``/``'once'`` or- numeric strings (``'3'``). Uncoerced strings previously died with- ``'<=' not supported between instances of 'str' and 'int'`` at create- (#66824/#64520/#7142/#71987/#95706) and were stored raw by update paths,- breaking ``mark_job_run`` later. Semantics: ``'forever'``-family -> None- (infinite), ``'once'``-family -> 1, numeric -> int, 0/negative -> None,- anything else -> ValueError (never store garbage).+ """Coerce a repeat value (int or user-facing string) into ``Optional[int]``.++ ``'forever'``-family -> None (infinite), ``'once'``-family -> 1, numeric -> int, 0/negative ->+ None, anything else -> ValueError (never store garbage that breaks ``mark_job_run`` later)."""if repeat is None:return None@@ -826,15 +667,7 @@ def normalize_repeat_value(repeat: Any) -> Optional[int]:def parse_duration(s: str) -> int:- """- Parse duration string into minutes.-- Examples:- "30m" → 30- "2h" → 120- "1d" → 1440- "hour" → 60 (bare unit, no leading number)- """+ """Parse a duration string into minutes: "30m" → 30, "2h" → 120, "1d" → 1440, bare "hour" → 60."""s = s.strip().lower()match = re.match(r'^(\d*)\s*(m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days)$', s)if not match:@@ -850,8 +683,7 @@ def parse_duration(s: str) -> int:return value * multipliers[unit]-# Natural-language day-spec phrases for the documented "every monday 9am" /-# "every day at 9am" schedule forms. Cron weekday numbering is+# Day-spec phrases for "every monday 9am" / "every day at 9am". Cron weekday numbering is# 0=Sunday … 6=Saturday (croniter's default)._WEEKDAY_TO_CRON_DOW = {"sunday": "0", "sun": "0",@@ -872,12 +704,8 @@ _DAYSPEC_TO_CRON_DOW = {def _parse_clock_time(text: str) -> Optional[tuple]:- """Parse a wall-clock time into a ``(hour, minute)`` 24-hour tuple.-- Accepts ``9am``, ``9:30am``, ``9 am``, ``14:00``, ``7`` (bare hour, 24h),- ``noon``/``midday``, and ``midnight``. Returns None when the text is not a- recognized clock time so the caller can reject the schedule cleanly.- """+ """Parse ``9am``/``9:30am``/``14:00``/``7`` (bare 24h hour)/``noon``/``midnight`` into a+ 24-hour ``(hour, minute)`` tuple, or None when unrecognized."""t = text.strip().lower().replace(" ", "")if not t:return None@@ -904,26 +732,13 @@ def _parse_clock_time(text: str) -> Optional[tuple]:def _natural_every_to_cron(rest: str) -> Optional[str]:- """Convert a documented ``every <when> [at] <time>`` phrase to a 5-field- cron expression, or None when *rest* is not such a phrase.-- Examples::-- "monday 9am" -> "0 9 * * 1"- "day at 9am" -> "0 9 * * *"- "weekday at 9am" -> "0 9 * * 1-5"- "monday, wednesday at 9am" -> "0 9 * * 1,3"-- Returning None lets ``parse_schedule`` fall back to the interval- (``every 30m``) path, so existing duration schedules are unaffected.- """+ """Convert ``<when> [at] <time>`` ("monday 9am", "weekday at 9am", "monday, wednesday at 9am")+ to a 5-field cron expr, or None so ``parse_schedule`` can fall back to the interval path."""tokens = rest.lower().replace(",", " ").split()if not tokens:return None- # Consume one or more leading day tokens: a keyword spec ("weekdays"),- # a single weekday, or a comma/"and"-separated weekday list- # ("monday, wednesday at 9am").+ # Leading day tokens: a keyword spec ("weekdays") or a comma/"and"-separated weekday list.day_token = tokens[0]dow = _DAYSPEC_TO_CRON_DOW.get(day_token)idx = 1@@ -959,120 +774,64 @@ def _natural_every_to_cron(rest: str) -> Optional[str]:return f"{minute} {hour} * * {dow}"+def _cron_schedule(expr: str, display: str, missing_croniter: str, invalid_label: str) -> Dict[str, Any]:+ """Validate a cron expression with croniter and build the stored schedule dict."""+ if not _ensure_croniter():+ raise ValueError(f"{missing_croniter} Install with: pip install croniter")+ try:+ croniter(expr)+ except Exception as e:+ raise ValueError(f"Invalid {invalid_label} '{display}': {e}")+ return {"kind": "cron", "expr": expr, "display": display}++def parse_schedule(schedule: str) -> Dict[str, Any]:- """- Parse schedule string into structured format.-- Returns dict with:- - kind: "once" | "interval" | "cron"- - For "once": "run_at" (ISO timestamp)- - For "interval": "minutes" (int)- - For "cron": "expr" (cron expression)-- Examples:- "30m" → every 30 minutes (recurring)- "2h" → every 2 hours (recurring)- "every 30m" → recurring every 30 minutes- "every 2h" → recurring every 2 hours- "every monday 9am" → recurring weekly (cron)- "every day at 9am" → recurring daily (cron)- "0 9 * * *" → cron expression- "2026-02-03T14:00" → once at timestamp- """+ """Parse a schedule string into ``{"kind": "once"|"interval"|"cron", ...}`` with ``run_at`` /+ ``minutes`` / ``expr``. "30m" and "every 30m" are recurring intervals; "every monday 9am" and+ "0 9 * * *" are cron; an ISO timestamp is once."""schedule = schedule.strip()original = scheduleschedule_lower = schedule.lower()- # "every X" pattern → recurring interval, OR a documented natural-language- # day/time phrase ("every monday 9am", "every day at 9am") → cron.+ # "every X" → recurring interval, or a natural day/time phrase → cron.if schedule_lower.startswith("every "):rest = schedule[6:].strip()cron_expr = _natural_every_to_cron(rest)if cron_expr is not None:- if not _ensure_croniter():- raise ValueError(- "Weekday/time schedules like 'every monday 9am' require the "- "'croniter' package. Install with: pip install croniter"- )- try:- croniter(cron_expr)- except Exception as e:- raise ValueError(f"Invalid schedule '{original}': {e}")- return {- "kind": "cron",- "expr": cron_expr,- "display": original,- }+ return _cron_schedule(+ cron_expr, original,+ "Weekday/time schedules like 'every monday 9am' require the 'croniter' package.",+ "schedule",+ )minutes = parse_duration(rest)- return {- "kind": "interval",- "minutes": minutes,- "display": f"every {minutes}m"- }+ return {"kind": "interval", "minutes": minutes, "display": f"every {minutes}m"}- # No-"every" natural day/time phrases advertised by the Desktop dialog:- # "weekdays at 9am", "monday at 9:30", "daily at 7am" (#51975). Reuse the- # same helper — the phrase shape is identical without the "every " prefix.+ # No-"every" phrases ("weekdays at 9am", "daily at 7am"): same shape sans prefix.cron_expr = _natural_every_to_cron(schedule_lower)if cron_expr is not None:- if not _ensure_croniter():- raise ValueError(- "Weekday/time schedules like 'weekdays at 9am' require the "- "'croniter' package. Install with: pip install croniter"- )- try:- croniter(cron_expr)- except Exception as e:- raise ValueError(f"Invalid schedule '{original}': {e}")- return {- "kind": "cron",- "expr": cron_expr,- "display": original,- }+ return _cron_schedule(+ cron_expr, original,+ "Weekday/time schedules like 'weekdays at 9am' require the 'croniter' package.",+ "schedule",+ )- # Check for cron expression (5 or 6 space-separated fields)- # Cron fields: minute hour day month weekday [year]- # Allow letters so named months/weekdays (JAN-DEC, MON-SUN, incl. ranges- # and lists like MON-FRI or MON,WED,FRI) are routed to croniter, which- # supports them. The previous digit-only pattern silently rejected these- # valid expressions as "Invalid schedule".+ # Cron expression (5-6 fields). Letters are allowed so named months/weekdays (JAN-DEC, MON-FRI)+ # reach croniter, which supports them; a digit-only pattern silently rejected them.parts = schedule.split()- if len(parts) >= 5 and all(- re.match(r'^[A-Za-z\d\*\-,/]+$', p) for p in parts[:5]- ):- if not _ensure_croniter():- raise ValueError("Cron expressions require 'croniter' package. Install with: pip install croniter")- # Validate cron expression- try:- croniter(schedule)- except Exception as e:- raise ValueError(f"Invalid cron expression '{schedule}': {e}")- return {- "kind": "cron",- "expr": schedule,- "display": schedule- }-+ if len(parts) >= 5 and all(re.match(r'^[A-Za-z\d\*\-,/]+$', p) for p in parts[:5]):+ return _cron_schedule(+ schedule, schedule, "Cron expressions require 'croniter' package.", "cron expression"+ )+# ISO timestamp (contains T or looks like date)if 'T' in schedule or re.match(r'^\d{4}-\d{2}-\d{2}', schedule):try:- # Parse and validatedt = datetime.fromisoformat(schedule.replace('Z', '+00:00'))- # Make naive timestamps timezone-aware at parse time so the stored- # value doesn't depend on the system timezone matching at check time.- #- # Anchor to the CONFIGURED Hermes timezone, not the server's local- # timezone. The due-check (`get_due_jobs`) compares `next_run_at`- # against `hermes_time.now()`, which uses the configured zone. If a- # naive "20:07" were interpreted as server-local (e.g. UTC) while- # now() runs in Asia/Kolkata, the stored instant would land hours- # off from the user's wall-clock intent — far enough that one-shots- # never become due and recurring jobs fire at the wrong time. Using- # the configured zone makes "20:07" mean 20:07 on the same clock the- # scheduler checks against (#51021).+ # Make naive timestamps aware at parse time, anchored to the CONFIGURED Hermes timezone+ # (not server-local): the due-check compares against hermes_time.now(), so a+ # server-local reading would land hours off the user's wall-clock intent.if dt.tzinfo is None:- hermes_tz = _hermes_now().tzinfo- dt = dt.replace(tzinfo=hermes_tz)+ dt = dt.replace(tzinfo=_hermes_now().tzinfo)return {"kind": "once","run_at": dt.isoformat(),@@ -1080,13 +839,9 @@ def parse_schedule(schedule: str) -> Dict[str, Any]:}except ValueError as e:raise ValueError(f"Invalid timestamp '{schedule}': {e}")-- # Duration like "30m", "2h", "1d" → RECURRING interval, matching the- # documented tool contract ("30m (every 30 minutes)"). Previously this- # returned kind="once", silently creating a one-shot job for a schedule- # the schema documents as recurring — an agent passing '30m' for "every- # 30 minutes" got a job that ran once and died (cron contract bug, fixed- # 2026-08-04). Explicit one-shot-by-duration is "in 30m"/"in 2h".++ # Bare duration ("30m") → RECURRING interval per the documented tool contract; the explicit+ # one-shot-by-duration form is "in 30m"/"in 2h".if schedule_lower.startswith("in "):duration_str = schedule[3:].strip()try:@@ -1096,21 +851,13 @@ def parse_schedule(schedule: str) -> Dict[str, Any]:f"Invalid duration '{duration_str}' after 'in '. Use e.g. 'in 30m', 'in 2h'.")run_at = _hermes_now() + timedelta(minutes=minutes)- return {- "kind": "once",- "run_at": run_at.isoformat(),- "display": f"once in {duration_str}",- }+ return {"kind": "once", "run_at": run_at.isoformat(), "display": f"once in {duration_str}"}try:minutes = parse_duration(schedule)- return {- "kind": "interval",- "minutes": minutes,- "display": f"every {minutes}m",- }+ return {"kind": "interval", "minutes": minutes, "display": f"every {minutes}m"}except ValueError:pass-+raise ValueError(f"Invalid schedule '{original}'. Use:\n"f" - Interval: '30m', 'every 30m', 'every 2h' (recurring)\n"@@ -1119,20 +866,10 @@ def parse_schedule(schedule: str) -> Dict[str, Any]:f" - Cron: '0 9 * * *' (cron expression)\n"f" - Timestamp: '2026-02-03T14:00:00' (one-shot at time)")--def _ensure_aware(dt: datetime) -> datetime:- """Return a timezone-aware datetime in Hermes configured timezone.-- Backward compatibility:- - Older stored timestamps may be naive.- - Naive values are interpreted as *system-local wall time* (the timezone- `datetime.now()` used when they were created), then converted to the- configured Hermes timezone.-- This preserves relative ordering for legacy naive timestamps across- timezone changes and avoids false not-due results.- """+ """Return an aware datetime in the configured Hermes timezone. Legacy naive values are read as+ *system-local* wall time (what created them) then converted, preserving ordering across+ timezone changes and avoiding false not-due results."""target_tz = _hermes_now().tzinfoif dt.tzinfo is None:local_tz = datetime.now().astimezone().tzinfo@@ -1140,27 +877,27 @@ def _ensure_aware(dt: datetime) -> datetime:return dt.astimezone(target_tz)-def _timezone_offset_mismatch(stored: datetime, current: datetime) -> bool:- """Return True when a stored aware timestamp uses a different UTC offset.+def _parse_aware(value: Any) -> Optional[datetime]:+ """``_ensure_aware(datetime.fromisoformat(value))``, or None when *value* is not a parseable ISO string."""+ try:+ return _ensure_aware(datetime.fromisoformat(value))+ except Exception:+ return None- Naive stored timestamps return False: they carry no offset to compare, and- are normalized by ``_ensure_aware`` instead — they intentionally never take- the offset-repair path.- """++def _timezone_offset_mismatch(stored: datetime, current: datetime) -> bool:+ """True when a stored aware timestamp uses a different UTC offset. Naive values return False:+ they are normalized by ``_ensure_aware`` and intentionally never take the offset-repair path."""if stored.tzinfo is None or current.tzinfo is None:return Falsereturn stored.utcoffset() != current.utcoffset()def _stored_wall_clock_is_future(stored: datetime, current: datetime) -> bool:- """Return True when the stored local wall-clock time has not arrived yet.-- Cron schedules express local wall-clock intent. If Hermes/system local time- changes after next_run_at was persisted, an old offset can make a future- wall-clock run look due at the converted absolute time (for example- 21:00+10 becomes 13:00+02). Comparing naive wall-clock values lets us- distinguish that migration case from a genuinely missed run whose scheduled- wall time has already passed.+ """True when the stored local wall-clock time has not arrived yet.++ Cron expresses wall-clock intent; after a timezone change an old offset can make a future run+ look due (21:00+10 → 13:00+02). Comparing naive wall clocks separates that from a genuine miss."""return stored.replace(tzinfo=None) > current.replace(tzinfo=None)@@ -1171,38 +908,23 @@ def _recoverable_oneshot_run_at(*,last_run_at: Optional[str] = None,) -> Optional[str]:- """Return a one-shot run time if it is still eligible to fire.-- One-shot jobs get a small grace window so jobs created a few seconds after- their requested minute still run on the next tick. Once a one-shot has- already run, it is never eligible again.- """+ """Return a one-shot run time if still eligible: a small grace window covers jobs created just+ after their minute; once run, a one-shot is never eligible again."""if not isinstance(schedule, dict) or schedule.get("kind") != "once":return Noneif last_run_at:return Nonerun_at = schedule.get("run_at")- if not run_at:- return None-- try:- run_at_dt = _ensure_aware(datetime.fromisoformat(run_at))- except Exception:- return None- if run_at_dt >= now - timedelta(seconds=ONESHOT_GRACE_SECONDS):+ run_at_dt = _parse_aware(run_at) if run_at else None+ if run_at_dt is not None and run_at_dt >= now - timedelta(seconds=ONESHOT_GRACE_SECONDS):return run_atreturn Nonedef _compute_grace_seconds(schedule: dict) -> int:- """Compute how late a job can be and still catch up instead of fast-forwarding.-- Uses half the schedule period (via ``_schedule_cadence_seconds``, the- single cadence-measurement implementation), clamped between 120 seconds- and 2 hours. This ensures daily jobs can catch up if missed by up to- 2 hours, while frequent jobs (every 5-10 min) still fast-forward quickly.- """+ """How late a job can be and still catch up rather than fast-forward: half the period, clamped+ to [120s, 2h], so daily jobs catch up but frequent jobs fast-forward quickly."""MIN_GRACE = 120MAX_GRACE = 7200 # 2 hours@@ -1213,22 +935,14 @@ def _compute_grace_seconds(schedule: dict) -> int:return max(MIN_GRACE, min(grace, MAX_GRACE))-# Missed-run visibility (#99879): a recurring dispatch within this many-# seconds of its scheduled instant renders as "on time". The built-in ticker-# runs once a minute and a busy tick can push dispatch a couple of minutes-# past the scheduled instant — that is normal cadence, not gateway downtime.+# A recurring dispatch within this many seconds of schedule renders "on time": a busy once-a-minute+# ticker can slip a couple of minutes — normal cadence, not gateway downtime._LATE_DISPATCH_TOLERANCE_SECONDS = 300def _classify_dispatch_lateness(lateness_seconds: float, grace_seconds: int) -> str:- """Classify a recurring dispatch by how late it fired.-- ``on_time`` — within normal ticker cadence slack;- ``late`` — missed the scheduled instant but within the catch-up- grace window (e.g. gateway briefly down);- ``catch_up`` — beyond the grace window; the due-scan skipped the- accumulated misses and executed once now.- """+ """``on_time`` (within ticker slack), ``late`` (within the catch-up grace window), or+ ``catch_up`` (beyond grace; accumulated misses skipped, executed once now)."""if lateness_seconds > grace_seconds:return "catch_up"if lateness_seconds > _LATE_DISPATCH_TOLERANCE_SECONDS:@@ -1236,17 +950,7 @@ def _classify_dispatch_lateness(lateness_seconds: float, grace_seconds: int) ->return "on_time"-# Durable (persisted-state) recovery counter for a recurring job wedged in a-# stale ``last_status == "error"`` state with ``next_run_at`` parked in the-# future. This is the restart-surviving half of the recurring-cron wedge-# (t_20e23f84 / t_8b5480b3): the in-memory stale-claim sweep in scheduler.py-# heals a leaked ``_running_job_ids`` claim in-process, but a job whose-# persisted ``next_run_at`` was re-armed into the future (the normal-# post-error re-arm by ``mark_job_run``) is invisible to that sweep — it is-# not in the running set, so nothing force-releases it, and it is not due, so-# ``get_due_jobs`` never returns it. It just sits. This recovery re-arms-# ``next_run_at`` to now so the next tick re-dispatches it, exactly like the-# operator's force-run / mech_red_guard's ``cron resume`` but built-in.+# Recovery counter for recurring jobs wedged in stale ``last_status == "error"`` with a future next_run_at._persisted_error_recoveries: int = 0# Bounded in-memory history kept by every probe-visible fire-path counter._TELEMETRY_RECENT_HISTORY = 20@@ -1258,59 +962,36 @@ def _job_is_stale_error_recurring(schedule: Dict[str, Any],now: datetime,) -> bool:- """True when a recurring job is wedged in a stale persisted error state.-- Condition (all must hold):- * it is a recurring (cron/interval) job (checked by caller);- * its persisted ``last_status == "error"`` (a prior fire errored and the- job never recovered);- * it has NOT successfully re-fired within its natural cadence — its- ``last_run_at`` is older than ``cadence + grace``, so this is not a- normal transient-error retry that will fire on its own soon, it is a- job that has been sitting errored for a full period with no recovery;- * it is not currently running in this process (a live run must never be- re-armed underneath itself, #62002-style).-- ``last_run_at`` being older than one cadence is the key discriminator: a- job that errors and is retried on its normal schedule keeps ``last_run_at``- fresh (mark_job_run stamps it on every fire, success or failure), so the- stale check does not fire for a job that is merely erroring-and-retrying.+ """True when a recurring job (caller-checked) is wedged in a stale persisted error state.++ Requires ``last_status == "error"``, not running in this process (a live run must never be+ re-armed underneath itself), and ``last_run_at`` older than ``cadence + grace``. The age is the+ key discriminator: mark_job_run stamps ``last_run_at`` on every fire, so a job merely+ erroring-and-retrying on schedule stays fresh and is not flagged."""if job.get("last_status") != "error":return Falseif _job_running_in_this_process(str(job.get("id") or "")):return Falselast_run = job.get("last_run_at")- if not last_run:- return False- try:- last_run_dt = _ensure_aware(datetime.fromisoformat(last_run))- except (ValueError, TypeError):+ last_run_dt = _parse_aware(last_run) if last_run else None+ if last_run_dt is None:return Falseage_seconds = (now - last_run_dt).total_seconds()if age_seconds < 0:return Falsecadence_seconds = _schedule_cadence_seconds(schedule)if cadence_seconds is None:- # Unknown cadence (croniter unavailable / malformed expr): fall back to- # the grace window so a badly-parked job is still recovered, but never- # re-arm anything younger than the 2h grace cap.+ # Unknown cadence: fall back to the grace window, never re-arming anything younger than it.cadence_seconds = _compute_grace_seconds(schedule)return age_seconds > (cadence_seconds + _compute_grace_seconds(schedule))def _schedule_cadence_seconds(schedule: Dict[str, Any]) -> Optional[float]:- """Approximate the natural period of a schedule, in seconds, or None.-- Interval jobs use ``minutes * 60``. Cron jobs measure the gap between the- next two fire times with croniter (falling back to None when croniter is- missing or the expr is malformed). Cron results are cached per expr —- this runs inside ``_jobs_lock`` on every tick for every stale-errored- job, and two croniter evaluations per call add up (the same reason- ``scheduler.py`` caches ``_cron_interval_minutes``). The measured gap- can vary with the base time for irregular exprs; the cache trades that- precision for not re-evaluating croniter under the lock, which is fine- for a staleness *threshold*.+ """Approximate schedule period in seconds, or None (croniter missing / malformed expr).++ Cron results are cached per expr because this runs under ``_jobs_lock`` every tick; the gap can+ vary with base time for irregular exprs, acceptable for a staleness *threshold*."""if not isinstance(schedule, dict):return None@@ -1338,9 +1019,7 @@ def _schedule_cadence_seconds(schedule: Dict[str, Any]) -> Optional[float]:result = gap if gap > 0 else Noneexcept Exception:result = None- # Hard bound so deleted/edited exprs can never grow the cache- # unboundedly in a long-lived gateway; a rare full clear costs two- # croniter evaluations per live expr to rebuild.+ # Hard bound so deleted/edited exprs can't grow the cache unboundedly in a long-lived gateway.if len(_cron_cadence_cache) >= 256:_cron_cadence_cache.clear()_cron_cadence_cache[expr] = result@@ -1353,13 +1032,9 @@ _cron_cadence_cache: Dict[str, Optional[float]] = {}def _append_telemetry_record(filename: str, entry: Dict[str, Any], recent: list) -> None:- """Keep ``entry`` in the bounded in-memory ``recent`` list and append it to- ``<cron_dir>/<filename>`` (best effort — telemetry must never break a tick).-- Shared by the probe-visible fire-path counters (persisted-error recovery,- timezone-migration catch-up); each keeps its own module-level int counter- because tests reset those by name.- """+ """Record ``entry`` in the bounded ``recent`` list and append to ``<cron_dir>/<filename>``+ (best effort — telemetry must never break a tick). Counters stay module-level ints per+ metric because tests reset them by name."""recent.append(entry)del recent[:-_TELEMETRY_RECENT_HISTORY]try:@@ -1400,12 +1075,9 @@ def _cron_next_run_matches_expr() -> bool:"""Whether ``next_run_dt`` is an occurrence of the schedule's current expr.- A direct ``jobs.json`` edit can change ``schedule.expr`` while leaving the- stored ``next_run_at`` computed under the *old* expression (#93049). The- stored instant is stale exactly when it is not an occurrence of the- current expression. Validation is best-effort: anything that cannot be- checked (non-cron kind, missing expr, croniter unavailable, malformed- input) reports a match so the fire path keeps its existing semantics.+ Detects a hand-edited ``schedule.expr`` whose stored ``next_run_at`` came from the old one.+ Best-effort: anything uncheckable (non-cron, no expr, no croniter, malformed) reports a match+ so the fire path keeps its existing semantics."""if schedule.get("kind") != "cron":return True@@ -1413,9 +1085,8 @@ def _cron_next_run_matches_expr(if not expr or not _ensure_croniter() or croniter is None:return Truetry:- # The last occurrence at-or-before the stored instant: base croniter- # a second past it so an exact occurrence is included, then compare- # at second granularity (croniter returns second-precision datetimes).+ # Last occurrence at-or-before the instant: base one second past it so an exact hit is+ # included, then compare at second granularity (croniter is second-precision).base = next_run_dt + timedelta(seconds=1)prev = croniter(str(expr), base).get_prev(datetime)return abs((prev - next_run_dt).total_seconds()) < 1.0@@ -1423,8 +1094,7 @@ def _cron_next_run_matches_expr(return True-# Classification results for a due cron instant that is NOT an occurrence of-# the job's current expression (see _classify_stale_cron_next_run).+# Classifications for a due cron instant NOT on the current expr (see _classify_stale_cron_next_run).STALE_CRON_MATCH = "match"STALE_CRON_TIMEZONE_MIGRATION = "timezone_migration"STALE_CRON_EXPR_EDIT = "expr_edit"@@ -1435,32 +1105,15 @@ def _classify_stale_cron_next_run(raw_next_run_dt: datetime,next_run_dt: datetime,) -> str:- """Explain WHY a stored ``next_run_at`` misses the current cron lattice.-- ``_cron_next_run_matches_expr`` answers "does the stored instant occur in- the current expression?" but not "why not?", and the two answers call for- opposite actions:-- * ``expr_edit`` — a direct ``jobs.json`` edit changed ``schedule.expr``- while leaving ``next_run_at`` computed under the old one (#93049). The- stored instant is a time the current expression *excludes*, so it must- be re-anchored WITHOUT firing.- * ``timezone_migration`` — the expression never changed; only the stored- value's *offset representation* did. Upgrading from a UTC-scheduling- build to one that honours the profile timezone leaves legacy rows like- ``2026-09-02T04:00:00+00:00`` for ``0 4 * * *``; normalizing to- Europe/Brussels turns that into ``06:00+02``, which the expression- excludes. Treating it as a stale edit re-anchored to tomorrow and- silently skipped a due occurrence that had never fired.-- The discriminator is whether *normalization itself* moved the wall clock.- Cron expressions describe local wall-clock intent, so a stored instant- whose OWN wall clock is a legal occurrence, and which only left the- lattice because ``_ensure_aware`` converted it into a different offset, is- a representation migration — not a schedule edit. When the offsets agree- (the common case, including every value this build wrote) the wall clock- is unchanged, so a genuine ``expr`` edit can never be misread as a- migration.+ """Explain WHY a stored ``next_run_at`` misses the current cron lattice; the causes need+ opposite actions.++ ``expr_edit``: a hand edit changed ``schedule.expr`` — the instant is excluded, so re-anchor+ WITHOUT firing. ``timezone_migration``: only the offset representation changed (legacy UTC rows+ normalized into the profile tz), and treating it as an edit would skip a due, never-fired+ occurrence. Discriminator: whether normalization itself moved the wall clock — a stored instant+ whose OWN wall clock is a legal occurrence is a migration. When offsets agree the wall clock is+ unchanged, so a genuine expr edit can never be misread as a migration."""if _cron_next_run_matches_expr(schedule, next_run_dt):return STALE_CRON_MATCH@@ -1472,13 +1125,7 @@ def _classify_stale_cron_next_run(return STALE_CRON_EXPR_EDIT-# Durable, probe-visible counter for offset-representation migrations caught-# on the fire path. Kept separate from `catch_up_occurrences` (runs skipped-# past their grace window — a migrated row that is ALSO past grace increments-# both) because this one means "an upgrade rewrote how next_run_at is-# represented" — an operator seeing it climb after a deploy is seeing the-# migration drain, and seeing it climb steadily afterwards is seeing a-# timezone that keeps changing under the store.+# Offset-migration catch-ups on the fire path: climbing after a deploy = draining; steady = TZ churn._timezone_migration_catchups: int = 0_timezone_migration_catchups_recent: list = []@@ -1513,11 +1160,7 @@ def get_timezone_migration_catchup_stats() -> Dict[str, Any]:def compute_next_run(schedule: Dict[str, Any], last_run_at: Optional[str] = None) -> Optional[str]:- """- Compute the next run time for a schedule.-- Returns ISO timestamp string, or None if no more runs.- """+ """Compute the next run time for a schedule as an ISO string, or None if no more runs."""now = _hermes_now()if not isinstance(schedule, dict):@@ -1533,16 +1176,8 @@ def compute_next_run(schedule: Dict[str, Any], last_run_at: Optional[str] = Noneminutes = schedule.get("minutes")if minutes is None:return None- if last_run_at:- try:- last = _ensure_aware(datetime.fromisoformat(last_run_at))- next_run = last + timedelta(minutes=minutes)- except Exception:- next_run = now + timedelta(minutes=minutes)- else:- # First run is now + interval- next_run = now + timedelta(minutes=minutes)- return next_run.isoformat()+ last = _parse_aware(last_run_at) if last_run_at else None+ return ((last or now) + timedelta(minutes=minutes)).isoformat()elif kind == "cron":expr = schedule.get("expr")@@ -1557,16 +1192,8 @@ def compute_next_run(schedule: Dict[str, Any], last_run_at: Optional[str] = Noneexpr,)return None- # Use last_run_at as the croniter base when available, consistent- # with interval jobs. This ensures that after a crash/restart,- # the next run is anchored to the actual last execution time- # rather than to an arbitrary restart time.- base_time = now- if last_run_at:- try:- base_time = _ensure_aware(datetime.fromisoformat(last_run_at))- except Exception:- base_time = now+ # Anchor on last_run_at (like interval jobs) so a restart doesn't re-anchor the schedule.+ base_time = (_parse_aware(last_run_at) if last_run_at else None) or nowcron = croniter(expr, base_time)next_run = cron.get_next(datetime)return next_run.isoformat()@@ -1574,66 +1201,23 @@ def compute_next_run(schedule: Dict[str, Any], last_run_at: Optional[str] = Nonereturn None-# =============================================================================-# Ticker heartbeat (liveness signal for `hermes cron status`)-# =============================================================================--def _atomic_write_epoch(path: Path) -> None:- """Atomically write the current epoch time to ``path``.-- Delegates to :func:`utils.atomic_write_text` (tmpfile + fsync +- ``atomic_replace``, same pattern as ``save_jobs``) so a concurrent reader- in another process (``hermes cron status``) never sees a torn/truncated- file. Best-effort: failures are swallowed by callers.- """- ensure_dirs()- atomic_write_text(path, str(time.time()), tmp_prefix=".hb_")-+# --- Ticker heartbeat (liveness signal for `hermes cron status`) ----def _atomic_write_counter(path: Path, value: int) -> None:- """Atomically persist a non-negative integer counter."""- ensure_dirs()- fd, tmp_path = tempfile.mkstemp(dir=str(path.parent), suffix=".tmp", prefix=".count_")+def _write_marker(name: str, text: str, tmp_prefix: str) -> None:+ """Atomic (never torn) best-effort marker write; failures swallowed so markers never break the tick."""try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(str(max(0, value)))- f.flush()- os.fsync(f.fileno())- atomic_replace(tmp_path, path)- except BaseException:- try:- os.unlink(tmp_path)- except OSError:- pass- raise+ ensure_dirs()+ atomic_write_text(_current_cron_store().cron_dir / name, text, tmp_prefix=tmp_prefix)+ except Exception:+ passdef record_ticker_heartbeat(success: bool = False) -> None:- """Record a ticker liveness signal, and optionally a successful-tick signal.-- The ticker calls this once per loop iteration. ``success=True`` additionally- bumps the *last successful tick* marker. We track two distinct signals so- `hermes cron status` can tell a thread that is merely *alive and looping*- (heartbeat fresh, success stale) from one that is actually *firing jobs*- (both fresh) — a ticker stuck failing every tick would otherwise keep the- plain heartbeat fresh and falsely report healthy (#32612, #32895).-- Resolution uses ``_current_cron_store()`` so the heartbeat is correctly- scoped to the active profile's store — critical under multiplex_profiles- where each profile needs its own liveness signal (#69377).-- Best-effort: a write failure must never disrupt the tick loop.- """- store = _current_cron_store()- try:- _atomic_write_epoch(store.cron_dir / "ticker_heartbeat")- except Exception:- pass+ """Record ticker liveness (+ last-success marker when ``success``) so `cron status` can tell+ "alive but failing" from "firing"; scoped per profile store."""+ _write_marker("ticker_heartbeat", str(time.time()), ".hb_")if success:- try:- _atomic_write_epoch(store.cron_dir / "ticker_last_success")- except Exception:- pass+ _write_marker("ticker_last_success", str(time.time()), ".hb_")def _epoch_file_age(path: Path) -> Optional[float]:@@ -1645,76 +1229,13 @@ def _epoch_file_age(path: Path) -> Optional[float]:def get_ticker_heartbeat_age() -> Optional[float]:- """Seconds since the ticker loop last iterated, or None if unknown.-- None = heartbeat file missing/unreadable (older build, never ran, or a- torn read). Callers treat None as "cannot determine", not "dead".-- Resolution uses ``_current_cron_store()`` so the heartbeat is correctly- scoped to the active profile — critical under multiplex_profiles where- ``hermes cron status`` must report per-profile liveness (#69377).- """- store = _current_cron_store()- return _epoch_file_age(store.cron_dir / "ticker_heartbeat")+ """Seconds since the ticker loop last iterated; None = missing/unreadable ("cannot determine", not "dead")."""+ return _epoch_file_age(_current_cron_store().cron_dir / "ticker_heartbeat")def get_ticker_success_age() -> Optional[float]:- """Seconds since the ticker last completed a tick WITHOUT raising, or None.-- Resolution uses ``_current_cron_store()`` so the heartbeat is correctly- scoped to the active profile — critical under multiplex_profiles where- ``hermes cron status`` must report per-profile liveness (#69377).- """- store = _current_cron_store()- return _epoch_file_age(store.cron_dir / "ticker_last_success")---def record_catch_up_occurrence() -> None:- """Increment the profile-local stale-schedule catch-up counter, best effort."""- path = _current_cron_store().cron_dir / "catch_up_occurrences"- try:- try:- value = int(path.read_text(encoding="utf-8").strip())- except (OSError, ValueError):- value = 0- _atomic_write_counter(path, max(0, value) + 1)- except Exception:- pass---def record_ticker_error(message: str) -> None:- """Persist the most recent tick failure so other processes can surface it.-- The ticker thread lives inside the gateway process; ``hermes cron- status``/``list`` run in a separate process and previously could only- infer "ticks may be failing" from marker staleness, with no clue WHY.- A root-owned ``jobs.json`` (#68483) failed every tick for ~14h with the- reason visible only in the gateway's errors.log. Writing the last error- next to the heartbeat markers gives the CLI something concrete to show.-- Best-effort: a write failure must never disrupt the tick loop.- """- store = _current_cron_store()- path = store.cron_dir / "ticker_last_error"- try:- ensure_dirs()- fd, tmp_path = tempfile.mkstemp(- dir=str(path.parent), suffix=".tmp", prefix=".terr_"- )- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(f"{time.time()}\n{message.strip()}\n")- f.flush()- os.fsync(f.fileno())- atomic_replace(tmp_path, path)- except BaseException:- try:- os.unlink(tmp_path)- except OSError:- pass- raise- except Exception:- pass+ """Seconds since the ticker last completed a tick WITHOUT raising, or None."""+ return _epoch_file_age(_current_cron_store().cron_dir / "ticker_last_success")def get_catch_up_occurrence_count() -> int:@@ -1726,6 +1247,16 @@ def get_catch_up_occurrence_count() -> int:return 0+def record_catch_up_occurrence() -> None:+ """Increment the profile-local stale-schedule catch-up counter, best effort."""+ _write_marker("catch_up_occurrences", str(get_catch_up_occurrence_count() + 1), ".count_")+++def record_ticker_error(message: str) -> None:+ """Persist the latest tick failure so `cron status` (another process) can show WHY, not just staleness."""+ _write_marker("ticker_last_error", f"{time.time()}\n{message.strip()}\n", ".terr_")++def clear_ticker_error() -> None:"""Remove the last-tick-error marker after a successful tick. Best-effort."""store = _current_cron_store()@@ -1749,19 +1280,11 @@ def get_ticker_last_error() -> Optional[str]:return message or None-# =============================================================================-# Job CRUD Operations-# =============================================================================+# --- Job CRUD Operations ---def _parse_jobs_file(jobs_file: Path) -> Tuple[Any, bool]:- """Tolerantly parse jobs.json; shared by load_jobs and the save-path peek.-- Returns ``(data, used_strict_fallback)``. utf-8-sig absorbs a Windows- BOM; a strict parse failure is retried with ``strict=False`` to survive- bare control characters in string values. IO errors from the open and- parse errors from the fallback propagate to the caller, which decides- between repair (load_jobs) and bail-out (peek).- """+ """Tolerant jobs.json parse -> ``(data, used_strict_fallback)``: utf-8-sig absorbs a BOM, strict+ failure retries with ``strict=False``. IO/fallback errors propagate (caller decides repair vs bail)."""with open(jobs_file, "r", encoding="utf-8-sig") as f:raw = f.read()try:@@ -1774,9 +1297,7 @@ def load_jobs() -> List[Dict[str, Any]]:"""Load all jobs from storage."""jobs_file = _current_cron_store().jobs_fileensure_dirs()- # Stamp BEFORE reading (fail-safe direction — see _record_load_stamp):- # a sibling write racing this load leaves the stamp older than disk, so- # the save-path merge runs instead of being wrongly skipped.+ # Stamp BEFORE reading (fail-safe, see _record_load_stamp): a racing write then forces the merge.pre_read_stamp = _jobs_file_stamp(jobs_file)if not jobs_file.exists():_record_load_stamp(None)@@ -1791,28 +1312,13 @@ def load_jobs() -> List[Dict[str, Any]]:logger.error("Failed to auto-repair jobs.json: %s", e)raise RuntimeError(f"Cron database corrupted and unrepairable: {e}") from e- # Validate the top-level JSON shape: accept a dict (expected) or a bare- # list (auto-repair). Anything else (str/number/null) is corruption that- # would otherwise raise an uncaught AttributeError on ``.get()`` and take- # down the whole cron subsystem.+ # Accept the canonical dict, or a bare list (auto-repair); any other top-level shape is corruption.+ repair = "had invalid control characters" if _strict_retry else Noneif isinstance(data, dict):jobs = data.get("jobs", [])- needs_shape_repair = Falseif isinstance(jobs, dict):- # ID-keyed map ({"jobs": {"<job_id>": {...}, ...}}) — written by- # external tools or hand edits, never by save_jobs(). The public- # load_jobs() contract and every CRUD/scheduler consumer expect a- # list; iterating the dict would yield bare id strings and blow up- # downstream (e.g. _normalize_job_record -> dict(<str>)). Flatten- # with an id-preserving merge: an inline "id" on the value wins,- # otherwise the map key is adopted as the id (external tools often- # key by id and omit the inline copy). Non-dict values are junk- # (a flattened record would not be a job) — skip them with a- # warning instead of crashing downstream.- # (_peek_jobs_unlocked() deliberately does NOT flatten —- # it returns None on a dict-shaped store so the save path never- # merges against an unrepaired baseline; the flatten lives only- # here at the load boundary.)+ # ID-keyed map from external tools: flatten (inline "id" wins, else the key), skip junk.+ # _peek_jobs_unlocked deliberately does NOT flatten, so saves never merge against it.skipped = [k for k, v in jobs.items() if not isinstance(v, dict)]if skipped:logger.warning(@@ -1821,48 +1327,25 @@ def load_jobs() -> List[Dict[str, Any]]:"y" if len(skipped) == 1 else "ies",", ".join(map(repr, skipped)),)- jobs = [- {**v, "id": v.get("id") or k}- for k, v in jobs.items()- if isinstance(v, dict)- ]- needs_shape_repair = True- if jobs and (_strict_retry or needs_shape_repair):- # Rewrite into the canonical {"jobs": [...]} form: either the parse- # hit control-character corruption (_strict_retry) or the store was- # an id-keyed map. save_jobs() re-emits the list shape every reader- # expects.- save_jobs(jobs)- if needs_shape_repair:- logger.warning("Auto-repaired jobs.json (id-keyed jobs map flattened to list)")- else:- logger.warning("Auto-repaired jobs.json (had invalid control characters)")- _record_load_stamp(pre_read_stamp)- return jobs- if isinstance(data, list):- # Bare array — likely saved/edited outside save_jobs(). Wrap it back- # into the expected {"jobs": [...]} structure.- if data:- save_jobs(data)- logger.warning("Auto-repaired jobs.json (bare list wrapped as dict)")- _record_load_stamp(pre_read_stamp)- return data-- raise RuntimeError(- f"Cron database corrupted: expected {{'jobs': [...]}}, got {type(data).__name__}"- )+ jobs = [{**v, "id": v.get("id") or k} for k, v in jobs.items() if isinstance(v, dict)]+ repair = "id-keyed jobs map flattened to list"+ elif isinstance(data, list):+ jobs = data+ repair = "bare list wrapped as dict"+ else:+ raise RuntimeError(+ f"Cron database corrupted: expected {{'jobs': [...]}}, got {type(data).__name__}"+ )+ if jobs and repair:+ save_jobs(jobs)+ logger.warning("Auto-repaired jobs.json (%s)", repair)+ _record_load_stamp(pre_read_stamp)+ return jobsdef _peek_jobs_unlocked() -> Optional[List[Dict[str, Any]]]:- """Best-effort read of on-disk jobs without repair side-effects.-- Caller must hold ``_jobs_lock()``. Returns ``[]`` when the file is- missing, ``None`` when the payload is unreadable/corrupt (caller should- not attempt a shrink-merge against an unknown baseline). Never calls- ``save_jobs`` — the repair-free property is what keeps the save path- re-entrancy-safe (a repairing read here would recurse through- ``_save_jobs_unlocked``).- """+ """Repair-free read under ``_jobs_lock()``: ``[]`` if missing, ``None`` if corrupt (never+ shrink-merge against an unknown baseline). Never saves — that would recurse."""jobs_file = _current_cron_store().jobs_fileif not jobs_file.exists():return []@@ -1879,17 +1362,8 @@ def _peek_jobs_unlocked() -> Optional[List[Dict[str, Any]]]:def _jobs_file_stamp(jobs_file: Path) -> Optional[Tuple[int, int, int]]:- """Cheap change-detection stamp for jobs.json: ``(mtime_ns, size, ino)``.-- ``None`` means the file is missing/unstatable. Used as a fast-path gate- in front of the shrink-merge so the healthy no-race save costs one- ``stat()`` instead of a full read+parse (the ``advance_next_runs``- batching exists because this path is hot — see its docstring).- ``st_ino`` is included because every legitimate writer goes through- mkstemp+rename (new inode), so even a same-size write inside one mtime- quantum on a coarse-clock filesystem (ext4 jiffies, network mounts)- cannot false-match.- """+ """Shrink-merge fast-path stamp ``(mtime_ns, size, ino)``; ``None`` if unstatable. ``st_ino`` is+ included because every writer uses mkstemp+rename, so a same-size write in one mtime quantum can't false-match."""try:st = jobs_file.stat()return (st.st_mtime_ns, st.st_size, st.st_ino)@@ -1898,73 +1372,46 @@ def _jobs_file_stamp(jobs_file: Path) -> Optional[Tuple[int, int, int]]:def _record_load_stamp(stamp: Optional[Tuple[int, int, int]]) -> None:- """Remember jobs.json's stamp for the enclosing _jobs_lock() section.-- No-op outside a critical section. Lets the save path skip the- shrink-merge parse when the file provably hasn't changed since this- section loaded it (#80703's fast-path). The caller must capture the- stamp BEFORE reading the file: a sibling landing mid-read then leaves- the recorded stamp OLDER than disk — a mismatch, so the merge runs- (fail-safe direction). Stamping after the read would let that sibling's- write be certified as "seen" without being in the loaded payload,- wrongly suppressing the recovery.- """+ """Remember jobs.json's stamp for the enclosing _jobs_lock() section (no-op outside one) so the+ save path can skip the shrink-merge when disk provably hasn't changed. Capture it BEFORE reading:+ a mid-read sibling then mismatches (fail-safe); stamping after would certify an unseen write."""if not getattr(_jobs_lock_state, "depth", 0):return_jobs_lock_state.load_stamp = stamp-def _merge_unexpected_disk_jobs(- jobs: List[Dict[str, Any]],- *,- removed_ids: Optional[Collection[str]] = None,+def _unmerged_disk_jobs(+ jobs: List[Dict[str, Any]], removed_ids: Optional[Collection[str]]) -> List[Dict[str, Any]]:- """Return *jobs* plus any on-disk jobs missing from the save payload (#80624).-- Under ``_jobs_lock()``'s degraded flock-timeout path (#60703), two- processes can both believe they own the store. A writer that loaded an- older/smaller snapshot then calls ``save_jobs`` and would otherwise- clobber concurrent creates (the filed ``no_agent`` watchdog pattern:- CLI/tool create succeeds, then a gateway tick/remove rewrites- ``jobs.json`` empty or without the new id).-- Intentional deletes pass ``removed_ids``. Any other id present on disk- but absent from *jobs* is treated as a concurrent create and merged- back before the atomic write. The caller's list is never mutated — a- new list is returned when anything was recovered.-- Fast path: when the enclosing critical section recorded a load stamp- and the file's ``(mtime_ns, size)`` still matches, nothing can have- changed underneath us, so the read+parse is skipped entirely — one- ``stat()`` on the healthy no-race save.- """+ """On-disk jobs missing from *jobs* and not intentionally removed. Stamp match => nothing landed,+ return without parsing; unreadable store => ``[]`` (never merge against an unknown baseline)."""stamp = getattr(_jobs_lock_state, "load_stamp", None)if stamp is not None and _jobs_file_stamp(_current_cron_store().jobs_file) == stamp:- return jobs-+ return []disk_jobs = _peek_jobs_unlocked()if disk_jobs is None:- return jobs-- intended_remove = {str(i) for i in (removed_ids or ()) if i}- new_ids: Set[str] = set()- for job in jobs:- if isinstance(job, dict) and job.get("id"):- new_ids.add(str(job["id"]))-+ return []+ seen = {str(j["id"]) for j in jobs if isinstance(j, dict) and j.get("id")}+ seen |= {str(i) for i in (removed_ids or ()) if i}recovered: List[Dict[str, Any]] = []for disk_job in disk_jobs:- if not isinstance(disk_job, dict):+ if not isinstance(disk_job, dict) or not disk_job.get("id"):continue- disk_id = disk_job.get("id")- if not disk_id:- continue- disk_id = str(disk_id)- if disk_id in new_ids or disk_id in intended_remove:- continue- recovered.append(disk_job)- new_ids.add(disk_id)+ disk_id = str(disk_job["id"])+ if disk_id not in seen:+ recovered.append(disk_job)+ seen.add(disk_id)+ return recovered++def _merge_unexpected_disk_jobs(+ jobs: List[Dict[str, Any]],+ *,+ removed_ids: Optional[Collection[str]] = None,+) -> List[Dict[str, Any]]:+ """*jobs* plus on-disk jobs absent from the payload (under the degraded flock-timeout path a stale+ writer would otherwise clobber concurrent creates). Deletes pass ``removed_ids``; never mutates *jobs*."""+ recovered = _unmerged_disk_jobs(jobs, removed_ids)if not recovered:return jobslogger.warning(@@ -1977,26 +1424,48 @@ def _merge_unexpected_disk_jobs(return jobs + recovered+def _unlink_quiet(path: Optional[str]) -> None:+ if path is None:+ return+ try:+ os.unlink(path)+ except OSError:+ pass+++def _stage_jobs_payload(jobs_file: Path, jobs: List[Dict[str, Any]]) -> str:+ """Serialize the store payload to a fsynced temp file next to *jobs_file*; return its path."""+ fd, tmp_path = tempfile.mkstemp(dir=str(jobs_file.parent), suffix=".tmp", prefix=".jobs_")+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as f:+ json.dump(+ {"jobs": jobs, "updated_at": _hermes_now().isoformat()},+ f,+ indent=2,+ ensure_ascii=False,+ )+ f.flush()+ os.fsync(f.fileno())+ except BaseException:+ _unlink_quiet(tmp_path)+ raise+ return tmp_path+++_SAVE_JOBS_MERGE_ATTEMPTS = 5++def _save_jobs_unlocked(jobs: List[Dict[str, Any]],*,removed_ids: Optional[Collection[str]] = None,replace: bool = False,):- """Save all jobs to storage. Caller must hold _jobs_lock().-- ``removed_ids`` lists job ids this mutation intentionally deleted.- ``replace=True`` skips the shrink-merge guard (tests / disaster recovery- that mean to rewrite the store wholesale).- """+ """Save all jobs; caller must hold _jobs_lock(). ``removed_ids`` = intentional deletes;+ ``replace=True`` skips the shrink-merge guard (wholesale rewrite for tests/disaster recovery)."""jobs_file = _current_cron_store().jobs_fileensure_dirs()- # Snapshot the current owner BEFORE the atomic replace so a privileged- # writer (root CLI in Docker) can hand ownership back to the gateway user- # afterwards instead of locking its ticker out (#68483). When the file is- # being created for the first time, inherit the cron dir's owner — in the- # Docker image that is the PUID/PGID gateway user who must be able to- # read the store on the next tick.+ # Owner snapshot BEFORE replace so a root writer can hand the file back to the gateway user.try:_stat_before = os.stat(jobs_file)except OSError:@@ -2005,141 +1474,76 @@ def _save_jobs_unlocked(except OSError:_stat_before = None- # Shrink-merge + rewrite loop (#80624): under the degraded flock-timeout- # path another process can create a job between our load and our write.- # Merge unexpected disk ids into the payload, stage the write, then- # re-peek; if new ids appeared, merge again and restage before replace.- # The merge itself fast-paths to a single stat() when the enclosing- # section's load stamp still matches (see _merge_unexpected_disk_jobs).+ # Shrink-merge loop: merge, stage, re-peek, repeat; the last attempt writes without a re-peek.tmp_path = Nonetry:- for _attempt in range(5):+ for attempt in range(_SAVE_JOBS_MERGE_ATTEMPTS + 1):if not replace:jobs = _merge_unexpected_disk_jobs(jobs, removed_ids=removed_ids)- fd, tmp_path = tempfile.mkstemp(- dir=str(jobs_file.parent), suffix=".tmp", prefix=".jobs_"- )- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- json.dump(- {"jobs": jobs, "updated_at": _hermes_now().isoformat()},- f,- indent=2,- ensure_ascii=False,- )- f.flush()- os.fsync(f.fileno())- except BaseException:- try:- os.unlink(tmp_path)- except OSError:- pass+ tmp_path = _stage_jobs_payload(jobs_file, jobs)+ # Verify-after-stage: a sibling landing during serialization forces another merge round.+ if (+ not replace+ and attempt < _SAVE_JOBS_MERGE_ATTEMPTS+ and _unmerged_disk_jobs(jobs, removed_ids)+ ):+ _unlink_quiet(tmp_path)tmp_path = None- raise-- if not replace:- # Verify-after-stage: a sibling landing while we serialized- # the payload must trigger another merge round. Same stamp- # fast path as the merge — an unchanged stamp proves nothing- # was written, so the full parse is skipped.- _stamp = getattr(_jobs_lock_state, "load_stamp", None)- _unchanged = (- _stamp is not None and _jobs_file_stamp(jobs_file) == _stamp- )- disk_jobs = None if _unchanged else _peek_jobs_unlocked()- if disk_jobs is not None:- payload_ids = {- str(j["id"])- for j in jobs- if isinstance(j, dict) and j.get("id")- }- intended = {str(i) for i in (removed_ids or ()) if i}- if any(- isinstance(dj, dict)- and dj.get("id")- and str(dj["id"]) not in payload_ids- and str(dj["id"]) not in intended- for dj in disk_jobs- ):- try:- os.unlink(tmp_path)- except OSError:- pass- tmp_path = None- continue-+ continueatomic_replace(tmp_path, jobs_file)tmp_path = None_secure_file(jobs_file)_preserve_file_ownership(jobs_file, _stat_before)- # Invalidate (never refresh) the stamp after writing: the stamp- # certifies "this section's loaded payload still matches disk",- # which stops being provable the moment anyone writes. A refresh- # here would let a nested save (e.g. create_job inside a broader- # section) certify disk against an OUTER caller's stale payload- # and deterministically clobber the nested create; it also races- # a degraded sibling landing between replace and stat. Later- # saves in this section simply take the full merge (fail-safe).+ # Invalidate (never refresh) the stamp: a refresh would let a nested save certify disk+ # against an OUTER caller's stale payload. Later saves take the full merge (fail-safe)._record_load_stamp(None)return-- # Exhausted retries — last merge + write without another re-peek.- if not replace:- jobs = _merge_unexpected_disk_jobs(jobs, removed_ids=removed_ids)- fd, tmp_path = tempfile.mkstemp(- dir=str(jobs_file.parent), suffix=".tmp", prefix=".jobs_"- )- with os.fdopen(fd, "w", encoding="utf-8") as f:- json.dump(- {"jobs": jobs, "updated_at": _hermes_now().isoformat()},- f,- indent=2,- ensure_ascii=False,- )- f.flush()- os.fsync(f.fileno())- atomic_replace(tmp_path, jobs_file)- tmp_path = None- _secure_file(jobs_file)- _preserve_file_ownership(jobs_file, _stat_before)except BaseException:- if tmp_path is not None:- try:- os.unlink(tmp_path)- except OSError:- pass+ _unlink_quiet(tmp_path)raise--def save_jobs(jobs: List[Dict[str, Any]],*,removed_ids: Optional[Collection[str]] = None,replace: bool = False,):- """Save all jobs to storage.-- See ``_save_jobs_unlocked`` for ``removed_ids`` / ``replace`` semantics- (shrink-merge guard against concurrent-create clobber, #80624).- """+ """Save all jobs under the lock; see ``_save_jobs_unlocked`` for ``removed_ids``/``replace``."""with _jobs_lock():_save_jobs_unlocked(jobs, removed_ids=removed_ids, replace=replace)+_MISSING = object()+++def _with_job(job_id: Any, fn: Callable[[List[Dict[str, Any]], int, Dict[str, Any]], Any], missing: Any = None) -> Any:+ """Run ``fn(jobs, i, job)`` on the first match under ``_jobs_lock()``; ``fn`` saves. *missing* if none."""+ with _jobs_lock():+ jobs = load_jobs()+ for i, job in enumerate(jobs):+ if job.get("id") == job_id:+ return fn(jobs, i, job)+ return missing+++def _complete_job_record(job: Dict[str, Any]) -> None:+ """Retire *job* in place as a terminal completion (record kept for `cronjob list`)."""+ job["enabled"] = False+ job["state"] = "completed"+ job["next_run_at"] = None+++def _activate_job_record(job: Dict[str, Any]) -> None:+ """Clear pause markers in place so *job* is runnable again."""+ job["enabled"] = True+ job["state"] = "scheduled"+ job["paused_at"] = None+ job["paused_reason"] = None++def _normalize_workdir(workdir: Optional[str]) -> Optional[str]:- """Normalize and validate a cron job workdir.-- Rules:- - Empty / None → None (feature off, preserves old behaviour).- - ``~`` is expanded. Relative paths are rejected — cron jobs run detached- from any shell cwd, so relative paths have no stable meaning.- - The path must exist and be a directory at create/update time. We do- NOT re-check at run time (a user might briefly unmount the dir; the- scheduler will just fall back to old behaviour with a logged warning).-- Returns the absolute path string, or None when disabled.- Raises ValueError on invalid input.- """+ """Workdir -> absolute path, or None when empty. ``~`` expands; relative paths are rejected+ (cron runs detached from any cwd); must be an existing dir now but is deliberately NOT+ re-checked at run time (scheduler falls back with a warning). ValueError when invalid."""if workdir is None:return Noneraw = str(workdir).strip()@@ -2160,17 +1564,8 @@ def _normalize_workdir(workdir: Optional[str]) -> Optional[str]:def _resolve_default_model_snapshot() -> Optional[str]:- """Resolve the global default model the same way the cron ticker does.-- Mirrors the unpinned-model resolution in ``cron/scheduler.py`` ``run_job``:- read ``config.yaml`` ``model.default`` (or the ``model`` alias / bare string- form), applying the managed-scope overlay and env expansion. Used by- ``create_job`` to snapshot the default model for unpinned jobs so a later- swap of the global default is detected at fire time (#44585).-- Returns the resolved model string, or ``None`` if config is missing/empty- or resolution fails (fail-open — caller treats ``None`` as "no snapshot").- """+ """Default model resolved as the ticker's ``run_job`` does, so unpinned jobs can snapshot it and+ detect a later swap. ``None`` on missing config or failure (fail-open: "no snapshot")."""try:from hermes_cli.config import _expand_env_vars, read_user_config_raw@@ -2184,8 +1579,6 @@ def _resolve_default_model_snapshot() -> Optional[str]:except Exception:passcfg = _expand_env_vars(cfg)- # Mirror run_job's precedence: the explicit cron-fleet default- # (cron.model) beats the global chat model for unpinned cron jobs.cron_cfg = cfg.get("cron") or {}if isinstance(cron_cfg, dict):cron_model = cron_cfg.get("model")@@ -2212,21 +1605,56 @@ def _normalize_job_optional_text(value: Any, *, strip_trailing_slash: bool = Falreturn text or None+def _normalize_base_url(value: Any) -> Optional[str]:+ return _normalize_job_optional_text(value, strip_trailing_slash=True)+++def _normalize_str_list(items: Any) -> Optional[List[str]]:+ """Non-blank stripped items of *items*, or None when nothing remains."""+ return [str(j).strip() for j in items if str(j).strip()] or None+++def _normalize_context_from(value: Any) -> Optional[List[str]]:+ """Accept a job id or a list of ids; anything else is None."""+ if isinstance(value, str):+ return _normalize_str_list([value])+ return _normalize_str_list(value) if isinstance(value, list) else None+++def _normalize_failure_deliver(value: Any) -> Optional[str]:+ """failure_deliver shares deliver's value grammar; flatten str/list like the tool layer's+ _normalize_deliver_param for direct create_job callers. Semantic validation happens at+ resolution time via the shared deliver path (NS-788)."""+ if isinstance(value, (list, tuple)):+ return ",".join(str(p).strip() for p in value if str(p).strip()) or None+ return _normalize_job_optional_text(value)+++# Normalizers for create_job (all fields) / update_job (present fields). Invalid values raise BEFORE storing.+_CREATE_FIELD_NORMALIZERS: Dict[str, Callable[[Any], Any]] = {+ "model": _normalize_job_optional_text,+ "provider": _normalize_job_optional_text,+ "base_url": _normalize_base_url,+ "script": _normalize_job_optional_text,+ "monitor_script": _normalize_job_optional_text,+ "monitor_url": _normalize_job_optional_text,+ "enabled_toolsets": lambda v: _normalize_str_list(v) if v else None,+ "workdir": _normalize_workdir,+ "no_agent": bool,+ "context_from": _normalize_context_from,+ "failure_deliver": _normalize_failure_deliver,+}+_UPDATE_FIELD_NORMALIZERS: Dict[str, Callable[[Any], Any]] = {+ "workdir": lambda v: None if v in {None, "", False} else _normalize_workdir(v),+ "monitor_script": _normalize_job_optional_text,+ "monitor_url": _normalize_job_optional_text,+}++def _normalize_reasoning_effort(value: Any) -> Optional[str]:- """Validate a per-job reasoning effort against the canonical grammar.-- Spelling-only validation at the storage choke point: the SAME parser- every other effort surface uses (``hermes_constants.parse_reasoning_effort``)- decides validity, so the cron knob can never be stricter or looser than- its config.yaml sibling. Capability (whether the resolved model supports- the level) is intentionally NOT checked here — the model is not knowable- at create time (unpinned jobs, auth fallback), and the provider- transports already clamp/omit at send time.-- Returns None for unset (None/empty string), the normalized lowercase- level for valid input, and raises ValueError otherwise so nothing- invalid ever persists for a fire-and-forget job.- """+ """Spelling-only validation via the shared parser (cron knob never stricter/looser than+ config.yaml); model capability is deliberately NOT checked (model unknowable at create time,+ transports clamp at send time). None for unset, lowercase level, or ValueError."""if value is None:return Nonetext = str(value).strip().lower()@@ -2240,8 +1668,6 @@ def _normalize_reasoning_effort(value: Any) -> Optional[str]:"none, minimal, low, medium, high, xhigh, max, ultra ""(empty string clears the override).")- # parse_reasoning_effort accepts disable aliases ("false", "disabled");- # store the canonical spelling so the record reads unambiguously.if text in {"false", "disabled"}:return "none"return text@@ -2254,19 +1680,11 @@ def _compute_provider_model_snapshots(base_url: Any,no_agent: Any,) -> Tuple[Optional[str], Optional[str]]:- """Snapshot unpinned inference axes for the provider/model drift guard.-- Agent cron jobs with unpinned provider/model follow global config at fire- time. Capture the current resolution for each unpinned axis so a later- global switch fails closed instead of silently changing spend. Pinned axes- and no-agent script jobs intentionally carry no snapshot.- """+ """Snapshot unpinned provider/model resolution so a later global switch fails closed at fire+ time instead of silently changing spend. Pinned axes and no-agent jobs carry no snapshot."""normalized_provider = _normalize_job_optional_text(provider)normalized_model = _normalize_job_optional_text(model)- normalized_base_url = _normalize_job_optional_text(- base_url,- strip_trailing_slash=True,- )+ normalized_base_url = _normalize_base_url(base_url)if bool(no_agent):return None, None@@ -2297,7 +1715,7 @@ def _normalized_inference_axes(job: Dict[str, Any]) -> Tuple[Optional[str], Optireturn (_normalize_job_optional_text(job.get("provider")),_normalize_job_optional_text(job.get("model")),- _normalize_job_optional_text(job.get("base_url"), strip_trailing_slash=True),+ _normalize_base_url(job.get("base_url")),bool(job.get("no_agent")),)@@ -2308,12 +1726,7 @@ def _validate_job_mode_invariants(no_agent: bool,script: Optional[str],) -> None:- """Shared create/update validation for job execution-mode invariants.-- ONE owner for the class: create_job and update_job both call this so an- invariant enforced at create time cannot be violated through the update- door (monitor jobs silently degrading when no_agent is flipped on, etc.).- """+ """Execution-mode invariants shared by create_job and update_job (no bypass via the update door)."""if monitor_script and monitor_url:raise ValueError("monitor_script and monitor_url are mutually exclusive — a job "@@ -2329,6 +1742,13 @@ def _validate_job_mode_invariants(raise ValueError(NO_AGENT_WITHOUT_SCRIPT_ERROR)+def _oneshot_past_grace_error(run_at: Any) -> ValueError:+ return ValueError(+ f"Requested one-shot time {run_at} is more than "+ f"{ONESHOT_GRACE_SECONDS}s in the past and cannot be scheduled."+ )++def create_job(prompt: Optional[str],schedule: str,@@ -2352,165 +1772,59 @@ def create_job(reasoning_effort: Optional[str] = None,failure_deliver: Optional[str] = None,) -> Dict[str, Any]:- """- Create a new cron job.-- Args:- prompt: The prompt to run (must be self-contained, or a task instruction when skill is set).- Ignored when ``no_agent=True`` except as an optional name hint.- schedule: Schedule string (see parse_schedule)- name: Optional friendly name- repeat: How many times to run (None = forever, 1 = once)- deliver: Where to deliver output ("origin", "local", "telegram", etc.)- origin: Source info where job was created (for "origin" delivery)- skill: Optional legacy single skill name to load before running the prompt- skills: Optional ordered list of skills to load before running the prompt- model: Optional per-job model override- provider: Optional per-job provider override- base_url: Optional per-job base URL override- script: Optional path to a script whose stdout feeds the job. With- ``no_agent=True`` the script IS the job — its stdout is- delivered verbatim. Without ``no_agent``, its stdout is- injected into the agent's prompt as context (data-collection /- change-detection pattern). Paths resolve under- ~/.hermes/scripts/; ``.sh`` / ``.bash`` files run via bash,- anything else via Python.- context_from: Optional job ID (or list of job IDs) whose most recent output- is injected into the prompt as context before each run.- Useful for chaining cron jobs: job A finds data, job B processes it.- enabled_toolsets: Optional list of toolset names to restrict the agent to.- When set, only tools from these toolsets are loaded, reducing- token overhead. When omitted, all default tools are loaded.- Ignored when ``no_agent=True``.- workdir: Optional absolute path. When set, the job runs as if launched- from that directory: AGENTS.md / CLAUDE.md / .cursorrules from- that directory are injected into the system prompt, and the- terminal/file/code_exec tools use it as their working directory- (via TERMINAL_CWD). When unset, the old behaviour is preserved- (no context files injected, tools use the scheduler's cwd).- With ``no_agent=True``, ``workdir`` is still applied as the- script's cwd so relative paths inside the script behave- predictably.- no_agent: When True, skip the agent entirely — run ``script`` on schedule- and deliver its stdout directly. Empty stdout = silent (no- delivery). Requires ``script`` to be set. Ideal for classic- watchdogs and periodic alerts that don't need LLM reasoning.- monitor_script: Optional path to a cheap monitor source script (same- resolution/containment rules as ``script``: relative to- ~/.hermes/scripts/, .sh/.bash via bash, else Python). Each- tick the script runs FIRST and its output is hashed as exact- bytes: unchanged output suppresses the agent run entirely- (recorded as a silent 'no_change' tick); changed output- injects a MONITOR CHANGE DETECTED block (unified diff + new- output) into the prompt before a normal agent run. Scripts- should emit stable output (no timestamps). Mutually exclusive- with ``monitor_url``; incompatible with ``no_agent=True``.- monitor_url: Optional http(s) URL used as the monitor source instead- of a script — fetched with a bounded GET each tick. Same- hash-suppression semantics as ``monitor_script``.- reasoning_effort: Optional per-job reasoning effort pin. One of the- canonical Hermes levels (none|minimal|low|medium|high|xhigh|- max|ultra, case-insensitive). When set, it wins over BOTH the- global ``agent.reasoning_effort`` and per-model- ``agent.reasoning_overrides`` at fire time. Capability is NOT- validated here: levels above what the resolved model supports- are clamped or omitted by the provider transport at send time,- exactly like config-set effort. Inert with ``no_agent=True``- (no LLM call to configure). None/empty = unset (job follows- config resolution, pre-existing behavior).-- Returns:- The created job dict+ """Create a new cron job and return the stored record.++ prompt: self-contained prompt (or task instruction when skills are set); with ``no_agent`` only+ a name hint. deliver: defaults to "origin" when ``origin`` is given, else "local". repeat: None =+ forever. skill/skills: legacy single / ordered list loaded before the prompt. script: stdout is+ injected as prompt context, or with ``no_agent=True`` IS the job (stdout delivered verbatim;+ empty = silent; requires ``script``); relative paths resolve under ~/.hermes/scripts/,+ .sh/.bash run via bash else Python. context_from: job id(s) whose latest output is injected+ (chaining). enabled_toolsets: restrict the agent (ignored with ``no_agent``). workdir: absolute+ cwd for tools/scripts; AGENTS.md/CLAUDE.md/.cursorrules injected; unset = legacy behaviour.+ monitor_script/monitor_url: cheap monitor source run FIRST each tick; output hashed as exact+ bytes — unchanged suppresses the agent run, changed injects a MONITOR CHANGE DETECTED block+ (diff + new output); mutually exclusive, incompatible with ``no_agent``. reasoning_effort:+ per-job pin (canonical levels, case-insensitive) that wins over global/per-model config;+ capability is NOT validated (provider transport clamps at send time); inert with ``no_agent``."""parsed_schedule = parse_schedule(schedule)- # Normalize repeat: treat 0 or negative values as None (infinite).- # String forms ('forever'/'once'/numeric) coerce via- # normalize_repeat_value — the shared chokepoint with update paths- # (#66824/#64520/#7142/#71987/#95706).repeat = normalize_repeat_value(repeat)-- # Auto-set repeat=1 for one-shot schedules if not specifiedif parsed_schedule["kind"] == "once" and repeat is None:repeat = 1-- # Default delivery to origin if available, otherwise localif deliver is None:deliver = "origin" if origin else "local"job_id = uuid.uuid4().hex[:12]now = _hermes_now().isoformat()+ raw = locals()+ f = {key: norm(raw[key]) for key, norm in _CREATE_FIELD_NORMALIZERS.items()}normalized_skills = _normalize_skill_list(skill, skills)- normalized_model = _normalize_job_optional_text(model)- normalized_provider = _normalize_job_optional_text(provider)- normalized_base_url = _normalize_job_optional_text(base_url, strip_trailing_slash=True)- normalized_script = str(script).strip() if isinstance(script, str) else None- normalized_script = normalized_script or None- normalized_toolsets = [str(t).strip() for t in enabled_toolsets if str(t).strip()] if enabled_toolsets else None- normalized_toolsets = normalized_toolsets or None- normalized_workdir = _normalize_workdir(workdir)- normalized_no_agent = bool(no_agent)normalized_attach = attach_to_session if isinstance(attach_to_session, bool) else Nonenormalized_reasoning_effort = _normalize_reasoning_effort(reasoning_effort)- # failure_deliver shares deliver's value grammar; the str/list- # flatten below mirrors the tool layer's _normalize_deliver_param for- # direct create_job callers (the tool pre-normalizes). Semantic- # validation happens at resolution time via the shared deliver path.- normalized_failure_deliver = (- str(failure_deliver).strip() if isinstance(failure_deliver, str) else None- )- if isinstance(failure_deliver, (list, tuple)):- normalized_failure_deliver = ",".join(- str(p).strip() for p in failure_deliver if str(p).strip()- )- normalized_failure_deliver = normalized_failure_deliver or None- normalized_monitor_script = str(monitor_script).strip() if isinstance(monitor_script, str) else None- normalized_monitor_script = normalized_monitor_script or None- normalized_monitor_url = str(monitor_url).strip() if isinstance(monitor_url, str) else None- normalized_monitor_url = normalized_monitor_url or None-- # Monitor-mode validation: exactly one source, and monitor mode only- # makes sense when there IS an agent to suppress/wake.- # no_agent jobs are meaningless without a script — the script IS the job.- # Surface these as clear ValueErrors at create time so bad configs never- # reach the scheduler (shared with update_job, see- # _validate_job_mode_invariants).- _validate_job_mode_invariants(- normalized_monitor_script,- normalized_monitor_url,- normalized_no_agent,- normalized_script,- )- # Normalize context_from: accept str or list of str, store as list or None- if isinstance(context_from, str):- context_from = [context_from.strip()] if context_from.strip() else None- elif isinstance(context_from, list):- context_from = [str(j).strip() for j in context_from if str(j).strip()] or None- else:- context_from = None+ _validate_job_mode_invariants(f["monitor_script"], f["monitor_url"], f["no_agent"], f["script"])prompt_text = _coerce_job_text(prompt).strip()-- if not prompt_text and not normalized_script and not normalized_skills:+ if not prompt_text and not f["script"] and not normalized_skills:raise ValueError(EMPTY_PAYLOAD_ERROR)- # Reject cron jobs that schedule gateway-lifecycle commands. Prevents- # agent-driven SIGTERM-respawn loops under launchd/systemd KeepAlive- # (#30719). Enforced here (not only in the CLI layer) so the agent's- # `cronjob` model tool — which calls create_job directly — is also- # covered, not just `hermes cron create`.+ # Reject gateway-lifecycle commands (respawn loops) here, not just the CLI, to cover the cronjob tool.from cron.lifecycle_guard import check_gateway_lifecycle- check_gateway_lifecycle(prompt_text, normalized_script)+ check_gateway_lifecycle(prompt_text, f["script"])- label_source = (prompt_text or (normalized_skills[0] if normalized_skills else None) or (normalized_script if normalized_no_agent else None)) or "cron job"+ label_source = (+ prompt_text+ or (normalized_skills[0] if normalized_skills else None)+ or (f["script"] if f["no_agent"] else None)+ or "cron job"+ )+ name = name or label_source[:50].strip()provider_snapshot, model_snapshot = _compute_provider_model_snapshots(- provider=normalized_provider,- model=normalized_model,- base_url=normalized_base_url,- no_agent=normalized_no_agent,+ provider=f["provider"], model=f["model"], base_url=f["base_url"], no_agent=f["no_agent"])next_run_at = compute_next_run(parsed_schedule)@@ -2518,43 +1832,30 @@ def create_job(run_at = parsed_schedule.get("run_at") or schedulelogger.warning("Rejecting one-shot cron job '%s': run_at %s is outside the %ss grace window",- name or label_source[:50].strip(),- run_at,- ONESHOT_GRACE_SECONDS,- )- raise ValueError(- f"Requested one-shot time {run_at} is more than "- f"{ONESHOT_GRACE_SECONDS}s in the past and cannot be scheduled."+ name, run_at, ONESHOT_GRACE_SECONDS,)+ raise _oneshot_past_grace_error(run_at)job = {"id": job_id,- "name": name or label_source[:50].strip(),+ "name": name,"prompt": prompt_text,"skills": normalized_skills,"skill": normalized_skills[0] if normalized_skills else None,- "model": normalized_model,- "provider": normalized_provider,- # Provider/model resolution captured at creation for unpinned jobs- # (#44585). None for pinned axes, no_agent jobs, resolution failures, and- # any pre-existing job written before these fields existed (back-compat).+ "model": f["model"],+ "provider": f["provider"],"provider_snapshot": provider_snapshot,"model_snapshot": model_snapshot,- "base_url": normalized_base_url,- "script": normalized_script,- "no_agent": normalized_no_agent,- "monitor_script": normalized_monitor_script,- "monitor_url": normalized_monitor_url,- # Hash-suppression state for monitor jobs: {"last_output_hash": ...,- # "last_changed_at": ...}. None until the first monitor tick.+ "base_url": f["base_url"],+ "script": f["script"],+ "no_agent": f["no_agent"],+ "monitor_script": f["monitor_script"],+ "monitor_url": f["monitor_url"],"monitor_state": None,- "context_from": context_from,+ "context_from": f["context_from"],"schedule": parsed_schedule,"schedule_display": parsed_schedule.get("display", schedule),- "repeat": {- "times": repeat, # None = forever- "completed": 0- },+ "repeat": {"times": repeat, "completed": 0}, # times None = forever"enabled": True,"state": "scheduled","paused_at": None,@@ -2565,45 +1866,32 @@ def create_job("last_status": None,"last_error": None,"last_delivery_error": None,- # Live-adapter targets whose last send was acked with no message_id /- # raw_response (accepted, but UNVERIFIED — surfaced by cron list/doctor).+ # Targets acked without message_id/raw_response (accepted but UNVERIFIED)."last_delivery_unverified": None,"failure_streak": 0,- # Delivery configuration"deliver": deliver,"origin": origin, # Tracks where job was created for "origin" delivery- "enabled_toolsets": normalized_toolsets,- "workdir": normalized_workdir,+ "enabled_toolsets": f["enabled_toolsets"],+ "workdir": f["workdir"],}- # Only persist attach_to_session when explicitly set, so existing jobs and- # the common case stay byte-identical (absent key => fall back to the- # global cron.mirror_delivery config, default off).+ # Persist only when explicitly set; absent key => fall back to global config resolution.if normalized_attach is not None:job["attach_to_session"] = normalized_attach- # Same conditional-persist rule for the per-job reasoning effort pin:- # absent key = job follows config resolution (pre-feature behavior).if normalized_reasoning_effort is not None:job["reasoning_effort"] = normalized_reasoning_effort- # Conditional-persist for failure_deliver too: absent key = failures- # follow deliver, byte-identical to pre-feature jobs (NS-788).- if normalized_failure_deliver is not None:- job["failure_deliver"] = normalized_failure_deliver+ # failure_deliver too: absent key = failures follow deliver, byte-identical to pre-feature jobs.+ if f["failure_deliver"] is not None:+ job["failure_deliver"] = f["failure_deliver"]with _jobs_lock():- jobs = load_jobs()- jobs.append(job)- save_jobs(jobs)-+ save_jobs(load_jobs() + [job])return jobdef get_job(job_id: str) -> Optional[Dict[str, Any]]:"""Get a job by ID."""- jobs = load_jobs()- for job in jobs:- if job["id"] == job_id:- return _normalize_job_record(job)- return None+ job = next((j for j in load_jobs() if j["id"] == job_id), None)+ return _normalize_job_record(job) if job is not None else Noneclass AmbiguousJobReference(LookupError):@@ -2620,13 +1908,8 @@ class AmbiguousJobReference(LookupError):def resolve_job_ref(ref: str) -> Optional[Dict[str, Any]]:- """Resolve a job reference (ID or name) to a job record.-- - Exact ID match wins (works even if a different job's name equals this ID).- - Otherwise, case-insensitive name match.- - If a name matches more than one job, raises AmbiguousJobReference so the- caller can surface the matching IDs rather than silently picking one.- """+ """Resolve an ID or name to a job record. Exact ID wins, then case-insensitive name; an+ ambiguous name raises AmbiguousJobReference rather than silently picking one."""if not ref:return Nonejobs = load_jobs()@@ -2660,190 +1943,124 @@ def list_jobs(include_disabled: bool = False) -> List[Dict[str, Any]]:return jobs+def _reject_terminal_activation(job: Dict[str, Any], updated: Dict[str, Any], job_id: str) -> None:+ """A genuinely terminal job cannot be reactivated through update_job (use cron resume)."""+ if (+ is_terminal_job(job)+ and not _is_recoverable_error_job(job)+ and (+ updated.get("state") not in {"completed", "error"}+ or updated.get("enabled") is True+ or updated.get("next_run_at") is not None+ )+ ):+ raise ValueError(+ f"Cannot activate terminal cron job '{job.get('name', job_id)}' "+ "through update_job; use cron resume --run-now or --at."+ )+++def _normalize_job_updates(job: Dict[str, Any], updates: Dict[str, Any]) -> None:+ """Normalize updates in place like create_job; invalid values raise BEFORE the merge. ``repeat``+ accepts the stored dict or a bare value (coerced, completed counter preserved)."""+ for key, norm in _UPDATE_FIELD_NORMALIZERS.items():+ if key in updates:+ updates[key] = norm(updates[key])+ if "reasoning_effort" in updates:+ updates["reasoning_effort"] = _normalize_reasoning_effort(updates["reasoning_effort"])+ if "repeat" in updates:+ _rp = updates["repeat"]+ completed = (job.get("repeat") or {}).get("completed", 0)+ if isinstance(_rp, dict):+ _rp = dict(_rp)+ _rp["times"] = normalize_repeat_value(_rp.get("times"))+ _rp.setdefault("completed", completed)+ updates["repeat"] = _rp+ else:+ updates["repeat"] = {"times": normalize_repeat_value(_rp), "completed": completed}++def update_job(job_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]:"""Update a job by ID, refreshing derived schedule fields when needed."""- # Block mutation of immutable fields. ``id`` in particular is a filesystem- # path component under OUTPUT_DIR — letting an update change it leaks- # path-escape values into output writes/deletes.+ # ``id`` is a path component under OUTPUT_DIR — changing it would leak path-escape values.bad_fields = _IMMUTABLE_JOB_FIELDS.intersection(updates or {})if bad_fields:raise ValueError(f"Cron job field(s) cannot be updated: {', '.join(sorted(bad_fields))}")- with _jobs_lock():- jobs = load_jobs()- for i, job in enumerate(jobs):- if job["id"] != job_id:- continue-- # Validate / normalize workdir if present in updates. Empty string- # or None both mean "clear the field" (restore old behaviour).- if "workdir" in updates:- _wd = updates["workdir"]- if _wd in {None, "", False}:- updates["workdir"] = None- else:- updates["workdir"] = _normalize_workdir(_wd)-- # Normalize monitor fields the same way create_job does (empty- # string clears the field).- for _mon_field in ("monitor_script", "monitor_url"):- if _mon_field in updates:- _mv = updates[_mon_field]- _mv = str(_mv).strip() if isinstance(_mv, str) else None- updates[_mon_field] = _mv or None-- # Validate/normalize the per-job reasoning effort pin the same- # way create_job does: canonical grammar only, empty string (or- # None) clears. Invalid values raise BEFORE the merge so the- # stored value stays untouched.- if "reasoning_effort" in updates:- updates["reasoning_effort"] = _normalize_reasoning_effort(- updates["reasoning_effort"]- )-- # Normalize repeat the same way create_job does. Callers pass- # either the stored dict shape ({"times": N, "completed": M}) or- # a bare value ("forever", "once", 3, "3"); bare values coerce- # through normalize_repeat_value and preserve the completed- # counter. A raw string stored here previously broke- # mark_job_run ('str' has no .get) and repeat accounting.- if "repeat" in updates:- _rp = updates["repeat"]- if isinstance(_rp, dict):- _rp = dict(_rp)- _rp["times"] = normalize_repeat_value(_rp.get("times"))- _rp.setdefault("completed", (job.get("repeat") or {}).get("completed", 0))- updates["repeat"] = _rp- else:- updates["repeat"] = {- "times": normalize_repeat_value(_rp),- "completed": (job.get("repeat") or {}).get("completed", 0),- }+ def apply(jobs, i, job):+ _normalize_job_updates(job, updates)+ previous_inference_axes = _normalized_inference_axes(job)+ updated = _apply_skill_fields({**job, **updates})+ _reject_terminal_activation(job, updated, job_id)++ # Re-check on the MERGED record; scoped to changed fields so legacy records keep loading.+ if {"monitor_script", "monitor_url", "no_agent", "script"}.intersection(updates):+ _validate_job_mode_invariants(+ updated.get("monitor_script") or None,+ updated.get("monitor_url") or None,+ bool(updated.get("no_agent")),+ _normalize_job_optional_text(updated.get("script")),+ )- previous_inference_axes = _normalized_inference_axes(job)- updated = _apply_skill_fields({**job, **updates})+ if any(k in updates for k in _PAYLOAD_FIELDS) and job_payload_is_empty(updated):+ raise ValueError(EMPTY_PAYLOAD_ERROR)+ inference_fields_changed = bool(+ {"provider", "model", "base_url", "no_agent"}.intersection(updates)+ ) and _normalized_inference_axes(updated) != previous_inference_axes++ if "schedule" in updates:+ updated_schedule = updated["schedule"]+ if isinstance(updated_schedule, str):+ updated_schedule = parse_schedule(updated_schedule)+ updated["schedule"] = updated_schedule+ updated["schedule_display"] = updates.get(+ "schedule_display",+ updated_schedule.get("display", updated.get("schedule_display")),+ )+ if updated.get("state") != "paused":+ updated_next_run = compute_next_run(updated_schedule)+ # Same guard as create_job: otherwise a ghost job (next_run_at=None) never fires.+ if updated_next_run is None and updated_schedule.get("kind") == "once":+ run_at = updated_schedule.get("run_at") or updated_schedule+ logger.warning(+ "Rejecting one-shot cron job update '%s': run_at %s "+ "is outside the %ss grace window",+ updated.get("name", job_id),+ run_at,+ ONESHOT_GRACE_SECONDS,+ )+ raise _oneshot_past_grace_error(run_at)+ updated["next_run_at"] = updated_next_run++ if inference_fields_changed:+ provider_snapshot, model_snapshot = _compute_provider_model_snapshots(+ provider=updated.get("provider"),+ model=updated.get("model"),+ base_url=updated.get("base_url"),+ no_agent=updated.get("no_agent"),+ )+ updated["provider_snapshot"] = provider_snapshot+ updated["model_snapshot"] = model_snapshot- if (- is_terminal_job(job)- and not _is_recoverable_error_job(job)- and (- updated.get("state") not in {"completed", "error"}- or updated.get("enabled") is True- or updated.get("next_run_at") is not None- )- ):+ if updated.get("enabled", True) and updated.get("state") != "paused" and not updated.get("next_run_at"):+ next_run = compute_next_run(updated["schedule"])+ if next_run is None and updated["schedule"].get("kind") == "once":+ run_at = updated["schedule"].get("run_at", "unknown")raise ValueError(- f"Cannot activate terminal cron job '{job.get('name', job_id)}' "- "through update_job; use cron resume --run-now or --at."- )-- # Re-check execution-mode invariants on the MERGED record when- # any participating field changes, so create-time invariants- # can't be violated through the update door (e.g. flipping- # no_agent=True on a monitor job would silently disable the- # monitor: the scheduler's no_agent short-circuit runs before- # the monitor gate). Scoped to changed fields so legacy records- # untouched by this update keep loading.- if {"monitor_script", "monitor_url", "no_agent", "script"}.intersection(updates):- _upd_script = updated.get("script")- _upd_script = str(_upd_script).strip() if isinstance(_upd_script, str) else None- _validate_job_mode_invariants(- updated.get("monitor_script") or None,- updated.get("monitor_url") or None,- bool(updated.get("no_agent")),- _upd_script or None,+ f"Requested one-shot time {run_at} is in the past "+ f"(grace window: {ONESHOT_GRACE_SECONDS}s) and cannot be scheduled.")+ updated["next_run_at"] = next_run- if any(k in updates for k in _PAYLOAD_FIELDS):- if job_payload_is_empty(updated):- raise ValueError(EMPTY_PAYLOAD_ERROR)- schedule_changed = "schedule" in updates- inference_fields_changed = bool(- {"provider", "model", "base_url", "no_agent"}.intersection(updates)- ) and _normalized_inference_axes(updated) != previous_inference_axes-- if "skills" in updates or "skill" in updates:- normalized_skills = _normalize_skill_list(updated.get("skill"), updated.get("skills"))- updated["skills"] = normalized_skills- updated["skill"] = normalized_skills[0] if normalized_skills else None-- if schedule_changed:- updated_schedule = updated["schedule"]- # The API may pass schedule as a raw string (e.g. "every 10m")- # instead of a pre-parsed dict. Normalize it the same way- # create_job() does so downstream code can call .get() safely.- if isinstance(updated_schedule, str):- updated_schedule = parse_schedule(updated_schedule)- updated["schedule"] = updated_schedule- updated["schedule_display"] = updates.get(- "schedule_display",- updated_schedule.get("display", updated.get("schedule_display")),- )- if updated.get("state") != "paused":- updated_next_run = compute_next_run(updated_schedule)- # Same guard as create_job: an UPDATE that sets a one-shot- # to a time >ONESHOT_GRACE_SECONDS in the past would store- # next_run_at=None with state="scheduled", re-creating the- # ghost job that never fires (#59395). Reject it here too so- # the bug can't re-enter through the update door.- if (- updated_next_run is None- and updated_schedule.get("kind") == "once"- ):- run_at = updated_schedule.get("run_at") or updated_schedule- logger.warning(- "Rejecting one-shot cron job update '%s': run_at %s "- "is outside the %ss grace window",- updated.get("name", job_id),- run_at,- ONESHOT_GRACE_SECONDS,- )- raise ValueError(- f"Requested one-shot time {run_at} is more than "- f"{ONESHOT_GRACE_SECONDS}s in the past and cannot be scheduled."- )- updated["next_run_at"] = updated_next_run-- if inference_fields_changed:- provider_snapshot, model_snapshot = _compute_provider_model_snapshots(- provider=updated.get("provider"),- model=updated.get("model"),- base_url=updated.get("base_url"),- no_agent=updated.get("no_agent"),- )- updated["provider_snapshot"] = provider_snapshot- updated["model_snapshot"] = model_snapshot-- if updated.get("enabled", True) and updated.get("state") != "paused" and not updated.get("next_run_at"):- next_run = compute_next_run(updated["schedule"])- if next_run is None and updated["schedule"].get("kind") == "once":- run_at = updated["schedule"].get("run_at", "unknown")- raise ValueError(- f"Requested one-shot time {run_at} is in the past "- f"(grace window: {ONESHOT_GRACE_SECONDS}s) and cannot be scheduled."- )- updated["next_run_at"] = next_run+ _reject_terminal_activation(job, updated, job_id)- if (- is_terminal_job(job)- and not _is_recoverable_error_job(job)- and (- updated.get("state") not in {"completed", "error"}- or updated.get("enabled") is True- or updated.get("next_run_at") is not None- )- ):- raise ValueError(- f"Cannot activate terminal cron job '{job.get('name', job_id)}' "- "through update_job; use cron resume --run-now or --at."- )+ jobs[i] = updated+ save_jobs(jobs)+ return _normalize_job_record(updated)- jobs[i] = updated- save_jobs(jobs)- return _normalize_job_record(jobs[i])- return None+ return _with_job(job_id, apply)def pause_job(job_id: str, reason: Optional[str] = None) -> Optional[Dict[str, Any]]:@@ -2890,15 +2107,8 @@ def resume_job(job_id: str) -> Optional[Dict[str, Any]]:def trigger_job(job_id: str, extra_prompt: Optional[str] = None) -> Optional[Dict[str, Any]]:- """Schedule a job to run on the next scheduler tick. Accepts a job ID or name.-- ``extra_prompt``: optional transient per-run context for the manual fire- (from ``cronjob(action='run', prompt=...)`` forwarded through the gateway- api_server). Stamped as ``manual_run_prompt`` alongside ``manual_run_at``- and consumed by ``run_one_job`` for that single fire only —- ``mark_job_run`` clears it, so it never persists into the job definition- or later scheduled fires.- """+ """Schedule a job for the next tick (ID or name). ``extra_prompt`` is stamped as+ ``manual_run_prompt`` for that single fire only; ``mark_job_run`` clears it."""job = resolve_job_ref(job_id)if not job:return None@@ -2919,11 +2129,8 @@ def trigger_job("paused_at": None,"paused_reason": None,"next_run_at": manual_run_at,- # Persist run-now intent alongside the arbitrary instant so cron- # expression/TZ repair guards do not mistake it for stale state.+ # Run-now intent, so cron expression/TZ repair guards don't treat it as stale state."manual_run_at": manual_run_at,- # Transient run context rides with the run-now intent (None- # clears any stale prompt from a previous trigger)."manual_run_prompt": (extra_prompt or None),},)@@ -2932,11 +2139,8 @@ def trigger_job(def _claim_is_live(claim: Any, now: datetime, ttl_seconds: float) -> bool:if not isinstance(claim, dict) or not claim.get("at"):return False- try:- age = (now - _ensure_aware(datetime.fromisoformat(claim["at"]))).total_seconds()- except (TypeError, ValueError):- return False- return 0 <= age < ttl_seconds+ claimed_at = _parse_aware(claim["at"])+ return claimed_at is not None and 0 <= (now - claimed_at).total_seconds() < ttl_secondsdef rearm_oneshot(job_id: str, run_at: Any) -> Optional[Dict[str, Any]]:@@ -2954,43 +2158,32 @@ def rearm_oneshot(job_id: str, run_at: Any) -> Optional[Dict[str, Any]]:)next_run_at = compute_next_run(parsed_schedule)if next_run_at is None:- requested = parsed_schedule.get("run_at") or run_at- raise ValueError(- f"Requested one-shot time {requested} is more than "- f"{ONESHOT_GRACE_SECONDS}s in the past and cannot be scheduled."- )+ raise _oneshot_past_grace_error(parsed_schedule.get("run_at") or run_at)++ def apply(jobs, _i, job):+ now = _hermes_now()+ if _claim_is_live(job.get("run_claim"), now, _oneshot_run_claim_ttl_seconds()):+ raise ValueError("Cannot re-arm one-shot over a live run claim.")+ if _claim_is_live(job.get("fire_claim"), now, 300):+ raise ValueError("Cannot re-arm one-shot over a live fire claim.")+ if job.get("schedule", {}).get("kind") != "once":+ raise ValueError(+ "Cannot re-arm recurring jobs: re-arm is one-shot-only; "+ "use plain resume or cron run."+ )+ repeat = job.get("repeat") or {}+ repeat["completed"] = 0+ job["schedule"] = parsed_schedule+ job["schedule_display"] = parsed_schedule.get("display", str(run_at))+ job["repeat"] = repeat+ job["run_claim"] = None+ job["fire_claim"] = None+ _activate_job_record(job)+ job["next_run_at"] = next_run_at+ save_jobs(jobs)+ return _normalize_job_record(job)- with _jobs_lock():- jobs = load_jobs()- for index, job in enumerate(jobs):- if job.get("id") != job_ref["id"]:- continue- now = _hermes_now()- if _claim_is_live(job.get("run_claim"), now, _oneshot_run_claim_ttl_seconds()):- raise ValueError("Cannot re-arm one-shot over a live run claim.")- if _claim_is_live(job.get("fire_claim"), now, 300):- raise ValueError("Cannot re-arm one-shot over a live fire claim.")- if job.get("schedule", {}).get("kind") != "once":- raise ValueError(- "Cannot re-arm recurring jobs: re-arm is one-shot-only; "- "use plain resume or cron run."- )- repeat = job.get("repeat") or {}- repeat["completed"] = 0- job["schedule"] = parsed_schedule- job["schedule_display"] = parsed_schedule.get("display", str(run_at))- job["repeat"] = repeat- job["run_claim"] = None- job["fire_claim"] = None- job["enabled"] = True- job["state"] = "scheduled"- job["paused_at"] = None- job["paused_reason"] = None- job["next_run_at"] = next_run_at- jobs[index] = job- save_jobs(jobs)- return _normalize_job_record(job)- return None+ return _with_job(job_ref["id"], apply)def remove_job(job_id: str) -> bool:@@ -3004,17 +2197,11 @@ def remove_job(job_id: str) -> bool:original_len = len(jobs)jobs = [j for j in jobs if j["id"] != canonical_id]if len(jobs) < original_len:- # Resolve the output dir BEFORE saving so a legacy unsafe ID (e.g.- # left over from before the create-time guard) fails closed without- # half-applying the removal.+ # Resolve BEFORE saving so a legacy unsafe ID fails closed without a half-applied removal.job_output_dir = _job_output_dir(canonical_id)save_jobs(jobs, removed_ids={canonical_id})- # Clean up output directory to prevent orphaned dirs accumulatingif job_output_dir.exists():shutil.rmtree(job_output_dir)- # Clean up the job's durable notepad (cron/notepad.db) — without- # this, removed jobs orphan their KV rows forever. Best effort:- # a notepad failure must never block the removal itself.try:from cron.notepad import clear_notepadclear_notepad(canonical_id)@@ -3023,8 +2210,7 @@ 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.+ # Prune the fire-fence lock entry so the registry doesn't grow monotonically._fence_key = f"{_current_cron_store().cron_dir.resolve()}::{canonical_id}"with _fire_fence_locks_guard:_fire_fence_locks.pop(_fence_key, None)@@ -3055,44 +2241,29 @@ def mark_job_run(def _set_alert_flag(job_id: str, field: str, value: bool) -> bool:- """Set/clear a persisted alert-dedup marker; return the PRIOR value.-- The marker records that the operator was already alerted about this- job's condition, so the scheduler alerts exactly once and stays silent- on subsequent ticks until the condition heals (same alert-once shape as- the dead-pin auto-pause in #73506). Persisted on the job record so the- dedup survives gateway restarts. Fields: ``preflight_alerted`` (blocked- config, T1-26) and ``drift_alerted`` (#44585 drift-guard skip).- """- with _jobs_lock():- jobs = load_jobs()- for i, job in enumerate(jobs):- if job["id"] == job_id:- prior = bool(job.get(field))- if value:- job[field] = True- else:- job.pop(field, None)- if prior != value:- jobs[i] = job- save_jobs(jobs)- return prior- return False-+ """Set/clear a persisted alert-dedup marker (alert exactly once until the condition heals;+ survives restarts) and return the PRIOR value. Fields: ``preflight_alerted``, ``drift_alerted``."""+ def apply(jobs, _i, job):+ prior = bool(job.get(field))+ if value:+ job[field] = True+ else:+ job.pop(field, None)+ if prior != value:+ save_jobs(jobs)+ return prior-def _set_preflight_alerted(job_id: str, value: bool) -> bool:- """Set/clear the preflight alert-dedup marker; return the PRIOR value."""- return _set_alert_flag(job_id, "preflight_alerted", value)+ return _with_job(job_id, apply, False)def mark_preflight_alerted(job_id: str) -> bool:"""Mark the job as preflight-alerted; return True if it already was."""- return _set_preflight_alerted(job_id, True)+ return _set_alert_flag(job_id, "preflight_alerted", True)def clear_preflight_alerted(job_id: str) -> None:"""Clear the preflight alert-dedup marker (config validates again)."""- _set_preflight_alerted(job_id, False)+ _set_alert_flag(job_id, "preflight_alerted", False)def mark_drift_alerted(job_id: str) -> bool:@@ -3100,41 +2271,19 @@ def mark_drift_alerted(job_id: str) -> bool:return _set_alert_flag(job_id, "drift_alerted", True)-def clear_drift_alerted(job_id: str) -> None:- """Clear the drift alert-dedup marker (resolution matches again)."""- _set_alert_flag(job_id, "drift_alerted", False)--def note_fire_forward_failure(job_id: str, detail: str) -> bool:"""Durably record that a scheduled fire could not be handed to the runner.- Written by the dashboard fire webhook when the loopback forward to the- gateway api_server fails (gateway unreachable / listener not bound) —- the shape behind "job runs manually but never auto-fires". Without this- stamp the miss is invisible outside gui.log: no execution row is created- (the claim never happens) and ``last_status``/``last_error`` only cover- runs that actually started.-- Stored as ``last_fire_error`` (``{"at": iso, "detail": str}``) on the job- record so `cronjob list`, the CLI, and the dashboard all surface it.- Cleared by the next successful run (``mark_job_run``). Repeated failures- overwrite in place — latest miss wins; per-fire history lives in the- scheduler's own logs.-- Returns True when a job record was found and stamped.+ Written by the dashboard fire webhook when the loopback forward to the gateway fails. Without+ it the miss is invisible: no execution row exists and last_status/last_error only cover runs+ that started. Stored as ``last_fire_error`` so list/CLI/dashboard surface it; mark_job_run clears it."""- with _jobs_lock():- jobs = load_jobs()- for i, job in enumerate(jobs):- if job["id"] == job_id:- job["last_fire_error"] = {- "at": _hermes_now().isoformat(),- "detail": str(detail or "")[:500],- }- jobs[i] = job- save_jobs(jobs)- return True- return False+ def apply(jobs, _i, job):+ job["last_fire_error"] = {"at": _hermes_now().isoformat(), "detail": str(detail or "")[:500]}+ save_jobs(jobs)+ return True++ return _with_job(job_id, apply, False)def _mark_job_run_locked(@@ -3146,403 +2295,257 @@ def _mark_job_run_locked(status: Optional[str] = None,expected_fire_owner: Optional[str] = None,) -> bool:+ """Mark a job as run: update last_run_at/last_status, bump completed, recompute next_run_at,+ and retire the record as a terminal completion when the repeat limit is reached.++ ``delivery_error`` is separate from the agent error: agent succeeded but delivery failed records+ ``last_status = "delivery_failed"`` (never "ok") while ``failure_streak`` is left alone. An+ explicit ``status`` (e.g. "blocked_config") overrides the derived value."""- Mark a job as having been run.-- Updates last_run_at, last_status, increments completed count,- computes next_run_at, and auto-deletes if repeat limit reached.-- ``delivery_error`` is tracked separately from the agent error — a job- can succeed (agent produced output) but fail delivery (platform down).-- A run that succeeded but failed delivery records- ``last_status = "delivery_failed"`` (never "ok") so the failure is- visible to every reader, while ``failure_streak`` stays untouched —- the agent did its job.-- ``status`` overrides the derived ``last_status`` ("ok"/"error"/- "delivery_failed") with a- specific terminal status for this run — e.g. ``"blocked_config"`` when- the pre-dispatch configuration validation refused to run the agent- (T1-26), so `cronjob list` distinguishes "your config is broken" from- "the run itself failed".- """- with _jobs_lock():- 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 False- now = _hermes_now().isoformat()- job["last_run_at"] = now- job.pop("manual_run_at", None)- # The transient manual-run context is single-fire: whatever- # run just completed consumed it (or superseded it).- job.pop("manual_run_prompt", None)- # A run whose agent succeeded but whose delivery failed is NOT- # "ok": recording it as such hid last_delivery_error behind a- # green status in `cron list`/the UI and made a job that never- # reached the user look like a quiet success (#83993). It gets- # its own status so every reader that keys off "ok" (CLI list,- # doctor, cronjob_tools) sees the failure. An explicit- # ``status`` override (e.g. "blocked_config") still wins.- if status:- job["last_status"] = status- elif not success:- job["last_status"] = "error"- elif isinstance(delivery_error, str) and delivery_error.strip():- job["last_status"] = "delivery_failed"- else:- job["last_status"] = "ok"- job["last_error"] = error if not success else None- # A healthy run means the configuration validates again — drop- # the preflight alert-dedup marker so a FUTURE config break- # re-alerts instead of being silently swallowed. Same contract- # for the drift marker (#44585 alert-once): a run that made it- # through the guard means resolution matches again.- if success:- job.pop("preflight_alerted", None)- job.pop("drift_alerted", None)- # The fire hand-off demonstrably works again — clear the- # forward-failure stamp so it only ever describes the- # CURRENT auto-fire health, not a healed past incident.- job.pop("last_fire_error", None)- # Consecutive agent-failure streak. Any successful run resets- # it; delivery failures alone do NOT count (the agent did its- # job). Read by the scheduler's failure-delivery path to nudge- # the user to review a repeatedly-failing automation- # (Poke-inspired; see cron/scheduler._failure_streak_nudge).- if success:- job["failure_streak"] = 0- else:- job["failure_streak"] = int(job.get("failure_streak") or 0) + 1- # Track delivery failures separately — cleared on successful delivery- job["last_delivery_error"] = delivery_error- # Clear any external-fire claim so a re-armed recurring job can- # be claimed again on its next fire (Phase 4C CAS).- job["fire_claim"] = None- # Clear the one-shot running-claim (#59229): the run is over, so- # a re-armed recurring job or a re-dispatched one-shot recovery- # is claimable again. No-op if the job never carried a claim.- if job.get("run_claim") is not None:- job["run_claim"] = None-- # Increment completed count. Finite one-shot jobs are- # pre-claimed by claim_dispatch() BEFORE the side effect runs- # (issue #38758), which already incremented completed — do not- # double-count them here. Recurring jobs and direct callers- # with no pre-run claim still get the legacy increment.- if job.get("repeat"):- repeat = job["repeat"]- times = repeat.get("times")- completed = repeat.get("completed", 0)- kind = job.get("schedule", {}).get("kind")- preclaimed_oneshot = (- kind == "once"- and times is not None- and times > 0- and completed > 0- )- if not preclaimed_oneshot:- completed += 1- repeat["completed"] = completed-- # Check if we've hit the repeat limit- if times is not None and times > 0 and completed >= times:- # Limit reached: retain the record as a terminal- # completion instead of popping it. Deleting the job- # here discarded the last_status / last_error /- # last_delivery_error written above — a finished- # one-shot vanished from `cronjob list` with no- # inspectable outcome, and a failed delivery was- # invisible. Mirror the terminal shape of the- # next_run_at-is-None branch below; the retention- # sweep prunes these after- # COMPLETED_ONESHOT_RETENTION_DAYS.- job["enabled"] = False- job["state"] = "completed"- job["next_run_at"] = None- save_jobs(jobs)- return True-- # Compute next run- job["next_run_at"] = compute_next_run(job["schedule"], now)-- # If no next run, decide whether this is terminal completion- # (one-shot) or a transient failure (recurring schedule couldn't- # compute — e.g. 'croniter' missing from the runtime env).- # Recurring jobs must NEVER be silently disabled: that turns a- # missing runtime dep into "job completed" and the user's- # schedule quietly goes off. See issue #16265.- if job["next_run_at"] is None:- kind = job.get("schedule", {}).get("kind")- if kind in {"cron", "interval"}:- job["state"] = "error"- if not job.get("last_error"):- job["last_error"] = (- "Failed to compute next run for recurring "- "schedule (is the 'croniter' package "- "installed in the gateway's Python env?)"- )- logger.error(- "Job '%s' (%s) could not compute next_run_at; "- "leaving enabled and marking state=error so the "- "job is not silently disabled.",- job.get("name", job.get("id", "?")),- kind,- )- else:- job["enabled"] = False- job["state"] = "completed"- elif job.get("state") != "paused":- job["state"] = "scheduled"+ def apply(jobs, _i, job):+ 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 False+ now = _hermes_now().isoformat()+ job["last_run_at"] = now+ job.pop("manual_run_at", None)+ # The transient manual-run context is single-fire: the run that just completed consumed it.+ job.pop("manual_run_prompt", None)+ delivery_failed = isinstance(delivery_error, str) and bool(delivery_error.strip())+ job["last_status"] = status or (+ "error" if not success else ("delivery_failed" if delivery_failed else "ok")+ )+ job["last_error"] = error if not success else None+ if success:+ # Healthy run: drop the alert-once dedup markers so a FUTURE break re-alerts, and clear+ # the forward-failure stamp so it only describes CURRENT auto-fire health.+ job.pop("preflight_alerted", None)+ job.pop("drift_alerted", None)+ job.pop("last_fire_error", None)+ job["failure_streak"] = 0+ else:+ # Consecutive agent-failure streak; delivery failures do NOT count (scheduler._failure_streak_nudge).+ job["failure_streak"] = int(job.get("failure_streak") or 0) + 1+ job["last_delivery_error"] = delivery_error+ # Clear both claims: the run is over, so the job is claimable again.+ job["fire_claim"] = None+ if job.get("run_claim") is not None: # keep key absence for legacy records+ job["run_claim"] = None+ kind = job.get("schedule", {}).get("kind")+ repeat = job.get("repeat")+ if repeat:+ times = repeat.get("times")+ finite = times is not None and times > 0+ completed = repeat.get("completed", 0)+ # Finite one-shots were pre-claimed by claim_dispatch() (completed already incremented) —+ # do not double-count; recurring jobs and direct callers still get the increment.+ if not (kind == "once" and finite and completed > 0):+ completed += 1+ repeat["completed"] = completed+ if finite and completed >= times:+ # Limit reached: retain a terminal record instead of popping it, so the status just+ # written stays inspectable in `cronjob list`; the retention sweep prunes it later.+ _complete_job_record(job)save_jobs(jobs)return True+ job["next_run_at"] = compute_next_run(job["schedule"], now)+ if job["next_run_at"] is None:+ # One-shot: terminal completion. Recurring: transient failure (e.g. croniter missing) —+ # disabling it would turn a missing dep into "job completed" and silently drop the schedule.+ if kind in {"cron", "interval"}:+ job["state"] = "error"+ if not job.get("last_error"):+ job["last_error"] = (+ "Failed to compute next run for recurring "+ "schedule (is the 'croniter' package "+ "installed in the gateway's Python env?)"+ )+ logger.error(+ "Job '%s' (%s) could not compute next_run_at; "+ "leaving enabled and marking state=error so the "+ "job is not silently disabled.",+ job.get("name", job.get("id", "?")),+ kind,+ )+ else:+ _complete_job_record(job)+ elif job.get("state") != "paused":+ job["state"] = "scheduled"++ save_jobs(jobs)+ return True++ found = _with_job(job_id, apply, missing=_MISSING)+ if found is _MISSING:logger.warning("mark_job_run: job_id %s not found, skipping save", job_id)return False+ return found+++def _write_oneshot_diagnostic(job: Dict[str, Any], text: str, what: str) -> bool:+ """Best-effort operator-visible trace in the job's output dir; never breaks the caller."""+ try:+ save_job_output(job.get("id", ""), text)+ return True+ except Exception as e:+ logger.debug("Failed to write %s diagnostic for job %r: %s", what, job.get("id"), e)+ return Falsedef _write_wedged_oneshot_diagnostic(job: Dict[str, Any]) -> None:"""Leave an operator-visible trace when a wedged one-shot is removed.- A finite one-shot whose dispatch was claimed (``repeat.completed`` >=- ``repeat.times``) but which never reached ``mark_job_run`` (``last_run_at``- is null) was interrupted mid-run — scheduler restart, gateway kill, or a- non-Exception escape (#73973). The recovery guards remove such jobs so- they stop appearing due, but a silent removal leaves the user with no- output, no error, and no job record. Write a small diagnostic file into- the job's output directory so the removal is observable and debuggable.-- Best-effort: diagnostics must never break the removal itself.+ A finite one-shot whose dispatch was claimed but which never reached mark_job_run was+ interrupted mid-run; removing it silently would leave no output, error, or record."""if job.get("last_run_at") is not None:return # a prior run was recorded — normal completion race, not a wedge- try:- repeat = job.get("repeat") or {}- claim = job.get("run_claim") or {}- text = (- "# Cron job removed without producing output\n\n"- f"- job id: {job.get('id')}\n"- f"- name: {job.get('name')}\n"- f"- dispatch claimed: {repeat.get('completed', '?')}/{repeat.get('times', '?')}\n"- f"- run claimed at: {claim.get('at', 'unknown')} by {claim.get('by', 'unknown')}\n"- f"- removed at: {_hermes_now().isoformat()}\n\n"- "This one-shot job's dispatch was claimed, but the run never "- "completed (`last_run_at` was never written) — the scheduler "- "process was most likely killed or restarted mid-execution. The "- "job has been removed to stop it re-firing; recreate it to run "- "again.\n"- )- save_job_output(job.get("id", ""), text)+ repeat = job.get("repeat") or {}+ claim = job.get("run_claim") or {}+ written = _write_oneshot_diagnostic(+ job,+ "# Cron job removed without producing output\n\n"+ f"- job id: {job.get('id')}\n"+ f"- name: {job.get('name')}\n"+ f"- dispatch claimed: {repeat.get('completed', '?')}/{repeat.get('times', '?')}\n"+ f"- run claimed at: {claim.get('at', 'unknown')} by {claim.get('by', 'unknown')}\n"+ f"- removed at: {_hermes_now().isoformat()}\n\n"+ "This one-shot job's dispatch was claimed, but the run never "+ "completed (`last_run_at` was never written) — the scheduler "+ "process was most likely killed or restarted mid-execution. The "+ "job has been removed to stop it re-firing; recreate it to run "+ "again.\n",+ "wedged-oneshot",+ )+ if written:logger.warning("Job '%s': removed without a completed run — diagnostic written to ""its output directory",job.get("name", job.get("id", "?")),)- except Exception as e:- logger.debug(- "Failed to write wedged-oneshot diagnostic for job %r: %s",- job.get("id"), e,- )def _write_missed_oneshot_diagnostic(job: Dict[str, Any], next_run: str) -> None:- """Leave an operator-visible trace when a never-ran one-shot is retired- because its persisted run time fell outside the grace window.-- The record is removed because the scheduler will never fire it (see the- grace gate in ``_get_due_jobs_locked``); without a diagnostic the job- would just vanish. Best-effort: a diagnostic failure never blocks the- removal itself.- """- try:- text = (- "# Cron job removed before firing (run time outside grace window)\n\n"- f"- job id: {job.get('id')}\n"- f"- name: {job.get('name')}\n"- f"- scheduled run time: {next_run}\n"- f"- grace window: {ONESHOT_GRACE_SECONDS}s\n"- f"- removed at: {_hermes_now().isoformat()}\n\n"- "This one-shot's run time is more than the grace window in the "- "past (scheduler down past the window, host asleep, or jobs.json "- "edited), which is outside the 'will never fire' contract "- "enforced at create/update/resume time. The job was removed "- "without running; recreate it (or use the Run button) to "- "schedule it again.\n"- )- save_job_output(job.get("id", ""), text)- except Exception as e:- logger.debug(- "Failed to write missed-oneshot diagnostic for job %r: %s",- job.get("id"), e,- )--+ """Trace for a never-ran one-shot retired outside the grace window (else it would just vanish)."""+ _write_oneshot_diagnostic(+ job,+ "# Cron job removed before firing (run time outside grace window)\n\n"+ f"- job id: {job.get('id')}\n"+ f"- name: {job.get('name')}\n"+ f"- scheduled run time: {next_run}\n"+ f"- grace window: {ONESHOT_GRACE_SECONDS}s\n"+ f"- removed at: {_hermes_now().isoformat()}\n\n"+ "This one-shot's run time is more than the grace window in the "+ "past (scheduler down past the window, host asleep, or jobs.json "+ "edited), which is outside the 'will never fire' contract "+ "enforced at create/update/resume time. The job was removed "+ "without running; recreate it (or use the Run button) to "+ "schedule it again.\n",+ "missed-oneshot",+ )def claim_dispatch(job_id: str) -> bool:- """Atomically claim a finite one-shot job dispatch BEFORE execution.-- Increments ``repeat.completed`` under the cross-process jobs lock and- persists the claim immediately, so that if the tick dies mid-execution- (gateway kill, OOM, segfault, hard-timeout) the dispatch is not lost.- This converts finite one-shot jobs from *at-least-once* to *at-most-times*- semantics — a job that self-destructs fires at most ``repeat.times`` times- instead of infinitely (issue #38758).-- Returns ``True`` if the caller may proceed to run the job, ``False`` if the- dispatch limit is already reached (in which case the stale job is removed).+ """Atomically claim a finite one-shot dispatch BEFORE execution.- Only claims jobs with ``schedule.kind == "once"`` and ``repeat.times > 0``.- Recurring jobs (they use ``advance_next_run``) and infinite-repeat / no-repeat- jobs are left unchanged and always allowed to proceed.+ Increments ``repeat.completed`` under the jobs lock and persists it, so a tick dying+ mid-execution cannot lose the dispatch: finite one-shots become *at-most-times* instead of+ *at-least-once*. Returns True if the caller may run the job, False when the limit is already+ reached (the stale job is removed). Only ``kind == "once"`` with ``repeat.times > 0`` is claimed."""- with _jobs_lock():- jobs = load_jobs()- for i, job in enumerate(jobs):- if job["id"] != job_id:- continue- if job.get("schedule", {}).get("kind") != "once":- return True # recurring jobs use advance_next_run(), not dispatch claims- repeat = job.get("repeat")- if not repeat:- return True # no repeat limit — always dispatch- times = repeat.get("times")- if times is None or times <= 0:- return True # infinite — always dispatch- completed = repeat.get("completed", 0)- if completed >= times:- # Already dispatched the max number of times.- if job.get("last_run_at") is not None:- # A prior run completed normally (e.g. mark_job_run raced- # with this tick). Retain the terminal record — same shape- # as mark_job_run's repeat-limit branch — instead of- # deleting the job and its final status/delivery error.- job["enabled"] = False- job["state"] = "completed"- job["next_run_at"] = None- save_jobs(jobs)- logger.info(- "Job '%s': dispatch limit reached (%d/%d) — marking completed",- job.get("name", job.get("id", "?")),- completed,- times,- )- return False- # A prior tick claimed the dispatch then died before the run- # completed (#73973) — a genuinely wedged claim. Remove it so- # it stops appearing as due, and leave an operator-visible- # diagnostic instead of vanishing silently.- jobs.pop(i)- save_jobs(jobs, removed_ids={job_id})- _write_wedged_oneshot_diagnostic(job)- logger.info(- "Job '%s': dispatch limit reached (%d/%d) — removing",- job.get("name", job.get("id", "?")),- completed,- times,- )- return False- # Claim this dispatch before the side effect runs.- repeat["completed"] = completed + 1- save_jobs(jobs)- logger.debug(- "Job '%s': claimed dispatch %d/%d",- job.get("name", job.get("id", "?")),- repeat["completed"],- times,- )+ def apply(jobs, i, job):+ repeat = job.get("repeat") or {}+ times = repeat.get("times")+ # Recurring jobs use advance_next_run(); no/infinite repeat limit always dispatches.+ if job.get("schedule", {}).get("kind") != "once" or times is None or times <= 0:return True+ completed = repeat.get("completed", 0)+ label = job.get("name", job.get("id", "?"))+ if completed >= times:+ if job.get("last_run_at") is not None:+ # A prior run completed normally (mark_job_run raced this tick). Retain the terminal+ # record, as mark_job_run's repeat-limit branch does, instead of deleting the status.+ _complete_job_record(job)+ save_jobs(jobs)+ logger.info("Job '%s': dispatch limit reached (%d/%d) — marking completed", label, completed, times)+ return False+ # A prior tick claimed the dispatch then died — a genuinely wedged claim. Remove it so+ # it stops appearing due, leaving an operator-visible diagnostic.+ jobs.pop(i)+ save_jobs(jobs, removed_ids={job_id})+ _write_wedged_oneshot_diagnostic(job)+ logger.info("Job '%s': dispatch limit reached (%d/%d) — removing", label, completed, times)+ return False+ # Claim this dispatch before the side effect runs.+ repeat["completed"] = completed + 1+ save_jobs(jobs)+ logger.debug("Job '%s': claimed dispatch %d/%d", label, repeat["completed"], times)+ return True+ claimed = _with_job(job_id, apply, missing=_MISSING)+ if claimed is _MISSING:logger.debug("claim_dispatch: job_id %s not in store — proceeding without claim ""(handed-in job dict; nothing to persist a claim against)",job_id,)return True+ return claimeddef heartbeat_run_claim(job_id: str, *, expected_owner: str) -> bool:"""Refresh a one-shot's ``run_claim`` timestamp while its run is alive.- Called periodically from the scheduler's run monitor (#62002) so a- legitimately long run keeps its claim fresh: an expired claim then really- does mean "the claiming process died", and neither another process's tick- nor this process's own next tick will re-dispatch or stale-remove the job- while the run is in flight. mark_job_run() clears the claim on completion.-- ``expected_owner`` is the stable owner copied from the dispatched job. The- compare-and-refresh prevents a stale runner that resumes after a long sleep- from extending a claim another scheduler process has since taken over.-- Returns True if this owner's one-shot claim was refreshed; False when the- job, claim, or ownership no longer matches.+ Called periodically by the run monitor so a long run keeps its claim fresh: an expired claim+ then really means the claiming process died. Compare-and-refresh on ``expected_owner`` stops a+ stale runner from extending a claim another process has since taken over. Returns False when+ the job, claim, or ownership no longer matches."""- with _jobs_lock():- jobs = load_jobs()- for job in jobs:- if job.get("id") != job_id:- continue- if job.get("schedule", {}).get("kind") != "once":- return False- claim = job.get("run_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 apply(jobs, _i, job):+ if job.get("schedule", {}).get("kind") != "once":+ return False+ return _refresh_claim(jobs, job.get("run_claim"), expected_owner)+ return _with_job(job_id, apply, False)-def clear_run_claim(job_id: str) -> bool:- """Clear a one-shot job's ``run_claim`` when its dispatch fails.- ``get_due_jobs`` stamps a ``run_claim`` before returning a one-shot as- due (#59229). ``mark_job_run`` clears it on *successful* completion.- When dispatch itself fails (interpreter shutdown, executor submit error,- execution-creation error) the job never reaches ``mark_job_run`` and the- stale claim blocks re-dispatch until the TTL expires (default 30 min).+def _refresh_claim(jobs: List[Dict[str, Any]], claim: Any, expected_owner: str) -> bool:+ """Compare-and-refresh a claim's ``at`` stamp; False unless *expected_owner* still holds it."""+ if not isinstance(claim, dict) or claim.get("by") != expected_owner:+ return False+ claim["at"] = _hermes_now().isoformat()+ save_jobs(jobs)+ return True- Calling this on every early-exit path restores the "the job stays due- and will fire on the next healthy tick" invariant that the scheduler- comment promises (#86522).++def clear_run_claim(job_id: str) -> bool:+ """Clear a one-shot's ``run_claim`` when dispatch itself fails.++ Such a job never reaches mark_job_run, so the stale claim would block re-dispatch until the TTL+ expires; calling this on every early-exit path keeps "stays due, fires on the next healthy tick"."""- with _jobs_lock():- jobs = load_jobs()- for job in jobs:- if job.get("id") != job_id:- continue- if job.get("schedule", {}).get("kind") != "once":- return False- if job.get("run_claim") is not None:- job["run_claim"] = None- save_jobs(jobs)- return True- return False # already cleared- return False+ def apply(jobs, _i, job):+ if job.get("schedule", {}).get("kind") != "once" or job.get("run_claim") is None:+ return False # recurring, or already cleared+ job["run_claim"] = None+ save_jobs(jobs)+ return True++ return _with_job(job_id, apply, False)def advance_next_runs(job_ids) -> int:- """Batch form of :func:`advance_next_run` for the due-dispatch loop.-- One ``load_jobs()`` + at most one ``save_jobs()`` for the whole due- set, instead of one of each per job — the per-job form costs- O(N loads + N saves) for N due jobs (~110 ms at N=50, measured), the- batch form O(1 + 1) (~2 ms). ``job_ids`` may contain ids of one-shot- or unknown jobs; they are skipped exactly as the per-job form skips- them. Returns the number of jobs whose ``next_run_at`` was advanced.-- Crash semantics: the batch persists once at the end, so a crash- mid-batch re-fires the whole set on restart (at-least-once burst)- rather than advancing a prefix — acceptable given the sub-10ms window,- and identical to the per-job form once the batch completes.+ """Batch form of :func:`advance_next_run`: one load + at most one save for the whole due set.++ One-shot/unknown ids are skipped as in the per-job form. Returns the count advanced. Crash+ semantics: persisted once at the end, so a crash mid-batch re-fires the whole set on restart+ (at-least-once burst) rather than a prefix — acceptable given the sub-10ms window."""ids = set(job_ids)if not ids:@@ -3552,12 +2555,11 @@ def advance_next_runs(job_ids) -> int:now = _hermes_now().isoformat()advanced = 0for job in jobs:- if job["id"] not in ids:- continue- if is_terminal_job(job) and not _is_recoverable_error_job(job):- continue- kind = job.get("schedule", {}).get("kind")- if kind not in {"cron", "interval"}:+ if (+ job["id"] not in ids+ or (is_terminal_job(job) and not _is_recoverable_error_job(job))+ or job.get("schedule", {}).get("kind") not in {"cron", "interval"}+ ):continuenew_next = compute_next_run(job["schedule"], now)if new_next and new_next != job.get("next_run_at"):@@ -3569,28 +2571,17 @@ def advance_next_runs(job_ids) -> int:def advance_next_run(job_id: str) -> bool:- """Preemptively advance next_run_at for a recurring job before execution.-- Call this BEFORE run_job() so that if the process crashes mid-execution,- the job won't re-fire on the next gateway restart. This converts the- scheduler from at-least-once to at-most-once for recurring jobs — missing- one run is far better than firing dozens of times in a crash loop.-- One-shot jobs are left unchanged so they can still retry on restart.-- Returns True if next_run_at was advanced, False otherwise.+ """Advance a recurring job's next_run_at BEFORE run_job() so a mid-run crash cannot re-fire it+ on restart (at-most-once for recurring jobs — one missed run beats a crash-loop burst).+ One-shots are left unchanged so they can retry. Returns True if next_run_at was advanced."""- # >= 1 (not == 1): a corrupted jobs file with duplicate ids advances- # every matching record; the wrapper still reports the advance.+ # >= 1 (not == 1): duplicate ids in a corrupted file all advance; still report the advance.return advance_next_runs([job_id]) >= 1def _machine_id() -> str:- """Stable-ish identifier for claim attribution/debugging (NOT correctness).-- Uses ``HERMES_MACHINE_ID`` if set, else hostname + pid. The CAS correctness- comes from the file lock + the fresh-claim check, not from this value.- """+ """Claim attribution/debugging id (NOT correctness — that comes from the file lock and the+ fresh-claim check): ``HERMES_MACHINE_ID`` if set, else hostname:pid."""explicit = os.getenv("HERMES_MACHINE_ID", "").strip()if explicit:return explicit@@ -3627,102 +2618,62 @@ def _claim_job_for_fire_locked(force: bool = False,return_job: bool = False,) -> Union[bool, Dict[str, Any]]:- """Atomically claim a job for a single external 'fire' (multi-machine- at-most-once). Returns True iff THIS caller won the claim.-- Used by the external-provider fire path (``CronScheduler.fire_due``) when an- 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. 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 a- fresh 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- re-delivery for the old time can't re-fire). One-shots keep ``next_run_at``- but the fresh ``fire_claim`` blocks a duplicate retry for the same fire.- ``mark_job_run`` clears the claim on completion so a re-armed recurring job- is claimable again next fire.-- The stale-claim TTL means a machine that crashed after claiming but before- completing doesn't wedge the job forever — after the TTL another fire can- reclaim it.- """- with _jobs_lock():- jobs = load_jobs()- for job in jobs:- if job["id"] != job_id:- continue- if is_terminal_job(job) and not _is_recoverable_error_job(job):- return False- # enabled + pause markers must both clear — a half-paused record- # (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 False- now = _hermes_now()- existing = job.get("fire_claim")- if existing:- try:- claimed_at = _ensure_aware(datetime.fromisoformat(existing["at"]))- # Bounded on BOTH sides (#60703): a claim stamped in the- # future (clock/TZ skew across a restart, or a corrupted- # timestamp) would otherwise have a negative age and stay- # "fresh" forever — the job becomes permanently unfireable- # and every manual `cron run` reports "already being- # fired". Treat future-dated claims as stale/overwritable.- _age = (now - claimed_at).total_seconds()- if 0 <= _age < claim_ttl_seconds:- return False # someone holds a fresh claim- except Exception:- pass # malformed claim → overwrite- 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"] = nxt- save_jobs(jobs)- return copy.deepcopy(job) if return_job else True- return False+ """Atomically claim a job for one external 'fire' (multi-machine at-most-once); True iff THIS+ caller won. Used by ``CronScheduler.fire_due`` so exactly one of N replicas runs a job.++ Under the file lock: reject missing/terminal/paused jobs unless ``force`` (an explicit manual+ fire, which also enables/resumes the job atomically; external callbacks must leave it false so+ a stale callback cannot resurrect a paused job). Lose if a fresh claim (younger than+ ``claim_ttl_seconds``) exists. Otherwise stamp ``fire_claim`` and, for recurring jobs, advance+ ``next_run_at`` so a stale re-delivery cannot re-fire; one-shots rely on the fresh claim alone.+ The TTL lets another fire reclaim a job whose claimant crashed; mark_job_run clears the claim.+ """+ def apply(jobs, _i, job):+ if is_terminal_job(job) and not _is_recoverable_error_job(job):+ return False+ # Both enabled and pause markers must clear — a half-paused record must not claim. ``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 False+ now = _hermes_now()+ # _claim_is_live bounds the age on BOTH sides: a claim stamped in the future (clock/TZ skew,+ # corrupted timestamp) must not stay "fresh" forever and wedge the job; malformed → overwrite.+ if _claim_is_live(job.get("fire_claim"), now, claim_ttl_seconds):+ return False # someone holds a fresh claim+ if force:+ _activate_job_record(job)+ # 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 match.+ job["fire_claim"] = {"at": now.isoformat(), "by": f"{_machine_id()}:{uuid.uuid4().hex}"}+ if job.get("schedule", {}).get("kind") in {"cron", "interval"}:+ nxt = compute_next_run(job["schedule"], now.isoformat())+ if nxt:+ job["next_run_at"] = nxt+ save_jobs(jobs)+ return copy.deepcopy(job) if return_job else True+ return _with_job(job_id, apply, False)-# Completed one-shot job records are retained in jobs.json (final status +-# delivery error stay inspectable via `cronjob list`) instead of being deleted-# at completion, then pruned by _sweep_completed_oneshots once they age out.-COMPLETED_ONESHOT_RETENTION_DAYS = 7+# Completed one-shots are retained in jobs.json (final status stays inspectable) and pruned by+# _sweep_completed_oneshots once they age out.+COMPLETED_ONESHOT_RETENTION_DAYS = 7-def _completed_oneshot_retention_days() -> float:- """Resolve the completed one-shot retention window from config.- ``cron.completed_retention_days`` (number, default- ``COMPLETED_ONESHOT_RETENTION_DAYS``). A non-positive value disables the- sweep, retaining completed one-shot records indefinitely.- """+def _cron_config_number(key: str, default: Any, cast: Callable[[Any], Any]) -> Any:+ """Read ``cron.<key>`` from config as *cast*, falling back to *default* on any failure."""try:from hermes_cli.config import load_configcfg = load_config() or {}cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}- return float(- cron_cfg.get(- "completed_retention_days", COMPLETED_ONESHOT_RETENTION_DAYS- )- )+ return cast(cron_cfg.get(key, default))except Exception:- return float(COMPLETED_ONESHOT_RETENTION_DAYS)+ return cast(default)+++def _completed_oneshot_retention_days() -> float:+ """``cron.completed_retention_days``; non-positive disables the sweep (records kept forever)."""+ return _cron_config_number("completed_retention_days", COMPLETED_ONESHOT_RETENTION_DAYS, float)def _sweep_completed_oneshots(@@ -3731,16 +2682,11 @@ def _sweep_completed_oneshots(*,removed_ids: Optional[Set[str]] = None,) -> bool:- """Prune terminal ``state == "completed"`` one-shot records past retention.-- Mutates *raw_jobs* in place; returns True when anything was removed (the- caller persists). Ids removed are added to *removed_ids* when provided so- ``save_jobs``'s shrink-merge guard (#80624) allows the intentional delete.- Only one-shot (``schedule.kind == "once"``) records in the terminal- completed state are candidates; recurring jobs and non-terminal one-shots- are never touched. Age is measured from ``last_run_at`` — a completed- record without a parseable ``last_run_at`` is kept (never guess a record- into deletion).+ """Prune completed one-shot records past retention (in place; True when anything was removed).++ Removed ids go into *removed_ids* so save_jobs's shrink-merge guard allows the delete. Only+ ``kind == "once"`` records in state "completed" are candidates; age is measured from+ ``last_run_at``, and a record without a parseable one is kept (never guess into deletion)."""retention_days = _completed_oneshot_retention_days()if retention_days <= 0:@@ -3756,13 +2702,8 @@ def _sweep_completed_oneshots(if kind != "once":continuelast_run = rj.get("last_run_at")- if not isinstance(last_run, str):- continue- try:- last_run_dt = _ensure_aware(datetime.fromisoformat(last_run))- except Exception:- continue- if last_run_dt >= cutoff:+ last_run_dt = _parse_aware(last_run) if isinstance(last_run, str) else None+ if last_run_dt is None or last_run_dt >= cutoff:continueraw_jobs.remove(rj)removed = True@@ -3796,612 +2737,446 @@ def heartbeat_fire_claim(job_id: str, *, expected_owner: str) -> bool: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+ """Refresh an active ``fire_claim`` without extending another owner's lease: an execution may+ outlive the TTL, and the owner check stops a stale runner from refreshing a recovered claim."""+ return _with_job(+ job_id, lambda jobs, _i, job: _refresh_claim(jobs, job.get("fire_claim"), expected_owner), False+ )def get_due_jobs() -> List[Dict[str, Any]]:- """Get all jobs that are due to run now.-- For recurring jobs (cron/interval), if the scheduled time is stale (more- than one period in the past, e.g. because the gateway was down OR because a- long-running previous execution overran the interval), the accumulated- missed runs are collapsed — ``next_run_at`` is fast-forwarded to the next- future occurrence so a backlog does NOT burst-fire on restart — but the job- still fires ONCE now. This prevents the perpetual-defer loop (#33315) where- a job whose runtime exceeds ``interval + grace`` would be skipped forever.-- Note: firing once on catch-up flows through ``mark_job_run``, so a job with- a ``repeat.times`` limit consumes one of its runs on that catch-up fire.+ """Return all jobs due now.++ A recurring job more than one period stale (gateway down, or a previous run overran the+ interval) has its backlog collapsed — next_run_at fast-forwards so nothing burst-fires — but+ still fires ONCE now, avoiding the perpetual-defer loop for runs longer than interval + grace.+ That catch-up fire flows through mark_job_run, so it consumes one ``repeat.times`` run."""with _jobs_lock():return _get_due_jobs_locked()-def _get_due_jobs_locked() -> List[Dict[str, Any]]:- """Inner implementation of get_due_jobs(); must be called with _jobs_lock held."""- now = _hermes_now()- raw_jobs = load_jobs()- needs_save = False- intentionally_removed: Set[str] = set()-- # Repair id-less records BEFORE anything keys off ``job["id"]``. A direct- # jobs.json edit that bypassed add_job() can leave a record without an "id"- # (older writers used "job_id"). Every downstream site — the logging- # helpers and the ``for rj in raw_jobs: if rj["id"] == job["id"]``- # persistence loops — indexes job["id"] eagerly, so a single malformed- # record raised KeyError mid-tick, aborting the whole scan before- # save_jobs() ran. That froze the entire profile's scheduler in a- # per-minute fast-forward loop (healthy jobs recomputed in memory, then- # discarded when the exception unwound). Recover the id from the drifted- # "job_id" key when present, else synthesize one, and persist.+@dataclass+class _DueScan:+ """Mutable state threaded through one due scan: the raw store records plus what to persist."""++ raw_jobs: List[Dict[str, Any]]+ now: datetime+ needs_save: bool = False+ removed: Set[str] = field(default_factory=set)++ def find(self, job_id: Any) -> Optional[Dict[str, Any]]:+ return next((rj for rj in self.raw_jobs if rj["id"] == job_id), None)++ def persist(self, job_id: Any, **fields: Any) -> None:+ """Write *fields* onto the raw record for *job_id* and flag a save (no-op if missing)."""+ rj = self.find(job_id)+ if rj is not None:+ rj.update(fields)+ self.needs_save = True++ def retire(self, job_id: Any) -> None:+ """Drop the raw record for *job_id* as an intentional removal."""+ rj = self.find(job_id)+ if rj is not None:+ self.raw_jobs.remove(rj)+ self.removed.add(str(job_id))+ self.needs_save = True+++def _normalize_due_scan_records(raw_jobs: List[Dict[str, Any]]) -> bool:+ """Repair malformed store records in place BEFORE the due scan keys off them.++ A missing ``id`` (older writers used ``job_id``), non-dict ``schedule``, or non-ISO timestamp+ used to raise mid-tick and abort the whole scan before save_jobs(), freezing the scheduler in a+ fast-forward loop. Recover/synthesize the id, reset a bad schedule to ``{}``, and strip bad+ timestamps so the "no next_run_at" path recomputes. Returns True when anything changed.+ """+ changed = Falsefor rj in raw_jobs:if not rj.get("id"):rj["id"] = rj.pop("job_id", None) or uuid.uuid4().hex[:12]- needs_save = True+ changed = True+ if not isinstance(rj.get("schedule"), dict):+ rj["schedule"] = {}+ changed = True+ for key in ("next_run_at", "last_run_at"):+ value = rj.get(key)+ if value is not None and _parse_aware(value) is None:+ rj.pop(key, None)+ changed = True+ return changed+++def _self_disable_half_paused(job: Dict[str, Any], scan: _DueScan) -> None:+ """Self-heal enabled=true with pause markers: the operator believes the job is frozen while the+ scheduler would still fire it. Force enabled=false so listings are honest; logged loudly since+ pause_job now sets both fields atomically, so this should be rare."""+ jid = job.get("id")+ logger.error(+ "Job '%s' (%s) has pause markers while enabled=true; "+ "self-disabling so it cannot fire (pause must be authoritative).",+ job.get("name", jid),+ jid,+ )+ rj = scan.find(jid)+ if rj is None:+ return+ rj["enabled"] = False+ rj["state"] = "paused"+ if not rj.get("paused_at"):+ rj["paused_at"] = scan.now.isoformat()+ if not rj.get("paused_reason"):+ rj["paused_reason"] = "auto-disabled: enabled+paused contradiction"+ scan.needs_save = True+++def _recover_missing_next_run(job: Dict[str, Any], scan: _DueScan) -> Optional[str]:+ """Recompute and persist a missing ``next_run_at``; None when unrecoverable. One-shots use the+ grace window; recurring jobs only get here after a direct jobs.json edit bypassed add_job(),+ and would otherwise be silently skipped forever."""+ schedule = job.get("schedule", {})+ kind = schedule.get("kind")+ recovered_next = _recoverable_oneshot_run_at(+ schedule, scan.now, last_run_at=job.get("last_run_at")+ )+ recovery_kind = "one-shot" if recovered_next else None+ if not recovered_next and kind in {"cron", "interval"}:+ recovered_next = compute_next_run(schedule, scan.now.isoformat())+ if recovered_next:+ recovery_kind = kind+ if not recovered_next:+ return None+ job["next_run_at"] = recovered_next+ logger.info(+ "Job '%s' had no next_run_at; recovering %s run at %s",+ job.get("name", job.get("id", "?")),+ recovery_kind,+ recovered_next,+ )+ scan.persist(job["id"], next_run_at=recovered_next)+ return recovered_next+++def _repair_timezone_shifted_cron(+ job: Dict[str, Any],+ schedule: Dict[str, Any],+ raw_next_run_dt: datetime,+ next_run_dt: datetime,+ scan: _DueScan,+) -> bool:+ """Repair a cron job whose stored offset no longer matches now's (TZ migration).++ next_run_at is an absolute instant but the expr means local wall clock, so a TZ change can make+ it look due hours early. If the stored wall clock is still in the future, recompute so we fire+ at the intended local time. True when re-anchored (caller skips this tick). TRADE-OFF: a DST+ offset change meeting the same conditions SKIPS the pending occurrence; accepted as rare.+ """+ if not (+ next_run_dt <= scan.now+ and _timezone_offset_mismatch(raw_next_run_dt, scan.now)+ and _stored_wall_clock_is_future(raw_next_run_dt, scan.now)+ ):+ return False+ new_next = compute_next_run(schedule, scan.now.isoformat())+ if not new_next:+ return False+ logger.info(+ "Job '%s' next_run_at offset changed (%s -> %s). "+ "Recomputing cron run to preserve local wall-clock intent: %s",+ job.get("name", job.get("id", "?")),+ raw_next_run_dt.utcoffset(),+ scan.now.utcoffset(),+ new_next,+ )+ scan.persist(job["id"], next_run_at=new_next)+ return True+++def _rearm_stale_error_recurring(+ job: Dict[str, Any],+ schedule: Dict[str, Any],+ kind: Optional[str],+ next_run: str,+ next_run_dt: datetime,+ scan: _DueScan,+) -> datetime:+ """Re-arm a recurring job wedged in persisted last_status=error; returns the effective next_run_dt.++ Such a job errored, mark_job_run parked next_run_at in the future, and nothing re-dispatched it+ (the in-memory stale-claim sweep cannot see it). Interval jobs re-arm to now (always a legal+ fire); cron jobs re-arm to the next LEGAL occurrence, since re-arming to now would fire at times+ the expression excludes. A correctly-parked cron value is left as-is.+ """+ if not (+ kind in ("cron", "interval")+ and next_run_dt > scan.now+ and _job_is_stale_error_recurring(job, schedule, scan.now)+ ):+ return next_run_dt+ jid = job.get("id")+ if kind == "interval":+ recovered_next = scan.now.isoformat()+ recovered_next_dt: Optional[datetime] = scan.now+ else:+ recovered_next = compute_next_run(schedule, scan.now.isoformat())+ recovered_next_dt = _parse_aware(recovered_next) if recovered_next else None+ if not (recovered_next and recovered_next_dt is not None and recovered_next_dt < next_run_dt):+ return next_run_dt+ logger.warning(+ "cron.persisted_error.recovered job='%s' id=%s — recurring "+ "job wedged in stale last_status=error without re-firing for "+ "a full cadence; re-arming next_run_at to %s so it "+ "re-dispatches without force-run/resume",+ job.get("name", jid),+ jid,+ recovered_next,+ )+ _record_persisted_error_recovery(job, next_run)+ job["next_run_at"] = recovered_next+ scan.persist(jid, next_run_at=recovered_next)+ return recovered_next_dt+++def _reanchor_stale_cron(+ job: Dict[str, Any],+ schedule: Dict[str, Any],+ next_run: str,+ raw_next_run_dt: datetime,+ next_run_dt: datetime,+ scan: _DueScan,+) -> bool:+ """Stale-schedule guard for a due cron instant; True when re-anchored without firing.++ A direct edit of schedule.expr leaves next_run_at on the old lattice, so re-anchor first (from+ the current expr, so this converges). An offset-representation migration also moves a legacy+ instant off the lattice, and re-anchoring THAT swallowed a due occurrence — so classify, and let+ the migration case fall through to fire ONCE (at-most-once holds: nothing re-reads the legacy+ instant after advance/mark_job_run rewrites it).+ """+ stale_class = _classify_stale_cron_next_run(schedule, raw_next_run_dt, next_run_dt)+ if stale_class == STALE_CRON_EXPR_EDIT:+ new_next = compute_next_run(schedule, scan.now.isoformat())+ logger.info(+ "Job '%s' next_run_at %s does not match its current "+ "cron expression %r (direct jobs.json edit?); "+ "re-anchoring to %s without firing.",+ job.get("name", job.get("id", "?")),+ next_run,+ schedule.get("expr"),+ new_next,+ )+ if new_next:+ scan.persist(job["id"], next_run_at=new_next)+ return True+ if stale_class == STALE_CRON_TIMEZONE_MIGRATION:+ logger.warning(+ "cron.timezone_migration.catch_up job='%s' id=%s expr=%r "+ "stored=%s normalized=%s — stored next_run_at carries a "+ "pre-migration UTC offset (%s, now %s) and is a legal "+ "occurrence at its own wall clock; firing the due run "+ "instead of re-anchoring past it.",+ job.get("name", job.get("id", "?")),+ job.get("id"),+ schedule.get("expr"),+ next_run,+ next_run_dt.isoformat(),+ raw_next_run_dt.utcoffset(),+ scan.now.utcoffset(),+ )+ _record_timezone_migration_catchup(job, raw_next_run_dt, next_run_dt)+ return False+++def _fast_forward_missed_recurring(+ job: Dict[str, Any],+ schedule: Dict[str, Any],+ next_run: str,+ next_run_dt: datetime,+ grace: int,+ scan: _DueScan,+) -> None:+ """Recurring job past its grace window: skip the accumulated misses, fire once now.++ The fast-forward is persisted immediately — NOT redundant with advance_next_run/mark_job_run:+ it protects the crash window before mark_job_run and covers the external fire_due path, which+ never calls advance_next_run. mark_job_run re-anchors on completion, so the value is provisional.+ """+ if (scan.now - next_run_dt).total_seconds() <= grace:+ return+ new_next = compute_next_run(schedule, scan.now.isoformat())+ if not new_next:+ return+ logger.info(+ "Job '%s' missed its scheduled time (%s, grace=%ds). "+ "Running now; next run provisionally set to: %s "+ "(re-anchored on completion)",+ job.get("name", job.get("id", "?")),+ next_run,+ grace,+ new_next,+ )+ scan.persist(job["id"], next_run_at=new_next)+ record_catch_up_occurrence()+++def _retire_expired_oneshot(+ job: Dict[str, Any], next_run: str, next_run_dt: datetime, scan: _DueScan+) -> bool:+ """One-shot grace gate; True when the job must not fire this tick.++ A one-shot beyond the grace window must never fire (create/update/resume reject such schedules+ and recovery never revives them; only the due scan used to dispatch them hours late). With no+ claim stamped, retire it with a diagnostic (never silently delete). A claim may mean a run is+ still in flight elsewhere — skip but keep the record so its mark_job_run can land.+ """+ if (scan.now - next_run_dt).total_seconds() <= ONESHOT_GRACE_SECONDS:+ return False+ if not (job.get("run_claim") or job.get("fire_claim")):+ _write_missed_oneshot_diagnostic(job, next_run)+ scan.retire(job["id"])+ return True+++def _oneshot_dispatch_limit_reached(job: Dict[str, Any], scan: _DueScan) -> bool:+ """One-shot dispatch-limit guard; True when the job must not fire this tick.++ A finite one-shot claimed via claim_dispatch() whose tick died before mark_job_run has+ completed >= times while still looking due. Remove it instead of re-firing — unless THIS+ process is still running it (a run outliving the run_claim TTL is slow, not stale).+ """+ repeat = job.get("repeat") or {}+ times = repeat.get("times")+ completed = repeat.get("completed", 0)+ if times is None or times <= 0 or completed < times:+ return False+ name = job.get("name", job.get("id", "?"))+ if _job_running_in_this_process(job.get("id", "")):+ logger.info(+ "Job '%s': dispatch limit reached (%d/%d) but its run is still in flight in this "+ "process — keeping entry",+ name, completed, times,+ )+ return True+ if job.get("last_run_at") is not None:+ # A record with last_run_at completed a real run and was re-armed without a budget reset+ # (old build or hand edit) — not the dead-tick case; warn so the removal leaves a trace.+ logger.warning(+ "Job '%s': one-shot dispatch limit reached (%d/%d) on a record that already completed "+ "a run (last_run_at=%s) — removing it WITHOUT firing. This record was re-armed "+ "without a budget reset (pre-#93615 store or hand edit); re-run it with "+ "'hermes cron resume <job> --run-now' (#93524).",+ name, completed, times, job.get("last_run_at"),+ )+ else:+ logger.info(+ "Job '%s': one-shot dispatch limit reached (%d/%d) — removing stale due entry",+ name, completed, times,+ )+ scan.retire(job["id"])+ # The claimed run never completed here by definition — leave an operator-visible diagnostic.+ _write_wedged_oneshot_diagnostic(job)+ return True+++def _evaluate_due_job(job: Dict[str, Any], scan: _DueScan, run_claim_ttl: float) -> bool:+ """Decide whether one enabled, non-terminal job fires this tick, persisting any repairs.+ Ordering matters: recover missing next_run_at, repair timezone shifts, re-arm stale-error+ recurring jobs, then once due: re-anchor stale cron instants, fast-forward missed recurring+ runs, retire/guard one-shots, and finally stamp the run claim / dispatch record."""+ now = scan.now+ # Cross-process guard: another process's live one-shot run_claim (younger than TTL) — do NOT+ # re-dispatch. Malformed/future-dated claims (clock/TZ skew) count as stale, never eternally fresh.+ if job.get("schedule", {}).get("kind") == "once" and _claim_is_live(job.get("run_claim"), now, run_claim_ttl):+ return False++ next_run = job.get("next_run_at") or _recover_missing_next_run(job, scan)+ if not next_run:+ return False+ raw_next_run_dt = datetime.fromisoformat(next_run)+ schedule = job.get("schedule", {})+ kind = schedule.get("kind")+ next_run_dt = _ensure_aware(raw_next_run_dt)+ # Intentionally string-exact on raw stored values: trigger_job stamps the SAME isoformat string+ # into both fields, and any rewrite of next_run_at (edit, re-anchor, fire-claim advance) must+ # invalidate the marker. Do not "fix" this with _ensure_aware normalization.+ manual_run = job.get("manual_run_at") == next_run+ if (+ kind == "cron"+ and not manual_run+ and _repair_timezone_shifted_cron(job, schedule, raw_next_run_dt, next_run_dt, scan)+ ):+ return False+ next_run_dt = _rearm_stale_error_recurring(job, schedule, kind, next_run, next_run_dt, scan)+ if next_run_dt > now:+ return False++ if (+ not manual_run+ and kind == "cron"+ and _reanchor_stale_cron(job, schedule, next_run, raw_next_run_dt, next_run_dt, scan)+ ):+ return False+ grace = _compute_grace_seconds(schedule)+ if not manual_run and kind in {"cron", "interval"}:+ _fast_forward_missed_recurring(job, schedule, next_run, next_run_dt, grace, scan)+ if kind == "once":+ if _retire_expired_oneshot(job, next_run, next_run_dt, scan):+ return False+ if _oneshot_dispatch_limit_reached(job, scan):+ return False+ # Durably claim the one-shot for the DURATION of its run: a second scheduler process on the+ # same HERMES_HOME must not re-dispatch it while in flight, and advancing next_run_at by a+ # fixed window is not enough for a run that outlives a tick. The other process sees the+ # fresh claim and skips; mark_job_run() clears it. The TTL only covers a tick that DIES.+ claim = {"at": now.isoformat(), "by": _machine_id()}+ job["run_claim"] = claim+ scan.persist(job["id"], run_claim=claim)++ # Missed-run visibility: persist scheduled-vs-actual timing so separate CLI processes can show+ # a late catch-up. Recurring only — expired one-shots were retired above; manual triggers aren't late.+ if not manual_run and kind in {"cron", "interval"}:+ lateness = max(0.0, (now - next_run_dt).total_seconds())+ dispatch_stamp = {+ "scheduled_at": next_run,+ "dispatched_at": now.isoformat(),+ "lateness_seconds": round(lateness, 1),+ "kind": _classify_dispatch_lateness(lateness, grace),+ }+ job["last_dispatch"] = dispatch_stamp+ scan.persist(job["id"], last_dispatch=dispatch_stamp)+ return True+++def _get_due_jobs_locked() -> List[Dict[str, Any]]:+ """Inner implementation of get_due_jobs(); must be called with _jobs_lock held."""+ raw_jobs = load_jobs()+ scan = _DueScan(raw_jobs, _hermes_now())+ scan.needs_save = _normalize_due_scan_records(raw_jobs)jobs = [_apply_skill_fields(j) for j in copy.deepcopy(raw_jobs)]- due = []- # Normalize malformed "schedule" records (direct jobs.json edit, old writers,- # corruption, etc.). "schedule" must be a dict; a null/string/etc. value- # makes `schedule.get("kind")` or direct `schedule["kind"]` / ["expr"] /- # ["minutes"] later raise and abort the entire scan *before* save_jobs().- # Healthy jobs then lose their fast-forwarded next_run_at (exactly the- # failure mode of the id-less job bug fixed above). Repair early at the- # source so the rest of the tick can proceed and persist progress for- # siblings.- for j in jobs:- if not isinstance(j.get("schedule"), dict):- j["schedule"] = {}- needs_save = True- for rj in raw_jobs:- if not isinstance(rj.get("schedule"), dict):- rj["schedule"] = {}- needs_save = True-- # Normalize malformed "next_run_at" records (direct jobs.json edit,- # corruption, migration, or buggy writer). If present but not a valid- # ISO string, datetime.fromisoformat(next_run) later raises and aborts- # the entire scan *before* save_jobs(). Healthy siblings then lose any- # fast-forwarded next_run_at (same class of bug as bad "id" or "schedule").- # Strip the bad value so the existing "no next_run_at" recovery path- # recomputes a sane value and persists it for this job.- for j in jobs:- nr = j.get("next_run_at")- if nr is not None:- if not isinstance(nr, str):- j.pop("next_run_at", None)- needs_save = True- else:- try:- datetime.fromisoformat(nr)- except Exception:- j.pop("next_run_at", None)- needs_save = True- for rj in raw_jobs:- nr = rj.get("next_run_at")- if nr is not None:- if not isinstance(nr, str):- rj.pop("next_run_at", None)- needs_save = True- else:- try:- datetime.fromisoformat(nr)- except Exception:- rj.pop("next_run_at", None)- needs_save = True-- # Same treatment for last_run_at (used as base in recovery / compute_next_run).- for j in jobs:- lr = j.get("last_run_at")- if lr is not None and not isinstance(lr, str):- j.pop("last_run_at", None)- needs_save = True- elif isinstance(lr, str):- try:- datetime.fromisoformat(lr)- except Exception:- j.pop("last_run_at", None)- needs_save = True- for rj in raw_jobs:- lr = rj.get("last_run_at")- if lr is not None and not isinstance(lr, str):- rj.pop("last_run_at", None)- needs_save = True- elif isinstance(lr, str):- try:- datetime.fromisoformat(lr)- except Exception:- rj.pop("last_run_at", None)- needs_save = True-- # Resolve the one-shot running-claim stale-recovery TTL once per scan- # (derived from HERMES_CRON_TIMEOUT). See _oneshot_run_claim_ttl_seconds.- _run_claim_ttl = _oneshot_run_claim_ttl_seconds()-- # Retention sweep: completed one-shots are retained (so their final- # status / delivery error stay inspectable via `cronjob list`) instead of- # being deleted on completion, but they must not accumulate in jobs.json- # forever. Prune terminal one-shot records older than the retention- # window each scan.- if _sweep_completed_oneshots(raw_jobs, now, removed_ids=intentionally_removed):- needs_save = True- jobs = [j for j in jobs if any(rj.get("id") == j.get("id") for rj in raw_jobs)]+ # One-shot run-claim TTL, resolved once per scan (see _oneshot_run_claim_ttl_seconds).+ run_claim_ttl = _oneshot_run_claim_ttl_seconds()+ # Retention sweep: completed one-shots are kept for inspection but must not accumulate forever.+ if _sweep_completed_oneshots(raw_jobs, scan.now, removed_ids=scan.removed):+ scan.needs_save = True+ jobs = [j for j in jobs if scan.find(j.get("id")) is not None]++ due = []for job in jobs:- # Per-job containment (structural guard): one malformed or- # unexpected job record must never abort the whole scan. The id /- # schedule / timestamp normalizations above repair the known shapes;- # this guard catches every FUTURE variant, degrading to "skip this- # job this tick" so healthy siblings still run and their recovered- # state still reaches save_jobs() below.+ # Per-job containment: one malformed record must never abort the whole scan. Normalization+ # above repairs known shapes; this catches FUTURE variants so healthy siblings still run/persist.try:if is_terminal_job(job) and not _is_recoverable_error_job(job):continueif not job.get("enabled", True):continue-- # Contradiction self-heal: enabled=true with pause markers means the- # operator believes the job is frozen while the scheduler would still- # fire it (07-30 outage). Refuse to run and force enabled=false so- # the next list/report is honest. Log loudly — this should be rare- # after pause_job sets both fields atomically.if _has_pause_marker(job):- jid = job.get("id")- logger.error(- "Job '%s' (%s) has pause markers while enabled=true; "- "self-disabling so it cannot fire (pause must be authoritative).",- job.get("name", jid),- jid,- )- for rj in raw_jobs:- if rj.get("id") != jid:- continue- rj["enabled"] = False- rj["state"] = "paused"- if not rj.get("paused_at"):- rj["paused_at"] = now.isoformat()- if not rj.get("paused_reason"):- rj["paused_reason"] = (- "auto-disabled: enabled+paused contradiction"- )- needs_save = True- break+ _self_disable_half_paused(job, scan)continue-- # Cross-process running-claim guard (#59229): if another scheduler- # process already claimed this one-shot and its run is still in flight- # (claim younger than the TTL), skip it — do NOT re-dispatch. The- # claim is stamped just before we return the job as due (below) and- # cleared by mark_job_run() on completion. A claim older than the TTL- # is treated as stale (the claiming tick died mid-run) and allowed- # through so the job is recovered rather than wedged forever.- existing_claim = job.get("run_claim")- if existing_claim and job.get("schedule", {}).get("kind") == "once":- try:- claimed_at = _ensure_aware(- datetime.fromisoformat(existing_claim["at"])- )- # 0 <= age: a future-dated claim (clock/TZ skew across a- # restart) must be treated as stale, not eternally fresh,- # or the one-shot is skipped forever (#60703).- _age = (now - claimed_at).total_seconds()- if 0 <= _age < _run_claim_ttl:- continue # a fresh claim is held by an in-flight run- except (KeyError, ValueError, TypeError):- pass # malformed claim → fall through and (re)claim-- next_run = job.get("next_run_at")- if not next_run:- schedule = job.get("schedule", {})- kind = schedule.get("kind")-- # One-shot jobs use a small grace window via the dedicated helper.- recovered_next = _recoverable_oneshot_run_at(- schedule,- now,- last_run_at=job.get("last_run_at"),- )- recovery_kind = "one-shot" if recovered_next else None-- # Recurring jobs reach here only when something — typically a- # direct jobs.json edit that bypassed add_job() — left- # next_run_at unset. Without this branch, such jobs are- # silently skipped forever; recompute next_run_at from the- # schedule so they pick up at their next scheduled tick.- if not recovered_next and kind in {"cron", "interval"}:- recovered_next = compute_next_run(schedule, now.isoformat())- if recovered_next:- recovery_kind = kind-- if not recovered_next:- continue-- job["next_run_at"] = recovered_next- next_run = recovered_next- logger.info(- "Job '%s' had no next_run_at; recovering %s run at %s",- job.get("name", job.get("id", "?")),- recovery_kind,- recovered_next,- )- for rj in raw_jobs:- if rj["id"] == job["id"]:- rj["next_run_at"] = recovered_next- needs_save = True- break-- raw_next_run_dt = datetime.fromisoformat(next_run)- schedule = job.get("schedule", {})- kind = schedule.get("kind")-- next_run_dt = _ensure_aware(raw_next_run_dt)- # Intentionally string-exact (raw stored values, not normalized- # datetimes): trigger_job stamps the SAME isoformat string into- # both fields, and any rewrite of next_run_at (schedule edit,- # recovery re-anchor, fire-claim advance) must invalidate the- # marker. Do not "fix" this with _ensure_aware normalization.- manual_run = job.get("manual_run_at") == next_run- # Migration repair: a cron job persists next_run_at as an absolute- # instant, but the cron expr describes local wall-clock intent. If the- # configured/system timezone changed after persistence, the stored- # instant's offset no longer matches now's, and its converted time can- # look due hours early (21:00+10 -> 13:00+02). When the stored *wall- # clock* is still in the future, recompute from the schedule so we fire- # at the intended local time instead of early-then-again.- #- # TRADE-OFF: this cannot distinguish a config/host TZ migration from a- # legitimate DST offset change. A DST boundary that satisfies all four- # conditions will recompute (and thus SKIP the pending occurrence, no- # catch-up) rather than fire it. Accepted: in the pure-migration case- # the recompute lands on the same wall-clock time later the same period,- # and DST-boundary collisions with a still-future stored wall clock are- # rare relative to the double-fire bug this prevents (#28934).- if (- kind == "cron"- and not manual_run- and next_run_dt <= now- and _timezone_offset_mismatch(raw_next_run_dt, now)- and _stored_wall_clock_is_future(raw_next_run_dt, now)- ):- new_next = compute_next_run(schedule, now.isoformat())- if new_next:- logger.info(- "Job '%s' next_run_at offset changed (%s -> %s). "- "Recomputing cron run to preserve local wall-clock intent: %s",- job.get("name", job.get("id", "?")),- raw_next_run_dt.utcoffset(),- now.utcoffset(),- new_next,- )- for rj in raw_jobs:- if rj["id"] == job["id"]:- rj["next_run_at"] = new_next- needs_save = True- break- continue-- # Persisted-state stale-error recovery (t_8b5480b3): a recurring- # job whose persisted state shows last_status=error and whose- # last_run_at is older than a full cadence has been sitting wedged- # (errored once, next_run_at re-armed into the future by- # mark_job_run, but never re-dispatched — the restart-surviving- # half of the 2026-08-14 incident, invisible to the in-memory- # in-flight sweep). Re-arm so the job re-dispatches WITHOUT- # force-run/resume:- # * interval jobs re-arm to now — interval schedules have no- # excluded times, so an immediate catch-up retry is always a- # legal fire (the 2026-08-14 incident jobs were intervals);- # * cron jobs re-arm to the next LEGAL occurrence from now —- # re-arming to now would fire at times the expression- # explicitly excludes (e.g. a weekday-only 9am job whose- # Friday run errored must fire Monday 9am, not Saturday).- # This still repairs values parked beyond the next legal- # occurrence; a correctly-parked cron value is left as-is.- if (- kind in ("cron", "interval")- and next_run_dt > now- and _job_is_stale_error_recurring(job, schedule, now)- ):- jid = job.get("id")- if kind == "interval":- recovered_next = now.isoformat()- recovered_next_dt = now- else:- recovered_next = compute_next_run(schedule, now.isoformat())- try:- recovered_next_dt = (- _ensure_aware(datetime.fromisoformat(recovered_next))- if recovered_next- else None- )- except (ValueError, TypeError):- recovered_next_dt = None- if recovered_next and recovered_next_dt is not None and recovered_next_dt < next_run_dt:- logger.warning(- "cron.persisted_error.recovered job='%s' id=%s — recurring "- "job wedged in stale last_status=error without re-firing for "- "a full cadence; re-arming next_run_at to %s so it "- "re-dispatches without force-run/resume",- job.get("name", jid),- jid,- recovered_next,- )- _record_persisted_error_recovery(job, next_run)- job["next_run_at"] = recovered_next- next_run_dt = recovered_next_dt- for rj in raw_jobs:- if rj["id"] == jid:- rj["next_run_at"] = recovered_next- needs_save = True- break-- if next_run_dt <= now:-- # Stale-schedule guard (#93049): a direct jobs.json edit that- # changed schedule.expr leaves next_run_at computed under the- # old expression, so the job would fire at an instant the- # current expression excludes. Both the within-grace fire and- # the catch-up "run once now" below inherit that wrong instant,- # so re-anchor before either can fire. Recomputation uses the- # current expression, so this converges — it cannot defer- # forever.- #- # Not every mismatch is an edit, though: an offset-representation- # migration (UTC-scheduling build -> profile-timezone build)- # moves a legacy instant off the lattice without the expression- # ever changing, and re-anchoring THAT silently swallowed a due- # occurrence. Classify first, and only the edit case skips.- stale_class = (- _classify_stale_cron_next_run(schedule, raw_next_run_dt, next_run_dt)- if not manual_run and kind == "cron"- else STALE_CRON_MATCH- )- if stale_class == STALE_CRON_EXPR_EDIT:- new_next = compute_next_run(schedule, now.isoformat())- logger.info(- "Job '%s' next_run_at %s does not match its current "- "cron expression %r (direct jobs.json edit?); "- "re-anchoring to %s without firing.",- job.get("name", job.get("id", "?")),- next_run,- schedule.get("expr"),- new_next,- )- if new_next:- for rj in raw_jobs:- if rj["id"] == job["id"]:- rj["next_run_at"] = new_next- needs_save = True- break- continue- if stale_class == STALE_CRON_TIMEZONE_MIGRATION:- # Fall through to the normal due path: the occurrence is- # real and overdue, so it fires ONCE here and the usual- # advance/mark_job_run re-anchor writes the value back in- # the current offset. At-most-once is preserved because- # nothing re-reads the legacy instant after that.- logger.warning(- "cron.timezone_migration.catch_up job='%s' id=%s expr=%r "- "stored=%s normalized=%s — stored next_run_at carries a "- "pre-migration UTC offset (%s, now %s) and is a legal "- "occurrence at its own wall clock; firing the due run "- "instead of re-anchoring past it.",- job.get("name", job.get("id", "?")),- job.get("id"),- schedule.get("expr"),- next_run,- next_run_dt.isoformat(),- raw_next_run_dt.utcoffset(),- now.utcoffset(),- )- _record_timezone_migration_catchup(job, raw_next_run_dt, next_run_dt)-- # For recurring jobs, check if the scheduled time is stale- # (gateway was down and missed the window). Fast-forward to- # the next future occurrence instead of firing a stale run.- grace = _compute_grace_seconds(schedule)- if (- not manual_run- and kind in {"cron", "interval"}- and (now - next_run_dt).total_seconds() > grace- ):- # Job is past its catch-up grace window — skip accumulated- # missed runs but still execute once now to avoid deferring- # indefinitely (e.g. a long-running job just finished).- new_next = compute_next_run(schedule, now.isoformat())- if new_next:- logger.info(- "Job '%s' missed its scheduled time (%s, grace=%ds). "- "Running now; next run provisionally set to: %s "- "(re-anchored on completion)",- job.get("name", job.get("id", "?")),- next_run,- grace,- new_next,- )- # Persist the fast-forward to storage now (skip accumulated- # slots). In the built-in ticker path this is shortly- # overwritten by advance_next_run + mark_job_run, but it is- # NOT redundant: it (a) protects the crash window between- # here and mark_job_run, and (b) covers the external- # fire_due provider path, which does not call- # advance_next_run. mark_job_run re-anchors next_run_at off- # the actual completion time, so this value is provisional.- for rj in raw_jobs:- if rj["id"] == job["id"]:- rj["next_run_at"] = new_next- needs_save = True- break- record_catch_up_occurrence()- # Fall through to due.append(job) — execute once now-- # One-shot grace gate: a one-shot whose persisted run time is- # beyond the grace window must never fire. create_job /- # update_job / resume_job all reject such schedules ("will- # never fire") and _recoverable_oneshot_run_at never recovers- # them — only the due-scan acted differently and dispatched a- # wall-clock one-shot hours late (gateway down past the- # window, host asleep, hand-edited jobs.json).- if kind == "once" and (now - next_run_dt).total_seconds() > ONESHOT_GRACE_SECONDS:- if not (job.get("run_claim") or job.get("fire_claim")):- # Nothing was ever dispatched — retire the record with- # a diagnostic so it stops being scanned and the miss- # is operator-visible (retire-not-silently-delete).- _write_missed_oneshot_diagnostic(job, next_run)- for rj in raw_jobs:- if rj["id"] == job["id"]:- raw_jobs.remove(rj)- intentionally_removed.add(str(job["id"]))- needs_save = True- break- # A (possibly stale) claim may mean a run is still in- # flight in another process — skip this scan but keep the- # record so its mark_job_run can still land.- continue-- # One-shot dispatch-limit guard (issue #38758): a finite one-shot- # claimed via claim_dispatch() but whose tick died before- # mark_job_run could remove it will have completed >= times while- # still looking due (last_run_at was never written, so the- # recovery helper re-armed it). Remove it instead of re-firing.- if kind == "once":- repeat = job.get("repeat")- if repeat:- times = repeat.get("times")- completed = repeat.get("completed", 0)- if times is not None and times > 0 and completed >= times:- # A live run must never have its job record deleted- # underneath it (#62002): a run that outlives the- # run_claim TTL (stream stall, laptop asleep- # mid-run) satisfies the same completed >= times +- # expired-claim condition as a dead tick, but- # mark_job_run() still needs the record to land- # last_run_at / last_status / last_delivery_error.- # If this process is still running the job, it is- # slow, not stale — keep the entry and skip.- if _job_running_in_this_process(job.get("id", "")):- logger.info(- "Job '%s': dispatch limit reached (%d/%d) "- "but its run is still in flight in this "- "process — keeping entry",- job.get("name", job.get("id", "?")),- completed,- times,- )- continue- if job.get("last_run_at") is not None:- # A record with last_run_at completed a real- # run and was later re-armed without a budget- # reset (e.g. a schedule edit before the- # #93524 fix, or a hand-edited store). This is- # NOT the dead-tick recovery case this guard- # was built for, and the wedged-oneshot- # diagnostic below will (correctly) not fire- # — so removing it silently at INFO would- # vanish the user's rescheduled run without a- # trace. Make it operator-visible.- logger.warning(- "Job '%s': one-shot dispatch limit reached "- "(%d/%d) on a record that already completed "- "a run (last_run_at=%s) — removing it "- "WITHOUT firing. This record was re-armed "- "without a budget reset (pre-#93615 store "- "or hand edit); re-run it with "- "'hermes cron resume <job> --run-now' "- "(#93524).",- job.get("name", job.get("id", "?")),- completed,- times,- job.get("last_run_at"),- )- else:- logger.info(- "Job '%s': one-shot dispatch limit reached (%d/%d) "- "— removing stale due entry",- job.get("name", job.get("id", "?")),- completed,- times,- )- for rj in raw_jobs:- if rj["id"] == job["id"]:- raw_jobs.remove(rj)- intentionally_removed.add(str(rj["id"]))- needs_save = True- break- # The claimed run never completed here by- # definition (last_run_at unwritten is what made- # the entry look due) — leave an operator-visible- # diagnostic instead of vanishing silently (#73973).- _write_wedged_oneshot_diagnostic(job)- continue-- # Durably claim a one-shot for the DURATION of its run before- # returning it as due, so a second scheduler process (gateway +- # desktop both run in-process 60s tickers on one HERMES_HOME)- # cannot re-dispatch it while the first run is still in flight- # (#59229). A plain one-shot's due-state is not resolved until- # mark_job_run() completes it minutes later, so advancing- # next_run_at by a fixed window is not enough — a job that outlives- # one tick (e.g. a 2.5-min research prompt) would simply re-fire on- # the next tick after the window. Instead we stamp a run_claim under- # the same lock get_due_jobs already holds; the other process reads- # a fresh claim on its next tick and skips (handled at the top of- # this loop). mark_job_run() clears the claim on completion. The TTL- # is only a safety valve: a claiming tick that DIES mid-run leaves a- # stale claim that expires after the resolved run-claim TTL- # (_oneshot_run_claim_ttl_seconds, derived from HERMES_CRON_TIMEOUT),- # so the job is re-dispatched rather than wedged forever.- if kind == "once":- claim = {"at": now.isoformat(), "by": _machine_id()}- job["run_claim"] = claim- for rj in raw_jobs:- if rj["id"] == job["id"]:- rj["run_claim"] = claim- needs_save = True- break-- # Missed-run visibility (#99879): persist scheduled-vs-actual- # dispatch timing on the job record so `hermes cron list` /- # `hermes cron status` (separate CLI processes) can show a- # late catch-up run as such instead of an ordinary on-time- # run. Recurring schedules only — one-shots beyond grace are- # retired above, and manual triggers have no scheduled- # instant to be late against.- if not manual_run and kind in {"cron", "interval"}:- lateness = max(0.0, (now - next_run_dt).total_seconds())- dispatch_stamp = {- "scheduled_at": next_run,- "dispatched_at": now.isoformat(),- "lateness_seconds": round(lateness, 1),- "kind": _classify_dispatch_lateness(lateness, grace),- }- job["last_dispatch"] = dispatch_stamp- for rj in raw_jobs:- if rj["id"] == job["id"]:- rj["last_dispatch"] = dispatch_stamp- needs_save = True- break-+ if _evaluate_due_job(job, scan, run_claim_ttl):due.append(job)except Exception:logger.exception(@@ -4410,40 +3185,24 @@ def _get_due_jobs_locked() -> List[Dict[str, Any]]:)continue- if needs_save:- save_jobs(raw_jobs, removed_ids=intentionally_removed or None)+ if scan.needs_save:+ save_jobs(raw_jobs, removed_ids=scan.removed or None)return due---# Per-run cron output (`cron/output/<job>/<timestamp>.md`) is written once per-# execution. Unlike the quick-snapshot store (`hermes_cli.backup`, capped at 20)-# it had no retention, so a frequently-scheduled job on a long-running deploy-# accumulated one file per run forever and could fill the disk (#52383). Keep the-# most recent N files per job; a non-positive value disables pruning (opt-out).+# Per-run output files (`cron/output/<job>/<timestamp>.md`) had no retention cap, so a frequent+# job could fill the disk over time._CRON_OUTPUT_DEFAULT_KEEP = 50def _cron_output_keep() -> int:- """Resolve the per-job output-file retention cap from config (``cron.output_retention``)."""- try:- from hermes_cli.config import load_config- cfg = load_config() or {}- cron_cfg = cfg.get("cron", {}) if isinstance(cfg, dict) else {}- return int(cron_cfg.get("output_retention", _CRON_OUTPUT_DEFAULT_KEEP))- except Exception:- return _CRON_OUTPUT_DEFAULT_KEEP+ """Per-job output-file retention cap (``cron.output_retention``)."""+ return _cron_config_number("output_retention", _CRON_OUTPUT_DEFAULT_KEEP, int)def _prune_job_output(job_output_dir: Path, keep: int) -> int:- """Remove the oldest ``*.md`` run-output files beyond *keep*. Returns count deleted.-- Mirrors the quick-snapshot retention in ``hermes_cli.backup._prune_quick_snapshots``:- output filenames are timestamp-based (``%Y-%m-%d_%H-%M-%S.md``) so a reverse- lexical sort orders newest-first, and everything past *keep* is the tail to- drop. A non-positive *keep* disables pruning. Pruning failures are swallowed- so they can never break output saving.- """+ """Remove the oldest ``*.md`` run-output files beyond *keep*; returns count deleted. Filenames+ are timestamps, so a reverse lexical sort is newest-first. Non-positive *keep* disables pruning;+ failures are swallowed so they can never break output saving."""if keep <= 0:return 0try:@@ -4473,45 +3232,22 @@ def save_job_output(job_id: str, output: str):timestamp = _hermes_now().strftime("%Y-%m-%d_%H-%M-%S")output_file = job_output_dir / f"{timestamp}.md"+ atomic_write_text(output_file, output, tmp_prefix=".output_")+ _secure_file(output_file)- fd, tmp_path = tempfile.mkstemp(dir=str(job_output_dir), suffix='.tmp', prefix='.output_')- try:- with os.fdopen(fd, 'w', encoding='utf-8') as f:- f.write(output)- f.flush()- os.fsync(f.fileno())- atomic_replace(tmp_path, output_file)- _secure_file(output_file)- except BaseException:- try:- os.unlink(tmp_path)- except OSError:- pass- raise-- # Bound per-job output growth so long-running deploys don't fill the disk (#52383).+ # Bound per-job output growth so long-running deploys don't fill the disk._prune_job_output(job_output_dir, _cron_output_keep())return output_file-# =============================================================================-# Skill reference rewriting (curator integration)-# =============================================================================+# --- Skill reference rewriting (curator integration) ---def _canonical_skill_ref(raw: Any) -> str:- """Reduce one job skill reference to the bare name the curator matches on.-- A job may store an absolute path under ``HERMES_HOME/skills`` or an- external skills dir; the scheduler resolves those through- ``normalize_skill_lookup_name`` before handing them to ``skill_view``.- The curator compares this set against bare skill names, so it has to- resolve them the same way — otherwise a path-referencing job's skill- looks unreferenced and gets archived out from under it.-- Best-effort: if the resolver is unavailable or rejects the value, fall- back to the plain cleanup so a broken import can never lose a name.- """+ """Reduce a job skill reference (possibly an absolute path) to the bare name the curator+ matches on, resolving it the same way the scheduler does — otherwise a path-referencing job's+ skill looks unreferenced and gets archived. Falls back to plain cleanup if the resolver fails,+ so a broken import can never lose a name."""value = str(raw or "").strip()if not value:return ""@@ -4527,19 +3263,10 @@ def _canonical_skill_ref(raw: Any) -> str:def referenced_skill_names() -> Set[str]:- """Return the set of skill names referenced by ANY cron job.-- Includes paused and disabled jobs deliberately: a paused job never- fires, so its skills never get a ``bump_use`` from the scheduler, yet- resuming it must still find its skills present. The curator uses this- set to protect referenced skills from inactivity archival — a skill a- live job depends on is "in use" regardless of when it was last loaded.-- Names are canonicalized the way the scheduler resolves them at load- time, so a job that stores an absolute skill path is protected too.-- Best-effort: a corrupt/unreadable jobs store returns an empty set- rather than raising, so a cron issue can never break the curator.+ """Skill names referenced by ANY cron job, deliberately including paused/disabled ones (a paused+ job never bumps its skills, yet resuming it must still find them). The curator uses this to+ protect referenced skills from inactivity archival. Names are canonicalized as the scheduler+ does, so absolute paths are protected too. A corrupt store yields an empty set, never raises."""try:jobs = load_jobs()@@ -4547,15 +3274,13 @@ def referenced_skill_names() -> Set[str]:logger.debug("referenced_skill_names: failed to load cron jobs", exc_info=True)return set()- names: Set[str] = set()- for job in jobs:- if not isinstance(job, dict):- continue- for name in _normalize_skill_list(job.get("skill"), job.get("skills")):- cleaned = _canonical_skill_ref(name)- if cleaned:- names.add(cleaned)- return names+ return {+ cleaned+ for job in jobs+ if isinstance(job, dict)+ for name in _normalize_skill_list(job.get("skill"), job.get("skills"))+ if (cleaned := _canonical_skill_ref(name))+ }def rewrite_skill_refs(@@ -4564,54 +3289,16 @@ def rewrite_skill_refs() -> Dict[str, Any]:"""Rewrite cron job skill references after a curator consolidation pass.- When the curator consolidates a skill X into umbrella Y (or archives X- as pruned), any cron job that lists ``X`` in its ``skills`` field will- fail to load ``X`` at run time — the scheduler logs a warning and- skips the skill, so the job runs without the instructions it was- scheduled to follow. See cron/scheduler.py where ``skill_view`` is- called per skill name.-- This function repairs cron jobs in-place:-- - A skill listed in ``consolidated`` is replaced with its umbrella- target (the ``into`` value). If the umbrella is already in the- job's skill list, the stale name is dropped without duplication.- - A skill listed in ``pruned`` is dropped outright — there is no- forwarding target.- - Ordering and other skills in the list are preserved.- - The legacy ``skill`` field is realigned via ``_apply_skill_fields``.-- Args:- consolidated: mapping of ``old_skill_name -> umbrella_skill_name``.- pruned: list of skill names that were archived with no forwarding- target.-- Returns a report dict::-- {- "rewrites": [- {- "job_id": ...,- "job_name": ...,- "before": [...],- "after": [...],- "mapped": {"old": "new", ...},- "dropped": ["old", ...],- },- ...- ],- "jobs_updated": N,- "jobs_scanned": M,- }-- Best-effort: exceptions from loading/saving propagate to the caller so- tests can assert behaviour; the curator invocation site wraps this- call in a try/except so a failure here never breaks the curator.+ A job listing a consolidated/pruned skill would otherwise run without it (the scheduler logs+ and skips missing skills). Consolidated names are replaced by their umbrella target without+ duplication, pruned names are dropped, ordering is preserved, and the legacy ``skill`` field is+ realigned. Returns ``{"rewrites": [{job_id, job_name, before, after, mapped, dropped}, ...],+ "jobs_updated": N, "jobs_scanned": M}``. Load/save exceptions propagate so tests can assert+ behaviour; the curator call site wraps this in try/except."""consolidated = dict(consolidated or {})pruned_set = set(pruned or [])- # A skill listed in both wins as "consolidated" — it has a target,- # which is the more useful of the two outcomes.+ # A skill listed in both wins as "consolidated" — it has a target, the more useful outcome.pruned_set -= set(consolidated.keys())if not consolidated and not pruned_set:@@ -4620,8 +3307,6 @@ def rewrite_skill_refs(with _jobs_lock():jobs = load_jobs()rewrites: List[Dict[str, Any]] = []- changed = False-for job in jobs:skills_before = _normalize_skill_list(job.get("skill"), job.get("skills"))if not skills_before:@@ -4644,11 +3329,8 @@ def rewrite_skill_refs(if not mapped and not dropped:continue-job["skills"] = new_skillsjob["skill"] = new_skills[0] if new_skills else None- changed = True-rewrites.append({"job_id": job.get("id"),"job_name": job.get("name") or job.get("id"),@@ -4658,14 +3340,7 @@ def rewrite_skill_refs("dropped": dropped,})- if changed:+ if rewrites:save_jobs(jobs)- logger.info(- "Curator rewrote skill references in %d cron job(s)", len(rewrites)- )-- return {- "rewrites": rewrites,- "jobs_updated": len(rewrites),- "jobs_scanned": len(jobs),- }+ logger.info("Curator rewrote skill references in %d cron job(s)", len(rewrites))+ return {"rewrites": rewrites, "jobs_updated": len(rewrites), "jobs_scanned": len(jobs)}diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.pyindex fb4c18e91c5..798f632dfbb 100644--- a/cron/lifecycle_guard.py+++ b/cron/lifecycle_guard.py@@ -1,41 +1,11 @@-"""Gateway lifecycle guard for cron job creation (#30719).--An agent running inside a gateway can schedule a cron job that calls-``hermes gateway restart`` (or ``launchctl kickstart ai.hermes.gateway``-or ``systemctl restart hermes-gateway``). When the cron fires, the-gateway dies, the supervisor (launchd KeepAlive / systemd Restart=)-revives it, auto-resume picks up the offending session, and the resumed-turn re-runs the same logic — a SIGTERM-respawn loop every ~10 seconds-until manually broken.--This module rejects cron job specs whose prompt or script contains a-direct shell-level gateway-lifecycle command. It is enforced at-``cron.jobs.create_job`` so it fires on every job-creation path: the-``hermes cron create`` CLI subcommand AND the agent's ``cronjob`` model-tool (which calls ``create_job`` directly, bypassing the CLI layer).--The pattern is intentionally command-shaped: it anchors on a concrete-command identifier (``hermes gateway``, ``launchctl ... hermes-gateway``,-``systemctl ... hermes-gateway``, ``pkill`` against the gateway) so it-cannot fire on prose. A cron ``prompt`` is fed to a future LLM, not a-shell, so an over-broad substring match on English ("Kong API gateway-autoscaling and restart behavior") would produce a high false-positive-rate without preventing the actual foot-gun, which requires a real-command shape.--This is a defence-in-depth layer. ``tools/terminal_tool.py`` blocks direct-commands and shell scripts they reference when ``_HERMES_GATEWAY=1``. It also-rejects ``launchctl submit`` in gateway sessions because launchd treats that-primitive as a persistent KeepAlive job, not a one-shot task. ``hermes gateway-stop|restart|uninstall`` separately refuse to self-target from inside the gateway.-Blocking cron specs at creation time as well means the agent gets an immediate,-informative rejection instead of scheduling a job that will only fail-(silently) when it fires.--The profile-flag form (``hermes -p <profile> gateway restart|stop``, #78028)-is handled profile-aware: it is blocked only when the named profile is the-profile running the guard. Sibling-profile restarts are legitimate fleet-operations and stay allowed.+"""Gateway lifecycle guard for cron job creation.++A cron job that restarts/stops the gateway from inside the gateway (``hermes gateway restart``,+``launchctl kickstart ai.hermes.gateway``, ``systemctl restart hermes-gateway``) kills the process,+the supervisor revives it, auto-resume re-runs the turn, and a SIGTERM-respawn loop results.+This module rejects such specs in ``cron.jobs.create_job`` (every creation path: CLI and the+``cronjob`` tool). Patterns are command-shaped — anchored on concrete command identifiers — so+they cannot fire on prose. Defence-in-depth layer."""from __future__ import annotations@@ -55,91 +25,55 @@ class GatewayLifecycleBlocked(ValueError):"""Raised when a cron job spec contains a gateway-lifecycle command."""-# Shell-level command shapes that target the gateway lifecycle. Each branch-# is anchored on a concrete command identifier so a match can only fire on-# actual shell-command-shaped strings, not on prose.+# Shell-level command shapes that target the gateway lifecycle; each branch is anchored on a+# concrete command identifier so it fires only on command-shaped strings, never prose._GATEWAY_LIFECYCLE_PATTERN = re.compile(r"(?i)"- # Branch A: destructive `hermes gateway` operations.- # The destructive operations are restart, stop, and uninstall.- # `start` is intentionally excluded: starting a gateway from inside a- # gateway is benign (a no-op or "already running" error), and a- # legitimate cron job might start a sibling profile's gateway.- # The lookbehind (#77173): `hermes` must not be a path component or a- # word tail. Excluding `/`, word chars, `.` and `-` keeps file paths- # with embedded spaces (`/docs/hermes gateway restart-notes.md`) from- # matching via the `/hermes` tail, while every real command position- # (start of text, whitespace, `;`/`&`/`|`, `$(`, backtick, even a- # U+FFFD from binary-content decoding) still matches.+ # Branch A: destructive `hermes gateway` ops (restart/stop/uninstall). `start` is excluded:+ # starting from inside a gateway is benign, and a job may legitimately start a sibling profile.+ # Lookbehind: `hermes` must not be a path component or word tail (excluding `/`, word chars, `.`,+ # `-`), so `/docs/hermes gateway restart-notes.md` does not match while every real command+ # position (text start, whitespace, `;`/`&`/`|`, `$(`, backtick, U+FFFD) still does.r"(?:(?<![/\w.\-])hermes\s+gateway\s+(?:restart|stop|uninstall)\b)"- # Branch B: launchctl ops on a hermes-gateway label. macOS launchd- # labels look like `ai.hermes.gateway` / `hermes-gateway`. Requiring the- # gateway identifier prevents blocking unrelated hermes services (e.g.- # `launchctl unload ai.hermes.update-checker.plist`).- # `submit` and `bootstrap` are included alongside the direct verbs- # (kickstart/etc.): `launchctl submit -l ai.hermes.gateway-<suffix> --- # <helper-script>` (or `launchctl bootstrap gui/<uid> <plist>`) creates- # a NEW keepalive job wrapping an arbitrary helper, which is how a- # blocked direct restart/kill gets laundered into a persistent restart- # loop instead (#62891) — same foot-gun, indirect shape. Neutral-label- # submissions that dodge this text anchor are caught separately by- # `contains_launchctl_submit_command` (execution-aware, label-independent).- # `bootout`/`remove`/`disable` sit alongside `unload`: Apple deprecated- # load/unload in favour of bootstrap/bootout, so `bootout` is the modern- # spelling of an already-listed verb, `remove` is its legacy sibling, and- # `disable` is what makes an unload durable across boots. Omitting them- # left the bypassable approval layer (tools/approval.py, skipped on- # force=True) as the only cover, while this hard block — documented as- # "force=True cannot help here" — let them through (#80260).+ # Branch B: launchctl ops anchored on a hermes-gateway label so unrelated hermes services+ # (`launchctl unload ai.hermes.update-checker.plist`) stay unblocked. `submit`/`bootstrap` are+ # included because they register a NEW keepalive job wrapping an arbitrary helper — a blocked+ # restart laundered into a persistent loop; neutral-label submissions are caught separately by+ # `contains_launchctl_submit_command`. `bootout`/`remove`/`disable` are the modern/legacy/durable+ # forms of `unload`; without them the bypassable approval layer (skipped on force=True) was the+ # only cover.r"|(?:launchctl\s+(?:kickstart|unload|load|stop|restart|submit|bootstrap|bootout|remove|disable)\b[^\n]*\bhermes[.\-]?gateway)"# Branch C: systemctl ops on a hermes-gateway unit.r"|(?:systemctl\s+(?:-\S+\s+)*(?:restart|stop|start)\b[^\n]*\bhermes[.\-]?gateway)"- # Branch D: pkill / kill targeting the hermes gateway process. Both- # token orders because real reproductions show both.- # Leading \b ensures we match "pkill" or "kill" as whole words, not as- # suffixes of other words (e.g. "skill" -> "kill").+ # Branch D: pkill/kill of the gateway process, both token orders. Leading \b keeps "skill" from+ # matching as "kill".r"|(?:\bp?kill\b[^\n]*\bhermes\b[^\n]*\bgateway)"r"|(?:\bp?kill\b[^\n]*\bgateway\b[^\n]*\bhermes)")-# A backslash immediately followed by a newline is a POSIX shell line-# continuation — the shell joins the two lines before parsing. Every branch-# above uses `[^\n]*` between its verb and the gateway identifier so the-# match can't span unrelated lines of a longer cron prompt/script, but that-# also means a real multi-line shell invocation split across continuation-# lines (e.g. `launchctl submit \` / ` -l ai.hermes.gateway-... \` / ` -- ...`,-# the exact reported shape in #62891) would otherwise slip past. Collapse-# continuations to a single space before matching, mirroring what the shell-# itself does, rather than loosening `[^\n]*` and risking false positives-# across genuinely separate lines.+# Backslash-newline is a POSIX line continuation. Every branch uses `[^\n]*` between verb and label so+# matches cannot span unrelated lines, which would let a continuation-split invocation slip past.+# Collapse continuations to a space before matching (as the shell does) rather than loosening `[^\n]*`._SHELL_LINE_CONTINUATION = re.compile(r"\\\r?\n[ \t]*")-# Python argv-list punctuation (#68289): `subprocess.run(["launchctl",-# "bootout", ...])` separates the words the OS will exec with brackets and-# commas rather than spaces. Stripped before the token-join re-scan only —-# never from the raw text, so prose stays governed by the primary pattern.+# Python argv-list punctuation (`subprocess.run(["launchctl", "bootout", ...])`) separates exec'd words+# with brackets/commas. Stripped only for the token-join re-scan, never from raw text (prose stays+# governed by the primary pattern)._ARGV_LIST_PUNCTUATION = re.compile(r"[\[\],]+")-# Branch A2 (#78028): the same foot-gun written with an explicit profile-# selector — `hermes -p <profile> gateway restart|stop` / `--profile <name>`-# / `--profile=<name>`. The selector token between `hermes` and `gateway`-# breaks Branch A's literal adjacency. Unlike Branch A this form is NOT-# unconditionally self-targeting: issued from inside gateway `zeus`,-# `hermes -p venus gateway restart` operates on a sibling profile's gateway-# and is a legitimate fleet operation. The pattern captures the named-# profile so `contains_gateway_lifecycle_command` can block only the-# self-targeting shape (named profile == the profile running the guard).-# `start` stays excluded for the same reason as Branch A.+# Branch A2: `hermes -p <profile> gateway restart|stop` (also `--profile <name>` / `--profile=<name>`).+# The selector breaks Branch A's adjacency. Not unconditionally self-targeting — a sibling-profile+# restart is a legitimate fleet operation — so the profile name is captured and+# `contains_gateway_lifecycle_command` blocks only when it equals the profile running the guard.+# `start` stays excluded as in Branch A._PROFILE_FLAG_LIFECYCLE_PATTERN = re.compile(r"(?i)"r"hermes\s+"# Any global flags before the profile selector (each may carry a value).r"(?:-{1,2}\S+(?:\s+\S+)?\s+)*"- # The selector itself: `--profile=<name>` or the space-separated- # `-p <name>` / `--profile <name>` — exactly the shapes the CLI's- # `_apply_profile_override` accepts.+ # The selector: exactly the shapes the CLI's `_apply_profile_override` accepts.r"(?:--profile=([^\s]+)|(?:-p|--profile)\s+([^\s]+))"# Any global flags between the selector and the subcommand.r"(?:\s+-{1,2}\S+(?:\s+\S+)?)*"@@ -148,14 +82,8 @@ _PROFILE_FLAG_LIFECYCLE_PATTERN = re.compile(def _current_profile_name() -> Optional[str]:- """Return the name of the profile running the guard, if determinable.-- Prefers the explicit ``HERMES_PROFILE_NAME`` / ``HERMES_PROFILE`` env- (set by the profile launcher and kanban worker spawns), falling back to- ``hermes_cli.profiles.get_active_profile_name`` (derived from- ``HERMES_HOME``, which the gateway process inherits from its launch- profile). Returns ``None`` when neither source yields a name.- """+ """Profile running the guard: ``HERMES_PROFILE_NAME``/``HERMES_PROFILE`` env first, then+ ``hermes_cli.profiles.get_active_profile_name`` (from ``HERMES_HOME``); ``None`` if neither."""for env_name in ("HERMES_PROFILE_NAME", "HERMES_PROFILE"):value = os.environ.get(env_name)if value and value.strip():@@ -172,32 +100,15 @@ def _named_profile_is_current(named: str) -> bool:"""True when *named* is the profile executing the guard (self-targeting)."""current = _current_profile_name()if not current:- # No profile identity available: cannot prove self-targeting, so do- # not block — sibling restarts must stay allowed (#78028).+ # No profile identity: cannot prove self-targeting, so do not block (sibling restarts stay allowed).return Falsereturn named.strip().casefold() == current.strip().casefold()-# Branch B only catches `launchctl <verb> ... hermes[.-]?gateway` when the-# label literally appears AFTER the verb in the same `[^\n]*` span, and its-# verb list is missing `bootout`/`kill`/`disable`/`remove` entirely (2026-08-02-# incident). `bootout` is the one that actually unloads a job's registration-# — worse than `stop`/`kickstart`, which just bounce a still-registered job.-#-# A shell loop that builds the label from a list defined EARLIER in the same-# command — `for item in 'ai.hermes.gateway-apollo:...' 'ai.hermes.gateway:...';-# do label=${item%%:*}; launchctl bootout "gui/$uid/$label"; done` — puts the-# literal label text in a different `;`-separated segment than the verb, so-# no amount of same-segment tokenization sees it: the token next to `bootout`-# is the unexpanded variable `$label`, not the string "hermes.gateway". This-# incident command evaded Branch B on both counts (missing verb AND order)-# and unloaded all 4 profiles' launchd jobs with zero approval.-#-# Unlike `submit`/`bootstrap` (handled separately, fully label-independent,-# because a NEW job's label is attacker-chosen), these verbs act on an-# EXISTING job, so anchoring to the hermes-gateway label is still correct —-# `test_safe_commands` requires unrelated-label ops (e.g. `launchctl unload-# ai.hermes.update-checker.plist`) to stay unblocked. The fix is checking+# Branch B needs the label AFTER the verb in one `[^\n]*` span. A loop that builds the label in an+# EARLIER `;`-segment (`label=${item%%:*}; launchctl bootout "gui/$uid/$label"`) leaves only the+# unexpanded `$label` next to the verb. These verbs act on an EXISTING job, so anchoring to the+# hermes-gateway label stays correct (unrelated labels must stay unblocked) — but the check is# "verb anywhere AND label anywhere", not "label right after verb"._LAUNCHCTL_LIFECYCLE_VERBS_RE = re.compile(r"(?i)\blaunchctl\s+(?:kickstart|unload|load|stop|restart|bootout|kill|disable|remove)\b"@@ -215,63 +126,37 @@ def _contains_launchctl_gateway_lifecycle(normalized_text: str) -> bool:def contains_gateway_lifecycle_command(text: str) -> bool:"""Return True if *text* contains a gateway lifecycle command pattern.- Matches in two passes. The first is the raw-text regex above — cheap,- and the only pass that can fire on non-shell inputs shlex can't- tokenize (e.g. a Python source string). The second re-runs the same- pattern against each command segment after shell tokenization, where- quotes and backslash escapes have already been resolved.-- That second pass exists because a real shell resolves quote-splicing- (``kick"start"``) and backslash-escaping (``kick\\start``) into one- literal word — ``kickstart`` — before the command ever runs. The raw- text still has the quote or backslash sitting between the verb's two- halves, so the first pass alone lets a spliced verb reach- ``launchctl``/``systemctl`` untouched while still executing as the- blocked lifecycle command (#80269, reported against #80260's bootout- parity fix). Tokenizing closes that gap while keeping the same- gateway-label anchoring (``_GATEWAY_LIFECYCLE_PATTERN`` still requires- a ``hermes``/``gateway`` token) — this function is the single choke- point ``_contains_unsafe_gateway_action`` calls at every recursion- level, so referenced-script and ``sh -c`` payload scanning inherit the- fix automatically.+ Two passes: the raw-text regex (cheap; the only pass that fires on inputs shlex cannot tokenize,+ e.g. Python source), then the same pattern on each shell-tokenized segment where quotes/escapes+ are resolved — closing splice bypasses like ``kick"start"`` / ``kick\\start`` that execute as+ ``kickstart``. Single choke point for every recursion level of ``_contains_unsafe_gateway_action``."""if not text:return False- # Heredoc bodies that are provably inert data (quoted delimiter, data-sink- # consumer like `cat > file <<'EOF'`) are masked before scanning (#88336):- # a runbook line "a human can run: hermes gateway restart" inside such a- # body is documentation, not a command this shell will execute. The- # stripper fails open on ANY ambiguity (unquoted delimiter, shell- # consumer, unterminated body), so executable heredocs are still scanned.+ # Provably inert heredoc bodies (quoted delimiter, data-sink consumer like `cat > f <<'EOF'`) are+ # documentation, not commands, and are masked first. The stripper fails open on ANY ambiguity+ # (unquoted delimiter, shell consumer, unterminated body), so executable heredocs are still scanned.from tools.shell_heredoc import strip_inert_heredoc_bodiestext = strip_inert_heredoc_bodies(text)normalized = _SHELL_LINE_CONTINUATION.sub(" ", text)if _GATEWAY_LIFECYCLE_PATTERN.search(normalized):return True- # Profile-flag form (#78028): `hermes -p <profile> gateway restart|stop`- # bypasses Branch A because the selector sits between `hermes` and- # `gateway`. It is only the same foot-gun when the named profile IS the- # profile running the guard — sibling-profile restarts are legitimate- # fleet operations and stay allowed.+ # Profile-flag form (`hermes -p <profile> gateway restart|stop`): blocked only when the named+ # profile IS the one running the guard — sibling-profile restarts are legitimate and stay allowed.profile_match = _PROFILE_FLAG_LIFECYCLE_PATTERN.search(normalized)if profile_match:named = profile_match.group(1) or profile_match.group(2)if named:- # Profile ids cannot contain quotes (hermes_cli.profiles- # enforces `^[a-z0-9][a-z0-9_-]{0,63}$`), so a shell-quoted+ # Profile ids cannot contain quotes (`^[a-z0-9][a-z0-9_-]{0,63}$`), so a shell-quoted# `-p 'zeus'` compares equal to the bare name.named = named.strip().strip("\"'")if _named_profile_is_current(named):return True- # Token-aware second pass (#80269): re-run the pattern on shell-tokenized- # segments where quotes/escapes are resolved, closing splice bypasses- # like `kick"start"`. Runs after the profile-flag check so both passes- # apply independently. Tokens are additionally re-joined with Python- # argv-list punctuation ([ ] ,) stripped (#68289): the same command- # reaches this guard as `subprocess.run(["launchctl", "bootout", ...])`- # from execute_code, where commas and brackets — not spaces — separate- # the argv words the OS will actually see.+ # Token-aware second pass: quotes/escapes resolved, closing splice bypasses like `kick"start"`.+ # Runs after the profile-flag check so both apply independently. Tokens are also re-joined with+ # Python argv-list punctuation stripped, since `subprocess.run(["launchctl", "bootout", ...])`+ # separates argv words with commas/brackets rather than spaces.for segment in _iter_command_segments(normalized):joined = " ".join(segment)if joined and _GATEWAY_LIFECYCLE_PATTERN.search(joined):@@ -279,11 +164,8 @@ def contains_gateway_lifecycle_command(text: str) -> bool:stripped = _ARGV_LIST_PUNCTUATION.sub(" ", joined)if stripped != joined and _GATEWAY_LIFECYCLE_PATTERN.search(stripped):return True- # Order-independent launchctl pass (#77083): a shell loop can build the- # gateway label from a variable defined in an earlier `;`-separated- # segment (`label=${item%%:*}; launchctl bootout "gui/$uid/$label"`), so- # neither the same-span regex nor same-segment tokenization sees verb- # and label together. Check "verb anywhere AND label anywhere" instead.+ # Order-independent launchctl pass: the label may be built in an earlier `;`-segment, so neither+ # the same-span regex nor same-segment tokenization sees verb and label together.return _contains_launchctl_gateway_lifecycle(normalized)@@ -294,23 +176,31 @@ _MAX_REFERENCED_SCRIPT_DEPTH = 8_CONTROL_CHARS = frozenset(";&|()")-# Directory names that sit directly under a `Library` path component and-# mark a FileProvider-backed subtree: `Mobile Documents` is iCloud Drive;-# `CloudStorage` hosts every third-party FileProvider domain (Dropbox,-# OneDrive, Google Drive, Box, ...) on modern macOS.+# Directory names directly under `Library` that mark a FileProvider-backed subtree: `Mobile Documents`+# is iCloud Drive; `CloudStorage` hosts third-party providers (Dropbox, OneDrive, Google Drive, ...)._CLOUD_PLACEHOLDER_MARKERS = frozenset({"Mobile Documents", "CloudStorage"})+def _resolve_lenient(path: Path) -> Path:+ """``path.resolve(strict=False)``, falling back to *path* on OSError (unreadable/long) or+ ValueError (embedded NUL from decoded binary tokenized as a path) — never crash the guard."""+ try:+ return path.resolve(strict=False)+ except (OSError, ValueError):+ return path+++def _on_cloud_path(path: Path) -> bool:+ """Lexical OR resolved cloud check: covers direct cloud paths and local symlinks into one."""+ return _is_cloud_placeholder_path(path) or _is_cloud_placeholder_path(_resolve_lenient(path))++def _is_cloud_placeholder_path(path: Path) -> bool:- """Return True for paths inside a macOS FileProvider-backed subtree.-- ``O_NONBLOCK`` does not make regular-file reads non-blocking. Opening an- evicted FileProvider placeholder below ``~/Library/Mobile Documents``- (iCloud Drive) or ``~/Library/CloudStorage`` (Dropbox / OneDrive /- Google Drive and other third-party providers) can therefore wait- indefinitely for hydration. The lifecycle guard runs before a terminal- command's timeout starts, so it must identify this boundary from path- metadata and fail closed without opening the file.+ """True for paths inside a macOS FileProvider-backed subtree.++ ``O_NONBLOCK`` does not make regular-file reads non-blocking, so opening an evicted placeholder+ can wait indefinitely for hydration — and the guard runs before any command timeout starts. The+ boundary must be identified from the path alone and fail closed without opening the file."""parts = path.partsreturn any(@@ -319,62 +209,32 @@ def _is_cloud_placeholder_path(path: Path) -> bool:if index)-# Executables whose arguments are DATA, not commands: search patterns, SQL-# statements, log filters. None of these can execute their argument text, so-# a lifecycle-shaped string inside their arguments (a grep pattern hunting-# for `systemctl restart hermes-gateway` in syslog, a SQL LIKE literal over a-# restart-events table) is diagnostics, not a lifecycle command. Deliberately-# conservative: no `awk` (system()), no `sed` (`s///e`), no `echo`/`printf`-# (routinely piped into a shell), no `mysql` (`\\!` and `system` escapes).+# Executables whose arguments are DATA (search patterns, SQL, log filters) and cannot execute their+# argument text, so a lifecycle-shaped string there is diagnostics, not a command. Deliberately+# conservative: no `awk` (system()), no `sed` (`s///e`), no `echo`/`printf` (routinely piped into a+# shell), no `mysql` (`\\!` and `system` escapes)._DATA_SINK_EXECUTABLES = frozenset({"grep", "egrep", "fgrep", "rg", "ag", "ack", "journalctl", "sqlite3", "psql"})-# Argument shapes that can smuggle execution back INTO a data sink: command-# and process substitution anywhere, sqlite3 dot-commands (`.shell ...`),-# psql backslash escapes (`\! ...`). Any hit disables masking for the whole-# segment — fail closed to the plain regex verdict.+# Argument shapes that smuggle execution back INTO a data sink (command/process substitution, psql+# `\!`). Any hit disables masking for the whole segment — fail closed to the plain regex verdict._UNSAFE_DATA_ARG_MARKERS = ("`", "$(", "<(", ">(", "\\!")-# A leading dot also disables masking, because sqlite3 spells its escapes as-# dot-commands (`.shell`, `.system`, `.import`). But `.`, `./x` and `../x`-# are ordinary path operands, and `grep -r <pattern> .` is a far more common-# shape than any dot-command — treating those as escapes disabled the-# exemption for the single most ordinary way to run a recursive search,-# blocking `grep -r 'systemctl restart hermes-gateway' .` outright. Require a-# dot followed by a NAME character so a relative path stays a path.+# sqlite3 dot-commands (`.shell`, `.system`) also disable masking. Dot must be followed by a NAME+# character so relative paths (`.`, `./x`) stay paths — `grep -r <pattern> .` is far more common._DOT_COMMAND_ARGUMENT = re.compile(r"^\.[A-Za-z]")-# A data sink piped into a shell/interpreter can feed matched lines straight-# to execution (`grep 'systemctl restart hermes-gateway' f | sh`); never mask-# such a line.+# A data sink piped into a shell/interpreter can feed matched lines to execution; never mask such a line._PIPE_TO_INTERPRETER = re.compile(r"\|\s*&?\s*(?:sudo\s+)?(?:sh|bash|dash|ksh|zsh|xargs|eval|source)\b")-# Executable-image magic numbers: ELF, PE/COFF, Mach-O (universal + thin,-# both endiannesses). A referenced file starting with one of these is a-# compiled binary, never a shell script — don't read or scan it at all.-_BINARY_MAGIC_PREFIXES = (- b"\x7fELF",- b"MZ",- b"\xca\xfe\xba\xbe",- b"\xcf\xfa\xed\xfe",- b"\xce\xfa\xed\xfe",- b"\xfe\xed\xfa\xce",- b"\xfe\xed\xfa\xcf",-)+# Bytes sniffed before reading a referenced file in full (see _BINARY_MAGICS)._BINARY_SNIFF_BYTES = 4096---_ReadRemoteScriptFn = Callable[[str], Optional[str]]def _split_logical_lines(text: str) -> list[str]:- """Split text on newlines that are not inside quotes.-- A newline inside a quoted string (single or double quotes) is data,- not a command separator. Handles escaped quotes within strings.- """+ """Split on newlines outside quotes (a quoted newline is data, not a separator); honors escapes."""lines = []current = []in_single = False@@ -409,103 +269,68 @@ def _split_logical_lines(text: str) -> list[str]:return lines+def _shlex_tokens(line: str) -> list[str]:+ """POSIX-tokenize one shell line, honoring quotes and `#` comments; raises ValueError."""+ lexer = shlex.shlex(line, posix=True, punctuation_chars=";&|()")+ lexer.whitespace_split = True+ lexer.commenters = "#"+ return list(lexer)+++def _split_segments(tokens: list[str], *, keep_controls: bool = False) -> Iterator[list[str]]:+ """Yield non-empty runs of *tokens* between control-operator tokens; with *keep_controls* each+ control token is also yielded as its own segment so the line can be rebuilt in order."""+ segment: list[str] = []+ for token in tokens:+ if token and set(token) <= _CONTROL_CHARS:+ if segment:+ yield segment+ segment = []+ if keep_controls:+ yield [token]+ continue+ segment.append(token)+ if segment:+ yield segment++def _iter_command_segments(command: str) -> Iterator[list[str]]:"""Yield shell-tokenized command segments, honoring quotes and comments.- A newline inside a quoted token is data, not a command separator.- First split on logical lines (newlines outside quotes), then tokenize- each logical line with shlex. If a logical line cannot be tokenized- (unbalanced quotes), fall back to per-physical-line tokenization for- that logical line.+ Split on logical lines (newlines outside quotes), shlex-tokenize each; on failure (unbalanced+ quotes) fall back to per-physical-line tokenization for that logical line."""normalized = command.replace("\\\n", "")- logical_lines = _split_logical_lines(normalized)-- for line in logical_lines:- # Try to tokenize the logical line as a whole.+ for line in _split_logical_lines(normalized):try:- lexer = shlex.shlex(- line,- posix=True,- punctuation_chars=";&|()",- )- lexer.whitespace_split = True- lexer.commenters = "#"- tokens = list(lexer)+ tokens = _shlex_tokens(line)except ValueError:- # Fall back to per-physical-line tokenization for this logical line.- # This handles cases where quotes are unbalanced across lines.for physical_line in line.splitlines():try:- lexer = shlex.shlex(- physical_line,- posix=True,- punctuation_chars=";&|()",- )- lexer.whitespace_split = True- lexer.commenters = "#"- tokens = list(lexer)+ yield from _split_segments(_shlex_tokens(physical_line))except ValueError:continue-- segment: list[str] = []- for token in tokens:- if token and set(token) <= _CONTROL_CHARS:- if segment:- yield segment- segment = []- continue- segment.append(token)- if segment:- yield segmentcontinue-- segment: list[str] = []- for token in tokens:- if token and set(token) <= _CONTROL_CHARS:- if segment:- yield segment- segment = []- continue- segment.append(token)- if segment:- yield segment--+ yield from _split_segments(tokens)def _executable_name(token: str) -> str:"""Return the command name for a tokenized executable token.- ``Path(token).name`` is right for real paths (``/usr/bin/bash`` →- ``bash``), but pathlib has no name component for the pure-path tokens- ``.``, ``..`` and ``/``, so it returns "" for them. The POSIX- dot-source builtin is spelled ``.``, so keying the sourced-script- branch on ``Path(token).name`` alone made it unreachable: ``source- ./helper.sh`` was scanned but its exact synonym ``. ./helper.sh`` was- not, letting a referenced script carrying a lifecycle command through- both the cron guard and the in-gateway terminal guard. Fall back to the- raw token so ``.`` survives.+ ``Path(token).name`` is "" for ``.``, ``..`` and ``/``; the POSIX dot-source builtin is spelled+ ``.``, so fall back to the raw token or ``. ./helper.sh`` would escape the sourced-script scan."""return Path(token).name or token-# Prefixes that hand execution straight to their argument tail: the command-# that actually runs sits further right. A guard that reads only the first-# token sees `sudo`/`env`/`nohup` and never inspects what they run, so-# `sudo bash ~/restart.sh` walked past the same walk that stops-# `bash ~/restart.sh`, and `sudo launchctl submit ...` past the-# label-independent submit block (#62891). `_PIPE_TO_INTERPRETER` above-# already reads `sudo ` this way for the pipe case; this generalises that-# reading to the command position.+# Wrappers that hand execution to their argument tail: the real command sits further right, so a+# first-token-only guard would let `sudo bash ~/restart.sh` or `sudo launchctl submit ...` walk past._TRANSPARENT_COMMAND_PREFIXES = frozenset({"sudo", "doas", "env", "nohup", "setsid", "nice", "ionice", "stdbuf","timeout", "exec", "command", "builtin", "eatmydata",- # Privilege and namespace wrappers. Same shape — options, then the- # command they hand execution to.+ # Privilege and namespace wrappers: options, then the command they run."pkexec", "su", "runuser", "setpriv", "systemd-run", "nsenter", "unshare",})-# Options of those wrappers that consume the NEXT token as their value, so a-# value is never mistaken for the wrapped command (`sudo -u deploy bash x.sh`).+# Wrapper options that consume the NEXT token, so a value is never mistaken for the command._TRANSPARENT_PREFIX_VALUE_OPTIONS = {"sudo": {"-u", "-g", "-U", "-C", "-p", "-r", "-t", "-T","--user", "--group", "--prompt"},@@ -531,18 +356,15 @@ _TRANSPARENT_PREFIX_VALUE_OPTIONS = {"-w", "--wd"},}-# Wrappers whose option carries a COMMAND STRING rather than an argv tail.-# The string is shell source and must be re-scanned like `sh -c` — skipping-# it as an opaque option value would hide whatever it runs-# (`env -S 'bash ~/restart.sh'`).+# Wrapper options carrying a COMMAND STRING (shell source, re-scanned like `sh -c`); treating it as+# an opaque value would hide whatever it runs (`env -S 'bash ~/restart.sh'`)._STRING_COMMAND_OPTIONS = {"env": ("-S", "--split-string"),"su": ("-c", "--command"),"runuser": ("-c", "--command"),}-# Wrappers whose first non-option operand is a VALUE, not the command-# (`timeout 60 bash x.sh`).+# Wrappers whose first non-option operand is a VALUE, not the command (`timeout 60 bash x.sh`)._TRANSPARENT_PREFIX_OPERANDS = {"timeout": 1}_ENV_ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")@@ -552,12 +374,8 @@ _MAX_PREFIX_PEELS = 8def _peel_transparent_prefixes(segment: list[str], index: int) -> int:- """Return the index of the command a wrapper chain actually executes.-- Returns *index* unchanged when the token there is not a wrapper, and may- return ``len(segment)`` when a wrapper has no operand — callers must- bounds-check before indexing.- """+ """Index of the command a wrapper chain actually executes. Unchanged if not a wrapper; may be+ ``len(segment)`` when a wrapper has no operand — callers must bounds-check."""for _ in range(_MAX_PREFIX_PEELS):if index >= len(segment):return index@@ -594,24 +412,25 @@ def _command_token_index(segment: list[str]) -> Optional[int]:return None+def _executed_command_index(segment: list[str]) -> Optional[int]:+ """Index of the command a segment actually executes (env assignments and wrappers peeled)."""+ index = _command_token_index(segment)+ if index is None:+ return None+ index = _peel_transparent_prefixes(segment, index)+ return index if index < len(segment) else None++def contains_launchctl_submit_command(command: str) -> bool:"""Detect an executed ``launchctl submit``/``bootstrap``, not quoted text.- Label-independent by design: the label of a submitted/bootstrapped job is- chosen by whoever writes it, so a neutral name (``ai.hermes.svc-reload-tmp``)- defeats any label-anchored regex (#62891, second reproduction). Both verbs- register a NEW persistent launchd job (``submit`` jobs get KeepAlive- semantics; ``bootstrap`` loads an arbitrary plist), which is never safe to- do from inside the gateway process.+ Label-independent by design: a NEW job's label is attacker-chosen, so a neutral name defeats any+ label-anchored regex. Both verbs register a persistent launchd job (KeepAlive / arbitrary plist),+ never safe from inside the gateway."""for segment in _iter_command_segments(command):- index = _command_token_index(segment)- if index is None:- continue- index = _peel_transparent_prefixes(segment, index)- if index >= len(segment):- continue- if _executable_name(segment[index]) == "launchctl":+ index = _executed_command_index(segment)+ if index is not None and _executable_name(segment[index]) == "launchctl":arguments = segment[index + 1 :]if arguments and arguments[0].lower() in {"submit", "bootstrap"}:return True@@ -621,28 +440,12 @@ def contains_launchctl_submit_command(command: str) -> bool:def _mask_data_sink_arguments(text: str) -> str:"""Replace data-sink executables' arguments with a neutral placeholder.- The lifecycle regex is command-shaped, but it cannot tell an EXECUTED- ``systemctl restart hermes-gateway`` from the same characters appearing- as *data* — a grep/rg pattern, a journalctl filter, a SQL string literal- passed to sqlite3/psql. Those diagnostics commands were being rejected- (false positives blocking legitimate cron prompts), e.g.::-- grep -c 'systemctl restart hermes-gateway' /var/log/syslog- sqlite3 db "SELECT msg FROM log WHERE msg LIKE '%systemctl restart hermes-gateway%'"-- This masker shell-tokenizes each line and, for command segments whose- executable is a known data sink (``_DATA_SINK_EXECUTABLES``), replaces- every argument with ``arg``. The caller then re-runs the lifecycle regex- on the masked text: a match that survives masking sits OUTSIDE any data- argument and is a real command.-- Strictly fail-closed: masking is skipped (leaving the original,- regex-matching text in place) whenever the line pipes into a shell or- interpreter, any argument carries an execution-capable marker- (substitution, sqlite3 ``.``-commands, psql ``\\!``), or the line cannot- be tokenized at all. Masking can therefore only ever ALLOW a command the- plain regex would have blocked — never block one it would have allowed —- so it runs solely as a second-pass exemption check.+ The regex cannot tell an EXECUTED lifecycle command from the same characters as *data* (a grep+ pattern, a SQL literal). For segments whose executable is in ``_DATA_SINK_EXECUTABLES`` every+ argument becomes ``arg``; a match that survives masking is a real command. Strictly fail-closed:+ masking is skipped when the line pipes into a shell/interpreter, any argument carries an+ execution marker, or the line cannot be tokenized. Masking can only ever ALLOW a command the plain+ regex would block, never block one it would allow — so it runs solely as a second-pass exemption."""lines_out: list[str] = []changed = False@@ -651,29 +454,13 @@ def _mask_data_sink_arguments(text: str) -> str:lines_out.append(line)continuetry:- lexer = shlex.shlex(line, posix=True, punctuation_chars=";&|()")- lexer.whitespace_split = True- lexer.commenters = "#"- tokens = list(lexer)+ tokens = _shlex_tokens(line)except ValueError:lines_out.append(line)continue- segments: list[list[str]] = []- current: list[str] = []- for token in tokens:- if token and set(token) <= _CONTROL_CHARS:- segments.append(current)- segments.append([token])- current = []- continue- current.append(token)- segments.append(current)-rebuilt: list[str] = []- for segment in segments:- if not segment:- continue+ for segment in _split_segments(tokens, keep_controls=True):index = _command_token_index(segment)if index is not None and Path(segment[index]).name in _DATA_SINK_EXECUTABLES:arguments = segment[index + 1 :]@@ -694,13 +481,8 @@ def _mask_data_sink_arguments(text: str) -> str:def _lifecycle_command_scan_with_data_exemption(text: str) -> bool:- """Lifecycle-regex scan that exempts matches living inside data arguments.-- Two-pass: the cheap regex first (the overwhelmingly common no-match case- pays nothing extra); on a raw match, re-scan with data-sink arguments- masked out. Only a match that survives masking — i.e. one in actual- command position — blocks.- """+ """Lifecycle scan exempting matches inside data arguments: cheap regex first (no-match pays+ nothing), then re-scan with data-sink arguments masked; only a surviving match blocks."""if not contains_gateway_lifecycle_command(text):return Falsenormalized = _SHELL_LINE_CONTINUATION.sub(" ", text)@@ -709,27 +491,15 @@ def _lifecycle_command_scan_with_data_exemption(text: str) -> bool:def _direct_lifecycle_scan(command: str) -> bool:"""Pure-string direct scans: lifecycle regex (data-exempted) + submit."""- return _lifecycle_command_scan_with_data_exemption(- command- ) or contains_launchctl_submit_command(command)+ return _lifecycle_command_scan_with_data_exemption(command) or contains_launchctl_submit_command(command)def _expand_candidate_path(candidate: str) -> Optional[Path]:"""Sanitize a tokenized path candidate at the ingestion boundary.- Candidate tokens come from shlex-splitting arbitrary command text —- including text recursively decoded from binaries or remote reads — so- they can carry NUL bytes or other junk no real filesystem path can- contain. Every OS-facing ``Path`` operation downstream (``expanduser``,- ``os.open``, ``resolve``) raises a *different* exception for the same- junk (``ValueError: embedded null byte``, ``RuntimeError: Could not- determine home directory`` when HOME is unset under launchd, OSError- for over-long paths). Rejecting here — once, before any OS call — is- the whole-class fix; catching per-syscall was the whack-a-mole that- produced #76762, #77703, #77780, and #78256.-- Returns ``None`` for candidates that cannot be a real path (nothing to- scan), otherwise the ``expanduser()``-expanded ``Path``.+ Tokens from shlex-splitting arbitrary (possibly binary-decoded) text can carry NUL or junk; each+ downstream ``Path`` op raises a different exception for it (ValueError, RuntimeError when HOME+ is unset under launchd, OSError). Reject once here. ``None`` = not a real path, nothing to scan."""if not candidate or "\x00" in candidate:return None@@ -752,6 +522,13 @@ def _resolve_terminal_script_path(candidate: str, cwd: Optional[str]) -> Optionareturn path+def _resolved_or_nothing(candidate: str, cwd: Optional[str]) -> Iterator[Path]:+ """Yield the resolved terminal script path for *candidate*, or nothing when it is not a path."""+ resolved = _resolve_terminal_script_path(candidate, cwd)+ if resolved is not None:+ yield resolved++def _iter_option_values(segment: list[str], start: int, option: str) -> Iterator[str]:@@ -776,9 +553,7 @@ def _references_at(if executable_name in {".", "source"}:if len(segment) > index + 1:- resolved = _resolve_terminal_script_path(segment[index + 1], cwd)- if resolved is not None:- yield resolved+ yield from _resolved_or_nothing(segment[index + 1], cwd)returnif executable_name in _SHELL_EXECUTABLES:@@ -798,25 +573,14 @@ def _references_at(arg_index += 1continuebreak- if arg_index < len(arguments) and arguments[arg_index] not in {- "-c",- "--command",- }:- resolved = _resolve_terminal_script_path(arguments[arg_index], cwd)- if resolved is not None:- yield resolved+ if arg_index < len(arguments) and arguments[arg_index] not in {"-c", "--command"}:+ yield from _resolved_or_nothing(arguments[arg_index], cwd)return- # A bare "/" token is pathlib's division operator in Python sources- # (e.g. `Path.home() / ".hermes"`), not an executable reference.- # Resolving it walks to the filesystem root and fails the- # regular-file check below, hard-blocking innocent .py scripts- # (#77131). Skip pure-separator tokens.- if executable.strip("/"):- if "/" in executable or executable.endswith((".sh", ".bash", ".zsh")):- resolved = _resolve_terminal_script_path(executable, cwd)- if resolved is not None:- yield resolved+ # A bare "/" is pathlib's division operator in Python sources, not an executable; resolving it hits+ # the filesystem root and fails the regular-file check, hard-blocking innocent .py scripts.+ if executable.strip("/") and ("/" in executable or executable.endswith((".sh", ".bash", ".zsh"))):+ yield from _resolved_or_nothing(executable, cwd)def _iter_referenced_shell_scripts(@@ -826,11 +590,8 @@ def _iter_referenced_shell_scripts() -> Iterator[Path]:"""Yield scripts executed directly or through a POSIX shell.- Each segment is read twice: once at the token the walk has always used,- and again at the command a wrapper chain hands off to. Additive on- purpose — peeling must never REMOVE a reference the un-peeled read would- have found. A local script named ``./timeout`` is a script, not the- coreutils wrapper, and reading only the peeled index would skip it.+ Each segment is read at the original token AND at the peeled wrapper target. Additive on purpose:+ peeling must never REMOVE a reference (a local ``./timeout`` is a script, not the coreutils wrapper)."""for segment in _iter_command_segments(command):index = _command_token_index(segment)@@ -848,16 +609,13 @@ def _iter_shell_command_payloads(command: str) -> Iterator[str]:index = _command_token_index(segment)if index is None:continue- # Command-string options are read at the ORIGINAL token: peeling past- # `su`/`env` would discard the very option carrying the command.+ # Read at the ORIGINAL token: peeling past `su`/`env` would discard the option carrying the command.for option in _STRING_COMMAND_OPTIONS.get(_executable_name(segment[index]), ()):yield from _iter_option_values(segment, index, option)- index = _peel_transparent_prefixes(segment, index)- if index >= len(segment):- continue- if _executable_name(segment[index]) not in _SHELL_EXECUTABLES:+ index = _executed_command_index(segment)+ if index is None or _executable_name(segment[index]) not in _SHELL_EXECUTABLES:continuearguments = segment[index + 1 :]for arg_index, argument in enumerate(arguments[:-1]):@@ -892,17 +650,11 @@ _BINARY_MAGICS = (def _has_binary_magic(data: bytes) -> bool:- """Return True when *data* starts with a known compiled-binary signature.+ """True when *data* starts with a known compiled-binary signature.- Deliberately narrower than "contains a NUL byte": a shell script that- happens to hold a NUL is still executed by ``bash``, so treating every- NUL-bearing file as an unscannable binary lets a padded script bypass the- lifecycle scan entirely.-- A shebang always wins — an interpreted script is never a binary, however- odd its payload. File extensions are deliberately *not* consulted: a- suffixless shell script must still be scanned (and, if oversized, still- fail closed).+ Deliberately narrower than "contains a NUL": ``bash`` still executes a NUL-bearing script, so a+ padded script must not bypass the scan. A shebang always wins (interpreted, never binary). File+ extensions are not consulted: a suffixless script must still be scanned and fail closed if oversized."""if data.startswith(b"#!"):return False@@ -912,60 +664,33 @@ def _has_binary_magic(data: bytes) -> bool:def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:"""Return ``(text, unsafe)`` using bounded, regular-file-only reads.- This is the shared choke point for every local script read the guard- performs (the terminal walk in ``_contains_unsafe_gateway_action`` AND- the cron-script scan in ``_read_script_for_scanning``), so the- cloud-placeholder refusal lives here: a FileProvider path must never be- opened — not even to discover whether the file is hydrated — because an- evicted placeholder's ``open()`` can hang preflight indefinitely- (#88052). The lexical check covers direct cloud paths; the resolved- check covers local launchers that are symlinks into a cloud subtree.+ Shared choke point for every local script read, so the cloud-placeholder refusal lives here: a+ FileProvider path is never opened — not even to check hydration — because an evicted placeholder's+ ``open()`` can hang preflight. Lexical check covers direct paths; resolved check covers symlinks."""- if _is_cloud_placeholder_path(path):- return None, True- try:- resolved = path.resolve(strict=False)- except (OSError, ValueError):- # OSError: unreadable/long paths. ValueError: embedded NUL byte- # from a binary's decoded contents tokenized as a path — a- # guarded path must never crash the guard (#76762).- resolved = path- if _is_cloud_placeholder_path(resolved):+ if _on_cloud_path(path):return None, Trueflags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)try:descriptor = os.open(path, flags)except (OSError, ValueError):- # OSError: unreadable / missing / over-long paths. ValueError: an- # embedded NUL byte in *path* itself — a binary's decoded bytes- # tokenized into a bogus script path by the recursion (#77703). A- # guarded read must never crash the guard, so treat either as- # "nothing to scan" (mirrors the resolve() ValueError guard below).+ # OSError: unreadable/missing/over-long. ValueError: embedded NUL in *path* (decoded binary+ # tokenized as a path). Never crash the guard — either is "nothing to scan".return None, Falsetry:metadata = os.fstat(descriptor)if not stat.S_ISREG(metadata.st_mode):- # Directories are not scripts. Docker Desktop writes- # ``fpath=(~/.docker/completions …)`` into ``~/.zshrc``; the- # walk then treats that dir as a referenced script and used- # to fail-closed, blocking ``source ~/.zshrc`` (#86753).- # Devices/sockets stay fail-closed.+ # Directories are not scripts (e.g. `fpath=(~/.docker/completions …)` in ~/.zshrc must not+ # block `source ~/.zshrc`). Devices/sockets stay fail-closed.if stat.S_ISDIR(metadata.st_mode):return None, Falsereturn None, True- # Sniff a small prefix first: files that are clearly compiled- # binaries (executable magic) are never shell scripts, so skip them- # WITHOUT reading the rest — reading a megabyte of machine code just- # to discard it wastes the guard's budget and (pre-#77703) fed- # decoded garbage into the recursion. Deliberately NOT keyed on the- # mere presence of a NUL byte (#77927): bash executes a text script- # straight past an embedded NUL, so NUL-bearing text must fall- # through to the magic-number check + NUL-strip below.+ # Sniff a small prefix first: compiled binaries (executable magic) are never shell scripts, so+ # skip them WITHOUT reading the rest or feeding decoded garbage into the recursion.data = os.read(descriptor, _BINARY_SNIFF_BYTES)- if data.startswith(_BINARY_MAGIC_PREFIXES):+ if _has_binary_magic(data):return None, False- # Read the remainder (bounded). Loop because os.read may return- # short for non-regular-file-backed descriptors.+ # Read the remainder (bounded); loop because os.read may return short.while len(data) <= _MAX_REFERENCED_SCRIPT_BYTES:chunk = os.read(descriptor, _MAX_REFERENCED_SCRIPT_BYTES + 1 - len(data)@@ -977,21 +702,12 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:return None, Falsefinally:os.close(descriptor)- # Identify binaries by MAGIC NUMBER, not by the mere presence of a NUL.- #- # "contains a NUL" and "is a compiled binary" are different questions, and- # the gap between them is a guard bypass: `bash` executes a *text* script- # straight past an embedded NUL, so a single pad byte in a shell script made- # the scan skip a file that still runs its lifecycle command. Match on the- # signature instead (ELF/Mach-O/PE/static archive/compressed), and treat a- # NUL-bearing *text* file as a script whose NULs are stripped before- # scanning — stripping can only splice tokens together, never apart, so it- # fails closed.+ # Identify binaries by MAGIC NUMBER, not by a NUL: `bash` executes a text script straight past an+ # embedded NUL, so a single pad byte must not make the scan skip a file that still runs.if _has_binary_magic(data):return None, False- # Check the size BEFORE stripping: stripping shrinks the buffer, so doing it- # first would let an oversized file slip under the threshold and skip this- # fail-closed branch.+ # Size check BEFORE NUL stripping: stripping shrinks the buffer and would let an oversized file+ # slip under the threshold past this fail-closed branch.if len(data) > _MAX_REFERENCED_SCRIPT_BYTES:return None, Trueif b"\x00" in data:@@ -1002,19 +718,10 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:def _sanitize_remote_script_text(text: Optional[str]) -> tuple[Optional[str], bool]:"""Apply the local-read contract to text from a ``read_remote_script`` callback.- The recursion boundary must not trust its callbacks: any backend (SSH,- Modal, Daytona, or a future one) can hand back raw binary bytes decoded- as text, or arbitrarily large output. Mirror- ``_read_referenced_script``'s semantics exactly — NUL bytes mean binary- (nothing to scan, checked first, #77703), oversized text fails closed- like an oversized local file (#76762) — so remote and local reads can- never diverge again. The size check re-encodes to compare *bytes*- (matching the local read and the ``head -c`` wire bound): a >1 MiB- multibyte file truncated at the byte cap decodes to fewer characters- than bytes, and a character-count check would scan the truncated text- instead of failing closed. Enforced here rather than inside each- callback so the guarantee holds for every callback, not just the ones- we hardened.+ Callbacks are untrusted: any backend can return decoded binary or huge output. Mirror+ ``_read_referenced_script``: NUL means binary (nothing to scan, checked first); oversized fails+ closed. Size compares *bytes* (re-encoded, matching the ``head -c`` wire bound): a >1 MiB multibyte+ file truncated at the byte cap decodes to fewer chars, and a char count would scan instead of failing."""if not text:return None, False@@ -1049,23 +756,10 @@ def _contains_unsafe_gateway_action(return Truefor script_path in _iter_referenced_shell_scripts(command, cwd=cwd):- # Do not touch a FileProvider path even to discover whether the file- # is hydrated. The lexical check covers direct cloud paths; the- # resolved check below covers local launchers that are symlinks into- # a cloud subtree. _read_referenced_script repeats both checks as the- # shared choke point, so every caller stays covered even if this- # walk-level short-circuit is bypassed.- if _is_cloud_placeholder_path(script_path):- return True- try:- resolved = script_path.resolve(strict=False)- except (OSError, ValueError):- # OSError: unreadable/long paths. ValueError: embedded NUL byte- # from a binary's decoded contents tokenized as a path — a- # guarded path must never crash the guard (#76762).- resolved = script_path- if _is_cloud_placeholder_path(resolved):+ # Do not touch a FileProvider path even to discover whether the file is hydrated.+ if _on_cloud_path(script_path):return True+ resolved = _resolve_lenient(script_path)if resolved in visited:continuevisited.add(resolved)@@ -1073,10 +767,8 @@ def _contains_unsafe_gateway_action(if unsafe:return Trueif script_text is None and read_remote_script is not None:- # Local path missing; try the remote backend if one is available.- # The callback's output crosses the same trust boundary as a- # local read — sanitize it identically before it enters the- # recursion (binary skip + size fail-closed).+ # Local path missing; try the remote backend. Its output crosses the same trust boundary+ # as a local read — sanitize identically (binary skip + size fail-closed).script_text, unsafe = _sanitize_remote_script_text(read_remote_script(str(script_path)))@@ -1084,8 +776,7 @@ def _contains_unsafe_gateway_action(return Trueif not script_text:continue- # Relative references inside a script resolve against that script's- # directory, not the original command's cwd.+ # Relative references inside a script resolve against that script's directory, not the cwd.script_dir = _resolve_script_directory(str(resolved)) or cwdif _contains_unsafe_gateway_action(script_text,@@ -1106,18 +797,9 @@ def contains_gateway_lifecycle_command_or_referenced_script() -> bool:"""Detect lifecycle/submit commands, including bounded nested scripts.- Total by construction: this function returns a verdict for *every*- input and never raises. The direct scans below are pure string- operations; the referenced-script walk touches the filesystem, remote- backends, and shlex on arbitrary decoded bytes, so it is best-effort- defense-in-depth — any unexpected failure inside it is logged and- treated as "walk found nothing" rather than crashing the caller.-- This is the contract #76762 established ("a guarded path must never- crash the guard") enforced at the boundary instead of per-syscall: a- guard crash propagates out of ``tools/terminal_tool.py`` and breaks- every terminal command until the gateway restarts (#77780, #78256),- which is strictly worse than either verdict.+ Total by construction: never raises. Direct scans are pure string ops; the referenced-script walk+ (filesystem, remote backends, shlex on decoded bytes) is best-effort defense-in-depth — an+ unexpected failure is logged and treated as "walk found nothing"."""try:# Includes the direct regex/submit scans at depth 0.@@ -1138,31 +820,15 @@ def contains_gateway_lifecycle_command_or_referenced_script(try:return _direct_lifecycle_scan(command)except Exception:- # The data-argument masker tokenizes arbitrary text; if even- # that fails, fall to the raw regex + submit scan so the guard- # stays total.- return contains_gateway_lifecycle_command(- command- ) or contains_launchctl_submit_command(command)--+ # If even the data-argument masker fails, fall to raw regex + submit scan so the guard stays total.+ return contains_gateway_lifecycle_command(command) or contains_launchctl_submit_command(command)def _resolve_script_path(script_path: str) -> Optional[Path]:"""Resolve a cron ``script`` value the same way the scheduler does.- The scheduler (``cron.scheduler``) resolves a bare/relative script path- under ``<HERMES_HOME>/scripts/`` and only accepts absolute paths as-is.- We MUST mirror that here so the guard scans the file that will actually- run — otherwise a job whose script lives at the scheduler's real location- (``~/.hermes/scripts/restart.sh``) but is passed as the bare name- ``restart.sh`` would read as a nonexistent relative path and silently- scan prompt-only content, letting the command through.-- Returns ``None`` for values that cannot be a real path (NUL bytes,- unexpandable ``~``) — the same ingestion contract as- ``_expand_candidate_path``; such a value can never name a file the- scheduler would execute, so there is nothing to scan.+ ``cron.scheduler`` resolves relative paths under ``<HERMES_HOME>/scripts/``; we MUST mirror it so+ the guard scans the file that will actually run, not a nonexistent relative path."""from hermes_constants import get_hermes_home@@ -1174,19 +840,14 @@ def _resolve_script_path(script_path: str) -> Optional[Path]:try:return get_hermes_home() / "scripts" / rawexcept (RuntimeError, OSError):- # get_hermes_home() falls back to Path.home(), which raises when- # neither HERMES_HOME nor HOME is resolvable (launchd/systemd- # environments) — same ingestion contract: nothing to scan.+ # get_hermes_home() falls back to Path.home(), which raises when neither HERMES_HOME nor HOME+ # is resolvable (launchd/systemd) — same ingestion contract: nothing to scan.return Nonedef _read_script_for_scanning(script_path: str) -> str:- """Read a cron script with the bounded terminal-script scanner.-- Non-regular or oversized inputs fail closed by returning a lifecycle-shaped- sentinel, while missing/unreadable/unresolvable paths remain empty so- ordinary scheduler path validation can report them.- """+ """Read a cron script with the bounded scanner. Non-regular/oversized inputs fail closed via a+ lifecycle-shaped sentinel; missing/unreadable paths stay empty so scheduler validation reports them."""resolved = _resolve_script_path(script_path)if resolved is None:return ""@@ -1200,60 +861,34 @@ def check_gateway_lifecycle(prompt: Optional[str],script: Optional[str] = None,) -> None:- """Raise ``GatewayLifecycleBlocked`` if *prompt* or *script* contains a- gateway-lifecycle command pattern.-- ``prompt`` is scanned directly. ``script``, when supplied, is read from- disk and concatenated for the scan. Both are considered together so a- job cannot slip through by splitting the command across the prompt and- the script.+ """Raise ``GatewayLifecycleBlocked`` if *prompt* or *script* contains a gateway-lifecycle command.- Callers should let the exception propagate when they want the create to- fail with a ``ValueError``-shaped error (the agent's ``cronjob`` tool- surfaces this as a tool error; the CLI prints it in red and exits 1).+ The script is read from disk and concatenated with the prompt so a command cannot slip through+ by being split across the two. Callers let the ``ValueError``-shaped exception propagate."""combined = prompt or ""python_script = Falseif script:resolved_script = _resolve_script_path(script)- if resolved_script is not None:- try:- real_script = resolved_script.resolve(strict=False)- except (OSError, ValueError):- real_script = resolved_script- if _is_cloud_placeholder_path(resolved_script) or _is_cloud_placeholder_path(- real_script- ):- # Attribute the refusal correctly: the script is not known to- # contain a lifecycle command — it lives on a cloud-synced- # FileProvider path (iCloud Drive / ~/Library/CloudStorage)- # that the guard refuses to open because an evicted- # placeholder can hang preflight indefinitely (#88052).- # Fail closed with the real reason instead of implying a- # dangerous lifecycle command.- raise GatewayLifecycleBlocked(- "Blocked: the cron script lives on a cloud-synced path "- "(iCloud Drive / ~/Library/CloudStorage). Opening an "- "evicted FileProvider placeholder can hang the guard's "- "preflight scan indefinitely, so it is refused without "- "being read. Move the script to a local, non-cloud path "- "(e.g. ~/.hermes/scripts/) and recreate the job."- )+ # Attribute the refusal correctly: not a known lifecycle command, but a cloud path the guard refuses to open.+ if resolved_script is not None and _on_cloud_path(resolved_script):+ raise GatewayLifecycleBlocked(+ "Blocked: the cron script lives on a cloud-synced path "+ "(iCloud Drive / ~/Library/CloudStorage). Opening an "+ "evicted FileProvider placeholder can hang the guard's "+ "preflight scan indefinitely, so it is refused without "+ "being read. Move the script to a local, non-cloud path "+ "(e.g. ~/.hermes/scripts/) and recreate the job."+ )python_script = resolved_script is not None and resolved_script.suffix == ".py"script_text = _read_script_for_scanning(script)if script_text:combined = f"{combined}\n{script_text}"if python_script:- # Python is executed by the interpreter, never through a POSIX- # shell: the shell-script reference walk is a false-positive- # generator on Python sources (pathlib's "/" operator resolves to- # the filesystem root and trips the regular-file check, blocking- # every innocent .py cron script, #77131). The direct command- # regex below still scans the full text, so a literal- # `hermes gateway restart` embedded in a .py script is still- # blocked. Non-regular/oversized script files still fail closed- # via the lifecycle-shaped sentinel in _read_script_for_scanning.+ # Python runs via the interpreter, never a POSIX shell, and the shell reference walk is a+ # false-positive generator on Python sources (pathlib "/" resolves to the filesystem root).+ # The regex still scans the full text; non-regular/oversized files still fail closed via the sentinel.unsafe = _lifecycle_command_scan_with_data_exemption(combined)else:script_dir = _resolve_script_directory(script) if script else None