The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cron): monitor-mode jobs — hash-suppressed change detection
Teknium6dff2109aab2
diff --git a/cron/jobs.py b/cron/jobs.pyindex 808241c8586..bf2470db3d2 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -1511,6 +1511,8 @@ def create_job(workdir: Optional[str] = None,no_agent: bool = False,attach_to_session: Optional[bool] = None,+ monitor_script: Optional[str] = None,+ monitor_url: Optional[str] = None,) -> Dict[str, Any]:"""Create a new cron job.@@ -1555,6 +1557,19 @@ def create_job(and deliver its stdout directly. Empty stdout = silent (nodelivery). Requires ``script`` to be set. Ideal for classicwatchdogs 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``.Returns:The created job dict@@ -1587,6 +1602,24 @@ def create_job(normalized_workdir = _normalize_workdir(workdir)normalized_no_agent = bool(no_agent)normalized_attach = attach_to_session if isinstance(attach_to_session, bool) else 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.+ if normalized_monitor_script and normalized_monitor_url:+ raise ValueError(+ "monitor_script and monitor_url are mutually exclusive — a job "+ "can only have one monitor source."+ )+ if (normalized_monitor_script or normalized_monitor_url) and normalized_no_agent:+ raise ValueError(+ "monitor_script/monitor_url cannot be combined with no_agent=True — "+ "the whole point of a monitor job is to suppress or wake the AGENT "+ "based on source changes. Use a plain no_agent script job instead."+ )# no_agent jobs are meaningless without a script — the script IS the job.# Surface this as a clear ValueError at create time so bad configs never@@ -1654,6 +1687,11 @@ def create_job("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.+ "monitor_state": None,"context_from": context_from,"schedule": parsed_schedule,"schedule_display": parsed_schedule.get("display", schedule),diff --git a/cron/monitor.py b/cron/monitor.pynew file mode 100644index 00000000000..80e809b99b3--- /dev/null+++ b/cron/monitor.py@@ -0,0 +1,212 @@+"""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.+"""++from __future__ import annotations++import difflib+import hashlib+import logging+from dataclasses import dataclass+from typing import Optional++logger = logging.getLogger(__name__)++# Cap for the unified diff injected into the prompt.+MAX_DIFF_CHARS = 4000+# Cap for the new-output block injected into the prompt (mirrors the 8k+# context_from truncation in cron/scheduler.py).+MAX_OUTPUT_CHARS = 8000+# Bounded GET limits for monitor_url sources.+URL_TIMEOUT_SECONDS = 30+MAX_URL_BYTES = 262_144 # 256 KiB++_SNAPSHOT_FILENAME = "monitor_last_output.txt"+++@dataclass+class MonitorOutcome:+ """Result of one monitor-source evaluation."""++ ok: bool+ changed: bool = False+ first_run: bool = False+ context_block: Optional[str] = None+ error: Optional[str] = None+++def hash_monitor_output(output: str) -> str:+ """Hash the monitor output as exact UTF-8 bytes (no normalization)."""+ return hashlib.sha256(output.encode("utf-8", errors="replace")).hexdigest()+++def build_monitor_diff(old: str, new: str) -> str:+ """Unified diff of old vs new monitor output, capped at MAX_DIFF_CHARS."""+ diff = "\n".join(+ difflib.unified_diff(+ old.splitlines(),+ new.splitlines(),+ fromfile="previous",+ tofile="current",+ lineterm="",+ )+ )+ if len(diff) > MAX_DIFF_CHARS:+ diff = diff[:MAX_DIFF_CHARS] + "\n... [diff truncated]"+ return diff+++def _snapshot_path(job_id: str):+ from cron.jobs import _job_output_dir++ return _job_output_dir(job_id) / _SNAPSHOT_FILENAME+++def _read_last_output(job_id: str) -> str:+ try:+ path = _snapshot_path(job_id)+ if path.exists():+ return path.read_text(encoding="utf-8")+ except Exception as exc:+ logger.warning("Monitor: failed to read last output for %r: %s", job_id, exc)+ return ""+++def _write_last_output(job_id: str, output: str) -> None:+ try:+ path = _snapshot_path(job_id)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(output, encoding="utf-8")+ except Exception as exc:+ logger.warning("Monitor: failed to persist last output for %r: %s", job_id, exc)+++def _fetch_monitor_url(url: str) -> tuple[bool, str]:+ """Bounded GET of a monitor URL. Returns (ok, body-or-error)."""+ import urllib.request++ if not str(url).lower().startswith(("http://", "https://")):+ return False, f"monitor_url must be http(s): {url!r}"+ try:+ req = urllib.request.Request(url, headers={"User-Agent": "hermes-cron-monitor"})+ with urllib.request.urlopen(req, timeout=URL_TIMEOUT_SECONDS) as resp: # nosec B310 — scheme checked above+ body = resp.read(MAX_URL_BYTES + 1)+ if len(body) > MAX_URL_BYTES:+ body = body[:MAX_URL_BYTES]+ return True, body.decode("utf-8", errors="replace")+ except Exception as exc:+ return False, f"monitor_url fetch failed: {exc}"+++def _run_monitor_source(job: dict) -> tuple[bool, str]:+ """Run the job's monitor source (script or URL). Returns (ok, output)."""+ monitor_script = (job.get("monitor_script") or "").strip()+ if monitor_script:+ # Same containment + interpreter rules as the existing `script` field.+ from cron.scheduler import _run_job_script++ workdir = (job.get("workdir") or "").strip() or None+ return _run_job_script(monitor_script, workdir=workdir)+ monitor_url = (job.get("monitor_url") or "").strip()+ if monitor_url:+ return _fetch_monitor_url(monitor_url)+ return False, "monitor job has neither monitor_script nor monitor_url"+++def job_has_monitor(job: dict) -> bool:+ return bool((job.get("monitor_script") or "").strip() or (job.get("monitor_url") or "").strip())+++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 failure nothing is persisted.+ """+ job_id = str(job.get("id") or "")+ ok, output = _run_monitor_source(job)+ if not ok:+ return MonitorOutcome(ok=False, error=output)++ new_hash = hash_monitor_output(output)+ raw_state = job.get("monitor_state")+ state = raw_state if isinstance(raw_state, dict) else {}+ last_hash = state.get("last_output_hash")++ if last_hash is not None and new_hash == last_hash:+ return MonitorOutcome(ok=True, changed=False)++ first_run = last_hash is None+ old_output = "" if first_run else _read_last_output(job_id)++ shown_output = output+ if len(shown_output) > MAX_OUTPUT_CHARS:+ shown_output = shown_output[:MAX_OUTPUT_CHARS] + "\n... [output truncated]"++ if first_run:+ context_block = (+ "## Monitor Baseline (first run)\n\n"+ "This is the first observation of the monitored source — there is "+ "no previous output to diff against.\n\n"+ f"### Current output\n\n```\n{shown_output}\n```"+ )+ else:+ diff = build_monitor_diff(old_output, output)+ context_block = (+ "## MONITOR CHANGE DETECTED\n\n"+ "The monitored source's output changed since the last run.\n\n"+ f"### Diff (previous → current)\n\n```diff\n{diff}\n```\n\n"+ f"### Current output\n\n```\n{shown_output}\n```"+ )++ _persist_monitor_state(job_id, new_hash, output)+ return MonitorOutcome(+ ok=True, changed=True, first_run=first_run, context_block=context_block+ )+++def _persist_monitor_state(job_id: str, new_hash: str, output: str) -> None:+ from cron.jobs import _hermes_now, update_job++ _write_last_output(job_id, output)+ try:+ update_job(+ job_id,+ {+ "monitor_state": {+ "last_output_hash": new_hash,+ "last_changed_at": _hermes_now().isoformat(),+ }+ },+ )+ except Exception as exc:+ logger.warning("Monitor: failed to persist state for %r: %s", job_id, exc)diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 2257889a82d..9378e92df7c 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -3026,6 +3026,61 @@ def run_job()return True, doc, output, None+ # ---------------------------------------------------------------+ # Monitor gate — hash-suppressed change detection (see cron/monitor.py).+ # Runs BEFORE any agent machinery is constructed so an unchanged tick+ # costs one cheap source run + one hash, no LLM, no delivery.+ # ---------------------------------------------------------------+ from cron.monitor import check_monitor, job_has_monitor++ _monitor_context: Optional[str] = None+ if job_has_monitor(job):+ _mon = check_monitor(job)+ _mon_now = _hermes_now().strftime("%Y-%m-%d %H:%M:%S")+ if not _mon.ok:+ # Source failure is an ERROR, never a change: alert the user so+ # a broken monitor can't silently stop watching. Stored hash is+ # untouched (check_monitor persists nothing on failure).+ logger.error("Job '%s': monitor source failed: %s", job_id, _mon.error)+ _mon_doc = (+ f"# Cron Job: {job_name}\n\n"+ f"**Job ID:** {job_id}\n"+ f"**Run Time:** {_mon_now}\n"+ f"**Mode:** monitor\n"+ f"**Status:** monitor source failed\n\n"+ f"{_mon.error}\n"+ )+ _mon_alert = (+ f"⚠ Cron monitor '{job_name}' source failed\n\n"+ f"{_mon.error}\n\n"+ f"Time: {_mon_now}"+ )+ return False, _mon_doc, _mon_alert, _mon.error+ if not _mon.changed:+ # Unchanged output — suppress the agent run entirely. Recorded+ # as a silent no_change tick (visible in the executions ledger+ # via this doc; SILENT_MARKER blocks delivery).+ logger.info(+ "Job '%s': monitor output unchanged — suppressing agent run",+ job_id,+ )+ _mon_doc = (+ f"# Cron Job: {job_name}\n\n"+ f"**Job ID:** {job_id}\n"+ f"**Run Time:** {_mon_now}\n"+ f"**Mode:** monitor\n"+ f"**Status:** no_change (agent run suppressed)\n"+ )+ return True, _mon_doc, SILENT_MARKER, None+ # Changed (or first run): inject the monitor context into the prompt+ # through the existing per-run context seam and fall through to a+ # normal agent run.+ _monitor_context = _mon.context_block+ if _monitor_context:+ extra_prompt = (+ f"{_monitor_context}\n\n{extra_prompt}" if extra_prompt else _monitor_context+ )+# ---------------------------------------------------------------# Default (LLM) path — import and construct the agent machinery now# that we know we actually need it. Doing these imports here instead ofdiff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex c5be7681c93..6258dfd4a8f 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -158,6 +158,12 @@ def cron_list(show_all: bool = False):script = job.get("script")if script:print(f" Script: {script}")+ monitor_source = job.get("monitor_script") or job.get("monitor_url")+ if monitor_source:+ print(f" Monitor: {monitor_source} (agent runs only on output change)")+ mon_state = job.get("monitor_state") or {}+ if mon_state.get("last_changed_at"):+ print(f" Changed: {mon_state['last_changed_at']}")if job.get("no_agent"):print(f" Mode: {color('no-agent', Colors.DIM)} (script stdout delivered directly)")workdir = job.get("workdir")@@ -352,6 +358,8 @@ def cron_create(args):model=getattr(args, "model", None),provider=getattr(args, "model_provider", None),no_agent=getattr(args, "no_agent", False) or None,+ monitor_script=getattr(args, "monitor_script", None),+ monitor_url=getattr(args, "monitor_url", None),)if not result.get("success"):print(color(f"Failed to create job: {result.get('error', 'unknown error')}", Colors.RED))@@ -364,6 +372,10 @@ def cron_create(args):job_data = result.get("job", {})if job_data.get("script"):print(f" Script: {job_data['script']}")+ if job_data.get("monitor_script"):+ print(f" Monitor: {job_data['monitor_script']} (agent runs only on output change)")+ if job_data.get("monitor_url"):+ print(f" Monitor: {job_data['monitor_url']} (agent runs only on output change)")if job_data.get("no_agent"):print(" Mode: no-agent (script stdout delivered directly)")if job_data.get("workdir"):@@ -417,6 +429,8 @@ def cron_edit(args):model=getattr(args, "model", None),provider=getattr(args, "model_provider", None),no_agent=getattr(args, "no_agent", None),+ monitor_script=getattr(args, "monitor_script", None),+ monitor_url=getattr(args, "monitor_url", None),)if not result.get("success"):print(color(f"Failed to update job: {result.get('error', 'unknown error')}", Colors.RED))@@ -432,6 +446,10 @@ def cron_edit(args):print(" Skills: none")if updated.get("script"):print(f" Script: {updated['script']}")+ if updated.get("monitor_script"):+ print(f" Monitor: {updated['monitor_script']} (agent runs only on output change)")+ if updated.get("monitor_url"):+ print(f" Monitor: {updated['monitor_url']} (agent runs only on output change)")if updated.get("no_agent"):print(" Mode: no-agent (script stdout delivered directly)")if updated.get("workdir"):diff --git a/hermes_cli/subcommands/cron.py b/hermes_cli/subcommands/cron.pyindex 331176116c3..c9d6f6a4b40 100644--- a/hermes_cli/subcommands/cron.py+++ b/hermes_cli/subcommands/cron.py@@ -66,6 +66,28 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:"pattern (memory alerts, disk alerts, CI pings)."),)+ cron_create.add_argument(+ "--monitor-script",+ dest="monitor_script",+ help=(+ "Monitor mode: path to a cheap source script under "+ "~/.hermes/scripts/ that runs each tick BEFORE the agent. "+ "Unchanged output (exact-bytes hash) suppresses the agent run "+ "entirely; changed output injects a MONITOR CHANGE DETECTED "+ "diff into the prompt. Script output must be stable (no "+ "timestamps). Mutually exclusive with --monitor-url; "+ "incompatible with --no-agent."+ ),+ )+ cron_create.add_argument(+ "--monitor-url",+ dest="monitor_url",+ help=(+ "Monitor mode: http(s) URL fetched with a bounded GET each tick "+ "instead of a script. Same hash-suppression semantics as "+ "--monitor-script."+ ),+ )cron_create.add_argument("--workdir",help="Absolute path for the job to run from. Injects AGENTS.md / CLAUDE.md / .cursorrules from that directory and uses it as the cwd for terminal/file/code_exec tools. Omit to preserve old behaviour (no project context files).",@@ -143,6 +165,21 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:const=False,help="Disable no-agent mode on this job (reverts to LLM-driven execution).",)+ cron_edit.add_argument(+ "--monitor-script",+ dest="monitor_script",+ help=(+ "Set/replace the monitor source script (see `hermes cron create "+ "--monitor-script`). Pass empty string to clear."+ ),+ )+ cron_edit.add_argument(+ "--monitor-url",+ dest="monitor_url",+ help=(+ "Set/replace the monitor source URL. Pass empty string to clear."+ ),+ )cron_edit.add_argument("--workdir",help="Absolute path for the job to run from (injects AGENTS.md etc. and sets terminal cwd). Pass empty string to clear.",diff --git a/tests/cron/test_monitor_kind.py b/tests/cron/test_monitor_kind.pynew file mode 100644index 00000000000..b9a1900e7e0--- /dev/null+++ b/tests/cron/test_monitor_kind.py@@ -0,0 +1,364 @@+"""Tests for monitor-mode cron jobs — cheap source each tick, hash-suppressed agent runs.++A monitor job runs a cheap *monitor source* (``monitor_script`` or+``monitor_url``) on every tick, hashes the exact output bytes, and:++* unchanged output → suppressed run: NO agent invocation, NO delivery,+ visible in the executions ledger as a silent no-change tick;+* changed output → a "MONITOR CHANGE DETECTED" block (unified diff of+ old vs new, capped, plus the new output) is injected into the prompt and+ the agent runs normally;+* first run → always runs the agent (nothing to compare against);+* source failure → treated as an ERROR (alert delivered), never as a+ change — and the stored hash is NOT updated.++State (`monitor_state.last_output_hash` / `last_changed_at`) lives on the+job record in jobs.json plus a snapshot file, so suppression survives+scheduler restarts.++Inspired by: ChatGPT Work monitor tasks (idea-level, docs-only);+enabler: #80774.+"""++from __future__ import annotations++import json+import sys++import pytest+++def hermes_env(tmp_path, monkeypatch):+ """Isolate HERMES_HOME for each test so jobs/scripts/snapshots don't leak."""+ home = tmp_path / ".hermes"+ home.mkdir()+ (home / "scripts").mkdir()+ (home / "cron").mkdir()++ monkeypatch.setenv("HERMES_HOME", str(home))++ # Reload modules that cache get_hermes_home() at import time.+ import importlib+ import hermes_constants+ importlib.reload(hermes_constants)+ import cron.jobs+ importlib.reload(cron.jobs)+ import cron.monitor+ importlib.reload(cron.monitor)+ import cron.scheduler+ importlib.reload(cron.scheduler)++ return home+++def _write_script(home, name: str, body: str) -> str:+ path = home / "scripts" / name+ path.write_text(body, encoding="utf-8")+ return name+++def _install_agent_stubs(monkeypatch, observed: dict):+ """Stub the agent machinery so run_job's LLM path executes without creds.++ ``observed["prompts"]`` collects the prompt each agent run received;+ ``observed["agent_runs"]`` counts real agent invocations.+ """+ import cron.scheduler as sched++ observed.setdefault("prompts", [])+ observed.setdefault("agent_runs", 0)++ class FakeAgent:+ def __init__(self, **kwargs):+ pass++ def run_conversation(self, prompt, *_a, **_kw):+ observed["agent_runs"] += 1+ observed["prompts"].append(prompt)+ return {"final_response": "agent done", "messages": []}++ def get_activity_summary(self):+ return {"seconds_since_activity": 0.0}++ fake_mod = type(sys)("run_agent")+ fake_mod.AIAgent = FakeAgent+ monkeypatch.setitem(sys.modules, "run_agent", fake_mod)++ from hermes_cli import runtime_provider as _rtp+ monkeypatch.setattr(+ _rtp,+ "resolve_runtime_provider",+ lambda **_kw: {+ "provider": "test",+ "api_key": "k",+ "base_url": "http://test.local",+ "api_mode": "chat_completions",+ },+ )++ monkeypatch.setattr(sched, "_resolve_origin", lambda job: None)+ monkeypatch.setattr(sched, "_resolve_delivery_target", lambda job: None)+ monkeypatch.setattr(sched, "_resolve_cron_enabled_toolsets", lambda job, cfg: None)+ monkeypatch.setenv("HERMES_CRON_TIMEOUT", "0")++ import dotenv+ monkeypatch.setattr(dotenv, "load_dotenv", lambda *_a, **_kw: True)+++# ---------------------------------------------------------------------------+# create_job: data-layer semantics for monitor fields+# ---------------------------------------------------------------------------+++def test_create_job_stores_monitor_script(hermes_env):+ from cron.jobs import create_job, get_job++ _write_script(hermes_env, "mon.sh", "echo stable\n")+ job = create_job(+ prompt="React to the change",+ schedule="every 5m",+ monitor_script="mon.sh",+ deliver="local",+ )+ reloaded = get_job(job["id"])+ assert reloaded["monitor_script"] == "mon.sh"+ assert reloaded.get("monitor_url") is None+ assert reloaded.get("monitor_state") is None+++def test_create_job_monitor_script_and_url_mutually_exclusive(hermes_env):+ from cron.jobs import create_job++ with pytest.raises(ValueError, match="monitor_script and monitor_url"):+ create_job(+ prompt="p",+ schedule="every 5m",+ monitor_script="mon.sh",+ monitor_url="https://example.com/status",+ )+++def test_create_job_monitor_rejected_with_no_agent(hermes_env):+ from cron.jobs import create_job++ _write_script(hermes_env, "w.sh", "echo hi\n")+ with pytest.raises(ValueError, match="no_agent"):+ create_job(+ prompt=None,+ schedule="every 5m",+ script="w.sh",+ no_agent=True,+ monitor_script="w.sh",+ )+++# ---------------------------------------------------------------------------+# cron.monitor: hashing + diff unit behavior+# ---------------------------------------------------------------------------+++def test_hash_is_exact_bytes(hermes_env):+ from cron.monitor import hash_monitor_output++ assert hash_monitor_output("a\nb") == hash_monitor_output("a\nb")+ # Exact-bytes contract: even whitespace-only differences are changes.+ assert hash_monitor_output("a\nb") != hash_monitor_output("a\nb ")+++def test_unified_diff_is_capped(hermes_env):+ from cron.monitor import MAX_DIFF_CHARS, build_monitor_diff++ old = "\n".join(f"line {i}" for i in range(5000))+ new = "\n".join(f"LINE {i}" for i in range(5000))+ diff = build_monitor_diff(old, new)+ assert len(diff) <= MAX_DIFF_CHARS + 200 # cap + truncation notice+ assert "truncated" in diff+++# ---------------------------------------------------------------------------+# scheduler.run_job: monitor gate behavior+# ---------------------------------------------------------------------------+++def _make_monitor_job(hermes_env, script_body: str):+ from cron.jobs import create_job++ _write_script(hermes_env, "mon.sh", script_body)+ return create_job(+ prompt="Summarize what changed",+ schedule="every 5m",+ monitor_script="mon.sh",+ deliver="local",+ )+++def test_first_run_always_runs_agent(hermes_env, monkeypatch):+ from cron.scheduler import run_job++ job = _make_monitor_job(hermes_env, "echo 'state A'\n")+ observed: dict = {}+ _install_agent_stubs(monkeypatch, observed)++ success, doc, final, error = run_job(job)+ assert success is True+ assert error is None+ assert observed["agent_runs"] == 1+ # First run: new output is injected as monitor context.+ assert "state A" in observed["prompts"][0]+++def test_unchanged_output_suppresses_agent_run(hermes_env, monkeypatch):+ from cron.jobs import get_job+ from cron.scheduler import SILENT_MARKER, run_job++ job = _make_monitor_job(hermes_env, "echo 'state A'\n")+ observed: dict = {}+ _install_agent_stubs(monkeypatch, observed)++ run_job(job)+ assert observed["agent_runs"] == 1++ # Second tick with identical output → suppressed: no agent, silent.+ job = get_job(job["id"])+ success, doc, final, error = run_job(job)+ assert success is True+ assert error is None+ assert final == SILENT_MARKER+ assert observed["agent_runs"] == 1 # unchanged — agent NOT re-invoked+ assert "no_change" in doc+++def test_changed_output_injects_diff(hermes_env, monkeypatch):+ from cron.jobs import get_job+ from cron.scheduler import run_job++ job = _make_monitor_job(hermes_env, "echo 'state A'\n")+ observed: dict = {}+ _install_agent_stubs(monkeypatch, observed)++ run_job(job)++ # Mutate the monitored source, then fire again.+ _write_script(hermes_env, "mon.sh", "echo 'state B'\n")+ job = get_job(job["id"])+ success, doc, final, error = run_job(job)+ assert success is True+ assert observed["agent_runs"] == 2+ prompt = observed["prompts"][1]+ assert "MONITOR CHANGE DETECTED" in prompt+ assert "-state A" in prompt+ assert "+state B" in prompt+ assert "state B" in prompt # new output included verbatim+++def test_hash_persists_across_scheduler_restart(hermes_env, monkeypatch):+ """Suppression state must survive a scheduler restart (module reload)."""+ import importlib++ from cron.scheduler import run_job++ job = _make_monitor_job(hermes_env, "echo 'state A'\n")+ observed: dict = {}+ _install_agent_stubs(monkeypatch, observed)++ run_job(job)+ assert observed["agent_runs"] == 1++ # Simulate restart: reload the cron modules, dropping in-memory state.+ import cron.jobs+ importlib.reload(cron.jobs)+ import cron.monitor+ importlib.reload(cron.monitor)+ import cron.scheduler+ importlib.reload(cron.scheduler)+ _install_agent_stubs(monkeypatch, observed)++ job = cron.jobs.get_job(job["id"])+ assert job["monitor_state"]["last_output_hash"]+ success, doc, final, error = cron.scheduler.run_job(job)+ assert success is True+ assert final == cron.scheduler.SILENT_MARKER+ assert observed["agent_runs"] == 1 # still suppressed after restart+++def test_monitor_script_failure_is_error_not_change(hermes_env, monkeypatch):+ from cron.jobs import get_job+ from cron.scheduler import run_job++ job = _make_monitor_job(hermes_env, "echo 'state A'\n")+ observed: dict = {}+ _install_agent_stubs(monkeypatch, observed)++ run_job(job)+ stored_hash = get_job(job["id"])["monitor_state"]["last_output_hash"]++ # Break the source: non-zero exit must be an error, never a "change".+ _write_script(hermes_env, "mon.sh", "echo boom >&2\nexit 3\n")+ job = get_job(job["id"])+ success, doc, final, error = run_job(job)+ assert success is False+ assert error is not None+ assert observed["agent_runs"] == 1 # agent NOT invoked on source failure+ # Stored hash untouched — a later recovery to 'state A' still suppresses.+ assert get_job(job["id"])["monitor_state"]["last_output_hash"] == stored_hash+++# ---------------------------------------------------------------------------+# cronjob tool: API-layer wiring+# ---------------------------------------------------------------------------+++def test_cronjob_tool_create_with_monitor_script(hermes_env):+ from cron.jobs import get_job+ from tools.cronjob_tools import cronjob++ _write_script(hermes_env, "mon.sh", "echo hi\n")+ result = json.loads(+ cronjob(+ action="create",+ prompt="React",+ schedule="every 5m",+ monitor_script="mon.sh",+ deliver="local",+ )+ )+ assert result.get("success") is True+ job = get_job(result["job_id"])+ assert job["monitor_script"] == "mon.sh"+++def test_cronjob_tool_rejects_monitor_script_path_escape(hermes_env):+ from tools.cronjob_tools import cronjob++ result = json.loads(+ cronjob(+ action="create",+ prompt="React",+ schedule="every 5m",+ monitor_script="../evil.sh",+ deliver="local",+ )+ )+ assert result.get("success") is False+++def test_cronjob_tool_update_clears_monitor_script(hermes_env):+ from cron.jobs import get_job+ from tools.cronjob_tools import cronjob++ _write_script(hermes_env, "mon.sh", "echo hi\n")+ created = json.loads(+ cronjob(+ action="create",+ prompt="React",+ schedule="every 5m",+ monitor_script="mon.sh",+ deliver="local",+ )+ )+ result = json.loads(+ cronjob(action="update", job_id=created["job_id"], monitor_script="")+ )+ assert result.get("success") is True+ assert get_job(created["job_id"]).get("monitor_script") is Nonediff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.pyindex 1f97aec2726..ec827aac4c6 100644--- a/tools/cronjob_tools.py+++ b/tools/cronjob_tools.py@@ -579,6 +579,12 @@ def _format_job(job: Dict[str, Any]) -> Dict[str, Any]:}if job.get("script"):result["script"] = job["script"]+ if job.get("monitor_script"):+ result["monitor_script"] = job["monitor_script"]+ if job.get("monitor_url"):+ result["monitor_url"] = job["monitor_url"]+ if job.get("monitor_state"):+ result["monitor_state"] = job["monitor_state"]if job.get("no_agent"):result["no_agent"] = Trueif job.get("enabled_toolsets"):@@ -1041,6 +1047,8 @@ def cronjob(workdir: Optional[str] = None,no_agent: Optional[bool] = None,attach_to_session: Optional[bool] = None,+ monitor_script: Optional[str] = None,+ monitor_url: Optional[str] = None,task_id: str = None,session_id: Optional[str] = None,) -> str:@@ -1080,6 +1088,12 @@ def cronjob(if script_error:return tool_error(script_error, success=False)+ # Validate monitor source (same containment rules as script).+ if monitor_script:+ monitor_error = _validate_cron_script_path(monitor_script)+ if monitor_error:+ return tool_error(monitor_error, success=False)+# Reject a model-supplied base_url that would route a named# provider's stored credential to an attacker endpoint (F8).base_url_error = _validate_cron_base_url(provider, base_url)@@ -1121,6 +1135,8 @@ def cronjob(workdir=_normalize_optional_job_value(workdir),no_agent=_no_agent,attach_to_session=attach_to_session,+ monitor_script=_normalize_optional_job_value(monitor_script),+ monitor_url=_normalize_optional_job_value(monitor_url),)except CronSchedulerRegistrationError as exc:_partial = exc.to_dict()@@ -1327,6 +1343,33 @@ def cronjob(if script_error:return tool_error(script_error, success=False)updates["script"] = _normalize_optional_job_value(script) if script else None+ if monitor_script is not None:+ # Pass empty string to clear an existing monitor_script+ if monitor_script:+ monitor_error = _validate_cron_script_path(monitor_script)+ if monitor_error:+ return tool_error(monitor_error, success=False)+ updates["monitor_script"] = (+ _normalize_optional_job_value(monitor_script) if monitor_script else None+ )+ if monitor_url is not None:+ # Pass empty string to clear an existing monitor_url+ updates["monitor_url"] = (+ _normalize_optional_job_value(monitor_url) if monitor_url else None+ )+ if monitor_script is not None or monitor_url is not None:+ eff_mon_script = (+ updates["monitor_script"] if "monitor_script" in updates else job.get("monitor_script")+ )+ eff_mon_url = (+ updates["monitor_url"] if "monitor_url" in updates else job.get("monitor_url")+ )+ if eff_mon_script and eff_mon_url:+ return tool_error(+ "monitor_script and monitor_url are mutually exclusive — "+ "clear one before setting the other.",+ success=False,+ )if context_from is not None:# Empty string / empty list clears the field; otherwise validate# each referenced job exists before storing. Normalized to a list@@ -1454,6 +1497,14 @@ Important safety rule: cron-run sessions should not recursively schedule more cr"type": "string","description": f"Optional path to a script that runs each tick. In the default mode its stdout is injected into the agent's prompt as context (data-collection / change-detection pattern). With no_agent=True, the script IS the job and its stdout is delivered verbatim (classic watchdog pattern). Relative paths resolve under {display_hermes_home()}/scripts/. ``.sh``/``.bash`` extensions run via bash, everything else via Python. On update, pass empty string to clear."},+ "monitor_script": {+ "type": "string",+ "description": f"Optional monitor-mode source script (same rules as `script`: relative to {display_hermes_home()}/scripts/, .sh/.bash via bash, else Python). Each tick it runs FIRST and its output is hashed as exact bytes: UNCHANGED output suppresses the agent run entirely (no LLM, no delivery, 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. The first tick always runs the agent (baseline). Scripts must emit STABLE output — no timestamps or random ordering — or every tick looks changed. Mutually exclusive with monitor_url; incompatible with no_agent=True. On update, pass empty string to clear."+ },+ "monitor_url": {+ "type": "string",+ "description": "Optional http(s) URL used as the monitor source instead of a script — fetched with a bounded GET (30s timeout, 256KB cap) each tick. Same hash-suppression semantics as monitor_script. Mutually exclusive with monitor_script. On update, pass empty string to clear."+ },"no_agent": {"type": "boolean","default": False,@@ -1555,6 +1606,8 @@ registry.register(enabled_toolsets=args.get("enabled_toolsets"),workdir=args.get("workdir"),no_agent=args.get("no_agent"),+ monitor_script=args.get("monitor_script"),+ monitor_url=args.get("monitor_url"),task_id=kw.get("task_id"),session_id=kw.get("session_id"),),