The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cron): compact scheduler_provider and small cron modules
Teknium064bcaf3c1ef
diff --git a/cron/__init__.py b/cron/__init__.pyindex 8e2934ee752..4eae7521362 100644--- a/cron/__init__.py+++ b/cron/__init__.py@@ -1,5 +1,4 @@-"""-Cron job scheduling system for Hermes Agent.+"""Cron job scheduling system for Hermes Agent.This module provides scheduled task execution, allowing the agent to:- Run automated tasks on schedules (cron expressions, intervals, one-shot)@@ -11,8 +10,8 @@ Cron jobs are executed automatically by the gateway daemon:sudo hermes gateway install --system # Linux servers: boot-time system servicehermes gateway # Or run in foreground-The gateway ticks the scheduler every 60 seconds. A file lock prevents-duplicate execution if multiple processes overlap.+The gateway ticks the scheduler every 60 seconds. A file lock prevents duplicate execution if+multiple processes overlap."""from cron.jobs import (diff --git a/cron/blueprint_catalog.py b/cron/blueprint_catalog.pyindex adfbffbe620..e6c34065d1d 100644--- a/cron/blueprint_catalog.py+++ b/cron/blueprint_catalog.py@@ -1,24 +1,8 @@-"""Automation Blueprints — parameterized automation blueprints with typed slots.--A *blueprint* is a one-place definition of an automation that every surface-renders natively:-- * Dashboard / GUI app -> a form (one field per slot)- * CLI / TUI / messenger -> a pre-filled ``/blueprint`` slash command- * Agent -> a seed prompt; it asks for any blank/ambiguous slot- * Docs catalog -> a copy-paste command + a ``hermes://`` deep-link--The single source of truth is the slot schema below. ``blueprint_form_schema``-emits what a form renderer needs; ``blueprint_slash_command`` emits the flattened-one-line command; ``fill_blueprint`` validates user-supplied values and turns a-blueprint into a ``cron.jobs.create_job`` kwargs dict (so there is no second job-engine). The form-where-there's-a-screen / agent-fills-where-there's-a-chat-split both consume this same module.--Design choice: users never type raw cron. A blueprint carries a fixed recurrence-in ``schedule_template`` and parameterizes only the human-friendly parts-(time-of-day, weekday set). Blueprints needing full flexibility expose a ``text``-slot named ``schedule`` that passes through verbatim.+"""Automation Blueprints — one slot-schema definition per automation that every surface renders+natively: dashboard form (``blueprint_form_schema``), pre-filled ``/blueprint`` slash command+(``blueprint_slash_command``), agent seed prompt, docs deep-link. ``fill_blueprint`` validates values+into ``cron.jobs.create_job`` kwargs — there is no second job engine. Users never type raw cron:+``schedule_template`` fixes the recurrence and only human-friendly parts (time, weekdays) are slots."""from __future__ import annotations@@ -68,10 +52,9 @@ class BlueprintSlot:options: tuple = () # for type="enum": allowed valuesoptional: bool = Falsehelp: str = ""- # When False, ``options`` are suggestions rather than a closed set —- # any value is accepted (e.g. the deliver slot, where the real set of- # valid platforms depends on the user's configured gateways and is- # validated downstream by the cron scheduler).+ # When False, ``options`` are suggestions rather than a closed set — any value is accepted (e.g.+ # the deliver slot, where the real set of valid platforms depends on the user's configured+ # gateways and is validated downstream by the cron scheduler).strict: bool = Truedef __post_init__(self) -> None:@@ -418,9 +401,8 @@ CATALOG: List[AutomationBlueprint] = [description="A periodic nudge during the day to drink water, stand up, ""and stretch.",category="general",- # NOTE: cron minute-field steps (*/90) wrap per hour — */90 and */120- # both degrade to hourly. Use an hour-field step instead so the chosen- # cadence is what actually fires.+ # NOTE: cron minute-field steps (*/90) wrap per hour — */90 and */120 both degrade to+ # hourly. Use an hour-field step instead so the chosen cadence is what actually fires.schedule_template="0 {start_hour}-{end_hour}/{interval_hours} * * 1-5",prompt_template=("Send the user a brief, friendly nudge to drink some water, stand "@@ -752,11 +734,10 @@ def fill_blueprint() -> Dict[str, Any]:"""Validate ``values`` and return ``cron.jobs.create_job`` kwargs.- Missing required (non-optional) slots raise BlueprintFillError naming the- slot, so a form can show field errors and the agent knows what to ask.- Unknown slot names are rejected (a typo'd ``tiem=07:15`` must not silently- create a job with the default time). Enum values are checked against their- options. The result is passed straight to ``create_job`` — no second schema.+ Missing required (non-optional) slots raise BlueprintFillError naming the slot, so a form can+ show field errors and the agent knows what to ask. Unknown slot names are rejected (a typo'd+ ``tiem=07:15`` must not silently create a job with the default time). Enum values are checked+ against their options. The result is passed straight to ``create_job`` — no second schema."""known = {s.name for s in blueprint.slots}unknown = sorted(set(values) - known)diff --git a/cron/executions.py b/cron/executions.pyindex efadab464a2..9f9bc6fbeb7 100644--- a/cron/executions.py+++ b/cron/executions.py@@ -70,15 +70,9 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:@contextmanagerdef _transaction() -> Iterator[sqlite3.Connection]:- """Open a connection, commit/rollback on exit, always close.-- ``sqlite3.Connection.__enter__``/``__exit__`` only commit or roll back- the transaction; it does not close the connection. Relying on that alone- leaks a connection (and its WAL/SHM file descriptors) on every call,- since closing then depends on the garbage collector. Schema init runs- inside the ``try`` too, so a PRAGMA/DDL failure after a successful- ``connect()`` still closes the connection instead of leaking it.- """+ """Open a connection, commit/rollback on exit, always close. ``sqlite3.Connection``'s own+ context manager does NOT close (leaks WAL/SHM fds until GC); schema init runs inside the ``try``+ so a PRAGMA/DDL failure after ``connect()`` still closes."""with _lock:conn = _connect()try:diff --git a/cron/incidents.py b/cron/incidents.pyindex 8ecc3017896..6b62bd92796 100644--- a/cron/incidents.py+++ b/cron/incidents.py@@ -1,23 +1,18 @@"""Durable cron failure incidents with signature dedup and ack.-The executions ledger (``cron.executions``) records every attempt; this module-groups the *failures* into durable incidents keyed by ``(job_id, error-signature)`` so the same job failing with the same error does not re-ping the-operator every run once they have acknowledged it.--Lifecycle: ``detected`` → ``alerted`` → ``closed``. Closing-(acking) an incident is per-signature: the same job + same normalized error-keeps resolving to the SAME incident id, so a closed incident stays closed (no-re-alert) until the error text changes, which mints a brand-new incident.-``detected`` means the failure was recorded; ``alerted`` means at least one-failure ping for the signature actually reached the operator. Richer states-(e.g. a dv9.6 ``reviewed``) are deliberately NOT reserved here — state-validity lives in ``INCIDENT_STATES`` (Python), not a SQLite CHECK, exactly-so a future slice can add states without a table rebuild.--Incidents live in the SAME ``cron/executions.db`` as ``cron.executions`` so-there is one durable cron store per profile. The schema is lazily created on-connect and a missing database never raises (directories are created).+The executions ledger (``cron.executions``) records every attempt; this module groups the *failures*+into durable incidents keyed by ``(job_id, error signature)`` so the same job failing with the same+error does not re-ping the operator every run once they have acknowledged it.++Lifecycle: ``detected`` → ``alerted`` → ``closed``. Closing (acking) an incident is per-signature:+the same job + same normalized error keeps resolving to the SAME incident id, so a closed incident+stays closed (no re-alert) until the error text changes, which mints a brand-new incident.+``detected`` means the failure was recorded; ``alerted`` means at least one failure ping for the+signature actually reached the operator. Other lifecycle words (e.g. ``reviewed``) are deliberately+NOT reserved here.++Incidents live in the SAME ``cron/executions.db`` as ``cron.executions`` (one ledger file, shared+connection settings)."""from __future__ import annotations@@ -63,10 +58,9 @@ def _connect() -> sqlite3.Connection:def _db_path() -> Path:"""Resolve the shared cron DB path.- Prefer the ``cron.executions`` override when one is installed so an- operator/test that redirects the executions ledger also redirects the- incident table — they must stay in the SAME database. Falls back to this- module's own override, then the canonical profile home.+ Prefer the ``cron.executions`` override when one is installed so an operator/test that redirects+ the executions ledger also redirects the incident table — they must stay in the SAME database.+ Falls back to this module's own override, then the canonical profile home."""try:from cron.executions import EXECUTIONS_FILE as _EXEC_OVERRIDE@@ -116,9 +110,8 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:def _transaction() -> Iterator[sqlite3.Connection]:"""Open a connection, commit/rollback on exit, always close.- Mirrors ``cron.executions._transaction``: schema init runs inside the- ``try`` so a PRAGMA/DDL failure after a successful ``connect()`` still- closes the connection instead of leaking it.+ Mirrors ``cron.executions._transaction``: schema init runs inside the ``try`` so a PRAGMA/DDL+ failure after a successful ``connect()`` still closes the connection instead of leaking it."""with _lock:conn = _connect()diff --git a/cron/monitor.py b/cron/monitor.pyindex e84c4ce4d73..9457e518631 100644--- a/cron/monitor.py+++ b/cron/monitor.py@@ -1,32 +1,12 @@"""Monitor-mode cron support — hash-suppressed change detection.-A monitor job attaches a cheap *monitor source* (``monitor_script`` or-``monitor_url``) to an ordinary LLM cron job. Each tick the scheduler runs-the source FIRST and compares a hash of its exact output bytes against the-hash stored from the last agent-triggering tick:--* unchanged → the agent run is suppressed entirely (no LLM, no delivery);- the tick is recorded as a silent ``no_change`` run.-* changed (or first run) → a "MONITOR CHANGE DETECTED" context block —- unified diff of old vs new output (capped) plus the new output — is- injected into the prompt and the agent runs normally.-* source failure → treated as an ERROR, never as a change. The stored hash- is left untouched so a source that recovers to its previous output still- suppresses.--Output is compared as EXACT BYTES — no timestamp stripping or whitespace-normalization. Monitor scripts should emit stable output (sort results,-omit "generated at" lines) or every tick will look like a change.--State lives in two places, both durable across scheduler restarts:--* ``job["monitor_state"]`` in jobs.json — ``last_output_hash`` +- ``last_changed_at`` (additive JSON fields, no migration needed);-* ``OUTPUT_DIR/<job_id>/monitor_last_output.txt`` — the previous output- text, kept only so the next change can render a diff.--Inspired by: ChatGPT Work monitor tasks (idea-level, docs-only);-enabler: #80774.+A monitor job attaches a cheap source (``monitor_script`` / ``monitor_url``) to an LLM cron job. Each+tick runs the source FIRST and hashes its EXACT output bytes (no timestamp/whitespace normalization —+scripts must emit stable output) against the hash from the last agent-triggering tick: unchanged →+agent run suppressed (silent ``no_change`` run); changed/first run → a "MONITOR CHANGE DETECTED"+block (capped unified diff + new output) is injected into the prompt; source failure → an ERROR,+never a change, and the stored hash is left untouched. State: ``job["monitor_state"]`` in jobs.json+(hash + last_changed_at) and ``OUTPUT_DIR/<job_id>/monitor_last_output.txt`` (for the diff)."""from __future__ import annotations@@ -148,9 +128,8 @@ def job_has_monitor(job: dict) -> bool:def check_monitor(job: dict) -> MonitorOutcome:"""Run the monitor source and decide whether the agent should run.- On change (or first run) the new hash + snapshot are persisted BEFORE- the agent runs — detection time is the state boundary, so a failed- agent run doesn't re-alert on the same content forever.+ On change (or first run) the new hash + snapshot are persisted BEFORE the agent runs — detection+ time is the state boundary, so a failed agent run doesn't re-alert on the same content forever.On failure nothing is persisted."""job_id = str(job.get("id") or "")diff --git a/cron/notepad.py b/cron/notepad.pyindex 450b951661d..d0d304b4daa 100644--- a/cron/notepad.py+++ b/cron/notepad.py@@ -1,24 +1,10 @@-"""Per-job durable notepad for cron jobs.+"""Per-job durable KV notepad (cursors, watermarks) carried across cron wake-ups; profile-local+SQLite next to the executions ledger (same connection/pragma pattern as ``cron/executions.py``).-A tiny KV scratchpad each cron job can use to carry state across scheduled-wake-ups (cursors, watermarks, watchlists). Stored in its own profile-local-SQLite file next to the executions ledger, following the same-connection/pragma pattern as ``cron/executions.py``.--Size caps (documented contract):--- ``MAX_VALUE_BYTES`` (16 KB): per-key value cap, measured in UTF-8 bytes.-- ``MAX_JOB_TOTAL_BYTES`` (64 KB): per-job cap over the sum of key+value- bytes. Oversized writes raise ``ValueError`` and leave the store- untouched — the notepad is prompt-injected each run, so unbounded growth- would bloat every wake-up's prompt.--Write path is the CLI (``hermes cron notepad <job_id> set <key> <value>``),-which the running agent invokes via its terminal tool; no model tool is-added.--Inspired by: Amp (Sourcegraph) cron notepad (idea-level, proprietary — zero-code).+Caps are a documented contract: ``MAX_VALUE_BYTES`` (16 KB per value, UTF-8) and+``MAX_JOB_TOTAL_BYTES`` (64 KB per job, key+value). Oversized writes raise ``ValueError`` and leave+the store untouched — the notepad is prompt-injected each run. Write path is the CLI+(``hermes cron notepad <job_id> set ...``) via the terminal tool; no model tool is added."""from __future__ import annotations@@ -32,10 +18,9 @@ from typing import Any, Dict, Iterator, List, Optionalfrom hermes_constants import get_hermes_homefrom hermes_time import now as _hermes_now-# Optional test override. Production resolves the path at transaction time so-# multiplexed profile ticks (set_hermes_home_override) cannot leak one-# profile's notepad rows into the import-time home — and remove_job's-# clear_notepad cannot wipe the wrong profile's DB (#86519). Same pattern as+# Optional test override. Production resolves the path at transaction time so multiplexed profile+# ticks (set_hermes_home_override) cannot leak one profile's notepad rows into the import-time home+# — and remove_job's clear_notepad cannot wipe the wrong profile's DB. Same pattern as# cron/executions.py.NOTEPAD_FILE: Optional[Path] = NoneMAX_VALUE_BYTES = 16 * 1024@@ -77,9 +62,8 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:def _transaction() -> Iterator[sqlite3.Connection]:"""Open a connection, commit/rollback on exit, always close.- Mirrors ``cron.executions._transaction``: schema init runs inside the- ``try`` so a PRAGMA/DDL failure still closes the connection instead of- leaking it.+ Mirrors ``cron.executions._transaction``: schema init runs inside the ``try`` so a PRAGMA/DDL+ failure still closes the connection instead of leaking it."""with _lock:conn = _connect()diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.pyindex 563cba345b2..6b1add10cfc 100644--- a/cron/scheduler_provider.py+++ b/cron/scheduler_provider.py@@ -1,62 +1,31 @@-"""CronScheduler provider interface (Axis B — the trigger).--⚠️ EXPERIMENTAL — this interface is validated by exactly ONE consumer (the-built-in) until an external provider (Chronos, Phase 4) shakes it out. Until-then the module path, method signatures, and start() kwargs MAY change without-a deprecation cycle. Once a second provider validates the shape it becomes-stable. Any growth MUST be additive (new optional method with a default), never-a changed signature on start() or a new abstractmethod.--A CronScheduler decides *when* a due job fires. It does NOT decide what firing-means: execution + delivery stay in cron.scheduler.run_job / _deliver_result,-shared by all providers. Providers must never reimplement agent construction or-delivery.--The built-in InProcessCronScheduler runs the historical 60s daemon-thread-ticker. Alternative providers (e.g. Chronos, a NAS-mediated managed-cron-provider for scale-to-zero deployments) live under plugins/cron_providers/<name>/ and are-selected via the `cron.provider` config key (empty = built-in).+"""CronScheduler provider interface (Axis B — the trigger). EXPERIMENTAL: shape MAY change until a+second provider validates it; growth MUST be additive (optional method with a default), never a+changed start() signature or new abstractmethod. Providers decide only *when* a job fires —+execution + delivery stay in cron.scheduler.run_job / _deliver_result; never reimplement them."""from __future__ import annotations+import contextlibimport inspectimport threadingfrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Any-# Cap for the exponential tick backoff applied while consecutive ticks fail-# with fd exhaustion (EMFILE/ENFILE, #87644). Base is the tick interval-# (60s by default); each consecutive EMFILE failure doubles the wait, capped-# here so a still-alive-but-exhausted gateway never sleeps longer than this-# between recovery attempts.+# Cap for exponential tick backoff during fd exhaustion (interval doubled per failure)._EMFILE_BACKOFF_MAX_SECONDS = 15 * 60 # 15 minutesdef _backoff_wait_seconds(interval: float, consecutive_failures: int) -> float:- """Exponential tick backoff shared by both ticker loops (#87644).-- Returns the plain ``interval`` while healthy; doubles per consecutive- fd-exhaustion failure, capped at ``_EMFILE_BACKOFF_MAX_SECONDS``.- """+ """Plain ``interval`` while healthy; doubles per fd-exhaustion failure, capped."""if consecutive_failures <= 0:return interval- return min(- interval * (2 ** (consecutive_failures - 1)),- _EMFILE_BACKOFF_MAX_SECONDS,- )+ return min(interval * (2 **(consecutive_failures - 1)), _EMFILE_BACKOFF_MAX_SECONDS)def _note_tick_failure(exc: BaseException, consecutive_failures: int) -> int:- """Classify one failed tick and return the updated failure counter.-- Shared by both ticker loops (#87644): on fd exhaustion, attempt- reclamation (gc.collect + raise the soft nofile limit) so the NEXT tick- can succeed, and bump the counter so ``_backoff_wait_seconds`` backs off- exponentially while the process has no chance of making progress. Any- other failure resets the counter — backoff is reserved for the- self-inflicted EMFILE storm, not transient errors.- """+ """On fd exhaustion: reclaim fds and bump the backoff counter; any other failure resets it —+ backoff is reserved for the EMFILE storm."""from cron.scheduler import _is_fd_exhaustion, _reclaim_fds_best_effortif _is_fd_exhaustion(exc):@@ -65,40 +34,34 @@ def _note_tick_failure(exc: BaseException, consecutive_failures: int) -> int:return 0+def _profile_entry(entry) -> tuple:+ """Normalize a ``profile_homes`` entry (``(name, home)`` tuple or bare home) to ``(name, home)``."""+ return entry if isinstance(entry, tuple) else (None, entry)++def _existing_profile_homes(profile_homes: list) -> list:- """Drop profile homes whose directory no longer exists on disk.-- The multiplex ticker's ``profile_homes`` is a snapshot taken at startup- (``web_server.py`` calls ``profiles_to_serve(multiplex=True)`` once, and- the gateway multiplex path does the same). If a profile is deleted while- the ticker runs — via ``hermes profile delete``, the desktop's DELETE- ``/api/profiles/<name>`` route, or any other path that removes the home- directory — that stale entry stays in the list.-- Ticking or heartbeating a deleted home recreates its ``cron/`` workspace- (``record_ticker_heartbeat`` -> ``ensure_dirs`` -> ``mkdir(parents=True)``)- on every 60s cycle, so the "deleted" profile silently comes back on disk- and in ``hermes profile list`` (#47368). Filtering on directory existence- leaves a deleted profile's home untouched, which is the correct invariant:- a home that does not exist cannot hold jobs to fire.- """- live = []- for entry in profile_homes:- home = entry[1] if isinstance(entry, tuple) else entry- if Path(home).is_dir():- live.append(entry)- return live+ """Drop homes no longer on disk: ticking/heartbeating a deleted home would recreate its+ ``cron/`` workspace and silently resurrect the profile."""+ return [entry for entry in profile_homes if Path(_profile_entry(entry)[1]).is_dir()]-class CronScheduler(ABC):- """Axis-B trigger provider. Decides WHEN a due cron job fires.+def _profile_cron_scope(home):+ """Scope the calling thread to one profile's home + cron store for the block."""+ from cron.jobs import use_cron_store+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override- Required surface is intentionally minimal: ``name`` + ``start``. ``stop``- and ``is_available`` carry safe defaults. The three Phase-4 hooks- (``on_jobs_changed`` / ``fire_due`` / ``reconcile``) are added later as- NON-abstract methods so the built-in keeps satisfying the ABC without- overriding them — see ``test_abc_growth_stays_additive``.- """+ home_token = set_hermes_home_override(str(home))+ try:+ with use_cron_store(home):+ yield+ finally:+ reset_hermes_home_override(home_token)+++class CronScheduler(ABC):+ """Decides WHEN a due cron job fires. Only ``name`` + ``start`` are required; keep every other+ hook NON-abstract with a safe default (``test_abc_growth_stays_additive``)."""@property@abstractmethod@@ -106,12 +69,7 @@ class CronScheduler(ABC):"""Short identifier, e.g. 'builtin', 'chronos'."""def is_available(self) -> bool:- """Whether this provider can run in the current environment.-- MUST NOT make network calls. The built-in is always available; an- external provider checks for configured endpoint/credentials. When a- named provider returns False, the resolver falls back to the built-in.- """+ """Whether this provider can run here. MUST NOT make network calls; False → built-in."""return True@abstractmethod@@ -123,39 +81,22 @@ class CronScheduler(ABC):loop: Any = None,interval: int = 60,) -> None:- """Begin firing due jobs.-- For the built-in this BLOCKS in the 60s loop until stop_event is set- (it is run inside a daemon thread by the caller, exactly as today).- An external provider may register a schedule/webhook and return- immediately; in that case it must still honor stop_event for teardown.- """+ """Begin firing due jobs. Built-in BLOCKS until stop_event is set (run in a daemon thread);+ an external provider may return immediately but must still honor stop_event."""def stop(self) -> None:- """Optional eager teardown hook. Default no-op; setting the stop_event- is the primary stop signal. Override for providers holding external- resources (queue consumers, HTTP servers)."""+ """Optional eager teardown; stop_event is the primary signal."""return None- # --- Optional hooks for external providers (added Phase 4). --------------- # All default-safe so the built-in inherits working behavior without- # overriding. Keep these NON-abstract — see test_abc_growth_stays_additive.+ # Optional hooks for external providers — default-safe; keep NON-abstract.def on_jobs_changed(self) -> None:- """Called after a successful store mutation (create/update/remove/- pause/resume). External providers reconcile their registry here (e.g.- Chronos re-provisions/cancels the affected one-shot via NAS).- Built-in: no-op (it re-reads jobs.json on every tick)."""+ """After a successful store mutation; external providers reconcile. Built-in: no-op."""return Nonedef register_job(self, job: dict[str, Any]) -> None:- """Register the first external trigger for one newly persisted job.-- The built-in provider reads the local store on every tick, so its- default is a no-op. External providers override this when creating a- job requires a remote registration before callers can honestly report- that the job is scheduled.- """+ """Register the external trigger for a newly persisted job (must complete before callers+ report it as scheduled). Built-in: no-op."""return Nonedef recover_interrupted(self) -> int:@@ -166,11 +107,7 @@ class CronScheduler(ABC):@propertydef supports_force_fire(self) -> bool:- """Whether ``fire_due`` accepts the additive ``force`` keyword.-- Signature detection keeps providers written before ``force`` was added- source-compatible. Providers accepting ``**kwargs`` are compatible.- """+ """Whether ``fire_due`` accepts ``force`` (signature-detected for older providers)."""return provider_supports_force_fire(self)def fire_due(@@ -181,30 +118,17 @@ class CronScheduler(ABC):loop: Any = None,force: bool = False,) -> bool:- """Run a single job NOW via the shared orchestrator. Called by the- inbound fire webhook when an external scheduler signals a job is due.-- The default claims the job with a store-level compare-and-set- (multi-machine at-most-once), then runs it via the shared- ``run_one_job`` body. Built-in never calls this (it has its own tick- loop); an external provider routes its inbound fire here.-- Returns True if THIS caller claimed and processed the attempt, even if- the job itself failed. Returns False only if the claim was lost- (another machine/retry won it) or the job no longer exists.- """+ """Run one job NOW (inbound fire webhook entry). Store CAS claim (multi-machine+ at-most-once) then shared ``run_one_job``. True if THIS caller claimed and processed the+ attempt (even if the job failed); False if the claim was lost or the job is gone."""claimed_job = self.claim_fire(job_id, force=force)if claimed_job is None:return Falsereturn self.fire_claimed(claimed_job, adapters=adapters, loop=loop)def claim_fire(self, job_id: str, *, force: bool = False) -> dict | None:- """Durably claim one fire and create its audit attempt before dispatch.-- Webhook transports call this synchronously before acknowledging the- external scheduler, then pass the exact owner-bearing snapshot to- ``fire_claimed`` in tracked background work.- """+ """Durably claim one fire + create its audit attempt. Transports call this synchronously+ before acknowledging, then pass the exact snapshot to ``fire_claimed`` off-thread."""from cron.executions import create_execution, finish_executionfrom cron.jobs import claim_job_for_fire@@ -222,11 +146,7 @@ class CronScheduler(ABC):)raiseif not isinstance(claimed_job, dict):- finish_execution(- execution["id"],- success=False,- error="Fire claim was not acquired",- )+ finish_execution(execution["id"], success=False, error="Fire claim was not acquired")return Noneclaimed_job["execution_id"] = execution["id"]return claimed_job@@ -239,27 +159,15 @@ class CronScheduler(ABC):loop: Any = None,cancel_event: Any = None,) -> bool:- """Run an exact snapshot returned by ``claim_fire``.-- ``cancel_event``: optional transport-owned ``threading.Event`` (or- compatible) that lets the caller stop this execution cooperatively- — e.g. the dashboard lifespan drain signalling pending webhook- fires before the event loop shuts down.- """+ """Run an exact ``claim_fire`` snapshot; ``cancel_event`` lets the transport stop it+ cooperatively (e.g. dashboard lifespan drain)."""from cron.scheduler import run_one_job- run_one_job(- claimed_job,- adapters=adapters,- loop=loop,- cancel_event=cancel_event,- )+ run_one_job(claimed_job, adapters=adapters, loop=loop, cancel_event=cancel_event)return Truedef reconcile(self) -> None:- """Converge the external registry toward jobs.json (the desired state):- arm missing one-shots, cancel orphaned ones, re-arm changed times.- Built-in: no-op."""+ """Converge the external registry toward jobs.json (desired state). Built-in: no-op."""return None@@ -281,31 +189,18 @@ def provider_supports_force_fire(provider: Any) -> bool:def provider_supports_split_fire(provider: Any) -> bool:- """Return whether a provider implements the two-phase fire contract.-- The webhook admission path uses ``claim_fire`` + ``fire_claimed`` so the- 202 response is backed by a durable, owner-fenced claim. A legacy- third-party provider that overrides the documented single-phase- ``fire_due`` hook (custom claim/re-arm/telemetry behavior) but inherits- the base ``claim_fire`` must keep being driven through its own- ``fire_due`` — silently routing around its override would drop that- behavior. Providers that customize ``claim_fire`` itself are already- split-aware and keep the two-phase path.- """+ """Whether a provider implements the two-phase fire contract. A legacy provider overriding only+ ``fire_due`` must keep being driven through it — routing around the override would drop its+ custom claim/re-arm/telemetry behavior."""cls = type(provider)fire_due_impl = getattr(cls, "fire_due", None)claim_fire_impl = getattr(cls, "claim_fire", None)fire_claimed_impl = getattr(cls, "fire_claimed", None)if claim_fire_impl is not None and claim_fire_impl is not CronScheduler.claim_fire:return True- # Overriding the second phase is also proof of split-awareness (the- # provider composes with the inherited claim path) — e.g. Chronos keeps- # its re-arm logic in ``fire_claimed`` only.if fire_claimed_impl is not None and fire_claimed_impl is not CronScheduler.fire_claimed:return True- if fire_due_impl is None or fire_due_impl is CronScheduler.fire_due:- return True- return False+ return fire_due_impl is None or fire_due_impl is CronScheduler.fire_duedef provider_supports_fire_cancel(provider: Any) -> bool:@@ -329,12 +224,7 @@ DEFAULT_MISFIRE_GRACE_MINUTES = 10def _misfire_grace_minutes() -> float:- """Resolve the misfire catch-up grace window from config.-- ``cron.misfire_grace_minutes`` (number, default- ``DEFAULT_MISFIRE_GRACE_MINUTES``). A non-positive value disables the- catch-up sweep entirely.- """+ """``cron.misfire_grace_minutes`` from config; non-positive disables the catch-up sweep."""try:from hermes_cli.config import cfg_get, load_config@@ -357,35 +247,11 @@ def fire_overdue_jobs(loop: Any = None,now: Any = None,) -> int:- """Fire jobs whose scheduled time passed without an external fire arriving.-- The misfire catch-up half of the hosted fire path. External providers- (Chronos) deliver scheduled fires over HTTP to this process's api_server- adapter; when that hop is down at fire time (gateway restart window,- api_server not bound, scheduler retry budget exhausted), the job's- ``next_run_at`` stays parked in the past and — because external providers- have no local tick loop — nothing ever runs it. The day is silently lost- even though the gateway may be healthy again minutes later.-- Called from the gateway housekeeping loop. Deliberately:-- - **No-op for the built-in provider.** Its tick loop already picks up- past-due jobs via ``get_due_jobs`` — local scheduling self-heals.- - **Routes through the provider's own two-phase fire path** — a- synchronous ``claim_fire`` (store CAS, so a late external retry- landing concurrently is de-duplicated) and then ``fire_claimed`` in- a daemon thread, mirroring the webhook admission pattern. The- housekeeping loop that calls this must never block for the length- of an agent run. Provider-specific re-arm logic (Chronos NAS- one-shots) runs exactly as for a normal fire.- - **Waits out a grace window** (``cron.misfire_grace_minutes``, default- 10, non-positive disables) so the external scheduler's own retry- backoff gets first right to deliver — catch-up is the backstop, not- a race.- - **Operates on the process-global cron store only** — same profile- scoping as the external provider's reconcile.-- Returns the number of jobs this sweep claimed and dispatched.+ """Misfire backstop (gateway housekeeping loop): fire jobs whose external HTTP fire never+ arrived, else ``next_run_at`` stays parked in the past forever. No-op for the built-in (its tick+ loop self-heals). Routes through the provider's own two-phase path so re-arm logic runs and a+ concurrent late external retry is de-duplicated by the store CAS; waits out+ ``cron.misfire_grace_minutes`` so the external retry gets first right. Returns jobs dispatched."""import loggingimport threading@@ -420,11 +286,7 @@ def fire_overdue_jobs(if overdue_seconds < grace_minutes * 60:continuejob_id = str(job.get("id") or "")- # One-shot jobs share the module-wide policy: more than- # ONESHOT_GRACE_SECONDS past their run time means "will never fire"- # (create/update/resume/recovery and, since #89571, the due-scan all- # enforce it). The misfire backstop must not resurrect them hours- # late after downtime — that's #93526.+ # One-shots past ONESHOT_GRACE_SECONDS "will never fire"; don't resurrect them hours late.schedule = job.get("schedule") or {}if str(schedule.get("kind") or "") == "once":from cron.jobs import ONESHOT_GRACE_SECONDS@@ -450,10 +312,7 @@ def fire_overdue_jobs(overdue_seconds / 60,)try:- # Two-phase, webhook-style: claim synchronously (fast store- # CAS — losing means an external retry beat us, which is- # fine), then run the job off-thread so the caller's loop is- # never blocked for the length of an agent run.+ # Claim synchronously (CAS loss = external retry beat us), run off-thread: never block.claimed = provider.claim_fire(job_id)if claimed is None:continue@@ -474,13 +333,8 @@ def fire_overdue_jobs(def resolve_cron_scheduler() -> "CronScheduler":- """Return the active cron scheduler provider.-- Reads ``cron.provider`` from config. Empty/absent → built-in. A named- provider that is missing, fails to load, or reports ``is_available() ==- False`` falls back to the built-in with a warning — cron must never be left- without a trigger.- """+ """Resolve ``cron.provider``; missing/failing/unavailable providers fall back to the built-in+ with a warning — cron must never be left without a trigger."""import logginglogger = logging.getLogger("cron.scheduler_provider")@@ -507,22 +361,15 @@ def resolve_cron_scheduler() -> "CronScheduler":logger.info("Using cron scheduler provider: %s", provider.name)return providerexcept Exception as e:- logger.warning(- "Failed to load cron.provider '%s' (%s); using built-in ticker", name, e- )+ logger.warning("Failed to load cron.provider '%s' (%s); using built-in ticker", name, e)return InProcessCronScheduler()def scheduler_for_profile_mode(provider: "CronScheduler", *, multiplex_profiles: bool) -> "CronScheduler":- """Return a scheduler that can safely serve the gateway's profile mode.-- External providers currently own one unscoped remote registry/client and- therefore cannot safely reconcile several profile stores from one process.- Fail closed to the built-in multiplex ticker until the provider API carries- explicit profile identity through lifecycle and webhook calls.- """+ """External providers own one unscoped remote registry and cannot reconcile several profile+ stores: fail closed to the built-in multiplex ticker until the API carries profile identity."""if not multiplex_profiles or isinstance(provider, InProcessCronScheduler):return provider@@ -536,14 +383,8 @@ def scheduler_for_profile_mode(class InProcessCronScheduler(CronScheduler):- """Default provider: the historical in-process 60s ticker.-- ``start()`` blocks in the tick loop until ``stop_event`` is set, identical- to the pre-refactor ``_start_cron_ticker`` core loop. The caller runs it in- a daemon thread. ``can_dispatch`` is an optional synchronous gate supplied- by GatewayRunner during external drain; skipped ticks leave due jobs intact- for the next allowed tick.- """+ """Default in-process 60s ticker; ``start()`` blocks until ``stop_event``. ``can_dispatch`` is+ an optional drain gate; skipped ticks leave due jobs intact for the next allowed tick."""@propertydef name(self) -> str:@@ -574,13 +415,7 @@ class InProcessCronScheduler(CronScheduler):logger = logging.getLogger("cron.scheduler_provider")logger.info("In-process cron scheduler started (interval=%ds)", interval)- # ── Multiplex profiles ────────────────────────────────────────────- # When profile_homes is set (multiplex_profiles on), tick EACH profile's- # cron store on every tick cycle so secondary-profile jobs actually fire- # instead of languishing in a store no ticker owns (#69377). Without this,- # only the process-global HERMES_HOME (the default profile) is ticked.- # Heartbeats and recovery are also scoped per profile so `hermes cron- # status` reflects liveness for every profile independently.+ # Multiplex: tick EACH profile's store every cycle, heartbeats/recovery scoped per profile.if profile_homes:self._start_multiplex(stop_event,@@ -595,21 +430,15 @@ class InProcessCronScheduler(CronScheduler):)return- # ── Single-profile (legacy) path ──────────────────────────────────recovered = self.recover_interrupted()if recovered:logger.warning("Marked %d interrupted cron execution(s) unknown after restart",recovered,)- # Heartbeat once before the first sleep so `hermes cron status` sees a- # live ticker immediately after startup, not only after the first tick.+ # Heartbeat before the first sleep so `hermes cron status` sees a live ticker immediately.record_ticker_heartbeat()- # Exponential backoff for consecutive tick failures — most importantly- # fd exhaustion (EMFILE/ENFILE, #87644). While FDs stay exhausted the- # ticker must NOT hammer the store every 60s; once they free (leak- # fixed, reclamation ran) the next tick succeeds and the backoff- # resets, so the scheduler self-heals without a gateway restart.+ # EMFILE backoff: don't hammer the store while fds are exhausted; a clean tick resets it.consecutive_failures = 0while not stop_event.is_set():ok = False@@ -626,35 +455,17 @@ class InProcessCronScheduler(CronScheduler):)ok = Trueexcept BaseException as e:- # Catch BaseException (not just Exception) so a SystemExit from- # a misbehaving provider SDK / agent retry path does not kill- # the ticker thread silently (#32612). KeyboardInterrupt is- # intentionally caught here too — gateway shutdown is driven by- # stop_event (set by the main thread's signal handler), not by- # an exception in this daemon thread, so swallowing it and- # re-checking stop_event keeps shutdown clean.+ # BaseException, not Exception: a SystemExit must not silently kill the ticker;+ # KeyboardInterrupt is caught on purpose — shutdown is driven by stop_event.if isinstance(e, CronTickYielded):- # Expected while this process is stale and a fresh gateway- # owns the runtime lock: not an error to debug, but it IS- # recorded below so status shows why ticks aren't firing- # from here. tick() already logged it once per episode.+ # Expected while a fresh gateway owns the lock; still recorded for status.logger.info("Cron tick yielded: %s", e)else:logger.error("Cron tick error: %s", e, exc_info=True)- # Persist the failure reason next to the heartbeat markers so- # `hermes cron status`/`list` (separate processes) can show- # WHY ticks fail, not just that the success marker is stale —- # e.g. a root-rewritten jobs.json locking out the ticker's- # uid went unnoticed for ~14h with the reason buried in the- # gateway log (#68483).+ # Persist the reason so `hermes cron status` (separate process) shows WHY.record_ticker_error(f"{type(e).__name__}: {e}")- # EMFILE: reclaim fds + back off exponentially so the- # exhausted process stops hammering the store while it has no- # chance of making progress (#87644).consecutive_failures = _note_tick_failure(e, consecutive_failures)- # Record liveness every iteration; bump the success marker only on a- # clean tick, so status can tell "alive but failing every tick" from- # "actually firing jobs" (#32612, #32895).+ # Liveness every iteration; success marker only on a clean tick.record_ticker_heartbeat(success=ok)if ok:clear_ticker_error()@@ -674,19 +485,9 @@ class InProcessCronScheduler(CronScheduler):default_profile=None,profile_gate=None,):- """Tick every served profile's cron store when multiplex_profiles is on.-- Each profile uses ``set_hermes_home_override()`` + ``use_cron_store()``- to scope its tick, heartbeat, recovery, lock file, config/.env, and- agent execution to that profile's home — mirroring how- ``_profile_runtime_scope`` scopes the multiplexed inbound path and- ``web_server.py`` scopes per-profile cron API calls.-- ``profile_gate(name, home) -> bool``, when given, is consulted every- cycle; a profile it rejects is neither ticked nor heartbeated that- cycle (the desktop ticker uses it to stand down for profiles whose- own gateway is running, #100489).- """+ """Tick every profile's store, each scoped via ``_profile_cron_scope``. ``profile_gate(name,+ home)``, when given, is consulted every cycle; a rejected profile is neither ticked nor+ heartbeated."""import loggingfrom cron.scheduler import tick as cron_tickfrom cron.scheduler import (@@ -699,9 +500,7 @@ class InProcessCronScheduler(CronScheduler):clear_ticker_error,record_ticker_error,record_ticker_heartbeat,- use_cron_store,)- from hermes_constants import set_hermes_home_override, reset_hermes_home_overridelogger = logging.getLogger("cron.scheduler_provider")logger.info(@@ -710,17 +509,11 @@ class InProcessCronScheduler(CronScheduler):[p[0] if isinstance(p, tuple) else p for p in profile_homes],)- # Recovery + initial heartbeat for every profile.- # A profile may have been deleted since this snapshot was taken;- # never recreate a deleted home's cron workspace via the heartbeat- # below (#47368).- # One profile's broken store (corrupt executions.db, unreadable- # cron dir) must not abort startup for every other profile (#74878).+ # Recovery + heartbeat per profile; one broken store must not abort startup for the others.for entry in _existing_profile_homes(profile_homes):- home = entry[1] if isinstance(entry, tuple) else entry- home_token = set_hermes_home_override(str(home))+ _, home = _profile_entry(entry)try:- with use_cron_store(home):+ with _profile_cron_scope(home):recovered = self.recover_interrupted()if recovered:logger.warning(@@ -736,60 +529,34 @@ class InProcessCronScheduler(CronScheduler):e,exc_info=True,)- finally:- reset_hermes_home_override(home_token)consecutive_failures = 0while not stop_event.is_set():ok = False_tick_error = None_profile_errors: dict[str, str] = {}- # Worst per-profile failure this cycle (fd exhaustion wins) so the- # #87644 backoff/reclaim is applied once per cycle, not per profile.+ # Worst failure this cycle (fd exhaustion wins); backoff applied once per cycle._cycle_exc: BaseException | None = None- cycle_homes = _existing_profile_homes(profile_homes)+ cycle_homes = [_profile_entry(e) for e in _existing_profile_homes(profile_homes)]if profile_gate is not None:- cycle_homes = [- entry- for entry in cycle_homes- if profile_gate(- entry[0] if isinstance(entry, tuple) else None,- entry[1] if isinstance(entry, tuple) else entry,- )- ]+ cycle_homes = [(name, home) for name, home in cycle_homes if profile_gate(name, home)]try:if can_dispatch is not None and not can_dispatch():logger.debug("Cron dispatch paused while gateway drains existing work")else:- for entry in cycle_homes:- _pname = entry[0] if isinstance(entry, tuple) else None- home = entry[1] if isinstance(entry, tuple) else entry- home_token = set_hermes_home_override(str(home))+ for _pname, home in cycle_homes:try:- with use_cron_store(home):- # Deliver each profile's cron via ITS OWN adapters.- # The shared `adapters` set belongs to the default- # profile only. A secondary profile uses its own map- # in profile_adapters[name], which is populated only- # once that profile's bot connects. A secondary must- # NEVER fall back to the default profile's `adapters`- # (that ships its cron output through the wrong bot),- # so before its adapter connects — map absent or empty- # — it simply does not deliver this tick.+ with _profile_cron_scope(home):+ # Deliver via the profile's OWN adapters; NEVER fall back to the+ # default profile's (wrong bot) — just skip delivery this tick.if _pname is None or _pname == default_profile:_tick_adapters = adapterselse:_tick_adapters = (profile_adapters or {}).get(_pname) or {}if not _tick_adapters and adapters:- # Credentialless satellite under- # gateway.profile_routes: no bot of its- # own, so its output may ride the- # PRIMARY adapter — but only for- # targets an exact enabled primary- # route maps to this profile- # (#101113). Unmatched targets still- # fail closed; this is not a default- # fallback.+ # Credentialless satellite may ride the PRIMARY adapter only+ # for targets an exact enabled route maps here; else fail+ # closed._tick_adapters = SharedRouteAdapters(adapters,_primary_profile_routes_for_current_home(),@@ -802,20 +569,11 @@ class InProcessCronScheduler(CronScheduler):can_dispatch=can_dispatch,)except CronTickYielded as e:- # This profile is served stale and a fresh- # gateway owns its runtime lock: record the yield- # for THIS profile's status only, and keep- # ticking the remaining profiles — one profile's- # fresh gateway must not cancel another profile's- # only ticker in the same cycle.+ # Yield for THIS profile only; one fresh gateway must not stop others.logger.info("Cron tick yielded for profile at %s: %s", home, e)_profile_errors[str(home)] = f"{type(e).__name__}: {e}"except BaseException as e:- # Any other failure is THIS profile's failure- # (#74878): record it against this profile's- # status and keep ticking the remaining profiles.- # BaseException for the same reason as the- # single-profile loop (#32612).+ # THIS profile only; BaseException as in the single-profile loop.logger.error("Cron tick error for profile at %s: %s",home,@@ -825,41 +583,24 @@ class InProcessCronScheduler(CronScheduler):_profile_errors[str(home)] = f"{type(e).__name__}: {e}"if _cycle_exc is None or _is_fd_exhaustion(e):_cycle_exc = e- finally:- reset_hermes_home_override(home_token)ok = not _profile_errorsif _cycle_exc is not None:consecutive_failures = _note_tick_failure(_cycle_exc, consecutive_failures)except BaseException as e:logger.error("Cron tick error: %s", e, exc_info=True)_tick_error = f"{type(e).__name__}: {e}"- # EMFILE: reclaim fds + exponential backoff (#87644).consecutive_failures = _note_tick_failure(e, consecutive_failures)- # Record per-profile heartbeat after each tick cycle. Distinguish- # a COMPLETED cycle (``_tick_error`` unset) — where each profile's- # beat reflects its own outcome, so a yielding profile does not- # darken healthy siblings — from an aborted one (exception), where- # no profile completed and all beats are unsuccessful (#32612).- for entry in cycle_homes:- home = entry[1] if isinstance(entry, tuple) else entry- home_token = set_hermes_home_override(str(home))- try:- with use_cron_store(home):- _home_ok = (- _tick_error is None and str(home) not in _profile_errors- )- record_ticker_heartbeat(success=_home_ok)- # Surface the failure reason (or clear it) per profile- # so `hermes cron status` can show WHY ticks fail- # (#68483).- if _home_ok:- clear_ticker_error()- elif str(home) in _profile_errors:- record_ticker_error(_profile_errors[str(home)])- elif _tick_error:- record_ticker_error(_tick_error)- finally:- reset_hermes_home_override(home_token)+ # Completed cycle: each profile's own outcome; aborted cycle: all beats unsuccessful.+ for _, home in cycle_homes:+ with _profile_cron_scope(home):+ _home_ok = _tick_error is None and str(home) not in _profile_errors+ record_ticker_heartbeat(success=_home_ok)+ if _home_ok:+ clear_ticker_error()+ elif str(home) in _profile_errors:+ record_ticker_error(_profile_errors[str(home)])+ elif _tick_error:+ record_ticker_error(_tick_error)if ok:consecutive_failures = 0stop_event.wait(_backoff_wait_seconds(interval, consecutive_failures))diff --git a/cron/suggestion_catalog.py b/cron/suggestion_catalog.pyindex deacf1e1349..39f77ba420d 100644--- a/cron/suggestion_catalog.py+++ b/cron/suggestion_catalog.py@@ -1,18 +1,12 @@"""Curated catalog of starter cron-job suggestions.-These are the built-in automations Hermes can offer a new user out of the box —-the ``catalog`` source of the unified suggestion surface. Each entry is a-ready-to-run ``cron.jobs.create_job`` spec wrapped as a suggestion; the user-accepts via ``/suggestions``. Nothing here auto-schedules.--The "important-mail monitor" entry is where the old proactive-monitor engine-lives now: its ``classify_items.py`` (poll a source -> LLM-score urgency ->-surface only above-threshold) is ONE catalog automation, not a standalone-feature.--Adding a catalog entry: append a CatalogEntry. Keep prompts self-contained-(cron jobs run with no chat context) and schedules sensible. The ``job_spec``-is passed verbatim to ``create_job`` on accept.+These are the built-in automations Hermes can offer a new user out of the box — the ``catalog``+source of the unified suggestion surface. Each entry is a ready-to-run ``cron.jobs.create_job`` spec+wrapped as a suggestion; the user accepts via ``/suggestions``. Nothing here auto-schedules.++The "important-mail monitor" entry (``classify_items.py``: poll -> LLM-score urgency -> surface+above-threshold) is ONE catalog automation, not a standalone feature. New entries: append a+CatalogEntry with a self-contained prompt (cron jobs run with no chat context)."""from __future__ import annotations@@ -128,11 +122,10 @@ def seed_catalog_suggestions() -> List[Dict[str, Any]]:"""Register catalog entries as pending suggestions.- ``add_fn`` defaults to ``cron.suggestions.add_suggestion`` (injectable for- tests). ``keys`` restricts to specific catalog entries; omit to seed all.- Entries already dismissed/accepted (by dedup key) or beyond the pending cap- are skipped by the store, so re-seeding is safe and idempotent. Returns the- list of suggestion records actually created.+ ``add_fn`` defaults to ``cron.suggestions.add_suggestion`` (injectable for tests). ``keys``+ restricts to specific catalog entries; omit to seed all. Entries already dismissed/accepted (by+ dedup key) or beyond the pending cap are skipped by the store, so re-seeding is safe and+ idempotent. Returns the list of suggestion records actually created."""if add_fn is None:from cron.suggestions import add_suggestion as add_fn # type: ignore[assignment]diff --git a/cron/suggestions.py b/cron/suggestions.pyindex afbd44dbda1..f88efeddc9c 100644--- a/cron/suggestions.py+++ b/cron/suggestions.py@@ -1,9 +1,8 @@"""Suggested cron jobs — proposed automations the user accepts with one tap.-A *suggestion* is a ready-to-run cron job spec that Hermes surfaces to the-user, who accepts it (creates the real cron job) or dismisses it (latched so-it is never re-offered). This is the single surface every automation proposal-flows through, regardless of where it came from:+A *suggestion* is a ready-to-run cron job spec that Hermes surfaces to the user, who accepts it+(creates the real cron job) or dismisses it (latched so it is never re-offered). This is the single+surface every automation proposal flows through, regardless of where it came from:* ``catalog`` — a curated starter automation (daily briefing, important-mailmonitor, weekly digest, ...).@@ -15,14 +14,12 @@ flows through, regardless of where it came from:* ``integration`` — the user connected an account (Gmail, GitHub, ...) andthe obvious automations for that surface are offered.-Accepting a suggestion just calls the existing ``cron.jobs.create_job`` with-the stored ``job_spec`` — there is NO second job engine. Suggestions never-auto-create jobs; acceptance is always explicit (consent-first). Dismissed-suggestions latch by a stable ``dedup_key`` so the same proposal is not+Accepting a suggestion just calls the existing ``cron.jobs.create_job`` with the stored ``job_spec``+— there is NO second job engine. Suggestions never auto-create jobs; acceptance is always explicit+(consent-first). Dismissed suggestions latch by a stable ``dedup_key`` so the same proposal is notre-offered after the user says no.-Storage mirrors ``cron/jobs.py``: ``~/.hermes/cron/suggestions.json``, atomic-writes, an in-process lock, and 0600 perms.+Storage mirrors ``cron/jobs.py``: ``~/.hermes/cron/suggestions.json``, atomic replace, 0600."""from __future__ import annotations@@ -42,14 +39,11 @@ from utils import atomic_replacelogger = logging.getLogger(__name__)-# Per-profile by design (issue #4707): suggestions live alongside the active-# profile's cron store. Anchor on get_hermes_home() (profile home), not the-# shared default root. See cron/jobs.py for the full rationale.-#-# Optional test override. Production resolves the path at call time so-# multiplexed profile ticks (set_hermes_home_override) cannot leak one-# profile's suggestions into the import-time home (#86519). Same pattern as-# cron/executions.py.+# Per-profile by design: suggestions live alongside the active profile's cron store. Anchor on+# get_hermes_home() (profile home), not the shared default root. See cron/jobs.py for the full+# rationale. Optional test override; production resolves the path at CALL time so multiplexed+# profile ticks (set_hermes_home_override) cannot leak one profile's suggestions into the+# import-time home.SUGGESTIONS_FILE: Optional[Path] = None@@ -144,13 +138,12 @@ def add_suggestion() -> Optional[Dict[str, Any]]:"""Register a pending suggestion. Returns the record, or None if skipped.- Skipped when: the source is unknown, the same ``dedup_key`` was already- dismissed or accepted (never re-offer), an identical pending suggestion- exists, or the pending list is full (``MAX_PENDING``).+ Skipped when: the source is unknown, the same ``dedup_key`` was already dismissed or accepted+ (never re-offer), an identical pending suggestion exists, or the pending list is full+ (``MAX_PENDING``).- ``job_spec`` is a dict of kwargs for ``cron.jobs.create_job`` — accepting- the suggestion passes it straight through, so there is no second schema to- keep in sync.+ ``job_spec`` is a dict of kwargs for ``cron.jobs.create_job`` — accepting the suggestion passes+ it straight through, so there is no second schema to keep in sync."""if source not in VALID_SOURCES:raise ValueError(f"unknown suggestion source: {source!r}")@@ -235,10 +228,9 @@ def dismiss_suggestion(ref: str) -> bool:def accept_suggestion(ref: str, *, origin: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:"""Accept a suggestion: create the real cron job from its ``job_spec``.- Returns the created cron job dict, or None if the suggestion isn't found /- not pending. The job_spec is passed straight to ``cron.jobs.create_job``;- an ``origin`` (platform/chat) is merged so "origin" delivery routes back to- the chat where the user accepted.+ Returns the created cron job dict, or None if the suggestion isn't found / not pending. The+ job_spec is passed straight to ``cron.jobs.create_job``; an ``origin`` (platform/chat) is merged+ so "origin" delivery routes back to the chat where the user accepted."""s = get_suggestion(ref)if not s or s.get("status") != _STATUS_PENDING: