Skip to content

The agent that grows with you

feat(cron): per-job failure_deliver — route or suppress failure notices (NS-788)

Victor Kyriazakosc9491e6a7d9c
diff --git a/cron/jobs.py b/cron/jobs.py
index 85ed2a9848a..0afd293c70a 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -2350,6 +2350,7 @@ def create_job(
monitor_script: Optional[str] = None,
monitor_url: Optional[str] = None,
reasoning_effort: Optional[str] = None,
+ failure_deliver: Optional[str] = None,
) -> Dict[str, Any]:
"""
Create a new cron job.
@@ -2452,6 +2453,16 @@ def create_job(
normalized_no_agent = bool(no_agent)
normalized_attach = attach_to_session if isinstance(attach_to_session, bool) else None
normalized_reasoning_effort = _normalize_reasoning_effort(reasoning_effort)
+ # failure_deliver shares deliver's grammar and normalization exactly —
+ # same helper, no parallel validation path (NS-788).
+ 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
@@ -2571,6 +2582,10 @@ def create_job(
# 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
with _jobs_lock():
jobs = load_jobs()
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 68a1a790411..3dd9b67d4b5 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -2838,7 +2838,7 @@ def _expand_routing_tokens(part: str) -> List[str]:
return expanded
-def _resolve_delivery_targets(job: dict) -> List[dict]:
+def _resolve_delivery_targets(job: dict, *, for_failure: bool = False) -> List[dict]:
"""Resolve all concrete auto-delivery targets for a cron job.
Accepts the legacy comma-separated ``deliver`` string plus the
@@ -2847,8 +2847,21 @@ def _resolve_delivery_targets(job: dict) -> List[dict]:
targets: ``origin,all`` and ``all,telegram:-100:17`` both work.
Duplicate (platform, chat_id, thread_id) tuples are collapsed by the
existing dedup pass.
+
+ ``for_failure=True`` resolves failure-category engine notices
+ (failure summaries, interrupted-run notices, drift/preflight
+ alerts): when the job carries a ``failure_deliver`` value, targets
+ resolve from it INSTEAD of ``deliver`` — ``failure_deliver: local``
+ is the structural opt-out for shared channels (NS-788, Coatue).
+ Absent ``failure_deliver``, failure delivery follows ``deliver``
+ exactly as before.
"""
- deliver = _normalize_deliver_value(job.get("deliver", "local"))
+ deliver_raw = job.get("deliver", "local")
+ if for_failure:
+ failure_deliver = job.get("failure_deliver")
+ if failure_deliver is not None and str(failure_deliver).strip():
+ deliver_raw = failure_deliver
+ deliver = _normalize_deliver_value(deliver_raw)
if deliver == "local":
return []
@@ -3141,7 +3154,9 @@ def _record_delivery_verification(job: dict, unverified_targets: list) -> None:
)
-def _deliver_result(job: dict, content: str, adapters=None, loop=None) -> Optional[str]:
+def _deliver_result(
+ job: dict, content: str, adapters=None, loop=None, *, for_failure: bool = False
+) -> Optional[str]:
"""
Deliver job output to the configured target(s) (origin chat, specific platform, etc.).
@@ -3150,11 +3165,17 @@ def _deliver_result(job: dict, content: str, adapters=None, loop=None) -> Option
the standalone HTTP path cannot encrypt. Falls back to standalone send if
the adapter path fails or is unavailable.
+ ``for_failure=True`` routes failure-category engine notices through the
+ job's ``failure_deliver`` override when present (NS-788).
+
Returns None on success, or an error string on failure.
"""
- targets = _resolve_delivery_targets(job)
+ targets = _resolve_delivery_targets(job, for_failure=for_failure)
if not targets:
- deliver_value = _normalize_deliver_value(job.get("deliver", "local"))
+ deliver_raw = job.get("deliver", "local")
+ if for_failure and str(job.get("failure_deliver") or "").strip():
+ deliver_raw = job.get("failure_deliver")
+ deliver_value = _normalize_deliver_value(deliver_raw)
if deliver_value == "local":
return None # local-only jobs don't deliver — not a failure
# deliver=origin with no resolvable origin and no configured home
@@ -7689,6 +7710,10 @@ def _run_one_job_body(
deliver_content,
adapters=adapters,
loop=loop,
+ # Failure summaries (and drift/blocked-config alerts
+ # composed into deliver_content on the failure path)
+ # honor the job's failure_deliver override (NS-788).
+ for_failure=not success,
)
except Exception as de:
if isinstance(de, _FireClaimLostDuringSideEffect):
@@ -7859,6 +7884,7 @@ def _run_one_job_body(
+ _failure_streak_nudge(job),
adapters=adapters,
loop=loop,
+ for_failure=True,
)
except Exception as delivery_exc:
delivery_error = str(delivery_exc)
diff --git a/gateway/run.py b/gateway/run.py
index 392433f2806..f34f7ef3b68 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -11767,7 +11767,9 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# deliver=local jobs — and deliver=origin jobs with no
# resolvable origin (#43014) — resolve to zero targets and
# must stay silent rather than fall back to a home channel.
- targets = _resolve_delivery_targets(job)
+ # Interrupted notices are failure-category engine status, so
+ # they honor the job's failure_deliver override (NS-788).
+ targets = _resolve_delivery_targets(job, for_failure=True)
except Exception as e:
logger.debug("Cron interrupt targets unresolved for %s: %s", job_id, e)
continue
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index 461c183e29d..cc19e94c6b1 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -791,6 +791,7 @@ def cron_create(args):
prompt=args.prompt,
name=getattr(args, "name", None),
deliver=getattr(args, "deliver", None),
+ failure_deliver=getattr(args, "failure_deliver", None),
repeat=getattr(args, "repeat", None),
skill=getattr(args, "skill", None),
skills=_normalize_skills(getattr(args, "skill", None), getattr(args, "skills", None)),
@@ -867,6 +868,7 @@ def cron_edit(args):
prompt=getattr(args, "prompt", None),
name=getattr(args, "name", None),
deliver=getattr(args, "deliver", None),
+ failure_deliver=getattr(args, "failure_deliver", None),
repeat=getattr(args, "repeat", None),
skills=final_skills,
script=getattr(args, "script", None),
diff --git a/hermes_cli/subcommands/cron.py b/hermes_cli/subcommands/cron.py
index b9d7f085693..4501578b2ca 100644
--- a/hermes_cli/subcommands/cron.py
+++ b/hermes_cli/subcommands/cron.py
@@ -42,6 +42,16 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:
"local profile's canonical Bot Chat as a message the bot responds to)"
),
)
+ cron_create.add_argument(
+ "--failure-deliver",
+ dest="failure_deliver",
+ help=(
+ "Override target for FAILURE notices only (same grammar as "
+ "--deliver). 'local' suppresses failure notices entirely; run "
+ "state stays visible in `hermes cron list`. Omit = failures "
+ "follow --deliver."
+ ),
+ )
cron_create.add_argument("--repeat", type=int, help="Optional repeat count")
cron_create.add_argument(
"--skill",
@@ -142,6 +152,14 @@ def build_cron_parser(subparsers, *, cmd_cron: Callable) -> None:
cron_edit.add_argument("--prompt", help="New prompt/task instruction")
cron_edit.add_argument("--name", help="New job name")
cron_edit.add_argument("--deliver", help="New delivery target")
+ cron_edit.add_argument(
+ "--failure-deliver",
+ dest="failure_deliver",
+ help=(
+ "Override target for failure notices (same grammar as --deliver; "
+ "'local' suppresses; '' clears the override)"
+ ),
+ )
cron_edit.add_argument("--repeat", type=int, help="New repeat count")
cron_edit.add_argument(
"--skill",
diff --git a/tests/cron/test_cron_drift_alert_once.py b/tests/cron/test_cron_drift_alert_once.py
index a6014f25918..c3e57eab293 100644
--- a/tests/cron/test_cron_drift_alert_once.py
+++ b/tests/cron/test_cron_drift_alert_once.py
@@ -48,7 +48,7 @@ def _tick(job, tmp_path, current_provider, deliveries):
"""Run one run_one_job tick with the provider resolution pinned."""
fake_db = MagicMock()
- def fake_deliver(job, content, adapters=None, loop=None):
+ def fake_deliver(job, content, adapters=None, loop=None, **kwargs):
deliveries.append(content)
return None
@@ -129,7 +129,7 @@ class TestDriftAlertOnce:
job = _job(provider_snapshot=None, drift_alerted=True)
deliveries = []
- def fake_deliver(jb, content, adapters=None, loop=None):
+ def fake_deliver(jb, content, adapters=None, loop=None, **kwargs):
deliveries.append(content)
return None
diff --git a/tests/cron/test_cron_failure_deliver.py b/tests/cron/test_cron_failure_deliver.py
new file mode 100644
index 00000000000..dab0e061ea7
--- /dev/null
+++ b/tests/cron/test_cron_failure_deliver.py
@@ -0,0 +1,343 @@
+"""Per-job ``failure_deliver`` routing (NS-788).
+
+A job's FAILURE notices (run failed, escaped scheduler exception, drift-skip /
+blocked-config alerts) resolve their delivery targets from ``failure_deliver``
+when the job sets it, falling back to ``deliver`` when unset — so existing
+jobs behave byte-identically. ``failure_deliver: local`` is structural silence
+for failures: nothing is sent, but state (last_status, run history, output
+file) is still recorded. Success-path delivery never reads ``failure_deliver``.
+
+The grammar is exactly the ``deliver`` grammar — same normalization, same
+validation — reused, not duplicated.
+"""
+
+import json
+
+import pytest
+
+import cron.scheduler as s
+from cron.scheduler import _resolve_delivery_targets
+
+
+def cron_env(tmp_path, monkeypatch):
+ """Isolated cron environment with temp HERMES_HOME."""
+ hermes_home = tmp_path / ".hermes"
+ hermes_home.mkdir()
+ (hermes_home / "cron").mkdir()
+ (hermes_home / "cron" / "output").mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+
+ import cron.jobs as jobs_mod
+ monkeypatch.setattr(jobs_mod, "HERMES_DIR", hermes_home)
+ monkeypatch.setattr(jobs_mod, "CRON_DIR", hermes_home / "cron")
+ monkeypatch.setattr(jobs_mod, "JOBS_FILE", hermes_home / "cron" / "jobs.json")
+ monkeypatch.setattr(jobs_mod, "OUTPUT_DIR", hermes_home / "cron" / "output")
+
+ return hermes_home
+
+
+def run_env(monkeypatch, tmp_path):
+ """Drive run_one_job with the REAL delivery path down to a fake sender.
+
+ Bookkeeping primitives are stubbed (recorded), but _deliver_result and
+ _resolve_delivery_targets are the genuine articles — the send that would
+ leave the process is captured at the platform-registry sender seam,
+ exactly where a real slack delivery exits.
+ """
+ home = tmp_path / "hermes-home"
+ home.mkdir()
+ (home / "config.yaml").write_text(
+ "platforms:\n slack:\n enabled: true\n token: xoxb-test\n"
+ )
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ send_calls = []
+
+ async def fake_sender(pconfig, chat_id, message, *, thread_id=None,
+ media_files=None, force_document=False, caption=None):
+ send_calls.append({"chat_id": chat_id, "message": message})
+ return {"success": True, "chat_id": chat_id, "message_id": "1.2"}
+
+ import gateway.platform_registry as reg
+ import hermes_cli.plugins as hp
+
+ entry = reg.platform_registry.get("slack")
+ if entry is None:
+ hp.discover_plugins()
+ entry = reg.platform_registry.get("slack")
+ if entry is None:
+ pytest.skip("slack platform entry not registered")
+ monkeypatch.setattr(entry, "standalone_sender_fn", fake_sender)
+ monkeypatch.setattr(hp, "discover_plugins", lambda *a, **k: None)
+
+ state = {"send": send_calls, "marked": [], "saved": [], "finished": []}
+
+ monkeypatch.setattr(s, "create_execution", lambda *_a, **_kw: {"id": "exec-t"})
+ monkeypatch.setattr(s, "claim_dispatch", lambda _job_id: True)
+ monkeypatch.setattr(s, "mark_execution_running", lambda _execution_id: None)
+ monkeypatch.setattr(
+ s, "save_job_output",
+ lambda jid, out: state["saved"].append(jid) or f"/tmp/{jid}.txt",
+ )
+ monkeypatch.setattr(
+ s, "mark_job_run",
+ lambda *a, **kw: state["marked"].append((a, kw)) or True,
+ )
+ monkeypatch.setattr(
+ s, "finish_execution",
+ lambda *a, **kw: state["finished"].append((a, kw)),
+ )
+ # No durable incident store in play: never acked, no id.
+ monkeypatch.setattr(
+ s, "_upsert_incident_for_failure", lambda *_a, **_kw: (False, None)
+ )
+ monkeypatch.setattr(s, "load_config", lambda: {})
+ return state
+
+
+def _failing_run_job(error="provider exploded"):
+ def _fake(job, **_kw):
+ return (False, "raw output", "", error)
+ return _fake
+
+
+def _succeeding_run_job(final="all good, here is the brief"):
+ def _fake(job, **_kw):
+ return (True, "raw output", final, None)
+ return _fake
+
+
+class TestFailureDeliverRouting:
+ def test_failure_without_failure_deliver_goes_to_deliver_targets(
+ self, run_env, monkeypatch
+ ):
+ """(a) Unset failure_deliver = today's behavior: failure summary to
+ the job's deliver targets."""
+ monkeypatch.setattr(s, "run_job", _failing_run_job())
+
+ s.run_one_job({"id": "j1", "name": "scout", "deliver": "slack:D0MAIN"})
+
+ assert [c["chat_id"] for c in run_env["send"]] == ["D0MAIN"]
+ assert "failed" in run_env["send"][0]["message"].lower()
+
+ def test_failure_deliver_local_is_silent_but_state_is_recorded(
+ self, run_env, monkeypatch
+ ):
+ """(b) failure_deliver: local — no delivery leaves the process, but
+ the run is still saved and marked failed."""
+ monkeypatch.setattr(s, "run_job", _failing_run_job())
+
+ s.run_one_job({
+ "id": "j2", "name": "scout",
+ "deliver": "slack:D0MAIN", "failure_deliver": "local",
+ })
+
+ assert run_env["send"] == []
+ # State recording is untouched by the silence.
+ assert run_env["saved"] == ["j2"]
+ assert len(run_env["marked"]) == 1
+ args, _kw = run_env["marked"][0]
+ assert args[0] == "j2" and args[1] is False
+ assert "provider exploded" in args[2]
+
+ def test_failure_deliver_explicit_target_wins_over_deliver(
+ self, run_env, monkeypatch
+ ):
+ """(c) failure_deliver set to a different target: the failure notice
+ goes THERE, and nothing goes to the deliver target."""
+ monkeypatch.setattr(s, "run_job", _failing_run_job())
+
+ s.run_one_job({
+ "id": "j3", "name": "scout",
+ "deliver": "slack:D0MAIN", "failure_deliver": "slack:D0ALERTS",
+ })
+
+ assert [c["chat_id"] for c in run_env["send"]] == ["D0ALERTS"]
+ assert "failed" in run_env["send"][0]["message"].lower()
+
+ def test_success_ignores_failure_deliver(self, run_env, monkeypatch):
+ """(d) Success output still goes to deliver — failure_deliver is
+ never consulted on the success path."""
+ monkeypatch.setattr(s, "run_job", _succeeding_run_job())
+
+ ok = s.run_one_job({
+ "id": "j4", "name": "scout",
+ "deliver": "slack:D0MAIN", "failure_deliver": "slack:D0ALERTS",
+ })
+
+ assert ok is True
+ assert [c["chat_id"] for c in run_env["send"]] == ["D0MAIN"]
+ assert "all good, here is the brief" in run_env["send"][0]["message"]
+
+
+class TestEscapedExceptionPath:
+ """The scheduler-layer exception handler is the second failure-delivery
+ site — it must honor failure_deliver identically."""
+
+ def _raise_run_job(self, monkeypatch):
+ monkeypatch.setattr(
+ s, "run_job",
+ lambda *_a, **_kw: (_ for _ in ()).throw(
+ RuntimeError("cannot import name X")
+ ),
+ )
+
+ def test_escaped_failure_honors_failure_deliver_target(
+ self, run_env, monkeypatch
+ ):
+ self._raise_run_job(monkeypatch)
+
+ ok = s.run_one_job({
+ "id": "j5", "name": "scout",
+ "deliver": "slack:D0MAIN", "failure_deliver": "slack:D0ALERTS",
+ })
+
+ assert ok is False
+ assert [c["chat_id"] for c in run_env["send"]] == ["D0ALERTS"]
+
+ def test_escaped_failure_with_failure_deliver_local_is_silent(
+ self, run_env, monkeypatch
+ ):
+ self._raise_run_job(monkeypatch)
+
+ ok = s.run_one_job({
+ "id": "j6", "name": "scout",
+ "deliver": "slack:D0MAIN", "failure_deliver": "local",
+ })
+
+ assert ok is False
+ assert run_env["send"] == []
+ # Failure is still recorded.
+ assert len(run_env["marked"]) == 1
+ args, _kw = run_env["marked"][0]
+ assert args[1] is False and "cannot import name X" in args[2]
+
+
+class TestResolutionGrammar:
+ """(e) failure_deliver shares deliver's exact value grammar — the same
+ normalization/expansion path, not a parallel one."""
+
+ def test_for_failure_resolves_failure_deliver_value(self):
+ job = {"deliver": "local", "failure_deliver": "slack:D0ALERTS"}
+ targets = _resolve_delivery_targets(job, for_failure=True)
+ assert [(t["platform"], t["chat_id"]) for t in targets] == [
+ ("slack", "D0ALERTS")
+ ]
+
+ def test_for_failure_falls_back_to_deliver_when_unset(self):
+ job = {"deliver": "slack:D0MAIN"}
+ targets = _resolve_delivery_targets(job, for_failure=True)
+ assert [(t["platform"], t["chat_id"]) for t in targets] == [
+ ("slack", "D0MAIN")
+ ]
+
+ def test_success_resolution_never_reads_failure_deliver(self):
+ job = {"deliver": "slack:D0MAIN", "failure_deliver": "slack:D0ALERTS"}
+ targets = _resolve_delivery_targets(job)
+ assert [(t["platform"], t["chat_id"]) for t in targets] == [
+ ("slack", "D0MAIN")
+ ]
+
+ def test_local_yields_zero_failure_targets(self):
+ job = {"deliver": "slack:D0MAIN", "failure_deliver": "local"}
+ assert _resolve_delivery_targets(job, for_failure=True) == []
+
+ def test_comma_list_and_thread_grammar(self):
+ """The comma-combine + platform:chat:thread forms deliver's grammar
+ supports work identically for failure_deliver."""
+ job = {
+ "deliver": "local",
+ "failure_deliver": "slack:D0ALERTS,telegram:-1001:17",
+ }
+ targets = _resolve_delivery_targets(job, for_failure=True)
+ assert [(t["platform"], t["chat_id"], t.get("thread_id")) for t in targets] == [
+ ("slack", "D0ALERTS", None),
+ ("telegram", "-1001", "17"),
+ ]
+
+ def test_legacy_list_value_is_flattened_like_deliver(self):
+ """Same list/tuple tolerance _normalize_deliver_value grants deliver."""
+ job = {"deliver": "local", "failure_deliver": ["slack:D0ALERTS"]}
+ targets = _resolve_delivery_targets(job, for_failure=True)
+ assert [(t["platform"], t["chat_id"]) for t in targets] == [
+ ("slack", "D0ALERTS")
+ ]
+
+
+class TestToolSurface:
+ """cronjob(action=create/update) accepts failure_deliver with deliver's
+ validation — reusing the same normalize/validate helpers."""
+
+ def test_create_stores_failure_deliver(self, cron_env):
+ from tools.cronjob_tools import cronjob
+ from cron.jobs import get_job
+
+ result = json.loads(cronjob(
+ action="create",
+ prompt="scan",
+ schedule="every 1h",
+ deliver="slack:D0MAIN",
+ failure_deliver="local",
+ ))
+ assert result["success"] is True
+ assert get_job(result["job_id"])["failure_deliver"] == "local"
+
+ def test_create_without_failure_deliver_does_not_persist_the_key(self, cron_env):
+ """Existing-job byte-identity: the field only exists when set."""
+ from tools.cronjob_tools import cronjob
+ from cron.jobs import get_job
+
+ result = json.loads(cronjob(
+ action="create", prompt="scan", schedule="every 1h",
+ ))
+ assert result["success"] is True
+ assert "failure_deliver" not in get_job(result["job_id"])
+
+ def test_create_flattens_list_value_like_deliver(self, cron_env):
+ from tools.cronjob_tools import cronjob
+ from cron.jobs import get_job
+
+ result = json.loads(cronjob(
+ action="create",
+ prompt="scan",
+ schedule="every 1h",
+ failure_deliver=["slack", "telegram"],
+ ))
+ assert result["success"] is True
+ assert get_job(result["job_id"])["failure_deliver"] == "slack,telegram"
+
+ def test_create_rejects_bad_bot_chat_profile_same_as_deliver(self, cron_env):
+ from tools.cronjob_tools import cronjob
+
+ via_failure = json.loads(cronjob(
+ action="create", prompt="scan", schedule="every 1h",
+ failure_deliver="bot-chat:no-such-profile-xyz",
+ ))
+ via_deliver = json.loads(cronjob(
+ action="create", prompt="scan", schedule="every 1h",
+ deliver="bot-chat:no-such-profile-xyz",
+ ))
+ assert via_failure["success"] is False
+ assert via_deliver["success"] is False
+ # Same validator, same message.
+ assert via_failure["error"] == via_deliver["error"]
+
+ def test_update_sets_and_clears_failure_deliver(self, cron_env):
+ from cron.jobs import create_job, get_job
+ from tools.cronjob_tools import cronjob
+
+ job = create_job(prompt="scan", schedule="every 1h")
+ result = json.loads(cronjob(
+ action="update", job_id=job["id"], failure_deliver="slack:D0ALERTS",
+ ))
+ assert result["success"] is True
+ assert get_job(job["id"])["failure_deliver"] == "slack:D0ALERTS"
+
+ # '' clears — job falls back to deliver on failures again.
+ result = json.loads(cronjob(
+ action="update", job_id=job["id"], failure_deliver="",
+ ))
+ assert result["success"] is True
+ assert not get_job(job["id"]).get("failure_deliver")
diff --git a/tests/cron/test_cron_incidents.py b/tests/cron/test_cron_incidents.py
index c495506336d..22ec1c1d95d 100644
--- a/tests/cron/test_cron_incidents.py
+++ b/tests/cron/test_cron_incidents.py
@@ -46,7 +46,7 @@ def _tick_failing(job, tmp_path, deliveries, error="boom unrelated"):
harness so the incident gating is exercised through the real scheduler."""
fake_db = MagicMock()
- def fake_deliver(jb, content, adapters=None, loop=None):
+ def fake_deliver(jb, content, adapters=None, loop=None, **kwargs):
deliveries.append(content)
return None
diff --git a/tests/cron/test_preflight_config.py b/tests/cron/test_preflight_config.py
index 0a12721d8bc..4e56b3d6e90 100644
--- a/tests/cron/test_preflight_config.py
+++ b/tests/cron/test_preflight_config.py
@@ -129,7 +129,7 @@ class TestMissingProviderKeyBlocks:
job = _job()
deliveries = []
- def fake_deliver(job, content, adapters=None, loop=None):
+ def fake_deliver(job, content, adapters=None, loop=None, **kwargs):
deliveries.append(content)
return None
@@ -233,7 +233,7 @@ class TestOptOut:
job = _job()
deliveries = []
- def fake_deliver(job, content, adapters=None, loop=None):
+ def fake_deliver(job, content, adapters=None, loop=None, **kwargs):
deliveries.append(content)
return None
diff --git a/tests/cron/test_run_one_job.py b/tests/cron/test_run_one_job.py
index a3b8bb425a9..93bcef00a51 100644
--- a/tests/cron/test_run_one_job.py
+++ b/tests/cron/test_run_one_job.py
@@ -29,7 +29,7 @@ def _patch_pipeline(monkeypatch, *, success=True, output="out", final="final res
calls.append(("save", jid))
return f"/tmp/{jid}.txt"
- def fake_deliver(job, content, adapters=None, loop=None):
+ def fake_deliver(job, content, adapters=None, loop=None, **kwargs):
calls.append(("deliver", job["id"]))
return None
diff --git a/tests/gateway/test_cron_interrupt_notification.py b/tests/gateway/test_cron_interrupt_notification.py
index bde4738c204..f157e17478e 100644
--- a/tests/gateway/test_cron_interrupt_notification.py
+++ b/tests/gateway/test_cron_interrupt_notification.py
@@ -120,6 +120,37 @@ class TestNotifyInterruptedCronJobs:
assert sent == 0
assert adapter.sent == []
+ @pytest.mark.asyncio
+ async def test_failure_deliver_local_suppresses_interrupt_notice(self):
+ """Interrupted notices are failure-category engine status (NS-788):
+ a job with failure_deliver='local' opted out of failure pings, and
+ the shutdown notice must honor that. Real target resolution — no
+ _resolve_delivery_targets patch — so the failure_deliver override is
+ actually exercised."""
+ runner, adapter = make_restart_runner()
+ _bind_notifier(runner)
+ job = dict(_telegram_job(), failure_deliver="local")
+
+ with patch("cron.jobs.get_job", return_value=job):
+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])
+
+ assert sent == 0
+ assert adapter.sent == []
+
+ @pytest.mark.asyncio
+ async def test_failure_deliver_unset_notice_reaches_deliver_target(self):
+ """Control for the suppress test: same job without failure_deliver,
+ same real resolution path — the notice goes to the deliver target."""
+ runner, adapter = make_restart_runner()
+ _bind_notifier(runner)
+ job = _telegram_job()
+
+ with patch("cron.jobs.get_job", return_value=job):
+ sent = await runner._notify_interrupted_cron_jobs([job["id"]])
+
+ assert sent == 1
+ assert adapter.sent_calls[0][0] == "123456"
+
@pytest.mark.asyncio
async def test_empty_job_list_is_a_noop(self):
runner, adapter = make_restart_runner()
diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.py
index a0b4fa507d7..54015836d07 100644
--- a/tools/cronjob_tools.py
+++ b/tools/cronjob_tools.py
@@ -1520,6 +1520,7 @@ def cronjob(
monitor_script: Optional[str] = None,
monitor_url: Optional[str] = None,
reasoning_effort: Optional[str] = None,
+ failure_deliver: Optional[Union[str, List[str]]] = None,
task_id: str = None,
session_id: Optional[str] = None,
) -> str:
@@ -1578,6 +1579,12 @@ def cronjob(
# bot-chat deliver targets are machine-local: named profiles must
# exist here, and a bad name should fail the CREATE, not the run.
bot_chat_error = _validate_bot_chat_deliver(_normalize_deliver_param(deliver))
+ if bot_chat_error:
+ return tool_error(bot_chat_error, success=False)
+ # failure_deliver shares deliver's grammar and validators (NS-788).
+ bot_chat_error = _validate_bot_chat_deliver(
+ _normalize_deliver_param(failure_deliver)
+ )
if bot_chat_error:
return tool_error(bot_chat_error, success=False)
@@ -1636,6 +1643,7 @@ def cronjob(
# dispatch below: models do not make model-config
# decisions (standing policy).
reasoning_effort=reasoning_effort,
+ failure_deliver=_normalize_deliver_param(failure_deliver),
)
except CronSchedulerRegistrationError as exc:
_partial = exc.to_dict()
@@ -1838,6 +1846,15 @@ def cronjob(
updates["deliver"] = _resolve_cron_context_deliver(
_normalize_deliver_param(deliver)
)
+ if failure_deliver is not None:
+ # '' clears the override (job falls back to deliver on
+ # failures); non-empty values share deliver's validation.
+ _norm_fd = _normalize_deliver_param(failure_deliver)
+ if _norm_fd:
+ bot_chat_error = _validate_bot_chat_deliver(_norm_fd)
+ if bot_chat_error:
+ return tool_error(bot_chat_error, success=False)
+ updates["failure_deliver"] = _norm_fd
if skills is not None or skill is not None:
canonical_skills = _canonical_skills(skill, skills)
updates["skills"] = canonical_skills
@@ -2027,6 +2044,10 @@ Jobs run in a fresh session with no current-chat context, so prompts must be sel
"type": "string",
"description": "Where the job's output is POSTED as a one-way message (the job itself always runs in a fresh session with no chat context). Omit to address the chat/topic this job was created from. Otherwise: 'local' (save only, no delivery), 'all' (every connected home channel, resolved at fire time), 'bot-chat' or 'bot-chat:<profile>' (inject into a Bot Chat as a real message), or platform:chat_id:thread_id (e.g. 'telegram:-1001234567890:17585'). Comma-combine like 'origin,all'."
},
+ "failure_deliver": {
+ "type": "string",
+ "description": "Optional override target for FAILURE notices only (same grammar as deliver). When set, engine failure/interruption notices go here instead of the deliver target; 'local' suppresses them entirely (state still recorded in cron list/run history). Use for jobs delivering into shared channels where failure noise is unwanted. Omit = failures follow deliver (default). On update, '' clears."
+ },
"skills": {
"type": "array",
"items": {"type": "string"},
@@ -2117,6 +2138,7 @@ def _cronjob_handler(args, **kw):
name=args.get("name"),
repeat=args.get("repeat"),
deliver=args.get("deliver"),
+ failure_deliver=args.get("failure_deliver"),
include_disabled=args.get("include_disabled", True),
skill=args.get("skill"),
skills=args.get("skills"),
diff --git a/website/docs/guides/automate-with-cron.md b/website/docs/guides/automate-with-cron.md
index 20bb490207b..c73d9b39ea3 100644
--- a/website/docs/guides/automate-with-cron.md
+++ b/website/docs/guides/automate-with-cron.md
@@ -74,6 +74,10 @@ Set up the cron job:
For cron monitoring jobs, instruct the agent to respond with only `[SILENT]` when nothing changed. Cron delivery treats `[SILENT]` as the quiet marker, so you only get notified when something actually happens — no spam on quiet hours.
:::
+:::tip Keeping failure notices out of shared channels
+`[SILENT]` only applies to successful runs — when a job hard-fails, the engine posts a `⚠️ Cron 'X' failed…` notice to the job's delivery target. For jobs that deliver into busy shared channels, set `--failure-deliver local` to suppress those notices entirely (run state stays visible in `hermes cron list` and run history), or point failures at an ops channel with `--failure-deliver slack:C_OPS`. Same grammar as `--deliver`; omit it and failures follow `--deliver` as before.
+:::
+
---
## Pattern 2: Weekly Report