Skip to content

The agent that grows with you

fix: admit agent cron runs through the canonical owner

Tekniumcdbe8c35adf2
diff --git a/cron/scheduler.py b/cron/scheduler.py
index e364ddd7fc3..e32a43abf08 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -1595,6 +1595,16 @@ def _open_cron_session_db(job: dict):
# no timeout of its own against a wedged sqlite3.connect (e.g. a stale flock left by a crashed sibling
# process). An unbounded hang here would wedge the job's worker thread, so the init is bounded and a
# timeout proceeds without a session store instead of blocking the run forever.
+ from gateway.session_cron import current_execution
+ owner = current_execution()
+ if owner is not None:
+ from hermes_state_registry import acquire
+ db = acquire(Path(owner[0].db.db_path))
+ if db is not owner[0].db:
+ from hermes_state_registry import release_or_close
+ release_or_close(db)
+ raise RuntimeError('cron requires the canonical owner store')
+ return db
from agent.runtime_session_store import WorkerPersistenceError, is_worker_process
if is_worker_process():
# Do not turn an unsupported worker assignment into the legacy None
@@ -2232,6 +2242,14 @@ def run_job(
``extra_prompt``: optional per-run context from ``cronjob(action='run', prompt=...)`` (#57331). Appended
to the stored prompt for this fire only — never persisted to the job definition.
"""
+ from gateway.session_cron import current_execution
+ owner_execution = current_execution()
+ if owner_execution is not None and owner_execution[2:] != (job['id'], execution_id):
+ owner_execution = None
+ if not job.get("no_agent") and owner_execution is None:
+ from cron.scheduler_authority import run_canonical_job
+ return run_canonical_job(job, extra_prompt=extra_prompt, cancel_event=cancel_event,
+ execution_id=execution_id)
job_id = job["id"]
job_name = str(job.get("name") or job.get("prompt") or job_id or "cron job")
@@ -2240,7 +2258,8 @@ def run_job(
return early
from run_agent import AIAgent
- _cron_session_id = f"cron_{job_id}_{_hermes_now().strftime('%Y%m%d_%H%M%S')}"
+ _cron_session_id = (owner_execution[1] if owner_execution is not None else
+ f"cron_{job_id}_{_hermes_now().strftime('%Y%m%d_%H%M%S')}")
logger.info("Running job '%s' (ID: %s)", job_name, job_id)
logger.info("Prompt: %s", prompt[:100])
@@ -2919,6 +2938,12 @@ def _run_one_job_body(
return _finish_completed_run(d, fire_owner, execution_id)
except BaseException as e: # noqa: BLE001 — deliberate: see below
+ from cron.scheduler_authority import CronExecutionUnknown
+ if isinstance(e, CronExecutionUnknown):
+ from cron.jobs import pause_job
+ pause_job(job["id"], reason=str(e))
+ logger.error("Cron %s paused with unverified admission: %s", job["id"], e)
+ return False
# BaseException, not Exception: CancelledError/KeyboardInterrupt/SystemExit propagate here.
# Without mark_job_run(False) a finite one-shot is wedged: claim_dispatch consumed
# repeat.completed but last_run_at is never written. Record first, then re-raise
diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.py
new file mode 100644
index 00000000000..fefee978443
--- /dev/null
+++ b/cron/scheduler_authority.py
@@ -0,0 +1,73 @@
+"""Transport-only cron execution; output/delivery remain with the firing scheduler."""
+import asyncio
+import hashlib
+import json
+import uuid
+
+
+class CronExecutionUnknown(RuntimeError):
+ """The owner may have accepted this fire; never book it as failed or re-fire."""
+
+
+def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_id=None):
+ from gateway.session_cron import owner_for_home, operation
+ from hermes_cli.gateway_client import connect_gateway
+ from hermes_constants import get_hermes_home
+ from utils import atomic_json_write
+
+ params = {'job_id': job['id'], 'request_id': execution_id or job.get('execution_id') or uuid.uuid4().hex,
+ 'extra_prompt': extra_prompt}
+ root = get_hermes_home() / 'cron' / 'admissions'
+ key = hashlib.sha256(json.dumps([params['job_id'], params['request_id']]).encode()).hexdigest()
+ journal = root / (key + '.json')
+ record = {'params': params, 'receipt': None}
+ if journal.exists():
+ record = json.loads(journal.read_text(encoding='utf-8'))
+ if record['params'] != params:
+ raise CronExecutionUnknown('cron admission identity conflict')
+ attempted = journal.exists()
+ owner = owner_for_home(get_hermes_home())
+
+ def save():
+ root.mkdir(parents=True, exist_ok=True)
+ atomic_json_write(journal, record, mode=0o600)
+
+ async def observe(call):
+ nonlocal attempted
+ attempted = True
+ save()
+ receipt = await call('submit', params)
+ record['receipt'] = receipt
+ save()
+ while True:
+ if cancel_event is not None and cancel_event.is_set():
+ await call('cancel', receipt)
+ state = await call('status', receipt)
+ if state['status'] == 'terminal':
+ journal.unlink(missing_ok=True)
+ return tuple(state['result'])
+ if state['status'] == 'unknown':
+ raise CronExecutionUnknown('unknown_execution: cron admission was not replayed')
+ await asyncio.sleep(.1)
+
+ async def remote():
+ async with connect_gateway() as client:
+ return await observe(lambda op, data: client.rpc('cron.' + op, **data))
+
+ try:
+ if owner is not None:
+ authority, loop = owner
+ try:
+ current = asyncio.get_running_loop()
+ except RuntimeError:
+ current = None
+ if current is loop:
+ raise RuntimeError('cron synchronous execution must run off the owner event loop')
+ return asyncio.run_coroutine_threadsafe(
+ observe(lambda op, data: operation(authority, op, data)), loop).result()
+ return asyncio.run(remote())
+ except Exception as exc:
+ if attempted:
+ raise CronExecutionUnknown(f'Cron execution unverified; reconcile {journal}: {exc}') from exc
+ error = f'{type(exc).__name__}: {exc}'
+ return False, f'# Cron Job: {job["id"]} (FAILED)\n\n{error}\n', '', error
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
new file mode 100644
index 00000000000..ce67f4a1686
--- /dev/null
+++ b/gateway/session_cron.py
@@ -0,0 +1,164 @@
+"""Trusted cron producer and owner execution of the existing scheduler contract.
+
+Public callers name a persisted job, never supply agent policy or arbitrary jobs.
+The ordinary admission ledger owns execution; the scheduler owns final delivery.
+"""
+import asyncio
+from contextvars import ContextVar
+from dataclasses import asdict, replace
+import json
+import os
+from pathlib import Path
+import threading
+
+from gateway.session_contract import Principal, SessionRef
+from hermes_state_runtime import RuntimeStoreError, admit_session_input, get_session_admission
+
+_execution: ContextVar[tuple | None] = ContextVar('cron_owner_execution', default=None)
+_owners = {}
+
+
+def bind_owner(authority):
+ home = Path(authority.db.db_path).resolve().parent
+ _owners[home] = (os.getpid(), authority, asyncio.get_running_loop())
+
+
+def unbind_owner(authority):
+ home = Path(authority.db.db_path).resolve().parent
+ bound = _owners.get(home)
+ if bound is not None and bound[1] is authority:
+ del _owners[home]
+
+
+def owner_for_home(home):
+ bound = _owners.get(Path(home).resolve())
+ if bound is not None and bound[0] == os.getpid() and not bound[2].is_closed():
+ return bound[1:]
+ return None
+
+
+def current_execution():
+ return _execution.get()
+
+
+def _actor(authority, actor):
+ if actor is None:
+ return Principal('cron-owner', authority.profile_id,
+ frozenset({'session:create', 'session:submit', 'session:read', 'session:control'}), 'cron-ticker')
+ if actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if not {'session:create', 'session:submit', 'session:control'} <= actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ # Cron fires belong to the profile scheduler, not the transport that observes
+ # them. The same execution ID from ticker and CLI must dedupe together.
+ return Principal('cron-owner', authority.profile_id, actor.capabilities, actor.transport_id)
+
+
+def _create(authority, actor, params):
+ from cron.jobs import get_job
+ from gateway.session_local_recovery import local_identity, restore_local_session
+ from gateway.session_policy import build_policy, bind_launch_key
+ from gateway.run import _load_gateway_config
+ from cron.scheduler import _load_cron_job_config
+ from hermes_state_local import commit_local_session
+ from gateway.config import Platform
+ from gateway.session import SessionSource, SessionEntry
+ from datetime import datetime, timezone
+
+ if set(params) != {'job_id', 'request_id', 'extra_prompt'}:
+ raise RuntimeStoreError('invalid_params')
+ jid, request_id, extra = params['job_id'], params['request_id'], params['extra_prompt']
+ if (not isinstance(jid, str) or not jid or not isinstance(request_id, str)
+ or not request_id or len(request_id) > 256 or (extra is not None and not isinstance(extra, str))):
+ raise RuntimeStoreError('invalid_params')
+ request_id = 'cron:' + jid + ':' + request_id
+ sid = local_identity(authority.profile_id, actor.subject, request_id)
+ if authority.db.get_session(sid) is not None:
+ return restore_local_session(authority, sid), request_id
+ job = get_job(jid)
+ if job is None or job.get('no_agent'):
+ raise RuntimeStoreError('not_found')
+ config = _load_gateway_config()
+ private = {}
+ launch = {'source': 'cli', 'request_id': request_id, 'toolsets': []}
+ if job.get('workdir'):
+ launch['cwd'] = job['workdir']
+ policy = build_policy(launch, config, private_secrets=private)
+ policy = replace(policy, source='cron', platform='cron', model=_load_cron_job_config(job, jid, job.get('name') or jid).model,
+ request_json=json.dumps({'cron_job': job, 'extra_prompt': extra, 'request_id': request_id}))
+ policy = bind_launch_key(authority, sid, policy, None, config_secrets=private)
+ source = SessionSource(platform=Platform.LOCAL, chat_id=sid, user_id=actor.subject, chat_type='dm')
+ route = authority.runner.session_store._generate_session_key(source)
+ now = datetime.now(timezone.utc)
+ entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
+ commit_local_session(authority.db, epoch=authority.epoch, receipt={
+ 'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
+ 'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)})
+ return restore_local_session(authority, sid), request_id
+
+
+async def operation(authority, name, params, actor=None):
+ actor = _actor(authority, actor)
+ authority._require_admission_open()
+ if name == 'submit':
+ ref, request_id = _create(authority, actor, params)
+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id=actor.subject,
+ session_id=ref.session_id, request_id=request_id,
+ payload={'text': params['extra_prompt'] or ''})
+ authority._publish_pending(ref)
+ authority._schedule(ref)
+ return {'session_id': ref.session_id, 'admission_id': row['admission_id']}
+ if set(params) != {'session_id', 'admission_id'} or name not in {'status', 'cancel'}:
+ raise RuntimeStoreError('invalid_params')
+ ref = SessionRef(authority.profile_id, params['session_id'])
+ authority.authorize(actor, ref, 'session:submit')
+ row = get_session_admission(authority.db, admission_id=params['admission_id'])
+ if row is None or row['target_session_id'] != ref.session_id or row['principal_id'] != actor.subject:
+ raise RuntimeStoreError('permission_denied')
+ if name == 'cancel':
+ event = getattr(authority, '_cron_cancellations', {}).get(row['admission_id'])
+ if event is not None:
+ event.set()
+ elif row['status'] == 'queued':
+ await authority.cancel_queued(actor, ref, row['admission_id'])
+ return {'ok': True}
+ result = None
+ if row['status'] == 'terminal':
+ from gateway.session_results import admission_result
+ saved = admission_result(authority.db, row['admission_id'])
+ result = saved['result'].get('cron_result') if saved else None
+ if result is None:
+ result = [False, '', '', row.get('outcome') or 'unknown_execution']
+ return {'status': row['status'], 'result': result}
+
+
+async def rpc(connection, name, params):
+ return await operation(connection.authority, name, params, connection.actor)
+
+
+async def execute(authority, ref, row, policy):
+ from cron.scheduler import run_job
+ from gateway.run import _profile_runtime_scope
+ data = json.loads(policy.request_json)
+ if (row['payload'] != {'text': data['extra_prompt'] or ''}
+ or row['request_id'] != data['request_id']
+ or row['principal_id'] != authority.sessions[ref.session_id].source.user_id):
+ raise RuntimeStoreError('admission_conflict')
+ cancellations = getattr(authority, '_cron_cancellations', None)
+ if cancellations is None:
+ cancellations = authority._cron_cancellations = {}
+ cancel = cancellations[row['admission_id']] = threading.Event()
+ token = _execution.set((authority, ref.session_id, data['cron_job']['id'], row['admission_id']))
+ try:
+ with _profile_runtime_scope(Path(authority.db.db_path).resolve().parent):
+ result = await asyncio.to_thread(run_job, data['cron_job'], extra_prompt=data['extra_prompt'],
+ execution_id=row['admission_id'], cancel_event=cancel)
+ authority.pending_results[row['admission_id']] = {
+ 'result': {'final_response': result[2], 'cron_result': list(result),
+ 'failed': not result[0], 'completed': result[0]}, 'usage': {}}
+ if not result[0]:
+ raise RuntimeError(result[3] or 'cron execution failed')
+ return result[2]
+ finally:
+ _execution.reset(token)
+ cancellations.pop(row['admission_id'], None)
diff --git a/tests/cron/test_canonical_cron.py b/tests/cron/test_canonical_cron.py
new file mode 100644
index 00000000000..e3a79e31d62
--- /dev/null
+++ b/tests/cron/test_canonical_cron.py
@@ -0,0 +1,79 @@
+"""Agent cron must enter the owner before importing any agent-side storage."""
+import asyncio
+from contextlib import asynccontextmanager
+
+from cron import scheduler
+
+
+def test_agent_cron_is_transport_only_and_refuses_without_owner(monkeypatch):
+ from hermes_cli import gateway_client
+ calls = []
+
+ @asynccontextmanager
+ async def unavailable():
+ calls.append('connect')
+ raise gateway_client.GatewayClientError('owner_unavailable')
+ yield
+
+ monkeypatch.setattr(gateway_client, 'connect_gateway', unavailable)
+ monkeypatch.setattr(scheduler, '_prepare_job_prompt', lambda *a: (_ for _ in ()).throw(
+ AssertionError('agent prompt preparation belongs to the owner')))
+ result = scheduler.run_job({'id': 'job', 'prompt': 'test'}, execution_id='fire')
+ assert calls == ['connect']
+ assert result[0] is False and 'owner_unavailable' in result[3]
+
+
+def test_owner_ticker_uses_direct_admission_without_loopback(monkeypatch):
+ from gateway import session_cron
+ from types import SimpleNamespace
+ from hermes_constants import get_hermes_home
+ import threading
+
+ async def probe():
+ authority = SimpleNamespace(db=SimpleNamespace(db_path=str(get_hermes_home() / 'state.db')))
+ session_cron.bind_owner(authority)
+ calls = []
+
+ async def request(owner, operation, params, actor=None):
+ assert owner is authority
+ calls.append((operation, threading.get_ident()))
+ if operation == 'submit':
+ return {'session_id': 'cron-fire', 'admission_id': 'admit'}
+ return {'status': 'terminal', 'result': [True, 'document', 'answer', None]}
+
+ monkeypatch.setattr(session_cron, 'operation', request)
+ # A nested job must not inherit its parent's execution authorization.
+ token = session_cron._execution.set((authority, 'parent-session', 'parent-job', 'parent-fire'))
+ try:
+ result = await asyncio.to_thread(scheduler.run_job, {'id': 'job'}, execution_id='fire')
+ finally:
+ session_cron._execution.reset(token)
+ assert result == (True, 'document', 'answer', None)
+ assert [op for op, _ in calls] == ['submit', 'status']
+ assert all(tid == threading.get_ident() for _, tid in calls)
+ session_cron.unbind_owner(authority)
+
+ asyncio.run(probe())
+
+
+def test_lost_cron_ack_retains_identity_instead_of_reporting_failure(tmp_path, monkeypatch):
+ from cron.scheduler_authority import run_canonical_job, CronExecutionUnknown
+ from hermes_cli import gateway_client
+ from hermes_constants import get_hermes_home
+ import json
+ import pytest
+
+ class Peer:
+ async def rpc(self, method, **params):
+ raise gateway_client.GatewayClientError('Gateway disconnected')
+
+ @asynccontextmanager
+ async def connected():
+ yield Peer()
+
+ monkeypatch.setattr(gateway_client, 'connect_gateway', connected)
+ with pytest.raises(CronExecutionUnknown):
+ run_canonical_job({'id': 'job'}, execution_id='fire')
+ records = list((get_hermes_home() / 'cron' / 'admissions').glob('*.json'))
+ assert len(records) == 1
+ assert json.loads(records[0].read_text())['params']['request_id'] == 'fire'
diff --git a/tests/cron/test_cron_request_overrides.py b/tests/cron/test_cron_request_overrides.py
index 6cf8d34d5c1..d0679c40cda 100644
--- a/tests/cron/test_cron_request_overrides.py
+++ b/tests/cron/test_cron_request_overrides.py
@@ -1,60 +1,15 @@
-"""Standalone regression test for cron runtime request_overrides forwarding.
+"""Cron's owner-side constructor retains provider-specific wire options."""
+from unittest.mock import MagicMock
-Split out of tests/cron/test_scheduler.py as an independent, upgrade-safe file
-(registered in the local-patch ledger's allowed_untracked list) so the local
-request_overrides forwarding hotfix no longer collides with upstream inserting
-new tests around its anchor in the large test_scheduler.py module.
+from cron.scheduler import _construct_cron_agent, _CronAgentSetup
-The functional change under test lives in cron/scheduler.py (run_job forwards
-runtime['request_overrides'] into the ephemeral AIAgent); that hunk stays in the
-source patch. Only this test moved here.
-"""
-from unittest.mock import patch, MagicMock
-
-from cron.scheduler import run_job
-
-
-class TestRunJobRequestOverrides:
- def test_run_job_forwards_runtime_request_overrides_to_agent(self, tmp_path):
- # runtime_provider may resolve provider-specific request_overrides;
- # cron must pass them into the ephemeral AIAgent or scheduled jobs
- # regress to SDK-default request settings.
- job = {
- "id": "request-overrides-job",
- "name": "request-overrides",
- "prompt": "hello",
- }
- fake_db = MagicMock()
- overrides = {
- "extra_headers": {
- "User-Agent": "codex_cli_rs/0.138.0 (Windows 10.0.26100; x86_64)"
- }
- }
-
- with patch("cron.scheduler._hermes_home", tmp_path), \
- patch("cron.scheduler_delivery._resolve_origin", return_value=None), \
- patch("dotenv.load_dotenv"), \
- patch("hermes_state_registry.acquire", return_value=fake_db), \
- patch(
- "hermes_cli.runtime_provider.resolve_runtime_provider",
- return_value={
- "api_key": "test-key",
- "base_url": "https://example.invalid/v1",
- "provider": "custom",
- "api_mode": "codex_responses",
- "request_overrides": overrides,
- },
- ), \
- patch("run_agent.AIAgent") as mock_agent_cls:
- mock_agent = MagicMock()
- mock_agent.run_conversation.return_value = {"final_response": "ok"}
- mock_agent_cls.return_value = mock_agent
-
- success, _output, final_response, error = run_job(job)
-
- assert success is True
- assert error is None
- assert final_response == "ok"
- kwargs = mock_agent_cls.call_args.kwargs
- assert kwargs["request_overrides"] == overrides
+def test_cron_constructor_forwards_runtime_request_overrides():
+ overrides = {'extra_headers': {'User-Agent': 'cron-provider-client'}}
+ factory = MagicMock()
+ setup = _CronAgentSetup(model='model', runtime={
+ 'api_key': 'test-key', 'base_url': 'https://example.invalid/v1',
+ 'provider': 'custom', 'api_mode': 'codex_responses', 'request_overrides': overrides})
+ _construct_cron_agent(factory, {'id': 'job'}, {}, setup,
+ workdir=None, session_id='session', session_db=MagicMock())
+ assert factory.call_args.kwargs['request_overrides'] == overrides
diff --git a/tests/gateway/test_session_cron.py b/tests/gateway/test_session_cron.py
new file mode 100644
index 00000000000..53b4321a42b
--- /dev/null
+++ b/tests/gateway/test_session_cron.py
@@ -0,0 +1,44 @@
+"""Cron admissions retain exact job identity and stored-job model policy."""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+
+def test_cron_admission_uses_job_model_and_exact_retry(tmp_path, monkeypatch):
+ from cron import jobs
+ from gateway import run, session_cron
+ from gateway.session import SessionStore
+ from gateway.session_authority import SessionAuthority
+ from gateway.session_contract import Principal
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch, RuntimeStoreError
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(jobs, 'get_job', lambda jid: {'id': jid, 'prompt': 'original', 'model': 'per-job-model'})
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})
+ db = SessionDB(tmp_path / 'state.db')
+ from gateway.config import GatewayConfig
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(_draining=False, session_store=store, adapters={})
+ authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='test', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='test'))
+ runner.session_authority = authority
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ actor = Principal('owner', str(tmp_path), frozenset({'session:create', 'session:submit', 'session:control'}), 'viewer')
+
+ async def probe():
+ params = {'job_id': 'job', 'request_id': 'fire', 'extra_prompt': 'extra'}
+ receipt = await session_cron.operation(authority, 'submit', params, actor)
+ assert await session_cron.operation(authority, 'submit', params, actor) == receipt
+ assert await session_cron.operation(authority, 'submit', params) == receipt
+ with pytest.raises(RuntimeStoreError):
+ await session_cron.operation(authority, 'submit', dict(params, extra_prompt='changed'), actor)
+ policy = runner.adapters[next(iter(runner.adapters))].policies[receipt['session_id']]
+ assert policy.model == 'per-job-model'
+ assert policy.source == 'cron'
+
+ try:
+ asyncio.run(probe())
+ finally:
+ db.close()