Skip to content

The agent that grows with you

fix(cron): harden gateway fire admission and provider compatibility

Evgenii1a8625abee3a
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 53fb4a34f14..13c59ab0de8 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -5918,7 +5918,10 @@ class APIServerAdapter(BasePlatformAdapter):
if not job_id:
return web.json_response({"error": "missing job_id"}, status=400)
- from cron.scheduler_provider import resolve_cron_scheduler
+ from cron.scheduler_provider import (
+ provider_supports_split_fire,
+ resolve_cron_scheduler,
+ )
provider = resolve_cron_scheduler()
loop = asyncio.get_running_loop()
@@ -5940,10 +5943,55 @@ class APIServerAdapter(BasePlatformAdapter):
runner = None
adapters = getattr(runner, "adapters", None) or None
- # Fire in the background (202 immediately). fire_due claims via the
- # store CAS, so a retry while this is in flight is de-duped.
+ if not provider_supports_split_fire(provider):
+ # Legacy single-phase provider: it overrides the documented
+ # ``fire_due`` hook (custom claim/re-arm/telemetry) but
+ # inherits the base ``claim_fire`` — driving it through the
+ # split claim path would silently bypass that override.
+ task = asyncio.create_task(
+ asyncio.to_thread(
+ provider.fire_due,
+ job_id,
+ adapters=adapters,
+ loop=loop,
+ )
+ )
+ reservation["detached"] = True
+ task.add_done_callback(
+ lambda _task: _release_pending_api_work(self, reservation)
+ )
+ try:
+ self._background_tasks.add(task)
+ task.add_done_callback(self._background_tasks.discard)
+ except (TypeError, AttributeError):
+ pass
+ return web.json_response(
+ {"status": "accepted", "job_id": job_id}, status=202
+ )
+
+ # Persist the attempt and exact store owner before acknowledging NAS.
+ # A failure here is retryable and the reservation remains attached.
+ try:
+ claimed_job = await asyncio.to_thread(provider.claim_fire, job_id)
+ except Exception as exc:
+ logger.error("cron fire admission failed for %s: %s", job_id, exc)
+ return web.json_response(
+ {"error": "cron fire admission failed", "job_id": job_id},
+ status=503,
+ )
+ if claimed_job is None:
+ return web.json_response(
+ {"status": "duplicate", "job_id": job_id},
+ status=200,
+ )
+
task = asyncio.create_task(
- asyncio.to_thread(provider.fire_due, job_id, adapters=adapters, loop=loop)
+ asyncio.to_thread(
+ provider.fire_claimed,
+ claimed_job,
+ adapters=adapters,
+ loop=loop,
+ )
)
reservation["detached"] = True
task.add_done_callback(
diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.py
index e92b3c5ce53..abe11f12cf8 100644
--- a/hermes_cli/web_routers/cron.py
+++ b/hermes_cli/web_routers/cron.py
@@ -44,6 +44,7 @@ _delete_cron_job_sync = late("_delete_cron_job_sync")
_find_cron_job_profile = late("_find_cron_job_profile")
_fire_cron_job_for_profile = late("_fire_cron_job_for_profile")
_forward_cron_fire_to_gateway = late("_forward_cron_fire_to_gateway")
+_notify_cron_provider_for_profile = late("_notify_cron_provider_for_profile")
_call_cron_for_profile = late("_call_cron_for_profile")
_raise_if_cron_registration_error = late("_raise_if_cron_registration_error")
load_config = late("load_config")
@@ -251,7 +252,13 @@ async def instantiate_blueprint(body: AutomationBlueprintInstantiate, profile: s
# like the sibling cron endpoints (partial avoids **spec keys ever
# colliding with the wrapper's own parameters).
_create = functools.partial(_call_cron_for_profile, profile, "create_job", **spec)
- return await _run_cron_dashboard_io(_create)
+ created = await _run_cron_dashboard_io(_create)
+ # Same contract as the other dashboard mutations: reconcile the
+ # profile-scoped provider (best-effort; fail-closed for external
+ # providers on a multi-profile dashboard). Off the event loop —
+ # a Chronos reconcile does file I/O plus NAS network calls.
+ await _run_cron_dashboard_io(_notify_cron_provider_for_profile, profile)
+ return created
except HTTPException:
raise
except Exception as e:
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index e64e06d30d5..14af2cde45e 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -365,12 +365,12 @@ async def _lifespan(app: "FastAPI"):
try:
yield
finally:
+ if cron_stop is not None:
+ cron_stop.set()
pty_reaper_task.cancel()
selftest_task.cancel()
auto_archive_task.cancel()
await PTY_REGISTRY.close_all()
- if cron_stop is not None:
- cron_stop.set()
if os.getenv("HERMES_DESKTOP") == "1":
_terminate_desktop_managed_gateway()
@@ -417,6 +417,7 @@ def _get_pty_active_session_files(app: "FastAPI") -> dict[str, Path]:
app = FastAPI(title="Hermes Agent", version=__version__, lifespan=_lifespan)
+
# Memory-provider OAuth connect routes live in the memory layer, not here.
from hermes_cli.memory_oauth import router as _memory_oauth_router # noqa: E402
@@ -12044,6 +12045,73 @@ def _call_cron_for_profile(target_profile: Optional[str], func_name: str, *args,
return result
+def _notify_cron_provider_for_profile(target_profile: Optional[str]) -> None:
+ """Best-effort provider reconcile against one profile's job store.
+
+ Fail-closed for external providers on a multi-profile dashboard: an
+ external provider's ``reconcile`` converges its REMOTE registry toward
+ one profile's jobs.json, and its orphan cleanup cancels every remote
+ entry absent from that store. The NAS registry is not profile-scoped,
+ so reconciling profile B would silently disarm profile A's one-shots.
+ Until the provider contract carries a profile identity through
+ arm/cancel/list, a multi-profile dashboard must not drive unscoped
+ external reconciles at all — the affected profile simply re-arms on
+ its next fire/start (idempotent via dedup_key). The built-in provider
+ re-reads jobs.json each tick and stays a no-op here.
+ """
+ try:
+ _profile_name, home = _cron_profile_home(target_profile)
+ from cron import jobs as cron_jobs
+ from cron.scheduler_provider import (
+ InProcessCronScheduler,
+ resolve_cron_scheduler,
+ )
+ from hermes_constants import (
+ reset_hermes_home_override,
+ set_hermes_home_override,
+ )
+
+ token = set_hermes_home_override(str(home))
+ try:
+ with cron_jobs.use_cron_store(home):
+ provider = resolve_cron_scheduler()
+ if not isinstance(provider, InProcessCronScheduler):
+ profile_names = [
+ str(p.get("name") or "")
+ for p in _cron_profile_dicts()
+ ]
+ if len([n for n in profile_names if n]) > 1:
+ _log.warning(
+ "Skipping cron provider reconcile for profile %s: "
+ "external provider '%s' reconcile is not "
+ "profile-scoped and would disarm other profiles' "
+ "armed one-shots. The mutated profile re-arms "
+ "idempotently on its next fire/start.",
+ target_profile,
+ provider.name,
+ )
+ return
+ provider.on_jobs_changed()
+ finally:
+ reset_hermes_home_override(token)
+ except Exception:
+ _log.debug(
+ "Cron provider reconciliation failed for profile %s",
+ target_profile,
+ exc_info=True,
+ )
+
+
+def _mutate_cron_for_profile(
+ target_profile: Optional[str], func_name: str, *args, **kwargs
+):
+ """Apply a cron store mutation and reconcile its scheduler provider."""
+ result = _call_cron_for_profile(target_profile, func_name, *args, **kwargs)
+ if result:
+ _notify_cron_provider_for_profile(target_profile)
+ return result
+
+
def _find_cron_job_profile(job_id: str) -> Optional[str]:
for profile in _cron_profile_dicts():
name = str(profile.get("name") or "")
@@ -12188,7 +12256,7 @@ def _create_cron_job_sync(body: CronJobCreate, profile: Optional[str] = None):
"script": script,
"no_agent": no_agent,
})
- return _call_cron_for_profile(
+ return _mutate_cron_for_profile(
profile_name,
"create_job",
prompt=body.prompt or "",
@@ -12241,7 +12309,7 @@ def _update_cron_job_sync(job_id: str, body: CronJobUpdate, profile: Optional[st
if "skills" in updates and "skill" not in updates:
effective["skill"] = None
_validate_dashboard_cron_effective_job(effective)
- job = _call_cron_for_profile(profile_name, "update_job", job_id, updates)
+ job = _mutate_cron_for_profile(profile_name, "update_job", job_id, updates)
except HTTPException:
raise
except ValueError as exc:
@@ -12257,7 +12325,7 @@ def _pause_cron_job_sync(job_id: str, profile: Optional[str] = None):
selected = profile or _find_cron_job_profile(job_id)
if not selected:
raise HTTPException(status_code=404, detail="Job not found")
- job = _call_cron_for_profile(selected, "pause_job", job_id)
+ job = _mutate_cron_for_profile(selected, "pause_job", job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return job
@@ -12269,7 +12337,7 @@ def _resume_cron_job_sync(job_id: str, profile: Optional[str] = None):
selected = profile or _find_cron_job_profile(job_id)
if not selected:
raise HTTPException(status_code=404, detail="Job not found")
- job = _call_cron_for_profile(selected, "resume_job", job_id)
+ job = _mutate_cron_for_profile(selected, "resume_job", job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return job
@@ -12281,10 +12349,34 @@ def _trigger_cron_job_sync(job_id: str, profile: Optional[str] = None):
selected = profile or _find_cron_job_profile(job_id)
if not selected:
raise HTTPException(status_code=404, detail="Job not found")
- job = _call_cron_for_profile(selected, "trigger_job", job_id)
+ job = _call_cron_for_profile(selected, "resolve_job_ref", job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
- return job
+ # Do not expose the job as due before claiming it: the built-in ticker and
+ # external/manual fire paths share the same durable claim, so only one can
+ # execute this selected run even if they race across processes. Active jobs
+ # keep the legacy provider call shape; paused jobs need the explicit force
+ # flag to resume and claim atomically.
+ force = not job.get("enabled", True) or job.get("state") == "paused"
+ ran = _fire_cron_job_for_profile(selected, job["id"], force=force)
+ refreshed = _call_cron_for_profile(selected, "get_job", job["id"])
+ if refreshed and refreshed.get("last_run_at") != job.get("last_run_at"):
+ return refreshed
+ if not ran:
+ raise HTTPException(
+ status_code=409,
+ detail="Job is already running or was claimed by another scheduler",
+ )
+ if refreshed:
+ return refreshed
+ # A one-shot may remove itself after exhausting repeat=1. Keep the response
+ # shape compatible without inventing an outcome that is no longer present
+ # in the job store; authoritative list refresh removes the completed row.
+ return {
+ **job,
+ "enabled": False,
+ "state": "completed",
+ }
@@ -12294,7 +12386,7 @@ def _delete_cron_job_sync(job_id: str, profile: Optional[str] = None):
if not selected:
raise HTTPException(status_code=404, detail="Job not found")
try:
- removed = _call_cron_for_profile(selected, "remove_job", job_id)
+ removed = _mutate_cron_for_profile(selected, "remove_job", job_id)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if not removed:
@@ -12304,8 +12396,17 @@ def _delete_cron_job_sync(job_id: str, profile: Optional[str] = None):
-def _fire_cron_job_for_profile(profile: str, job_id: str) -> bool:
- """DEPRECATED — retained only until callers migrate; do not add new uses.
+def _fire_cron_job_for_profile(
+ profile: str,
+ job_id: str,
+ *,
+ force: bool = False,
+) -> bool:
+ """DEPRECATED for NAS webhook fires (superseded by gateway forwarding);
+ retained for the dashboard trigger path — do not add new uses.
+
+ Run ONE due cron job end-to-end for ``profile`` via the resolved
+ scheduler provider's ``fire_due`` (store CAS claim + ``run_one_job``).
Superseded by :func:`_forward_cron_fire_to_gateway`: cron fires must
execute in the GATEWAY process (which owns the live platform adapters),
@@ -12317,7 +12418,10 @@ def _fire_cron_job_for_profile(profile: str, job_id: str) -> bool:
"""
_profile_name, home = _cron_profile_home(profile)
from cron import jobs as cron_jobs
- from cron.scheduler_provider import resolve_cron_scheduler
+ from cron.scheduler_provider import (
+ provider_supports_force_fire,
+ resolve_cron_scheduler,
+ )
from hermes_constants import (
reset_hermes_home_override,
set_hermes_home_override,
@@ -12327,6 +12431,18 @@ def _fire_cron_job_for_profile(profile: str, job_id: str) -> bool:
try:
with cron_jobs.use_cron_store(home):
provider = resolve_cron_scheduler()
+ if force:
+ if not provider_supports_force_fire(provider):
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ f"Cron provider '{getattr(provider, 'name', 'custom')}' "
+ "does not support atomic forced firing of paused jobs"
+ ),
+ )
+ return bool(
+ provider.fire_due(job_id, adapters=None, loop=None, force=True)
+ )
return bool(provider.fire_due(job_id, adapters=None, loop=None))
finally:
reset_hermes_home_override(token)
diff --git a/plugins/cron_providers/chronos/__init__.py b/plugins/cron_providers/chronos/__init__.py
index b46d1d6dc58..a4c80977a4b 100644
--- a/plugins/cron_providers/chronos/__init__.py
+++ b/plugins/cron_providers/chronos/__init__.py
@@ -225,15 +225,28 @@ class ChronosCronScheduler(CronScheduler):
# -- fire -------------------------------------------------------------
- def fire_due(self, job_id: str, *, adapters: Any = None, loop: Any = None) -> bool:
- """Run the due job (claim + run_one_job via the ABC default), then
- re-arm the NEXT one-shot through NAS.
-
- Re-arm happens AFTER the run so next_run_at reflects the completed fire.
- If the job is gone (one-shot completed / repeat-N exhausted), get_job
- returns None → nothing to re-arm (the schedule naturally stops).
- """
- ran = super().fire_due(job_id, adapters=adapters, loop=loop)
+ # NOTE: no ``fire_due`` override on purpose. The base implementation
+ # virtually dispatches through ``self.claim_fire``/``self.fire_claimed``,
+ # and ``provider_supports_split_fire`` treats ANY ``fire_due`` override
+ # (even a pure ``super()`` delegate) as the legacy single-phase signal —
+ # overriding it here would silently opt Chronos out of claim admission,
+ # duplicate detection, and the cancel-aware drain on the fire webhook.
+
+ def fire_claimed(
+ self,
+ claimed_job: dict,
+ *,
+ adapters: Any = None,
+ loop: Any = None,
+ cancel_event: Any = None,
+ ) -> bool:
+ job_id = claimed_job["id"]
+ ran = super().fire_claimed(
+ claimed_job,
+ adapters=adapters,
+ loop=loop,
+ cancel_event=cancel_event,
+ )
if ran:
from cron.jobs import get_job
job = get_job(job_id)
diff --git a/tests/gateway/test_cron_active_work_drain.py b/tests/gateway/test_cron_active_work_drain.py
index 07616a7880a..0a025288bc0 100644
--- a/tests/gateway/test_cron_active_work_drain.py
+++ b/tests/gateway/test_cron_active_work_drain.py
@@ -30,9 +30,11 @@ def _reset_cron_running_set():
import cron.scheduler as sched
sched._running_job_ids.clear()
+ sched._running_fire_owners.clear()
sched._interrupted_job_ids.clear()
yield
sched._running_job_ids.clear()
+ sched._running_fire_owners.clear()
sched._interrupted_job_ids.clear()
@@ -88,6 +90,9 @@ class TestKillToolSubprocessesMarksCronInterrupted:
adapter.disconnect = _make_async_noop()
sched._running_job_ids.add("job-1")
+ sched._running_fire_owners["job-1"] = {
+ object(): ("owner-1", sched._get_hermes_home().resolve())
+ }
monkeypatch.setattr(_pr.process_registry, "kill_all", lambda task_id=None: 1)
monkeypatch.setattr(_tt, "cleanup_all_environments", lambda: None)
diff --git a/tests/gateway/test_cron_fire_webhook.py b/tests/gateway/test_cron_fire_webhook.py
index f6a9f94a7f2..e315030a300 100644
--- a/tests/gateway/test_cron_fire_webhook.py
+++ b/tests/gateway/test_cron_fire_webhook.py
@@ -39,13 +39,18 @@ def adapter():
class _SpyProvider:
- """Records fire_due calls; stands in for the resolved provider."""
+ """Records durable admission and claimed dispatch calls."""
def __init__(self):
+ self.claimed = []
self.fired = []
- def fire_due(self, job_id, *, adapters=None, loop=None):
- self.fired.append(job_id)
+ def claim_fire(self, job_id):
+ self.claimed.append(job_id)
+ return {"id": job_id, "execution_id": f"exec-{job_id}"}
+
+ def fire_claimed(self, job, *, adapters=None, loop=None):
+ self.fired.append(job["id"])
return True
@@ -58,7 +63,10 @@ async def test_valid_fire_reservation_blocks_drain_before_body_and_task(adapter,
release_fire = threading.Event()
class BlockingProvider:
- def fire_due(self, job_id, *, adapters=None, loop=None):
+ def claim_fire(self, job_id):
+ return {"id": job_id, "execution_id": "exec-1"}
+
+ def fire_claimed(self, job, *, adapters=None, loop=None):
fired.set()
release_fire.wait(timeout=2)
return True
@@ -104,6 +112,78 @@ async def test_valid_fire_reservation_blocks_drain_before_body_and_task(adapter,
assert adapter.active_agent_work_count() == 0
+async def test_admission_failure_is_retryable_and_never_dispatches(adapter, monkeypatch):
+ class FailingProvider(_SpyProvider):
+ def claim_fire(self, job_id):
+ raise OSError("ledger unavailable")
+
+ provider = FailingProvider()
+ monkeypatch.setattr("cron.scheduler_provider.resolve_cron_scheduler", lambda: provider)
+ monkeypatch.setattr(
+ "plugins.cron_providers.chronos.verify.get_fire_verifier",
+ lambda: (lambda **kw: {"purpose": "cron_fire"}),
+ )
+
+ app = _create_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ response = await cli.post(
+ "/api/cron/fire",
+ headers={"Authorization": "Bearer good"},
+ json={"job_id": "abc123"},
+ )
+
+ assert response.status == 503
+ assert provider.fired == []
+ assert adapter.active_agent_work_count() == 0
+
+
+async def test_accepted_response_waits_for_durable_admission(adapter, monkeypatch):
+ claim_started = threading.Event()
+ release_claim = threading.Event()
+
+ class BlockingAdmissionProvider(_SpyProvider):
+ def claim_fire(self, job_id):
+ claim_started.set()
+ release_claim.wait(timeout=2)
+ return super().claim_fire(job_id)
+
+ provider = BlockingAdmissionProvider()
+ monkeypatch.setattr("cron.scheduler_provider.resolve_cron_scheduler", lambda: provider)
+ monkeypatch.setattr(
+ "plugins.cron_providers.chronos.verify.get_fire_verifier",
+ lambda: (lambda **kw: {"purpose": "cron_fire"}),
+ )
+
+ app = _create_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ request_task = asyncio.create_task(
+ cli.post(
+ "/api/cron/fire",
+ headers={"Authorization": "Bearer good"},
+ json={"job_id": "abc123"},
+ )
+ )
+ assert await asyncio.to_thread(claim_started.wait, 2)
+ await asyncio.sleep(0)
+ assert not request_task.done()
+
+ release_claim.set()
+ response = await request_task
+ # The 202 guarantees durable ADMISSION only — the fire itself runs as
+ # tracked background work, so wait for it to actually land (fast
+ # locally, but CI scheduling can lose this race).
+ for _ in range(200):
+ if provider.fired:
+ break
+ await asyncio.sleep(0.01)
+
+ assert response.status == 202
+ assert provider.claimed == ["abc123"]
+ assert provider.fired == ["abc123"]
+
+
@pytest.mark.asyncio
async def test_missing_job_id_400(adapter, monkeypatch):
"""Valid token but no job_id → 400, no fire."""
diff --git a/tests/hermes_cli/test_cron_fire_dashboard.py b/tests/hermes_cli/test_cron_fire_dashboard.py
index 9ec70d4ade6..bfbadfce914 100644
--- a/tests/hermes_cli/test_cron_fire_dashboard.py
+++ b/tests/hermes_cli/test_cron_fire_dashboard.py
@@ -9,8 +9,9 @@ hosted agents don't expose). It must:
the JWT verifier runs,
- reject a bad/missing NAS-JWT with 401 (the JWT is the real gate),
- 400 on missing job_id,
- - on a valid token, resolve the job's profile and run fire_due in the
- background, returning 202.
+ - on a valid token, FORWARD the fire to the gateway api_server (which owns
+ cron execution and the live delivery adapters) and pass its response
+ through — 503 when the gateway is unreachable so NAS retries.
"""
import pytest
diff --git a/tests/hermes_cli/test_web_server_cron_profiles.py b/tests/hermes_cli/test_web_server_cron_profiles.py
index 8e49f4a294b..adc3ddafcd3 100644
--- a/tests/hermes_cli/test_web_server_cron_profiles.py
+++ b/tests/hermes_cli/test_web_server_cron_profiles.py
@@ -167,6 +167,175 @@ def test_dashboard_create_reports_saved_but_unregistered(
assert "private callback URL and token" not in str(exc_info.value.detail)
+def test_notify_cron_provider_scopes_store_and_runtime_home_together(
+ isolated_profiles,
+ monkeypatch,
+):
+ """Provider reconciliation must observe the mutated profile, not default."""
+ from cron import jobs as cron_jobs
+ from cron import scheduler
+ from hermes_cli import web_server
+
+ from hermes_constants import (
+ reset_hermes_home_override,
+ set_hermes_home_override,
+ )
+
+ default_home = isolated_profiles["default"]
+ worker_home = isolated_profiles["worker_alpha"]
+ monkeypatch.setattr(scheduler, "_hermes_home", None)
+ monkeypatch.setattr(
+ web_server,
+ "_cron_profile_dicts",
+ lambda: [{"name": "worker_alpha"}],
+ )
+ captured = {}
+
+ class RecordingProvider:
+ def on_jobs_changed(self):
+ captured["runtime_home"] = scheduler._get_hermes_home()
+ captured["jobs_file"] = cron_jobs._current_cron_store().jobs_file
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: RecordingProvider(),
+ )
+
+ outer_token = set_hermes_home_override(default_home)
+ try:
+ web_server._notify_cron_provider_for_profile("worker_alpha")
+ assert captured == {
+ "runtime_home": worker_home,
+ "jobs_file": worker_home / "cron" / "jobs.json",
+ }
+ assert scheduler._get_hermes_home() == default_home
+ finally:
+ reset_hermes_home_override(outer_token)
+
+
+def test_notify_cron_provider_failure_is_best_effort(
+ isolated_profiles,
+ monkeypatch,
+):
+ from hermes_cli import web_server
+
+ class FailNotifyProvider:
+ @property
+ def name(self):
+ return "fail-notify"
+
+ def register_job(self, job):
+ return None
+
+ def on_jobs_changed(self):
+ raise RuntimeError("provider unavailable")
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: FailNotifyProvider(),
+ )
+
+ created = web_server._mutate_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="survives provider failure",
+ schedule="every 1h",
+ name="best-effort-notify",
+ )
+
+ assert created["profile"] == "worker_alpha"
+ assert created["name"] == "best-effort-notify"
+
+
+def test_external_provider_reconcile_fails_closed_with_multiple_profiles(
+ isolated_profiles,
+ monkeypatch,
+):
+ """Multi-profile dashboard + external provider: the unscoped reconcile
+ must NOT run — its orphan cleanup would disarm the other profiles'
+ armed one-shots in the shared NAS registry. The mutation itself still
+ succeeds (fail-closed only skips the remote converge)."""
+ from cron import scheduler
+ from hermes_cli import web_server
+
+ monkeypatch.setattr(scheduler, "_hermes_home", None)
+ monkeypatch.setattr(
+ web_server,
+ "_cron_profile_dicts",
+ lambda: [{"name": "default"}, {"name": "worker_alpha"}],
+ )
+ notified = []
+
+ class ExternalProvider:
+ @property
+ def name(self):
+ return "chronos"
+
+ def register_job(self, job):
+ return None
+
+ def on_jobs_changed(self):
+ notified.append(True)
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: ExternalProvider(),
+ )
+
+ created = web_server._mutate_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="must not disarm siblings",
+ schedule="every 1h",
+ name="multi-profile-guard",
+ )
+
+ assert created["profile"] == "worker_alpha"
+ assert notified == [], (
+ "external provider reconcile must stay fail-closed on a "
+ "multi-profile dashboard"
+ )
+
+
+def test_builtin_provider_hook_still_fires_with_multiple_profiles(
+ isolated_profiles,
+ monkeypatch,
+):
+ """The built-in provider re-reads jobs.json per tick — its hook is a
+ safe no-op and must NOT be blocked by the multi-profile guard."""
+ from cron import scheduler
+ from cron.scheduler_provider import InProcessCronScheduler
+ from hermes_cli import web_server
+
+ monkeypatch.setattr(scheduler, "_hermes_home", None)
+ monkeypatch.setattr(
+ web_server,
+ "_cron_profile_dicts",
+ lambda: [{"name": "default"}, {"name": "worker_alpha"}],
+ )
+ notified = []
+
+ class BuiltinProbe(InProcessCronScheduler):
+ def on_jobs_changed(self):
+ notified.append(True)
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: BuiltinProbe(),
+ )
+
+ created = web_server._mutate_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="builtin notify",
+ schedule="every 1h",
+ name="builtin-notify",
+ )
+
+ assert created["profile"] == "worker_alpha"
+ assert notified == [True]
+
+
def test_profile_call_cannot_retarget_ticker_store_mid_write(
isolated_profiles,
monkeypatch,
@@ -281,6 +450,482 @@ async def test_cron_mutation_without_profile_finds_named_profile_job(isolated_pr
assert worker_jobs[0]["enabled"] is False
+async def test_dashboard_cron_mutations_notify_selected_profile_provider(
+ isolated_profiles,
+ monkeypatch,
+):
+ from hermes_cli import web_server
+
+ notified_profiles = []
+ monkeypatch.setattr(
+ web_server,
+ "_notify_cron_provider_for_profile",
+ notified_profiles.append,
+ )
+
+ created = await web_server.create_cron_job(
+ web_server.CronJobCreate(
+ prompt="managed by named profile",
+ schedule="every 1h",
+ name="provider-notify-job",
+ ),
+ profile="worker_alpha",
+ )
+ await web_server.update_cron_job(
+ created["id"],
+ web_server.CronJobUpdate(updates={"name": "provider-notify-job-updated"}),
+ profile="worker_alpha",
+ )
+ await web_server.pause_cron_job(created["id"], profile="worker_alpha")
+ await web_server.resume_cron_job(created["id"], profile="worker_alpha")
+ await web_server.delete_cron_job(created["id"], profile="worker_alpha")
+
+ assert notified_profiles == ["worker_alpha"] * 5
+
+
+async def test_blueprint_instantiation_notifies_selected_profile_provider(
+ isolated_profiles,
+ monkeypatch,
+):
+ from hermes_cli import web_server
+
+ notified_profiles = []
+ monkeypatch.setattr(
+ web_server,
+ "_notify_cron_provider_for_profile",
+ notified_profiles.append,
+ )
+
+ created = await web_server.instantiate_blueprint(
+ web_server.AutomationBlueprintInstantiate(
+ blueprint="morning-brief",
+ values={"time": "07:30", "deliver": "local"},
+ ),
+ profile="worker_alpha",
+ )
+
+ assert created["profile"] == "worker_alpha"
+ assert notified_profiles == ["worker_alpha"]
+
+
+async def test_trigger_cron_job_fires_only_selected_job_and_returns_refreshed_state(
+ isolated_profiles,
+ monkeypatch,
+):
+ from cron import jobs as cron_jobs
+ from hermes_cli import web_server
+
+ selected = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="run immediately",
+ schedule="every 1h",
+ name="selected-trigger-job",
+ )
+ sibling = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="leave scheduled",
+ schedule="every 1h",
+ name="sibling-job",
+ )
+ fired = []
+
+ class RecordingProvider:
+ def fire_due(self, job_id, *, adapters=None, loop=None, force=False):
+ fired.append(
+ {
+ "job_id": job_id,
+ "jobs_file": cron_jobs._current_cron_store().jobs_file,
+ "force": force,
+ }
+ )
+ cron_jobs.mark_job_run(job_id, success=True)
+ return True
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: RecordingProvider(),
+ )
+ monkeypatch.setattr(
+ cron_jobs,
+ "trigger_job",
+ lambda _job_id: (_ for _ in ()).throw(
+ AssertionError("manual fire must not expose the job to the ticker first")
+ ),
+ )
+
+ triggered = await web_server.trigger_cron_job(
+ selected["id"],
+ profile="worker_alpha",
+ )
+
+ assert fired == [
+ {
+ "job_id": selected["id"],
+ "jobs_file": isolated_profiles["worker_alpha"] / "cron" / "jobs.json",
+ "force": False,
+ }
+ ]
+ assert triggered["last_status"] == "ok"
+ assert triggered["last_run_at"] is not None
+ untouched = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "get_job",
+ sibling["id"],
+ )
+ assert untouched["last_run_at"] is None
+
+
+async def test_trigger_cron_job_reports_lost_claim_as_conflict(
+ isolated_profiles,
+ monkeypatch,
+):
+ from hermes_cli import web_server
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="already running",
+ schedule="every 1h",
+ name="claimed-trigger-job",
+ )
+
+ class ClaimLostProvider:
+ def fire_due(self, job_id, *, adapters=None, loop=None, force=False):
+ return False
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: ClaimLostProvider(),
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await web_server.trigger_cron_job(job["id"], profile="worker_alpha")
+
+ assert exc.value.status_code == 409
+ assert "already running" in exc.value.detail
+
+
+async def test_trigger_cron_job_forces_paused_job_atomically(
+ isolated_profiles,
+ monkeypatch,
+):
+ from cron import jobs as cron_jobs
+ from hermes_cli import web_server
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="resume me",
+ schedule="every 1h",
+ name="paused-trigger-job",
+ )
+ web_server._call_cron_for_profile("worker_alpha", "pause_job", job["id"])
+ observed = {}
+
+ class ForceProvider:
+ def fire_due(self, job_id, *, adapters=None, loop=None, force=False):
+ observed["force"] = force
+ assert cron_jobs.claim_job_for_fire(job_id, force=force) is True
+ cron_jobs.mark_job_run(job_id, success=True)
+ return True
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: ForceProvider(),
+ )
+
+ triggered = await web_server.trigger_cron_job(
+ job["id"],
+ profile="worker_alpha",
+ )
+
+ assert observed["force"] is True
+ assert triggered["enabled"] is True
+ assert triggered["state"] == "scheduled"
+ assert triggered["last_status"] == "ok"
+
+
+async def test_trigger_paused_job_rejects_legacy_provider_without_mutating_job(
+ isolated_profiles,
+ monkeypatch,
+):
+ from fastapi import HTTPException
+ from hermes_cli import web_server
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="stay paused",
+ schedule="every 1h",
+ name="legacy-paused-trigger-job",
+ )
+ web_server._call_cron_for_profile("worker_alpha", "pause_job", job["id"])
+ calls = []
+
+ class LegacyProvider:
+ def fire_due(self, job_id, *, adapters=None, loop=None):
+ calls.append(job_id)
+ return True
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: LegacyProvider(),
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await web_server.trigger_cron_job(job["id"], profile="worker_alpha")
+
+ assert exc.value.status_code == 409
+ assert "forced" in exc.value.detail.lower()
+ assert calls == []
+ persisted = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "get_job",
+ job["id"],
+ )
+ assert persisted["state"] == "paused"
+ assert persisted["enabled"] is False
+
+
+async def test_trigger_cron_job_returns_refreshed_execution_failure(
+ isolated_profiles,
+ monkeypatch,
+):
+ from cron import jobs as cron_jobs
+ from hermes_cli import web_server
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="fail visibly",
+ schedule="every 1h",
+ name="failed-trigger-job",
+ )
+
+ class FailedProvider:
+ def fire_due(self, job_id, *, adapters=None, loop=None, force=False):
+ cron_jobs.mark_job_run(job_id, success=False, error="expected failure")
+ return False
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: FailedProvider(),
+ )
+
+ triggered = await web_server.trigger_cron_job(
+ job["id"],
+ profile="worker_alpha",
+ )
+
+ assert triggered["last_status"] == "error"
+ assert triggered["last_error"] == "expected failure"
+
+
+async def test_trigger_cron_job_returns_completed_snapshot_for_retained_oneshot(
+ isolated_profiles,
+ monkeypatch,
+):
+ from cron import jobs as cron_jobs
+ from hermes_cli import web_server
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="run once",
+ schedule="30m",
+ name="completed-trigger-job",
+ )
+
+ class SuccessfulProvider:
+ def fire_due(self, job_id, *, adapters=None, loop=None, force=False):
+ cron_jobs.mark_job_run(job_id, success=True)
+ return True
+
+ monkeypatch.setattr(
+ "cron.scheduler_provider.resolve_cron_scheduler",
+ lambda: SuccessfulProvider(),
+ )
+
+ triggered = await web_server.trigger_cron_job(
+ job["id"],
+ profile="worker_alpha",
+ )
+
+ assert triggered["state"] == "completed"
+ assert triggered["enabled"] is False
+ # Completed one-shots are retained for the retention window (#80624) with
+ # their terminal status inspectable — the trigger response is the real
+ # record, not a synthetic pre-removal snapshot.
+ assert triggered["last_status"] == "ok"
+ assert triggered["last_run_at"] is not None
+ retained = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "get_job",
+ job["id"],
+ )
+ assert retained is not None
+ assert retained["state"] == "completed"
+
+
+async def test_cron_profile_scan_runs_off_event_loop(isolated_profiles, monkeypatch):
+ from hermes_cli import web_server
+
+ worker_job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="managed by named profile",
+ schedule="every 1h",
+ name="thread-offload-job",
+ )
+
+ event_loop_thread = threading.get_ident()
+ profile_scan_threads = SimpleQueue()
+ worker_threads = SimpleQueue()
+ original_profile_dicts = web_server._cron_profile_dicts
+ original_find = web_server._find_cron_job_profile
+
+ def tracking_profile_dicts():
+ profile_scan_threads.put(threading.get_ident())
+ return original_profile_dicts()
+
+ def tracking_find(job_id):
+ worker_threads.put(threading.get_ident())
+ return original_find(job_id)
+
+ monkeypatch.setattr(web_server, "_cron_profile_dicts", tracking_profile_dicts)
+ monkeypatch.setattr(web_server, "_find_cron_job_profile", tracking_find)
+
+ jobs = await web_server.list_cron_jobs(profile="all")
+ paused = await web_server.pause_cron_job(worker_job["id"])
+
+ assert any(job["id"] == worker_job["id"] for job in jobs)
+ assert paused["profile"] == "worker_alpha"
+ profile_scan_thread_ids = _drain_queue(profile_scan_threads)
+ worker_thread_ids = _drain_queue(worker_threads)
+ assert profile_scan_thread_ids
+ assert worker_thread_ids
+ assert all(thread_id != event_loop_thread for thread_id in profile_scan_thread_ids)
+ assert all(thread_id != event_loop_thread for thread_id in worker_thread_ids)
+
+
+async def test_cron_dashboard_io_rejects_async_callables():
+ from hermes_cli import web_server
+
+ async def async_callable():
+ return "nope"
+
+ with pytest.raises(TypeError, match="only accepts sync callables"):
+ await web_server._run_cron_dashboard_io(async_callable)
+
+
+
+async def test_update_cron_job_normalizes_dashboard_core_fields(isolated_profiles, tmp_path):
+ from hermes_cli import web_server
+
+ scripts_dir = isolated_profiles["worker_alpha"] / "scripts"
+ scripts_dir.mkdir()
+ (scripts_dir / "collect.py").write_text("print('ok')\n", encoding="utf-8")
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="managed by named profile",
+ schedule="every 1h",
+ name="normalizes-dashboard-fields",
+ )
+
+ updated = await web_server.update_cron_job(
+ job["id"],
+ web_server.CronJobUpdate(
+ updates={
+ "base_url": "https://example.invalid/v1/",
+ "script": str(scripts_dir / "collect.py"),
+ "context_from": "",
+ "no_agent": True,
+ }
+ ),
+ profile="worker_alpha",
+ )
+
+ assert updated["base_url"] == "https://example.invalid/v1"
+ assert updated["script"] == "collect.py"
+ assert updated["context_from"] is None
+ assert updated["no_agent"] is True
+
+
+async def test_create_cron_job_rejects_script_outside_profile_scripts(
+ isolated_profiles, tmp_path
+):
+ from hermes_cli import web_server
+
+ outside = tmp_path / "outside.py"
+ outside.write_text("print('nope')\n", encoding="utf-8")
+
+ with pytest.raises(HTTPException) as exc:
+ await web_server.create_cron_job(
+ web_server.CronJobCreate(
+ schedule="every 1h",
+ script=str(outside),
+ no_agent=True,
+ ),
+ profile="worker_alpha",
+ )
+
+ assert exc.value.status_code == 400
+ assert "inside" in exc.value.detail
+
+
+async def test_create_cron_job_rejects_empty_agent_job(isolated_profiles):
+ from hermes_cli import web_server
+
+ with pytest.raises(HTTPException) as exc:
+ await web_server.create_cron_job(
+ web_server.CronJobCreate(schedule="every 1h"),
+ profile="worker_alpha",
+ )
+
+ assert exc.value.status_code == 400
+ assert "prompt, skill, or script" in exc.value.detail
+
+
+async def test_update_cron_job_no_agent_reuses_existing_script(isolated_profiles):
+ from hermes_cli import web_server
+
+ scripts_dir = isolated_profiles["worker_alpha"] / "scripts"
+ scripts_dir.mkdir()
+ (scripts_dir / "collect.py").write_text("print('ok')\n", encoding="utf-8")
+
+ job = await web_server.create_cron_job(
+ web_server.CronJobCreate(
+ schedule="every 1h",
+ script=str(scripts_dir / "collect.py"),
+ ),
+ profile="worker_alpha",
+ )
+
+ updated = await web_server.update_cron_job(
+ job["id"],
+ web_server.CronJobUpdate(updates={"no_agent": True}),
+ profile="worker_alpha",
+ )
+
+ assert updated["no_agent"] is True
+ assert updated["script"] == "collect.py"
@pytest.mark.asyncio
@@ -327,3 +972,218 @@ async def test_dashboard_cron_rejects_missing_context_from(isolated_profiles):
+async def test_dashboard_cron_noop_inference_fields_keep_existing_snapshots(
+ isolated_profiles,
+ monkeypatch,
+):
+ from hermes_cli import runtime_provider, web_server
+
+ current_provider = {"name": "initial-provider"}
+ monkeypatch.setattr(
+ runtime_provider,
+ "resolve_runtime_provider",
+ lambda **kwargs: {"provider": current_provider["name"]},
+ )
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="managed by named profile",
+ schedule="every 1h",
+ name="dashboard-edit-job",
+ )
+
+ assert job["provider_snapshot"] == "initial-provider"
+ assert job["model_snapshot"] == "test-model"
+
+ current_provider["name"] = "changed-provider"
+ (isolated_profiles["worker_alpha"] / "config.yaml").write_text(
+ "model: changed-model\n",
+ encoding="utf-8",
+ )
+
+ updated = await web_server.update_cron_job(
+ job["id"],
+ web_server.CronJobUpdate(
+ updates={
+ "name": "dashboard-edit-job-renamed",
+ "provider": None,
+ "model": None,
+ "base_url": None,
+ "no_agent": False,
+ }
+ ),
+ profile="worker_alpha",
+ )
+
+ assert updated["name"] == "dashboard-edit-job-renamed"
+ assert updated["provider_snapshot"] == "initial-provider"
+ assert updated["model_snapshot"] == "test-model"
+
+
+async def test_update_cron_job_clears_snapshots_for_no_agent(
+ isolated_profiles,
+ monkeypatch,
+):
+ from hermes_cli import runtime_provider, web_server
+
+ monkeypatch.setattr(
+ runtime_provider,
+ "resolve_runtime_provider",
+ lambda **kwargs: {"provider": "worker-provider"},
+ )
+ scripts_dir = isolated_profiles["worker_alpha"] / "scripts"
+ scripts_dir.mkdir()
+ (scripts_dir / "collect.py").write_text("print('ok')\n", encoding="utf-8")
+
+ job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="managed by named profile",
+ schedule="every 1h",
+ name="agent-to-script-job",
+ )
+
+ assert job["provider_snapshot"] == "worker-provider"
+ assert job["model_snapshot"] == "test-model"
+
+ updated = await web_server.update_cron_job(
+ job["id"],
+ web_server.CronJobUpdate(
+ updates={
+ "script": str(scripts_dir / "collect.py"),
+ "no_agent": True,
+ }
+ ),
+ profile="worker_alpha",
+ )
+
+ assert updated["provider_snapshot"] is None
+ assert updated["model_snapshot"] is None
+
+
+async def test_update_cron_job_rejects_id_mutation(isolated_profiles, monkeypatch):
+ """Dashboard surfaces a 400 (not a 500 or silent rename) when an
+ id-mutation attempt is rejected by cron/jobs.update_job."""
+ from hermes_cli import web_server
+
+ notified_profiles = []
+ monkeypatch.setattr(
+ web_server,
+ "_notify_cron_provider_for_profile",
+ notified_profiles.append,
+ )
+ worker_job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="managed by named profile",
+ schedule="every 1h",
+ name="immutable-id-job",
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await web_server.update_cron_job(
+ worker_job["id"],
+ web_server.CronJobUpdate(updates={"id": "../escape"}),
+ profile="worker_alpha",
+ )
+
+ assert exc.value.status_code == 400
+ assert "id" in exc.value.detail
+ assert notified_profiles == []
+ worker_jobs = await web_server.list_cron_jobs(profile="worker_alpha")
+ assert [job["id"] for job in worker_jobs] == [worker_job["id"]]
+
+
+async def test_cron_delete_with_profile_deletes_only_target_profile(isolated_profiles):
+ from hermes_cli import web_server
+
+ default_job = web_server._call_cron_for_profile(
+ "default",
+ "create_job",
+ prompt="same-ish default",
+ schedule="every 1h",
+ name="shared-name",
+ )
+ worker_job = web_server._call_cron_for_profile(
+ "worker_alpha",
+ "create_job",
+ prompt="same-ish worker",
+ schedule="every 1h",
+ name="shared-name-worker",
+ )
+
+ deleted = await web_server.delete_cron_job(worker_job["id"], profile="worker_alpha")
+ assert deleted == {"ok": True}
+
+ remaining_default = await web_server.list_cron_jobs(profile="default")
+ remaining_worker = await web_server.list_cron_jobs(profile="worker_alpha")
+ assert [job["id"] for job in remaining_default] == [default_job["id"]]
+ assert remaining_worker == []
+
+
+async def test_cron_profile_validation_errors(isolated_profiles):
+ from hermes_cli import web_server
+
+ with pytest.raises(HTTPException) as bad_name:
+ await web_server.list_cron_jobs(profile="../bad")
+ assert bad_name.value.status_code == 400
+
+ with pytest.raises(HTTPException) as missing:
+ await web_server.list_cron_jobs(profile="missing_profile")
+ assert missing.value.status_code == 404
+
+
+async def test_create_cron_job_without_profile_uses_backend_own_profile(
+ isolated_profiles, monkeypatch
+):
+ """A pool backend scoped to a named profile must not default creates to
+ ``~/.hermes`` when the request carries no explicit ``profile`` (the
+ Desktop app's pre-profileScoped clients sent none)."""
+ from hermes_cli import web_server
+
+ monkeypatch.setenv(
+ "HERMES_HOME", str(isolated_profiles["worker_alpha"])
+ )
+
+ job = await web_server.create_cron_job(
+ web_server.CronJobCreate(
+ prompt="runs in my own profile",
+ schedule="every 1h",
+ name="own-profile-job",
+ ),
+ profile=None,
+ )
+
+ assert job["profile"] == "worker_alpha"
+ assert (isolated_profiles["worker_alpha"] / "cron" / "jobs.json").exists()
+ assert not (isolated_profiles["default"] / "cron" / "jobs.json").exists()
+
+
+async def test_create_cron_job_without_profile_defaults_when_unscoped(
+ isolated_profiles, monkeypatch
+):
+ """HERMES_HOME at the default home (or unrecognized) keeps the legacy
+ ``default`` fallback."""
+ from hermes_cli import web_server
+
+ monkeypatch.setenv("HERMES_HOME", str(isolated_profiles["default"]))
+
+ job = await web_server.create_cron_job(
+ web_server.CronJobCreate(
+ prompt="runs in default",
+ schedule="every 1h",
+ name="default-job",
+ ),
+ profile=None,
+ )
+
+ assert job["profile"] == "default"
+ assert (isolated_profiles["default"] / "cron" / "jobs.json").exists()
diff --git a/tests/plugins/test_chronos_cron.py b/tests/plugins/test_chronos_cron.py
index bf0cdca7976..75971ea2d30 100644
--- a/tests/plugins/test_chronos_cron.py
+++ b/tests/plugins/test_chronos_cron.py
@@ -118,9 +118,16 @@ def test_reconcile_arms_all_enabled(temp_home, chronos, monkeypatch):
def test_fire_due_rearms_next_oneshot(chronos, monkeypatch):
prov, fake = chronos
- # super().fire_due runs the job; stub the ABC default to "ran".
- monkeypatch.setattr("cron.scheduler_provider.CronScheduler.fire_due",
- lambda self, jid, **kw: True)
+ # Keep the two-phase provider flow intact while stubbing durable admission
+ # and the shared runner body.
+ monkeypatch.setattr(
+ "cron.scheduler_provider.CronScheduler.claim_fire",
+ lambda self, jid, **kw: {"id": jid, "execution_id": "exec-1"},
+ )
+ monkeypatch.setattr(
+ "cron.scheduler_provider.CronScheduler.fire_claimed",
+ lambda self, job, **kw: True,
+ )
monkeypatch.setattr("cron.jobs.get_job",
lambda jid: {"id": jid, "enabled": True, "next_run_at": "2026-06-18T12:05:00+00:00"})
@@ -128,3 +135,105 @@ def test_fire_due_rearms_next_oneshot(chronos, monkeypatch):
assert [p["job_id"] for p in fake.provisions] == ["j1"]
assert fake.provisions[0]["fire_at"] == "2026-06-18T12:05:00+00:00"
+
+def test_fire_due_rearms_after_claimed_job_failure(chronos, monkeypatch):
+ """A claimed attempt is consumed even when the job pipeline reports failure."""
+ prov, fake = chronos
+ claimed = {"id": "j1", "fire_claim": {"by": "owner-1"}}
+ persisted = {
+ "id": "j1",
+ "enabled": True,
+ "next_run_at": "2026-06-18T12:05:00+00:00",
+ }
+
+ monkeypatch.setattr("cron.jobs.claim_job_for_fire", lambda jid, **kw: claimed)
+ monkeypatch.setattr(
+ "cron.executions.create_execution",
+ lambda jid, source: {"id": "exec-1"},
+ )
+ monkeypatch.setattr("cron.scheduler.run_one_job", lambda *args, **kwargs: False)
+ monkeypatch.setattr("cron.jobs.get_job", lambda jid: persisted)
+
+ assert prov.fire_due("j1") is True
+ assert [provision["job_id"] for provision in fake.provisions] == ["j1"]
+
+
+def test_fire_due_forwards_manual_force_to_claim(chronos, monkeypatch):
+ """A manual force fire must reach the store claim as force=True."""
+ prov, _fake = chronos
+ seen = []
+ monkeypatch.setattr(
+ "cron.jobs.claim_job_for_fire",
+ lambda jid, **kw: seen.append(kw) or False,
+ )
+ monkeypatch.setattr(
+ "cron.executions.create_execution",
+ lambda jid, source: {"id": "exec-1"},
+ )
+
+ assert prov.fire_due("j1", force=True) is False
+ assert seen == [{"return_job": True, "force": True}]
+
+
+def test_fire_due_no_rearm_when_job_gone(chronos, monkeypatch):
+ """repeat-N exhausted / one-shot completed → mark_job_run deleted the job →
+ get_job None → no re-arm (the schedule stops cleanly)."""
+ prov, fake = chronos
+ monkeypatch.setattr("cron.scheduler_provider.CronScheduler.fire_due",
+ lambda self, jid, **kw: True)
+ monkeypatch.setattr("cron.jobs.get_job", lambda jid: None)
+
+ assert prov.fire_due("j1") is True
+ assert fake.provisions == []
+
+
+def test_fire_due_no_rearm_when_claim_lost(chronos, monkeypatch):
+ """If the run didn't happen (claim lost), don't re-arm."""
+ prov, fake = chronos
+ monkeypatch.setattr("cron.scheduler_provider.CronScheduler.fire_due",
+ lambda self, jid, **kw: False)
+
+ assert prov.fire_due("j1") is False
+ assert fake.provisions == []
+
+
+# -- provider capability classification ----------------------------------------
+
+def test_chronos_is_split_fire_capable(chronos):
+ """Regression: Chronos must be classified as a split-aware provider so the
+ fire webhook uses durable claim admission (not the legacy fire_due path).
+ Chronos deliberately has NO fire_due override — its re-arm logic lives in
+ fire_claimed, which the split path invokes."""
+ from cron.scheduler_provider import (
+ provider_supports_fire_cancel,
+ provider_supports_force_fire,
+ provider_supports_split_fire,
+ )
+
+ prov, _fake = chronos
+ assert provider_supports_split_fire(prov) is True
+ assert provider_supports_force_fire(prov) is True
+ assert provider_supports_fire_cancel(prov) is True
+
+
+def test_fire_claimed_no_rearm_when_run_failed(chronos, monkeypatch):
+ prov, fake = chronos
+ monkeypatch.setattr(
+ "cron.scheduler_provider.CronScheduler.fire_claimed",
+ lambda self, job, **kw: False,
+ )
+
+ assert prov.fire_claimed({"id": "j1"}) is False
+ assert fake.provisions == []
+
+
+def test_fire_claimed_no_rearm_when_job_gone(chronos, monkeypatch):
+ prov, fake = chronos
+ monkeypatch.setattr(
+ "cron.scheduler_provider.CronScheduler.fire_claimed",
+ lambda self, job, **kw: True,
+ )
+ monkeypatch.setattr("cron.jobs.get_job", lambda jid: None)
+
+ assert prov.fire_claimed({"id": "j1"}) is True
+ assert fake.provisions == []
diff --git a/tests/tools/test_cronjob_run_background.py b/tests/tools/test_cronjob_run_background.py
index d33858c8b66..a35d4c4a8fb 100644
--- a/tests/tools/test_cronjob_run_background.py
+++ b/tests/tools/test_cronjob_run_background.py
@@ -67,7 +67,7 @@ class TestBackgroundDispatch:
return True
with _bound_session_key():
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True) as m_claim, \
+ with patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: {**_job(jid), "fire_claim": {"by": "bg-owner"}}) as m_claim, \
patch("cron.scheduler.run_one_job", side_effect=slow_run_one_job), \
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "ok", "last_error": None}):
@@ -79,7 +79,7 @@ class TestBackgroundDispatch:
assert res["claimed"] is True
assert res["dispatched"] is True
assert res["delegation_id"]
- m_claim.assert_called_once_with("job-bg-01")
+ m_claim.assert_called_once_with("job-bg-01", return_job=True)
# The job actually starts on the daemon executor.
assert run_started.wait(timeout=5.0), "job never started in background"
finally:
@@ -95,7 +95,7 @@ class TestBackgroundDispatch:
# The runner executes on a daemon thread — the patches must stay
# active until the completion event lands, so poll INSIDE the blocks.
with _bound_session_key("agent:main:telegram:dm:777"):
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: {**_job(jid), "fire_claim": {"by": "bg-owner"}}), \
patch("cron.scheduler.run_one_job", return_value=True), \
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "ok", "last_error": None,
@@ -128,7 +128,7 @@ class TestBackgroundDispatch:
from tools.process_registry import process_registry
with _bound_session_key("agent:main:telegram:dm:778"):
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: {**_job(jid), "fire_claim": {"by": "bg-owner"}}), \
patch("cron.scheduler.run_one_job", return_value=True), \
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "error",
@@ -183,7 +183,7 @@ class TestSyncFallbacks:
def test_pool_at_capacity_runs_inline(self):
"""A rejected dispatch must not strand the already-taken claim."""
with _bound_session_key():
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: {**_job(jid), "fire_claim": {"by": "bg-owner"}}), \
patch("tools.async_delegation.dispatch_async_delegation",
return_value={"status": "rejected", "error": "capacity"}), \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
@@ -278,7 +278,7 @@ class TestCronjobRunToolIntegration:
"""cronjob(action='run') surfaces the handle + do-not-wait note."""
with _bound_session_key():
with patch("tools.cronjob_tools.resolve_job_ref", return_value=_job('job-bg-12')), \
- patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: {**_job(jid), "fire_claim": {"by": "bg-owner"}}), \
patch("cron.scheduler.run_one_job", return_value=True), \
patch("tools.cronjob_tools.get_job",
return_value={"id": "job-bg-12", "name": "bg run",
@@ -296,7 +296,7 @@ class TestCronjobRunToolIntegration:
execution_success populated from the completed run)."""
ran = {"job": "after-run", "last_status": "ok", "last_error": None}
with patch("tools.cronjob_tools.resolve_job_ref", return_value=_job('job-bg-13')), \
- patch("tools.cronjob_tools.claim_job_for_fire", return_value=True) as m_claim, \
+ patch("tools.cronjob_tools.claim_job_for_fire", side_effect=lambda jid, **kw: {**_job(jid), "fire_claim": {"by": "bg-owner"}}) as m_claim, \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job", return_value=ran):
out = json.loads(cronjob(action="run", job_id="job-bg-13"))
@@ -304,5 +304,5 @@ class TestCronjobRunToolIntegration:
assert out["success"] is True
assert out["job"]["executed"] is True
assert out["job"]["execution_success"] is True
- m_claim.assert_called_once_with("job-bg-13")
+ m_claim.assert_called_once_with("job-bg-13", return_job=True)
m_run.assert_called_once()
diff --git a/tests/tools/test_cronjob_run_immediate.py b/tests/tools/test_cronjob_run_immediate.py
index ad24d02f257..beb8c098c3c 100644
--- a/tests/tools/test_cronjob_run_immediate.py
+++ b/tests/tools/test_cronjob_run_immediate.py
@@ -29,8 +29,9 @@ class TestCronjobRunExecutesImmediately:
def test_run_action_claims_and_fires_via_run_one_job(self):
"""action='run' must claim the job then fire it through run_one_job."""
ran = {"job": "after-run", "last_status": "ok", "last_error": None}
+ claimed = {**_JOB, "fire_claim": {"by": "manual-owner"}}
with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
- patch("tools.cronjob_tools.claim_job_for_fire", return_value=True) as m_claim, \
+ patch("tools.cronjob_tools.claim_job_for_fire", return_value=claimed) as m_claim, \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job", return_value=ran):
out = json.loads(cronjob(action="run", job_id="job-run-1"))
@@ -38,9 +39,80 @@ class TestCronjobRunExecutesImmediately:
assert out["success"] is True
assert out["job"]["executed"] is True
assert out["job"]["execution_success"] is True
- m_claim.assert_called_once_with("job-run-1") # at-most-once claim taken
- m_run.assert_called_once() # fired via the shared body
+ m_claim.assert_called_once_with("job-run-1", return_job=True)
+ m_run.assert_called_once_with(claimed, adapters=None, loop=None, extra_prompt=None)
+ def test_run_reconciles_external_provider_after_claimed_execution(self):
+ """A direct run must re-arm Chronos after it advances next_run_at.
+
+ Otherwise a scheduled Chronos fire that loses its claim to this direct
+ run is consumed without a successor one-shot, permanently stalling the
+ recurring job.
+ """
+ order = []
+ ran = {"id": "job-run-1", "last_status": "ok", "last_error": None}
+ claimed = {**_JOB, "fire_claim": {"by": "manual-owner"}}
+ with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
+ patch("tools.cronjob_tools.claim_job_for_fire", return_value=claimed), \
+ patch("cron.scheduler.run_one_job",
+ side_effect=lambda *a, **kw: order.append("run") or True), \
+ patch("tools.cronjob_tools.get_job", return_value=ran), \
+ patch("tools.cronjob_tools._notify_provider_jobs_changed_safe",
+ side_effect=lambda: order.append("notify")) as m_notify:
+ out = json.loads(cronjob(action="run", job_id="job-run-1"))
+
+ assert out["job"]["executed"] is True
+ m_notify.assert_called_once_with()
+ # Reconcile only AFTER the run persisted its final state (mark_job_run
+ # inside run_one_job), so the provider arms the post-run next_run_at.
+ assert order == ["run", "notify"]
+
+ def test_run_reconciles_external_provider_even_when_claimed_run_fails(self):
+ """A claimed direct run advances next_run_at at claim time, so the
+ provider must be reconciled even when the execution itself fails."""
+ failed = {"id": "job-run-1", "last_status": "error", "last_error": "provider 500"}
+ claimed = {**_JOB, "fire_claim": {"by": "manual-owner"}}
+ with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
+ patch("tools.cronjob_tools.claim_job_for_fire", return_value=claimed), \
+ patch("cron.scheduler.run_one_job", side_effect=RuntimeError("boom")), \
+ patch("tools.cronjob_tools.mark_job_run"), \
+ patch("tools.cronjob_tools.get_job", return_value=failed), \
+ patch("tools.cronjob_tools._notify_provider_jobs_changed_safe") as m_notify:
+ out = json.loads(cronjob(action="run", job_id="job-run-1"))
+
+ assert out["job"]["executed"] is True
+ assert out["job"]["execution_success"] is False
+ m_notify.assert_called_once_with()
+
+ def test_run_skips_when_claim_lost(self):
+ """If the scheduler already holds the fire claim, do NOT double-run."""
+ with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
+ patch("tools.cronjob_tools.claim_job_for_fire", return_value=False), \
+ patch("cron.scheduler.run_one_job") as m_run, \
+ patch("tools.cronjob_tools.get_job", return_value=dict(_JOB)), \
+ patch("tools.cronjob_tools._notify_provider_jobs_changed_safe") as m_notify:
+ out = json.loads(cronjob(action="run", job_id="job-run-1"))
+
+ assert out["success"] is True
+ assert out["job"]["executed"] is False
+ assert out["job"]["execution_success"] is False
+ assert "execution_skipped" in out["job"]
+ m_run.assert_not_called() # claim lost -> never fired
+ m_notify.assert_not_called() # the winning scheduler owns the re-arm
+
+ def test_run_reports_failure_from_last_status(self):
+ """A failed run is reported via the re-read job's last_status/last_error."""
+ failed = {"id": "job-run-1", "last_status": "error", "last_error": "provider 500"}
+ claimed = {**_JOB, "fire_claim": {"by": "manual-owner"}}
+ with patch("tools.cronjob_tools.resolve_job_ref", return_value=dict(_JOB)), \
+ patch("tools.cronjob_tools.claim_job_for_fire", return_value=claimed), \
+ patch("cron.scheduler.run_one_job", return_value=True), \
+ patch("tools.cronjob_tools.get_job", return_value=failed):
+ out = json.loads(cronjob(action="run", job_id="job-run-1"))
+
+ assert out["job"]["executed"] is True
+ assert out["job"]["execution_success"] is False
+ assert out["job"]["execution_error"] == "provider 500"
def test_execute_job_now_bails_without_claim(self):
"""_execute_job_now never calls run_one_job when the claim is lost."""
@@ -58,7 +130,7 @@ class TestCronjobRunExecutesImmediately:
runner = SimpleNamespace(adapters=adapters, _gateway_loop=gateway_loop)
completed = {"id": "job-run-1", "last_status": "ok", "last_error": None}
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \
patch("gateway.run._gateway_runner_ref", return_value=runner), \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job", return_value=completed):
@@ -66,7 +138,7 @@ class TestCronjobRunExecutesImmediately:
assert res["success"] is True
m_run.assert_called_once_with(
- _JOB,
+ {**_JOB, "fire_claim": {"by": "manual-owner"}},
adapters=adapters,
loop=gateway_loop,
extra_prompt=None,
@@ -76,18 +148,24 @@ class TestCronjobRunExecutesImmediately:
"""CLI-only runs retain the standalone delivery path."""
completed = {"id": "job-run-1", "last_status": "ok", "last_error": None}
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \
patch.dict(sys.modules, {"gateway.run": None}), \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job", return_value=completed):
res = _execute_job_now(dict(_JOB))
assert res["success"] is True
- m_run.assert_called_once_with(_JOB, adapters=None, loop=None, extra_prompt=None)
+ m_run.assert_called_once_with(
+ {**_JOB, "fire_claim": {"by": "manual-owner"}},
+ adapters=None,
+ loop=None,
+ extra_prompt=None,
+ )
def test_execute_job_now_marks_failure_on_exception(self):
"""An exception during fire is captured, marked failed, not propagated."""
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ claimed = {**_JOB, "fire_claim": {"by": "manual-owner"}}
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value=claimed), \
patch("cron.scheduler.run_one_job", side_effect=RuntimeError("boom")), \
patch("tools.cronjob_tools.mark_job_run") as m_mark, \
patch("tools.cronjob_tools.get_job", return_value=dict(_JOB)):
@@ -95,7 +173,12 @@ class TestCronjobRunExecutesImmediately:
assert res["claimed"] is True
assert res["success"] is False
assert "boom" in res["error"]
- m_mark.assert_called_once()
+ m_mark.assert_called_once_with(
+ "job-run-1",
+ False,
+ "boom",
+ expected_fire_owner="manual-owner",
+ )
def test_execute_job_now_heartbeats_while_job_runs(self):
"""A manual run ticks the caller's activity tracker while the job
@@ -116,7 +199,7 @@ class TestCronjobRunExecutesImmediately:
assert heartbeat_seen.wait(timeout=5.0), "no heartbeat within 5s"
return True
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \
patch("tools.cronjob_tools._CRON_RUN_HEARTBEAT_INTERVAL", 0.05), \
patch("cron.scheduler.run_one_job", side_effect=slow_run) as m_run, \
patch("tools.cronjob_tools.get_job",
@@ -134,7 +217,7 @@ class TestCronjobRunExecutesImmediately:
heartbeat thread is never started and behavior is unchanged."""
set_activity_callback(None)
try:
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \
patch("cron.scheduler.run_one_job", return_value=True) as m_run, \
patch("tools.cronjob_tools.get_job",
return_value={"last_status": "ok", "last_error": None}), \
@@ -165,7 +248,7 @@ class TestCronjobRunExecutesImmediately:
time.sleep(0.2)
return True
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \
patch("tools.cronjob_tools._CRON_RUN_HEARTBEAT_INTERVAL", 0.05), \
patch("tools.cronjob_tools._CRON_RUN_HEARTBEAT_CEILING", 0.0), \
patch("cron.scheduler.run_one_job", side_effect=slow_run), \
@@ -198,7 +281,7 @@ class TestCronjobRunExecutesImmediately:
"heartbeat stopped after one callback exception"
return True
- with patch("tools.cronjob_tools.claim_job_for_fire", return_value=True), \
+ with patch("tools.cronjob_tools.claim_job_for_fire", return_value={**_JOB, "fire_claim": {"by": "manual-owner"}}), \
patch("tools.cronjob_tools._CRON_RUN_HEARTBEAT_INTERVAL", 0.05), \
patch("cron.scheduler.run_one_job", side_effect=slow_run), \
patch("tools.cronjob_tools.get_job",
diff --git a/tools/cronjob_tools.py b/tools/cronjob_tools.py
index 6fb94b35b68..15638fe0ab8 100644
--- a/tools/cronjob_tools.py
+++ b/tools/cronjob_tools.py
@@ -680,9 +680,11 @@ def _execute_job_now(
Returns {"claimed": bool, "success": bool, "error": str|None}.
"""
job_id = job["id"]
+ claimed_job = None
try:
# At-most-once claim: bail without running if a tick/other fire owns it.
- if not claim_job_for_fire(job_id):
+ claimed_job = claim_job_for_fire(job_id, return_job=True)
+ if not isinstance(claimed_job, dict):
# claim_job_for_fire returns False for paused/disabled/missing
# jobs too — don't mislabel those as "already being fired"
# (#60703): that message sends the user chasing a phantom
@@ -703,7 +705,7 @@ def _execute_job_now(
pass
return {"claimed": True, "success": False, "error": str(e)}
- return _run_claimed_job(job, extra_prompt=extra_prompt)
+ return _run_claimed_job(claimed_job, extra_prompt=extra_prompt)
def _run_claimed_job(
@@ -720,6 +722,7 @@ def _run_claimed_job(
"""
job_id = job["id"]
_registered = False
+ fire_owner = None
try:
from cron.scheduler import (
release_running_job,
@@ -745,8 +748,13 @@ def _run_claimed_job(
}
_registered = True
+ claim = job.get("fire_claim")
+ fire_owner = str(claim.get("by") or "") if isinstance(claim, dict) else None
+
# run_one_job records last_run_at/last_status via mark_job_run (which
# also clears the fire claim) and returns True iff it processed the job.
+ # ``job`` here is the exact claimed snapshot (owner-bearing), so the
+ # shared body fences every terminal write by that owner.
#
# A manual `run` executes the job synchronously on the caller's thread,
# and a cron job is itself a full agent run that routinely takes
@@ -854,10 +862,19 @@ def _run_claimed_job(
except Exception:
pass
try:
- mark_job_run(job_id, False, str(e))
+ mark_job_run(
+ job_id,
+ False,
+ str(e),
+ expected_fire_owner=fire_owner,
+ )
except Exception:
pass
- return {"claimed": True, "success": False, "error": str(e)}
+ return {
+ "claimed": True,
+ "success": False,
+ "error": str(e),
+ }
def _latest_job_output_excerpt(job_id: str, max_chars: int = 2000) -> Optional[str]:
@@ -978,7 +995,10 @@ def _try_dispatch_background_run(
except Exception:
pass
- if not claim_job_for_fire(job_id):
+ # Same snapshot claim as _execute_job_now: carry the owner-bearing
+ # record into the run so terminal writes stay fenced by this owner.
+ claimed_job = claim_job_for_fire(job_id, return_job=True)
+ if not isinstance(claimed_job, dict):
refreshed = get_job(job_id)
if refreshed is None:
reason = "Job no longer exists; nothing to run."
@@ -1015,7 +1035,7 @@ def _try_dispatch_background_run(
"cronjob run: async delegation registry unavailable (%s); "
"running job '%s' inline.", e, job_name,
)
- result = _run_claimed_job(job, extra_prompt=extra_prompt)
+ result = _run_claimed_job(claimed_job, extra_prompt=extra_prompt)
result["dispatched"] = False
return result
@@ -1030,7 +1050,7 @@ def _try_dispatch_background_run(
deliver = job.get("deliver", "local")
def _runner() -> Dict[str, Any]:
- res = _run_claimed_job(job, extra_prompt=extra_prompt)
+ res = _run_claimed_job(claimed_job, extra_prompt=extra_prompt)
duration = round(time.time() - started_at, 2)
refreshed = get_job(job_id) or {}
lines = [