The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): isolate bot receipts and keep headless cron no-spawn
Brian Fernstromcdf36315e95e
diff --git a/cron/scheduler_authority.py b/cron/scheduler_authority.pyindex c9605550a62..7ee02b72847 100644--- a/cron/scheduler_authority.py+++ b/cron/scheduler_authority.py@@ -77,8 +77,12 @@ def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_iderror = 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."""+def reconcile_pending(*, allow_connect=True):+ """Observe prepared fires; never submit missing or interrupted work.++ With allow_connect=False, a headless tick leaves durable receipts for the next+ live owner instead of ensuring or spawning a gateway.+ """from gateway.session_cron import owner_for_home, operationfrom hermes_constants import get_hermes_homefrom hermes_cli.gateway_client import connect_gateway@@ -95,6 +99,8 @@ def reconcile_pending():if journal != journal_path(params['job_id'], params['request_id']):raise ValueError('cron journal identity conflict')owner = owner_for_home(get_hermes_home())+ if owner is None and not allow_connect:+ continueasync def observe():if owner is not None:return await operation(owner[0], 'recover', params)diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.pyindex a3e4a8cb27e..073d9d5bcb4 100644--- a/cron/scheduler_tick.py+++ b/cron/scheduler_tick.py@@ -53,7 +53,10 @@ def _tick_admitted(return 0from cron.scheduler_authority import reconcile_pending- reconcile_pending()+ if headless:+ reconcile_pending(allow_connect=False)+ else:+ reconcile_pending()_sched._maybe_reap_dead_owners()# Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.try:diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 436d3a48426..ceba3850ccb 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -4,6 +4,7 @@ The mailbox is a delivery receipt, not an execution queue. A committed canonicaladmission is the only consumer; unknown execution is never retried as inference."""import asyncio+import loggingfrom pathlib import Pathfrom agent.turn_author import parse_turn_author@@ -15,6 +16,19 @@ from hermes_state_runtime import RuntimeStoreError, get_session_admissionfrom tools.bot_live_delivery import _delivery_id, _locked, _read, _write+def _scan_records(root):+ """Bulk mailbox scan: isolate unreadable records without weakening exact-id reads."""+ for path in root.glob('*.json'):+ try:+ record = _read(path)+ except (OSError, ValueError):+ logging.getLogger(__name__).warning(+ "Skipping unreadable Bot mailbox receipt %s", path, exc_info=True)+ continue+ if record is not None:+ yield path, record++def _home(authority, actor, profile):from gateway.session_authorities import served_profile_namehome = Path(authority.db.db_path).parent.resolve()@@ -124,7 +138,7 @@ def relay_operation(connection, operation, params):async def _migrate(authority, actor, home, root):- records = [(path, _read(path)) for path in root.glob('*.json')]+ records = list(_scan_records(root))legacy = [(path, record) for path, record in recordsif record and 'owner' in record and not record.get('admission_id')and record['status'] in {'queued', 'claimed'}]@@ -153,7 +167,7 @@ async def recover_bot_deliveries(authority):"""Rebuild derivative replies and queued legacy admissions at owner startup."""home = Path(authority.db.db_path).parent.resolve()with _locked(home) as root:- records = [(path, _read(path)) for path in root.glob('*.json')]+ records = list(_scan_records(root))for path, record in records:if not record or record.get('profile_home') != str(home) or not record.get('admission_id'):continuediff --git a/tests/cron/test_tick_without_gateway.py b/tests/cron/test_tick_without_gateway.pyindex ff6809ddf3d..df4abe5ba7a 100644--- a/tests/cron/test_tick_without_gateway.py+++ b/tests/cron/test_tick_without_gateway.py@@ -133,12 +133,37 @@ def test_tick_holds_agent_jobs_while_gateway_is_starting_or_silent(cron_home, moassert len([r for r in caplog.records if "skipped" in r.getMessage()]) == 1+def test_headless_receipt_recovery_never_connects_or_spawns(cron_home, monkeypatch):+ import json+ from hermes_cli import gateway_client++ job = J.create_job(prompt="summarise inbox", schedule="every 1h", name="agent", deliver="local")+ request_id = "prepared-fire"+ journal = scheduler_authority.journal_path(job["id"], request_id)+ journal.parent.mkdir(parents=True, exist_ok=True)+ journal.write_text(json.dumps({+ "params": {"job_id": job["id"], "request_id": request_id, "extra_prompt": None},+ "receipt": None,+ }), encoding="utf-8")++ monkeypatch.setattr("gateway.session_cron.owner_for_home", lambda home: None)+ monkeypatch.setattr(+ gateway_client, "connect_gateway",+ lambda *a, **k: pytest.fail("headless recovery must not connect/ensure a gateway"))++ scheduler_authority.reconcile_pending(allow_connect=False)++ assert journal.exists(), "deferred evidence stays durable for the next live owner"++def test_no_agent_jobs_still_fire_without_a_gateway(cron_home, monkeypatch):counter = cron_home / "fires.txt"script = cron_home / "scripts" / "fire.sh"script.write_text(f"#!/bin/sh\necho fired >> {counter}\necho fired\n", encoding="utf-8")script.chmod(0o755)- monkeypatch.setattr(scheduler_authority, "reconcile_pending", lambda: None)+ monkeypatch.setattr(+ scheduler_authority, "reconcile_pending",+ lambda *, allow_connect=True: None)job = J.create_job(prompt=None, schedule="every 1h", name="script", script="fire.sh",no_agent=True, deliver="local")_make_due(job["id"])diff --git a/tests/gateway/test_bot_result_recovery.py b/tests/gateway/test_bot_result_recovery.pyindex b4c9576a228..df16d5a229c 100644--- a/tests/gateway/test_bot_result_recovery.py+++ b/tests/gateway/test_bot_result_recovery.py@@ -75,10 +75,13 @@ def test_cancelled_queued_admission_is_a_terminal_cancelled_receipt_not_ambiguouepoch = begin_runtime_epoch(db, instance_id='restart')recover_session_inputs(db, epoch=epoch)authority = SimpleNamespace(db=db, waiters={})+ with _locked(tmp_path) as root:+ (root / 'unreadable.json').write_text('{not-json', encoding='utf-8')asyncio.run(recover_bot_deliveries(authority))with _locked(tmp_path) as root:recovered = {key: _read(root / f'{key}.json')['status'] for key in records}assert recovered == {'a' * 32: 'failed', 'b' * 32: 'cancelled'}+ assert (tmp_path / 'runtime' / 'bot_live_delivery' / 'unreadable.json').exists()# The exact retry reads the same classification from the durable admission row.assert _result(authority, records['b' * 32])['status'] == 'cancelled'assert _result(authority, records['a' * 32])['status'] == 'failed'