The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: queue due gateway heartbeat ticks through canonical admission
Tekniumab44af2c0732
diff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex ba7cc3eed44..393347f20b2 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -135,6 +135,10 @@ class GatewayGoalsMixin:adapter = self._adapter_for_source(source)if adapter is None or not adapter._message_handler:return+ if getattr(self, 'session_authority', None) is not None:+ from gateway.run_heartbeat_acceptance import admit_heartbeat+ await admit_heartbeat(self, adapter, source, session_id, quick_key)+ returnif (self._is_session_running(quick_key)or quick_key in adapter._active_sessionsdiff --git a/gateway/run_heartbeat_acceptance.py b/gateway/run_heartbeat_acceptance.pyindex 170ac42622b..99e06a161a7 100644--- a/gateway/run_heartbeat_acceptance.py+++ b/gateway/run_heartbeat_acceptance.py@@ -42,3 +42,33 @@ def settle_heartbeat_attempt(event, manager):manager.abandon_fire()except Exception:logger.warning("Failed to refund unexecuted heartbeat", exc_info=True)+++async def admit_heartbeat(runner, adapter, source, session_id, route):+ """Coalesce overdue ticks behind the canonical FIFO, not an adapter-local slot."""+ import json+ from gateway.platforms.event import MessageEvent+ from hermes_cli.heartbeat import HeartbeatManager+ from hermes_state_runtime import list_session_admissions++ authority = runner.session_authority+ pending = list_session_admissions(authority.db, session_id=session_id)+ if any(row['payload'].get('native_text_v1', {}).get('automation', {}).get('heartbeat')+ for row in pending):+ return+ manager = HeartbeatManager(session_id)+ prompt = manager.due_prompt()+ if prompt is None:+ return+ state = manager.state+ identity = json.dumps(['heartbeat', session_id, state.created_at, state.fire_count], separators=(',', ':'))+ event = MessageEvent(text=prompt, source=source, internal=True, message_id=identity,+ metadata={'gateway_session_key': route, 'gateway_session_id': session_id})+ event._heartbeat_session_id = session_id+ try:+ await authority.admit_automation(adapter, event, identity)+ except BaseException:+ # Readiness is not a delivery attempt, and cancellation before commit is not ACK.+ if getattr(event, '_gateway_accepted', False) is not True:+ manager.abandon_fire()+ raisediff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 82e99484f55..de53fc04d1f 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -84,6 +84,8 @@ def snapshot_automation(authority, adapter, event, identity):'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),'event': {'message_id': identity}, 'provenance': provenance,'automation': {'identity': identity, 'owner': entry.session_id}}+ if getattr(event, '_heartbeat_session_id', None):+ envelope['automation']['heartbeat'] = event._heartbeat_session_ididentities = event.metadata.get('automation_identities')if identities:envelope['automation']['identities'] = sorted(set(identities))diff --git a/gateway/session_envelope.py b/gateway/session_envelope.pyindex 778b2d7477d..1a4b9940033 100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@ -138,6 +138,8 @@ def restore_native(payload, runner=None):**deepcopy(envelope['event']))if 'automation' in envelope:event.internal = True+ if envelope['automation'].get('heartbeat'):+ event._heartbeat_session_id = envelope['automation']['heartbeat']event.metadata = {'gateway_session_key': envelope['route'],'gateway_session_id': envelope['automation']['owner']}return eventdiff --git a/tests/gateway/fixtures/automation_peer.py b/tests/gateway/fixtures/automation_peer.pyindex 2a68684ed51..1fca1a56110 100644--- a/tests/gateway/fixtures/automation_peer.py+++ b/tests/gateway/fixtures/automation_peer.py@@ -28,7 +28,7 @@ class Model(BaseHTTPRequestHandler):last = next((m.get('content', '') for m in reversed(messages) if m['role'] == 'user'), '')if 'HOLD_AUTOMATION' in str(last):self.server.blocked.set()- self.server.release.wait(60)+ self.server.release.wait(120)message = {'role': 'assistant', 'content': 'AUTOMATION_ACK'}if 'SPAWN_AUTOMATION' in str(last) and messages[-1]['role'] != 'tool':code = ('import pathlib,time; p=pathlib.Path(' + repr(str(self.server.gate)) + '); '@@ -54,7 +54,7 @@ class Model(BaseHTTPRequestHandler):self.wfile.write(payload)-async def probe(root, base):+async def probe(root, base, mode):home, user = base / 'state', base / 'user'home.mkdir(); user.mkdir()model = ThreadingHTTPServer(('127.0.0.1', 0), Model)@@ -127,9 +127,13 @@ async def probe(root, base):await ws.send(json.dumps({'type': 'inbound', 'event': {'text': text,'message_id': identity, 'source': {'platform': 'telegram', 'chat_id': 'automation-chat','chat_type': 'dm', 'user_id': 'fixture-user'}}}) + '\n')- await send('spawn', 'SPAWN_AUTOMATION')+ await send('spawn', 'SPAWN_AUTOMATION' if mode == 'terminal' else 'WARM_AUTOMATION')await wait_for(lambda: any(r['request_id'] == 'spawn' and r['status'] == 'terminal' for r in rows()))- assert 'REAL_TERMINAL_COMPLETION' in json.dumps(model.requests), 'model did not request real terminal'+ if mode == 'terminal':+ assert 'REAL_TERMINAL_COMPLETION' in json.dumps(model.requests), 'model did not request real terminal'+ else:+ await send('timer-config', '/heartbeat every 1m TIMER_AUTOMATION')+ await wait_for(lambda: 'Heartbeat' in json.dumps(outgoing))sid = rows()[0]['target_session_id']async with websocket(home, desc) as observer:assert 'result' in await rpc(observer, 'session.resume', session_id=sid)@@ -138,7 +142,8 @@ async def probe(root, base):await send('human-follower', 'HUMAN_FIFO_FOLLOWER')await wait_for(lambda: any(r['request_id'] == 'human-follower' for r in rows()))model.gate.touch()- await asyncio.sleep(8) # production notify watcher polls every five seconds+ # Real cadence: process polls every five seconds; heartbeat interval is one minute.+ await asyncio.sleep(8 if mode == 'terminal' else 70)ledger = rows()automatic = [r for r in ledger if r['principal_id'].startswith('automation:')]assert automatic, {'failure': 'producer ACK bypassed canonical durable FIFO', 'ledger': ledger,@@ -151,7 +156,8 @@ async def probe(root, base):assert all(r['outcome'] == 'completed' for r in rows()), rows()texts = [next((m.get('content', '') for m in reversed(r['messages']) if m['role'] == 'user'), '')for r in model.requests if r.get('messages')]- assert 'REAL_TERMINAL_COMPLETION' in str(texts[-1]), texts+ marker = 'REAL_TERMINAL_COMPLETION' if mode == 'terminal' else 'TIMER_AUTOMATION'+ assert marker in str(texts[-1]), textsassert 'HUMAN_FIFO_FOLLOWER' in str(texts[-2]), textsprint(json.dumps({'daemon_pid': proc.pid, 'ledger': rows(), 'model_inputs': texts,'observer_closed_before_completion': True}))@@ -167,4 +173,4 @@ async def probe(root, base):if __name__ == '__main__':- asyncio.run(probe(Path(__file__).resolve().parents[3], Path(sys.argv[1])))+ asyncio.run(probe(Path(__file__).resolve().parents[3], Path(sys.argv[1]), sys.argv[2]))diff --git a/tests/gateway/test_authority_automation.py b/tests/gateway/test_authority_automation.pyindex 1291fb6b737..1d564c2abdc 100644--- a/tests/gateway/test_authority_automation.py+++ b/tests/gateway/test_authority_automation.py@@ -5,12 +5,20 @@ import subprocessimport sys-def test_terminal_completion_commits_while_ordinary_daemon_model_is_held(tmp_path):+def _probe(tmp_path, mode):root = Path(__file__).resolve().parents[2]env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}env['PYTHONPATH'] = str(root)result = subprocess.run([sys.executable, str(root / 'tests/gateway/fixtures/automation_peer.py'),- str(tmp_path)], env=env, cwd=root, stdin=subprocess.DEVNULL,- capture_output=True, text=True, timeout=150)+ str(tmp_path), mode], env=env, cwd=root, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=200)assert result.returncode == 0, result.stdout + result.stderrprint(result.stdout)+++def test_terminal_completion_commits_while_ordinary_daemon_model_is_held(tmp_path):+ _probe(tmp_path, 'terminal')+++def test_heartbeat_timer_commits_while_ordinary_daemon_model_is_held(tmp_path):+ _probe(tmp_path, 'heartbeat')