The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: reconcile canonical cron receipts into durable delivery
Tekniumc1172b1a8278
diff --git a/cron/jobs.py b/cron/jobs.pyindex 03572a99893..d97ccc0add2 100644--- a/cron/jobs.py+++ b/cron/jobs.py@@ -2311,6 +2311,7 @@ def mark_job_run(status: Optional[str] = None,*,expected_fire_owner: Optional[str] = None,+ execution_id: Optional[str] = None,) -> bool:"""Mark a job as run: update last_run_at/last_status, bump completed, recompute next_run_at,and retire the record as a terminal completion when the repeat limit is reached.@@ -2321,6 +2322,8 @@ def mark_job_run(can't be taken, the job is missing, or ``expected_fire_owner`` no longer holds the fire claim."""def apply(jobs, _i, job):+ if execution_id is not None and execution_id in job.get("canonical_completions", []):+ return Trueif expected_fire_owner is not None:claim = job.get("fire_claim")if not isinstance(claim, dict) or claim.get("by") != expected_fire_owner:@@ -2330,6 +2333,8 @@ def mark_job_run(return Falsenow = _hermes_now().isoformat()_record_run_outcome(job, success, error, delivery_error, status, now)+ if execution_id is not None:+ job.setdefault("canonical_completions", []).append(execution_id)_advance_after_run(job, now)save_jobs(jobs)return Truediff --git a/cron/scheduler.py b/cron/scheduler.pyindex e32a43abf08..d3731b4ba4a 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -2683,6 +2683,12 @@ def _save_compose_deliver(if not d.should_deliver:return+ execution_id = job.get('execution_id')+ if execution_id and not job.get('no_agent'):+ from cron.delivery_queue import enqueue+ queued = enqueue(execution_id, job, deliver_content, for_failure=not d.success)+ job['last_delivery_queued'] = {'canonical': {'status': queued['status'], 'execution_id': execution_id}}+ returnd.unresolved_origin = (_normalize_deliver_value(_delivery_lane_value(job, for_failure=not d.success)) == "origin"and not _resolve_delivery_targets(job, for_failure=not d.success)@@ -2736,6 +2742,10 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_update_job(job["id"], {"last_delivery_queued": None})job["last_delivery_queued"] = Nonemark_kwargs = {"delivery_error": d.delivery_error}+ from cron.scheduler_authority import journal_path+ journal = journal_path(job['id'], execution_id)+ if not job.get('no_agent'):+ mark_kwargs['execution_id'] = execution_idif d.success and not d.delivery_error and d.should_deliver and job.get("last_delivery_queued"):mark_kwargs["status"] = "delivery_queued"if fire_owner is not None:@@ -2763,6 +2773,7 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution__mark_incident_alerted(d.failure_incident_id)finish_execution(execution_id, success=d.success, error=d.error, delivery_outcome=delivery_outcome)+ journal.unlink(missing_ok=True)return True@@ -2818,6 +2829,7 @@ def _run_one_job_body(if not execution_id:execution_id = create_execution(job["id"], source="direct", scheduled_instant=job.get("_scheduled_instant"))["id"]+ job = dict(job, execution_id=execution_id)delivery_attempted = Falsedelivery_error = Nonefrom agent.secret_scope import (@@ -3723,6 +3735,8 @@ def tick(logger.debug("Cron dispatch paused while gateway drains existing work")return 0+ from cron.scheduler_authority import reconcile_pending+ reconcile_pending()_maybe_reap_dead_owners()# Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.try:diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.pyindex fefee978443..e0bc2180f08 100644--- a/cron/scheduler_authority.py+++ b/cron/scheduler_authority.py@@ -9,6 +9,12 @@ class CronExecutionUnknown(RuntimeError):"""The owner may have accepted this fire; never book it as failed or re-fire."""+def journal_path(job_id, request_id):+ from hermes_constants import get_hermes_home+ key = hashlib.sha256(json.dumps([job_id, request_id]).encode()).hexdigest()+ return get_hermes_home() / 'cron' / 'admissions' / (key + '.json')++def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_id=None):from gateway.session_cron import owner_for_home, operationfrom hermes_cli.gateway_client import connect_gateway@@ -18,8 +24,7 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_idparams = {'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')+ journal = journal_path(params['job_id'], params['request_id'])record = {'params': params, 'receipt': None}if journal.exists():record = json.loads(journal.read_text(encoding='utf-8'))@@ -44,7 +49,6 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_idawait 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')@@ -71,3 +75,49 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_idraise CronExecutionUnknown(f'Cron execution unverified; reconcile {journal}: {exc}') from excerror = f'{type(exc).__name__}: {exc}'return False, f'# Cron Job: {job["id"]} (FAILED)\n\n{error}\n', '', error++def reconcile_pending():+ """Observe prepared fires; never submit missing or interrupted work."""+ from gateway.session_cron import owner_for_home, operation+ from hermes_constants import get_hermes_home+ from hermes_cli.gateway_client import connect_gateway+ from cron.jobs import pause_job, mark_job_run, save_job_output+ from cron.scheduler import _compose_run_delivery, _is_cron_silence_response+ from cron.delivery_queue import enqueue+ import logging++ root = get_hermes_home() / 'cron' / 'admissions'+ for journal in sorted(root.glob('*.json')):+ try:+ record = json.loads(journal.read_text(encoding='utf-8'))+ params = record['params']+ if journal != journal_path(params['job_id'], params['request_id']):+ raise ValueError('cron journal identity conflict')+ owner = owner_for_home(get_hermes_home())+ async def observe():+ if owner is not None:+ return await operation(owner[0], 'recover', params)+ async with connect_gateway() as client:+ return await client.rpc('cron.recover', **params)+ if owner is not None:+ state = asyncio.run_coroutine_threadsafe(observe(), owner[1]).result(timeout=20)+ else:+ state = asyncio.run(observe())+ if state['status'] != 'terminal':+ if state['status'] in {'unknown', 'missing'}:+ pause_job(params['job_id'], reason='Canonical cron ' + state['status'] + '; no automatic re-execution')+ continue+ success, output, answer, error = state['result']+ job = state['job']+ job['execution_id'] = params['request_id']+ output_file = save_job_output(job['id'], output)+ content, _, silent, _, _ = _compose_run_delivery(+ job, success=success, error=error, final_response=answer, output_file=output_file)+ deliver = bool(content.strip()) and not silent and not (success and _is_cron_silence_response(content))+ if deliver:+ enqueue(params['request_id'], job, content, for_failure=not success)+ mark_job_run(job['id'], success, error, status='delivery_queued' if deliver else None,+ execution_id=params['request_id'])+ journal.unlink(missing_ok=True)+ except Exception:+ logging.getLogger(__name__).warning('Cron receipt recovery deferred: %s', journal, exc_info=True)diff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex ce67f4a1686..faab508fa74 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -100,6 +100,29 @@ def _create(authority, actor, params):async def operation(authority, name, params, actor=None):actor = _actor(authority, actor)authority._require_admission_open()+ if name == 'recover':+ from gateway.session_local_recovery import local_identity+ if (set(params) != {'job_id', 'request_id', 'extra_prompt'}+ or any(not isinstance(params[k], str) or not params[k] for k in ('job_id', 'request_id'))+ or (params['extra_prompt'] is not None and not isinstance(params['extra_prompt'], str))):+ raise RuntimeStoreError('invalid_params')+ request_id = 'cron:' + params['job_id'] + ':' + params['request_id']+ sid = local_identity(authority.profile_id, actor.subject, request_id)+ from hermes_state_runtime import list_session_admissions+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ row = next((r for r in rows if r['request_id'] == request_id and r['principal_id'] == actor.subject), None)+ if row is None:+ return {'status': 'missing', 'result': None}+ state = await operation(authority, 'status', {'session_id': sid, 'admission_id': row['admission_id']}, actor)+ from gateway.session_local_recovery import restore_local_session+ restore_local_session(authority, sid)+ from gateway.config import Platform+ policy = authority.runner.adapters[Platform.LOCAL].policies[sid]+ frozen = json.loads(policy.request_json)+ if frozen['extra_prompt'] != params['extra_prompt']:+ raise RuntimeStoreError('admission_conflict')+ state['job'] = frozen['cron_job']+ return stateif name == 'submit':ref, request_id = _create(authority, actor, params)row = admit_session_input(authority.db, epoch=authority.epoch, principal_id=actor.subject,diff --git a/hermes_cli/cron.py b/hermes_cli/cron.pyindex a016272e007..f4c257f9488 100644--- a/hermes_cli/cron.py+++ b/hermes_cli/cron.py@@ -664,6 +664,9 @@ def _job_action(action: str, job_id: str, success_verb: str) -> int:print(f" Next run: {result['job']['next_run_at']}")if action == "run":print(f" {_run_outcome(result.get('job', {}))}")+ if (job.get('executed') and job.get('execution_success') is False+ and not job.get('delegation_id') and job.get('execution_mode') != 'background'):+ return 1return 0diff --git a/tests/cron/test_cron_recovery.py b/tests/cron/test_cron_recovery.pynew file mode 100644index 00000000000..bb440e35e29--- /dev/null+++ b/tests/cron/test_cron_recovery.py@@ -0,0 +1,70 @@+"""Terminal owner receipts recover delivery without replay or double bookkeeping."""+import asyncio+import json+from types import SimpleNamespace++from cron import jobs, scheduler+from gateway import run, session_cron+from gateway.session import SessionStore+from gateway.session_authority import SessionAuthority+from gateway.config import GatewayConfig+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch, claim_session_input, settle_session_input+++def test_lost_ack_reconciles_frozen_delivery_once(tmp_path, monkeypatch):+ from cron import scheduler_authority, delivery_queue+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})+ with jobs.use_cron_store(tmp_path / 'cron'):+ job = jobs.create_job(prompt='original', schedule='every 1h', deliver='local')+ db = SessionDB(tmp_path / 'state.db')+ runner = SimpleNamespace(_draining=False, session_store=SessionStore(tmp_path / 'sessions', GatewayConfig()), adapters={})+ authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='test', db=db,+ epoch=begin_runtime_epoch(db, instance_id='test'))+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ runner.session_authority = authority+ async def probe():+ params = {'job_id': job['id'], 'request_id': 'fire', 'extra_prompt': None}+ receipt = await session_cron.operation(authority, 'submit', params)+ row = claim_session_input(db, epoch=authority.epoch, session_id=receipt['session_id'])+ settle_session_input(db, epoch=authority.epoch, admission_id=row['admission_id'], generation=row['generation'], outcome='completed',+ result={'result': {'cron_result': [True, 'document', 'answer', None]}, 'usage': {}})+ root = tmp_path / 'cron' / 'admissions'; root.mkdir()+ journal = scheduler_authority.journal_path(job['id'], 'fire')+ journal.write_text(json.dumps({'params': params, 'receipt': None}))+ session_cron.bind_owner(authority)+ try:+ await asyncio.to_thread(scheduler_authority.reconcile_pending)+ assert delivery_queue.get_status('fire')['status'] == 'pending'+ assert jobs.get_job(job['id'])['last_status'] == 'delivery_queued'+ completed = jobs.get_job(job['id'])['repeat']['completed']+ journal.write_text(json.dumps({'params': params, 'receipt': None}))+ await asyncio.to_thread(scheduler_authority.reconcile_pending)+ assert jobs.get_job(job['id'])['repeat']['completed'] == completed+ assert delivery_queue.claim_next()['content'] == 'answer'+ assert delivery_queue.claim_next() is None+ unknown = dict(params, request_id='unknown')+ accepted = await session_cron.operation(authority, 'submit', unknown)+ claim_session_input(db, epoch=authority.epoch, session_id=accepted['session_id'])+ from hermes_state_runtime import recover_session_inputs+ authority.epoch = begin_runtime_epoch(db, instance_id='restart')+ recover_session_inputs(db, epoch=authority.epoch)+ unknown_journal = scheduler_authority.journal_path(job['id'], 'unknown')+ unknown_journal.write_text(json.dumps({'params': unknown, 'receipt': None}))+ await asyncio.to_thread(scheduler_authority.reconcile_pending)+ assert unknown_journal.exists()+ assert jobs.get_job(job['id'])['state'] == 'paused'+ assert delivery_queue.claim_next() is None+ finally:+ session_cron.unbind_owner(authority)+ try:+ asyncio.run(probe())+ finally:+ db.close()+++def test_failed_manual_run_exits_nonzero(monkeypatch):+ from hermes_cli import cron+ monkeypatch.setattr(cron, '_cron_api', lambda **kw: {'success': True, 'job': {'executed': True, 'execution_success': False}})+ assert cron._job_action('run', 'job', 'Triggered') == 1diff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.pyindex 1712e0ddab6..dc82450e0e2 100644--- a/tests/hermes_cli/test_cron.py+++ b/tests/hermes_cli/test_cron.py@@ -528,7 +528,7 @@ class TestCronRunBackgroundDispatch:rc, out = self._run_cmd(capsys)- assert rc == 0+ assert rc == 1assert "Ran now: failed." in outdef test_delegation_id_alone_counts_as_background(self, monkeypatch, capsys):diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.mdindex 288d41f4276..8b6942cb6f6 100644--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@ -41,6 +41,19 @@ Whichever provider a job resolves to, its provider-specific request settings (e.Cron-run sessions cannot recursively create more cron jobs. Hermes disables cron management tools inside cron executions to prevent runaway scheduling loops.:::+## Admission recovery++Agent-backed runs retain their fire identity until output and a durable delivery handoff are recorded.+The scheduler reconciles unfinished receipts on each tick, including after an owner restart. A known+terminal result is handed to the delivery queue without running the agent again; duplicate handoffs+and bookkeeping use the original fire identity. Delivery interrupted after a send claim stays+unknown and is not retried automatically.++An interrupted execution or a prepared fire that cannot be found stays paused for operator review.+Recovery never creates another admission for it. Paused jobs are not automatically resumed, even+when their completed result is recovered. `hermes cron run` exits nonzero for a known synchronous+execution failure; background dispatch is not a terminal success/failure verdict.+## Creating scheduled tasks### In chat with `/cron`