The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: capture passive evidence at hosted task transitions
Tekniumf2aa31f24767
diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pyindex 755d03e6a14..da14eff9e0f 100644--- a/gateway/hosted_room_driver.py+++ b/gateway/hosted_room_driver.py@@ -474,6 +474,8 @@ def _transition(if guard is not None:guard(row)fenced_update(conn, sql, params, StaleTaskError(stale))+ from gateway.hosted_room_work_records import capture_transition_locked+ capture_transition_locked(conn, identity.room_id)return _task_from_row(_load_task(conn, identity))@@ -608,6 +610,8 @@ def admit_task(db_path: DbPath, identity: TaskIdentity, *, payload: Any, clock:(*dataclasses.astuple(identity), normalized_payload["source_event_seq"], payload_json, payload_digest,now, now))+ from gateway.hosted_room_work_records import capture_transition_locked+ capture_transition_locked(conn, identity.room_id)return _task_from_row(_load_task(conn, identity))@@ -642,6 +646,8 @@ def start_task((execution_generation, *_run_fence(lease), now, now, identity.room_id, identity.task_id,expected_cancel_generation), StaleTaskError("task changed during start"))+ from gateway.hosted_room_work_records import capture_transition_locked+ capture_transition_locked(conn, identity.room_id)return TaskAttempt(identity=identity, lease=lease, execution_generation=execution_generation,cancel_generation=expected_cancel_generation)@@ -813,6 +819,8 @@ def recover_room(db_path: DbPath, lease: DriverLease, *, clock: Clock) -> dict[sconn.execute(f"""UPDATE hosted_room_driver_tasks SET status='indeterminate', indeterminate_at=?, updated_at=?WHERE {foreign_running}""", (now, now, *fence))+ from gateway.hosted_room_work_records import capture_transition_locked+ capture_transition_locked(conn, lease.room_id)return {status: [_task_identity_from_row(row) for row in _tasks_in_order(conn, lease.room_id, status)]for status in ("queued", "indeterminate")}diff --git a/gateway/hosted_room_work_records.py b/gateway/hosted_room_work_records.pyindex a2f99ddc90e..be9818d345d 100644--- a/gateway/hosted_room_work_records.py+++ b/gateway/hosted_room_work_records.py@@ -222,6 +222,31 @@ def _capture_tasks(conn, room_id):return tasks, receipts, None+def capture_transition_locked(conn, room_id):+ """Observe committed driver facts, without making evidence an execution gate.++ The caller's transaction owns both facts and evidence. A rejected evidence+ write rolls back only its savepoint; malformed retained bytes are classified+ in place, never replaced with a fabricated current snapshot.+ """+ import logging+ owner = conn.execute(+ "SELECT authority_gateway_id FROM hosted_rooms WHERE room_id=? AND disbanded_at IS NULL",+ (room_id,)).fetchone()+ if owner is None:+ return+ conn.execute("SAVEPOINT work_transition_capture")+ try:+ capture_locked(conn, room_id=room_id, local_gateway_id=owner[0])+ except InvalidStoredWorkRecord:+ logging.getLogger(__name__).warning("Hosted work evidence invalid for room %s", room_id)+ except (WorkRecordError, sqlite3.Error):+ conn.execute("ROLLBACK TO work_transition_capture")+ logging.getLogger(__name__).warning("Hosted work evidence unavailable for room %s", room_id, exc_info=True)+ finally:+ conn.execute("RELEASE work_transition_capture")++def capture(db_path, *, room_id: str, local_gateway_id: str, through_seq: int | None = None) -> dict:"""Commit a new revision only when one consistent source view changes."""with rooms._transaction(db_path, immediate=True) as conn:diff --git a/tests/gateway/test_room_work_service_capture.py b/tests/gateway/test_room_work_service_capture.pynew file mode 100644index 00000000000..06f2d9d02f8--- /dev/null+++ b/tests/gateway/test_room_work_service_capture.py@@ -0,0 +1,40 @@+"""Canonical hosted producer reaches passive capture without an explicit publisher."""+import asyncio+import json+from types import SimpleNamespace++import pytest++from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch+++async def test_canonical_send_and_stop_retain_driver_evidence(tmp_path, monkeypatch):+ from gateway.session_hosted_service import CanonicalHostedRoomService+ from gateway import hosted_room_work_records as work+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(db=db, profile_id=str(tmp_path), epoch=begin_runtime_epoch(db, instance_id='test'))+ service = CanonicalHostedRoomService(authority, asyncio.get_running_loop())+ service.authorize_room('alice', 'room', create=True)+ service.create_room(room_id='room', name='Room', members=[+ {'member_id': 'one', 'profile': 'default', 'handle': 'one'},+ {'member_id': 'two', 'profile': 'other', 'handle': 'two',+ 'target': {'kind': 'peer', 'installation_id': 'peer', 'profile': 'other',+ 'peer_id': 'peer', 'capability_digest': 'a' * 64}}])+ service.send(room_id='room', event_id='input', payload={'text': '@one hello', 'thread_id': 'thread'})+ def evidence():+ with db._read_ctx() as conn:+ row = conn.execute(f'SELECT record_json FROM {work.SOURCE_TABLE}').fetchone()+ assert row is not None+ return work.validate(json.loads(row[0]))+ before = evidence()+ assert before['availability'] == 'available'+ assert before['tasks'][0]['phase'] == 'queued'+ service.stop_room('room', cancel_id='stop')+ after = evidence()+ assert after['revision'] > before['revision']+ assert after['tasks'][0]['phase'] == 'cancelled'+ assert after['stop']['cancel_id'] == 'stop'+ assert after['stop']['revocation_complete'] is Falsediff --git a/tests/gateway/test_room_work_transition_capture.py b/tests/gateway/test_room_work_transition_capture.pynew file mode 100644index 00000000000..e3113d0e4b1--- /dev/null+++ b/tests/gateway/test_room_work_transition_capture.py@@ -0,0 +1,70 @@+"""Real driver transitions retain passive evidence without becoming replay authority."""+import json+from contextlib import closing+import sqlite3++import pytest++from gateway import hosted_room_driver as driver+from gateway import hosted_room_work_records as work+from gateway import hosted_rooms as rooms+++def snapshot(path):+ with closing(sqlite3.connect(path)) as conn:+ row = conn.execute(f"SELECT record_json FROM {work.SOURCE_TABLE} WHERE disposition='current'").fetchone()+ assert row is not None+ return work.validate(json.loads(row[0]))+++def test_driver_transitions_capture_without_manual_publication(tmp_path):+ path = tmp_path / 'state.db'+ rooms.create_room(path, room_id='room', name='Room', members=[{'profile': 'ops', 'handle': 'ops'}],+ authority_gateway_id='owner', now=10)+ rooms.append_event(path, room_id='room', event_id='input', kind='message.user',+ actor={'kind': 'user', 'id': 'alice'}, payload={'text': 'hello'},+ authority_gateway_id='owner', authority_epoch=1)+ identity = driver.TaskIdentity('room', 'task', 'thread', 'turn')+ payload = {'target_profile': 'ops', 'prompt': 'private input', 'source_event_seq': 1}+ driver.admit_task(path, identity, payload=payload, clock=lambda: 10)+ queued = snapshot(path)+ assert queued['tasks'][0]['phase'] == 'queued'+ assert 'private input' not in work.encode(queued)+ driver.admit_task(path, identity, payload=payload, clock=lambda: 10)+ assert snapshot(path) == queued+ lease = driver.acquire_lease(path, room_id='room', gateway_id='owner', authority_epoch=1,+ process_generation='process-a', ttl_seconds=10, clock=lambda: 10)+ driver.start_task(path, identity, lease, expected_cancel_generation=0, clock=lambda: 10)+ running = snapshot(path)+ assert running['revision'] > queued['revision']+ assert running['tasks'][0]['phase'] == 'running'+ successor = driver.acquire_lease(path, room_id='room', gateway_id='owner', authority_epoch=1,+ process_generation='process-b', ttl_seconds=10, clock=lambda: 21)+ driver.recover_room(path, successor, clock=lambda: 21)+ unknown = snapshot(path)+ assert unknown['tasks'][0]['phase'] == 'indeterminate'+ with pytest.raises(driver.InvalidTaskTransitionError):+ driver.start_task(path, identity, successor, expected_cancel_generation=0, clock=lambda: 21)+ assert snapshot(path) == unknown+ driver.begin_task_cancel(path, identity, cancel_id='stop', expected_cancel_generation=0, clock=lambda: 21)+ assert snapshot(path)['tasks'][0]['phase'] == 'stopping'+ driver.complete_task_cancel(path, identity, cancel_id='stop', expected_cancel_generation=1, clock=lambda: 21)+ assert snapshot(path)['tasks'][0]['phase'] == 'cancelled'+++def test_broken_passive_evidence_does_not_authorize_or_block_stop(tmp_path):+ path = tmp_path / 'state.db'+ rooms.create_room(path, room_id='room', name='Room', members=[{'profile': 'ops', 'handle': 'ops'}],+ authority_gateway_id='owner', now=10)+ rooms.append_event(path, room_id='room', event_id='input', kind='message.user',+ actor={'kind': 'user', 'id': 'alice'}, payload={'text': 'hello'},+ authority_gateway_id='owner', authority_epoch=1)+ identity = driver.TaskIdentity('room', 'task', 'thread', 'turn')+ driver.admit_task(path, identity, payload={'target_profile': 'ops', 'prompt': 'hello', 'source_event_seq': 1}, clock=lambda: 10)+ snapshot(path)+ with closing(sqlite3.connect(path)) as conn, conn:+ conn.execute(f"UPDATE {work.SOURCE_TABLE} SET record_json='broken'")+ driver.cancel_task(path, identity, cancel_id='stop', expected_cancel_generation=0, clock=lambda: 10)+ assert driver.get_task(path, identity)['status'] == 'cancelled'+ with closing(sqlite3.connect(path)) as conn:+ assert conn.execute(f"SELECT disposition,record_json FROM {work.SOURCE_TABLE}").fetchone() == ('invalid', 'broken')