The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): DbPath alias in hosted_rooms_common for the shared Path | str db parameter
Teknium886747eeaf19
diff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pyindex 533e396f7dd..08ddfc6c033 100644--- a/gateway/hosted_room_driver.py+++ b/gateway/hosted_room_driver.py@@ -15,11 +15,10 @@ import mathimport sqlite3from dataclasses import dataclassfrom functools import partial-from pathlib import Pathfrom typing import Any, Callable, Literal, get_argsfrom gateway.hosted_rooms_common import (- bounded_int, canonical_json, compact_json, connect, identifier, table_columns, text, transaction)+ DbPath, bounded_int, canonical_json, compact_json, connect, identifier, table_columns, text, transaction)Clock = Callable[[], float]TaskStatus = Literal["queued", "running", "settled", "failed", "cancelled", "indeterminate", "deferred", "stopping"]@@ -283,7 +282,7 @@ def _migrate_task_status_constraint(conn: sqlite3.Connection) -> None:conn.execute(_TASK_INDEX_SQL.format(if_not_exists=""))-def _connect(db_path: Path | str) -> sqlite3.Connection:+def _connect(db_path: DbPath) -> sqlite3.Connection:"""Open the store; existing tables are validated (after the status-constraint migration when needed).The driver schema never shipped, so an incompatible draft fails closed in ``_validate_schema``.@@ -304,7 +303,7 @@ def _connect(db_path: Path | str) -> sqlite3.Connection:return conn-def _transaction(db_path: Path | str):+def _transaction(db_path: DbPath):return transaction(_connect, db_path, immediate=True)@@ -460,8 +459,8 @@ def _require_cancel_generation(row: sqlite3.Row, expected_cancel_generation: intdef _transition(- db_path: Path | str, identity: TaskIdentity, *, sql: str, set_params: tuple[Any, ...],- fence_params: tuple[Any, ...], stale: str, now: float, lease: DriverLease | None = None, lease_first: bool = True,+ db_path: DbPath, identity: TaskIdentity, *, sql: str, set_params: tuple[Any, ...], fence_params: tuple[Any, ...],+ stale: str, now: float, lease: DriverLease | None = None, lease_first: bool = True,replay: Callable[[sqlite3.Row], dict[str, Any] | None] | None = None,guard: Callable[[sqlite3.Row], None] | None = None) -> dict[str, Any]:"""Run one fenced task transition: load -> idempotent replay -> lease/fence guard -> UPDATE.@@ -489,7 +488,7 @@ def _transition(def _generation_transition(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, name: str, execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, name: str, execution_generation: int,cancel_generation: int, *, now: float, set_params: tuple[Any, ...],replay: Callable[[sqlite3.Row], Any] | None = None) -> dict[str, Any]:"""Lease-first transition from ``_GENERATION_TRANSITIONS`` fenced on status + both generations."""@@ -503,7 +502,7 @@ def _generation_transition(def _run_fence_transition(- db_path: Path | str, attempt: TaskAttempt, *, guard_stale: str, lease_generation: Callable[[Any], int] = int,+ db_path: DbPath, attempt: TaskAttempt, *, guard_stale: str, lease_generation: Callable[[Any], int] = int,**transition: Any) -> dict[str, Any]:"""Transition fenced on this attempt's running generation under its exact lease (row guard + SQL fence).@@ -525,8 +524,8 @@ def _run_fence_transition(def acquire_lease(- db_path: Path | str, *, room_id: Any, gateway_id: Any, authority_epoch: Any, process_generation: Any,- ttl_seconds: Any, clock: Clock) -> DriverLease:+ db_path: DbPath, *, room_id: Any, gateway_id: Any, authority_epoch: Any, process_generation: Any, ttl_seconds: Any,+ clock: Clock) -> DriverLease:"""Acquire an empty or expired room lease with a monotonic generation."""room_id = _identifier(room_id, label="room_id")gateway_id = _identifier(gateway_id, label="gateway_id")@@ -568,7 +567,7 @@ def acquire_lease(return _lease_from_row(conn.execute(_SELECT_LEASE, (room_id,)).fetchone(), reclaimed=True)-def renew_lease(db_path: Path | str, lease: DriverLease, *, ttl_seconds: Any, clock: Clock) -> DriverLease:+def renew_lease(db_path: DbPath, lease: DriverLease, *, ttl_seconds: Any, clock: Clock) -> DriverLease:"""Renew the exact active lease generation or fail closed."""ttl_seconds = _ttl(ttl_seconds)now = _timestamp(clock)@@ -585,7 +584,7 @@ def renew_lease(db_path: Path | str, lease: DriverLease, *, ttl_seconds: Any, clreturn dataclasses.replace(lease, expires_at=expires_at, reclaimed=False)-def release_lease(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> dict[str, Any]:+def release_lease(db_path: DbPath, lease: DriverLease, *, clock: Clock) -> dict[str, Any]:"""Release the exact active lease generation idempotently."""now = _timestamp(clock)with _transaction(db_path) as conn:@@ -609,7 +608,7 @@ def release_lease(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> dreturn {"lease": _lease_from_row(current), "idempotent": False}-def admit_task(db_path: Path | str, identity: TaskIdentity, *, payload: Any, clock: Clock) -> dict[str, Any]:+def admit_task(db_path: DbPath, identity: TaskIdentity, *, payload: Any, clock: Clock) -> dict[str, Any]:"""Persist a queued task, or return the identical admission."""normalized_payload, payload_json, payload_digest = _task_payload(payload)now = _timestamp(clock)@@ -638,7 +637,7 @@ def admit_task(db_path: Path | str, identity: TaskIdentity, *, payload: Any, clodef start_task(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_cancel_generation: int, clock: Clock+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_cancel_generation: int, clock: Clock) -> TaskAttempt:"""Move one queued task to running under the current driver lease."""_check_same_room(lease, identity)@@ -677,7 +676,7 @@ def start_task(def settle_task(- db_path: Path | str, attempt: TaskAttempt, *, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock+ db_path: DbPath, attempt: TaskAttempt, *, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock) -> dict[str, Any]:"""Commit one terminal result if every lease and task fence still matches."""settlement_id = _terminal_settlement_id(settlement_id, status)@@ -690,7 +689,7 @@ def settle_task(def settle_stopping_task(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,expected_cancel_generation: int, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock) -> dict[str, Any]:"""Commit a completion that won the race with an unacknowledged Stop."""@@ -708,7 +707,7 @@ def settle_stopping_task(def resolve_indeterminate_task(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,expected_cancel_generation: int, settlement_id: Any, status: TerminalStatus, result: Any, clock: Clock) -> dict[str, Any]:"""Commit a verified historical receipt under the current room lease."""@@ -723,7 +722,7 @@ def resolve_indeterminate_task(def resolve_indeterminate_cancellation(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,expected_cancel_generation: int, cancel_id: Any, clock: Clock) -> dict[str, Any]:"""Commit a verified terminal cancellation for an uncertain attempt."""_expected_generations(lease, identity, expected_execution_generation, expected_cancel_generation)@@ -735,7 +734,7 @@ def resolve_indeterminate_cancellation(def requeue_indeterminate_task(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,expected_cancel_generation: int, clock: Clock) -> dict[str, Any]:"""Explicitly retry uncertain work after an operator accepts at-least-once risk."""_expected_generations(lease, identity, expected_execution_generation, expected_cancel_generation)@@ -746,7 +745,7 @@ def requeue_indeterminate_task(def defer_indeterminate_task(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,expected_cancel_generation: int, reason: Any, clock: Clock) -> dict[str, Any]:"""Fence one uncertain attempt and release later room work."""_expected_generations(lease, identity, expected_execution_generation, expected_cancel_generation)@@ -762,7 +761,7 @@ def defer_indeterminate_task(def requeue_deferred_task(- db_path: Path | str, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,+ db_path: DbPath, identity: TaskIdentity, lease: DriverLease, *, expected_execution_generation: int,expected_cancel_generation: int, clock: Clock) -> dict[str, Any]:"""Explicitly retry a fenced deferred turn under a new generation."""_expected_generations(lease, identity, expected_execution_generation, expected_cancel_generation)@@ -772,7 +771,7 @@ def requeue_deferred_task(now=now, set_params=(now,))-def requeue_not_admitted_task(db_path: Path | str, attempt: TaskAttempt, *, clock: Clock) -> dict[str, Any]:+def requeue_not_admitted_task(db_path: DbPath, attempt: TaskAttempt, *, clock: Clock) -> dict[str, Any]:"""Return a running task to its durable queue after proven non-admission."""now = _timestamp(clock)_check_same_room(attempt.lease, attempt.identity)@@ -790,7 +789,7 @@ def requeue_not_admitted_task(db_path: Path | str, attempt: TaskAttempt, *, clocdef cancel_task(- db_path: Path | str, identity: TaskIdentity, *, cancel_id: Any, expected_cancel_generation: int, clock: Clock+ db_path: DbPath, identity: TaskIdentity, *, cancel_id: Any, expected_cancel_generation: int, clock: Clock) -> dict[str, Any]:"""Cancel a queued task before any external work was admitted."""cancel_id = _identifier(cancel_id, label="cancel_id")@@ -809,7 +808,7 @@ def cancel_task(def begin_task_cancel(- db_path: Path | str, identity: TaskIdentity, *, cancel_id: Any, expected_cancel_generation: int, clock: Clock+ db_path: DbPath, identity: TaskIdentity, *, cancel_id: Any, expected_cancel_generation: int, clock: Clock) -> dict[str, Any]:"""Persist a stop intent without claiming the remote run has stopped."""cancel_id = _identifier(cancel_id, label="cancel_id")@@ -826,7 +825,7 @@ def begin_task_cancel(def complete_task_cancel(- db_path: Path | str, identity: TaskIdentity, *, cancel_id: Any, expected_cancel_generation: int, clock: Clock+ db_path: DbPath, identity: TaskIdentity, *, cancel_id: Any, expected_cancel_generation: int, clock: Clock) -> dict[str, Any]:"""Commit cancellation only after the transport acknowledges exact Stop."""cancel_id = _identifier(cancel_id, label="cancel_id")@@ -841,7 +840,7 @@ def complete_task_cancel(stale="task changed during stop acknowledgement")-def recover_room(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> dict[str, list[TaskIdentity]]:+def recover_room(db_path: DbPath, lease: DriverLease, *, clock: Clock) -> dict[str, list[TaskIdentity]]:"""Fence abandoned running attempts without requeueing uncertain work."""now = _timestamp(clock)foreign_running = f"room_id=? AND status='running' AND NOT ({_RUN_FENCE})"@@ -859,7 +858,7 @@ def recover_room(db_path: Path | str, lease: DriverLease, *, clock: Clock) -> difor status in ("queued", "indeterminate")}-def _read(db_path: Path | str, query: Callable[[sqlite3.Connection], Any]) -> Any:+def _read(db_path: DbPath, query: Callable[[sqlite3.Connection], Any]) -> Any:conn = _connect(db_path)try:return query(conn)@@ -867,12 +866,12 @@ def _read(db_path: Path | str, query: Callable[[sqlite3.Connection], Any]) -> Anconn.close()-def get_task(db_path: Path | str, identity: TaskIdentity) -> dict[str, Any]:+def get_task(db_path: DbPath, identity: TaskIdentity) -> dict[str, Any]:"""Read one task without mutating its state."""return _read(db_path, lambda conn: _task_from_row(_load_task(conn, identity)))-def list_tasks(db_path: Path | str, *, room_id: Any, status: TaskStatus | None = None) -> list[dict[str, Any]]:+def list_tasks(db_path: DbPath, *, room_id: Any, status: TaskStatus | None = None) -> list[dict[str, Any]]:"""Return room tasks in deterministic admission order."""room_id = _identifier(room_id, label="room_id")if status is not None and status not in TASK_STATUSES:@@ -881,7 +880,7 @@ def list_tasks(db_path: Path | str, *, room_id: Any, status: TaskStatus | None =def prune_published_terminal_tasks(- db_path: Path | str, *, room_id: Any, clock: Clock, retention_seconds: float = TERMINAL_TASK_RETENTION_SECONDS,+ db_path: DbPath, *, room_id: Any, clock: Clock, retention_seconds: float = TERMINAL_TASK_RETENTION_SECONDS,retain: int = MAX_RETAINED_TERMINAL_TASKS) -> int:"""Bound execution rows after outcomes are durable in the room log."""room_id = _identifier(room_id, label="room_id")diff --git a/gateway/hosted_room_links.py b/gateway/hosted_room_links.pyindex 10efc6254d7..d6a317b1cc4 100644--- a/gateway/hosted_room_links.py+++ b/gateway/hosted_room_links.py@@ -19,7 +19,7 @@ from typing import Any, Mappingfrom gateway import hosted_roomsfrom gateway.hosted_room_peer import (GatewayRoomCatalog, HostedRoomPeerError, TransportSecurity, validate_room_link_url)-from gateway.hosted_rooms_common import compact_json, exact_fields, identifier+from gateway.hosted_rooms_common import DbPath, compact_json, exact_fields, identifierMAX_LINKS = 512@@ -111,18 +111,18 @@ def _short_string(value: Any, field: str) -> str:invalid=f"{field} is invalid")-def _link_rows(db_path: Path | str) -> list[dict[str, Any]]:+def _link_rows(db_path: DbPath) -> list[dict[str, Any]]:rows = hosted_rooms.list_room_link_records(db_path)if len(rows) > MAX_LINKS:raise HostedRoomPeerError("stored room link list is invalid")return rows-def load_room_links(db_path: Path | str) -> tuple[StoredRoomLink, ...]:+def load_room_links(db_path: DbPath) -> tuple[StoredRoomLink, ...]:return tuple(StoredRoomLink.from_record(row) for row in _link_rows(db_path))-def load_room_links_tolerant(db_path: Path | str) -> tuple[tuple[StoredRoomLink, ...], tuple[str, ...]]:+def load_room_links_tolerant(db_path: DbPath) -> tuple[tuple[StoredRoomLink, ...], tuple[str, ...]]:"""Load healthy routes while quarantining malformed rows by identity."""links = []errors = []@@ -136,14 +136,14 @@ def load_room_links_tolerant(db_path: Path | str) -> tuple[tuple[StoredRoomLink,return tuple(links), tuple(errors)-def save_room_link(db_path: Path | str, link: StoredRoomLink) -> None:+def save_room_link(db_path: DbPath, link: StoredRoomLink) -> None:hosted_rooms.upsert_room_link_record(db_path, record=link.as_record(), max_links=MAX_LINKS)if os.name == "posix":with contextlib.suppress(OSError):Path(db_path).chmod(0o600)-def mark_room_link_status(db_path: Path | str, *, room_id: str, member_id: str, status: str) -> bool:+def mark_room_link_status(db_path: DbPath, *, room_id: str, member_id: str, status: str) -> bool:if status not in _STATUSES:raise HostedRoomPeerError("stored room link status is invalid")return hosted_rooms.update_room_link_status(diff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.pyindex 5387dea7374..67deec59232 100644--- a/gateway/hosted_room_policy_checkpoint.py+++ b/gateway/hosted_room_policy_checkpoint.py@@ -14,7 +14,7 @@ from pathlib import Pathfrom typing import Any, Callable, Mappingfrom gateway import hosted_rooms-from gateway.hosted_rooms_common import compact_json+from gateway.hosted_rooms_common import DbPath, compact_jsonMAX_ACTIVE_POLICY_EVENTS = 64@@ -97,7 +97,7 @@ def _settled_message(class HostedRoomPolicyCheckpoint:"""Incrementally index room policy without compacting visible history."""- def __init__(self, db_path: Path | str) -> None:+ def __init__(self, db_path: DbPath) -> None:self.db_path = Path(db_path)with self._connect() as conn:for ddl in _SCHEMA_DDL:diff --git a/gateway/hosted_room_replicas.py b/gateway/hosted_room_replicas.pyindex 07484326d9e..93ec8b69bd3 100644--- a/gateway/hosted_room_replicas.py+++ b/gateway/hosted_room_replicas.py@@ -13,13 +13,12 @@ import jsonimport sqlite3from contextlib import contextmanagerfrom functools import partial-from pathlib import Pathfrom typing import Any, Iteratorfrom gateway.hosted_rooms import (MAX_ACTOR_ID_CHARS, HostedRoomError, RoomConflictError, _actor_json, _connect, _payload_json, _room_id,_transaction, _validate_identifier, _validate_members, _validate_room_name, local_authority_gateway_id)-from gateway.hosted_rooms_common import bounded_int, clock, utf8_len+from gateway.hosted_rooms_common import DbPath, bounded_int, clock, utf8_lenMAX_REPLICA_ROOMS = 256MAX_REPLICA_EVENT_BYTES = 256 * 1024 * 1024@@ -57,7 +56,7 @@ def _initialize_replica_schema(conn: sqlite3.Connection) -> None:@contextmanager-def _replica_transaction(db_path: Path | str) -> Iterator[sqlite3.Connection]:+def _replica_transaction(db_path: DbPath) -> Iterator[sqlite3.Connection]:"""Ensure the replica schema (own autocommit connection), then open an IMMEDIATE transaction.The DDL is deliberately re-run inside the transaction: that double init is the established statement order.@@ -147,7 +146,7 @@ def _store_replica(def ingest_page(- db_path: Path | str, *, room_id: Any, room_name: Any, members: Any, page: Any, now: float | None = None+ db_path: DbPath, *, room_id: Any, room_name: Any, members: Any, page: Any, now: float | None = None) -> dict[str, Any]:"""Persist one verbatim ``read_events()`` page idempotently; refuses seq gaps and epoch regressions."""room_id = _room_id(room_id)@@ -187,7 +186,7 @@ def ingest_page("caught_up": new_last >= max(latest_seq, new_last)}-def replica_state(db_path: Path | str, *, room_id: Any) -> dict[str, Any]:+def replica_state(db_path: DbPath, *, room_id: Any) -> dict[str, Any]:"""Return the stored replica's coverage and authority lineage."""room_id = _room_id(room_id)with _replica_transaction(db_path) as conn:@@ -202,7 +201,7 @@ def replica_state(db_path: Path | str, *, room_id: Any) -> dict[str, Any]:def promote_replica(- db_path: Path | str, *, room_id: Any, reason: Any = "authority-unreachable", now: float | None = None+ db_path: DbPath, *, room_id: Any, reason: Any = "authority-unreachable", now: float | None = None) -> dict[str, Any]:"""Continue a replicated room on THIS gateway at ``epoch + 1``.@@ -259,7 +258,7 @@ def promote_replica(def demote_room(- db_path: Path | str, *, room_id: Any, observed_gateway_id: Any, observed_epoch: Any, now: float | None = None+ db_path: DbPath, *, room_id: Any, observed_gateway_id: Any, observed_epoch: Any, now: float | None = None) -> dict[str, Any]:"""Fence THIS gateway's stale room authority against a proven newer epoch.diff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.pyindex e01e43a84fd..4e2622de82d 100644--- a/gateway/hosted_rooms.py+++ b/gateway/hosted_rooms.py@@ -17,7 +17,7 @@ from pathlib import Pathfrom typing import Any, Mapping, NoReturnfrom gateway.hosted_rooms_common import (- bounded_int, canonical_json, clock as _now, compact_json, connect, identifier, open_sqlite, table_columns,+ DbPath, bounded_int, canonical_json, clock as _now, compact_json, connect, identifier, open_sqlite, table_columns,table_exists, transaction)PROTOCOL_VERSION = 2@@ -445,13 +445,13 @@ def local_authority_gateway_id() -> str:return _actor_id(f"install:{install_id}", "authority_gateway_id")-def _connect(db_path: Path | str) -> sqlite3.Connection:+def _connect(db_path: DbPath) -> sqlite3.Connection:return connect(db_path, db_label="state.db (hosted_rooms)", ready=_schema_is_current,initialize=lambda conn: _initialize_schema(conn), lock_retries=_JOURNAL_MODE_LOCK_RETRIES)-def _read_connection(db_path: Path | str) -> sqlite3.Connection:+def _read_connection(db_path: DbPath) -> sqlite3.Connection:"""Open the room store without steady-state journal or migration writes."""path = Path(db_path)if not path.is_file():@@ -464,7 +464,7 @@ def _read_connection(db_path: Path | str) -> sqlite3.Connection:return open_sqlite(path)-def _transaction(db_path: Path | str, *, immediate: bool = False):+def _transaction(db_path: DbPath, *, immediate: bool = False):return transaction(_connect, db_path, immediate=immediate)@@ -619,7 +619,7 @@ def _prune_disbanded_rooms_locked(return len(room_ids)-def prune_disbanded_rooms(db_path: Path | str, *, now: float | None = None) -> int:+def prune_disbanded_rooms(db_path: DbPath, *, now: float | None = None) -> int:"""Purge deleted Group Chat payloads while reserving their identities."""timestamp = _now(now)with _transaction(db_path, immediate=True) as conn:@@ -629,7 +629,7 @@ def prune_disbanded_rooms(db_path: Path | str, *, now: float | None = None) -> i# --- room links / grants / reservations / remote runs ----------------------------------def list_room_link_records(db_path: Path | str) -> list[dict[str, Any]]:+def list_room_link_records(db_path: DbPath) -> list[dict[str, Any]]:"""Return private RoomLink records without logging or formatting grants."""with _transaction(db_path) as conn:rows = conn.execute("""SELECT room_id, member_id, target_url, target_profile, grant,@@ -641,7 +641,7 @@ def list_room_link_records(db_path: Path | str) -> list[dict[str, Any]]:return [dict(row) for row in rows]-def upsert_room_link_record(db_path: Path | str, *, record: Mapping[str, Any], max_links: int) -> None:+def upsert_room_link_record(db_path: DbPath, *, record: Mapping[str, Any], max_links: int) -> None:"""Atomically insert or replace one private RoomLink record."""with _transaction(db_path, immediate=True) as conn:existing = conn.execute(@@ -670,7 +670,7 @@ def upsert_room_link_record(db_path: Path | str, *, record: Mapping[str, Any], mdef update_room_link_status(- db_path: Path | str, *, room_id: str, member_id: str, status: str, now: float | None = None) -> bool:+ db_path: DbPath, *, room_id: str, member_id: str, status: str, now: float | None = None) -> bool:"""Persist a non-secret route health classification."""with _transaction(db_path, immediate=True) as conn:cursor = conn.execute(@@ -679,7 +679,7 @@ def update_room_link_status(return cursor.rowcount == 1-def delete_room_link_records(db_path: Path | str, *, room_id: str) -> int:+def delete_room_link_records(db_path: DbPath, *, room_id: str) -> int:"""Delete persisted peer routes after their target grants are revoked."""with _transaction(db_path, immediate=True) as conn:return conn.execute("DELETE FROM hosted_room_links WHERE room_id=?", (room_id,)).rowcount@@ -698,7 +698,7 @@ def _room_grant_scope_key(claims: Mapping[str, Any]) -> str:def revoke_room_grant_scope(- db_path: Path | str, *, claims: Mapping[str, Any], expires_at: float, now: float | None = None) -> None:+ db_path: DbPath, *, claims: Mapping[str, Any], expires_at: float, now: float | None = None) -> None:"""Revoke every grant issued at or before now for one exact room scope."""scope_key = _room_grant_scope_key(claims)timestamp = _now(now)@@ -742,7 +742,7 @@ def _reservation_superseded(row: sqlite3.Row, gateway_id: str, epoch: int) -> bodef reserve_peer_room(- db_path: Path | str, *, claims: Mapping[str, Any], expires_at: float, now: float | None = None) -> None:+ db_path: DbPath, *, claims: Mapping[str, Any], expires_at: float, now: float | None = None) -> None:"""Fence direct Desktop prompts before the first peer run is admitted."""timestamp = _now(now)expiry = float(expires_at)@@ -778,19 +778,19 @@ def reserve_peer_room(updated_at=excluded.updated_at""", (*values, expiry, timestamp, timestamp))-def _read_one(db_path: Path | str, sql: str, params: tuple[Any, ...]) -> sqlite3.Row | None:+def _read_one(db_path: DbPath, sql: str, params: tuple[Any, ...]) -> sqlite3.Row | None:with _transaction(db_path) as conn:return conn.execute(sql, params).fetchone()-def peer_room_is_reserved(db_path: Path | str, *, room_id: str, target_profile: str, now: float | None = None) -> bool:+def peer_room_is_reserved(db_path: DbPath, *, room_id: str, target_profile: str, now: float | None = None) -> bool:"""Return whether a live target-side RoomLink reservation fences Desktop."""timestamp = _now(now)params = (_room_id(room_id), _actor_id(target_profile, "target_profile"), timestamp)return _read_one(db_path, _SELECT_LIVE_RESERVATION, params) is not None-def peer_room_grant_is_current(db_path: Path | str, *, claims: Mapping[str, Any], now: float | None = None) -> bool:+def peer_room_grant_is_current(db_path: DbPath, *, claims: Mapping[str, Any], now: float | None = None) -> bool:"""Require a grant to match the target's current live reservation."""timestamp = _now(now)values = _reservation_claims(claims)@@ -802,7 +802,7 @@ def peer_room_grant_is_current(db_path: Path | str, *, claims: Mapping[str, Any]return row is not None-def room_grant_is_revoked(db_path: Path | str, *, claims: Mapping[str, Any], now: float | None = None) -> bool:+def room_grant_is_revoked(db_path: DbPath, *, claims: Mapping[str, Any], now: float | None = None) -> bool:"""Return whether a grant predates its exact scope's revocation fence."""timestamp = _now(now)scope_key = _room_grant_scope_key(claims)@@ -818,7 +818,7 @@ def _remote_run_identity(record: Mapping[str, Any]) -> tuple[Any, ...]:return tuple(record[column] for column in _REMOTE_RUN_IDENTITY_COLUMNS)-def upsert_remote_run_receipt(db_path: Path | str, *, record: Mapping[str, Any], now: float | None = None) -> None:+def upsert_remote_run_receipt(db_path: DbPath, *, record: Mapping[str, Any], now: float | None = None) -> None:"""Durably bind one logical peer task attempt to its remote run handle."""timestamp = _now(now)identity = _remote_run_identity(record)@@ -840,7 +840,7 @@ def upsert_remote_run_receipt(db_path: Path | str, *, record: Mapping[str, Any],def list_remote_run_receipts(- db_path: Path | str, *, room_id: str | None = None, target_profile: str | None = None, session_id: str | None = None+ db_path: DbPath, *, room_id: str | None = None, target_profile: str | None = None, session_id: str | None = None) -> list[dict[str, Any]]:"""Return remote run handles in durable task order."""filters = [@@ -856,7 +856,7 @@ def list_remote_run_receipts(return [dict(row) for row in rows]-def remote_run_receipt(db_path: Path | str, *, record: Mapping[str, Any]) -> dict[str, Any] | None:+def remote_run_receipt(db_path: DbPath, *, record: Mapping[str, Any]) -> dict[str, Any] | None:"""Return the exact durable remote run handle for one task attempt."""row = _read_one(db_path, _SELECT_REMOTE_RUN, _remote_run_identity(record))return dict(row) if row is not None else None@@ -896,7 +896,7 @@ def _adopt_legacy_room(def create_room(- db_path: Path | str, *, room_id: Any, name: Any, members: Any, authority_gateway_id: Any, now: float | None = None+ db_path: DbPath, *, room_id: Any, name: Any, members: Any, authority_gateway_id: Any, now: float | None = None) -> dict[str, Any]:"""Create a room, or return the identical existing room idempotently."""room_id = _room_id(room_id)@@ -942,7 +942,7 @@ def create_room(def list_rooms(- db_path: Path | str, *, include_disbanded: bool = False, limit: int = MAX_ROOM_LIST_LIMIT, offset: int = 0+ db_path: DbPath, *, include_disbanded: bool = False, limit: int = MAX_ROOM_LIST_LIMIT, offset: int = 0) -> list[dict[str, Any]]:"""Return one bounded read-only page ordered by most recent change."""limit = _bounded_limit(limit, MAX_ROOM_LIST_LIMIT)@@ -958,8 +958,7 @@ def list_rooms(return [_room_from_row(row) for row in rows]-def rename_room(- db_path: Path | str, *, room_id: Any, event_id: Any, name: Any, now: float | None = None) -> dict[str, Any]:+def rename_room(db_path: DbPath, *, room_id: Any, event_id: Any, name: Any, now: float | None = None) -> dict[str, Any]:"""Rename a live room and append its replay event atomically."""room_id = _room_id(room_id)event_id = _event_id(event_id)@@ -994,7 +993,7 @@ def rename_room(def append_event(- db_path: Path | str, *, room_id: Any, event_id: Any, kind: Any, actor: Any, payload: Any,+ db_path: DbPath, *, room_id: Any, event_id: Any, kind: Any, actor: Any, payload: Any,authority_gateway_id: Any = None, authority_epoch: Any = None, now: float | None = None) -> dict[str, Any]:"""Append one immutable event and allocate its per-room sequence atomically.@@ -1056,7 +1055,7 @@ def _probe(path: Path, table: str, query: str, params: tuple[Any, ...], unavailaraise RoomProbeUnavailableError(unavailable) from exc-def probe_hosted_room(db_path: Path | str, *, room_id: Any) -> bool:+def probe_hosted_room(db_path: DbPath, *, room_id: Any) -> bool:"""Check room ownership without creating or migrating the shared store.Runs on the synchronous prompt-admission path for older Desktop clients, so it fails fast@@ -1069,7 +1068,7 @@ def probe_hosted_room(db_path: Path | str, *, room_id: Any) -> bool:def probe_peer_room_reservation(- db_path: Path | str, *, room_id: Any, target_profile: Any, now: float | None = None) -> bool:+ db_path: DbPath, *, room_id: Any, target_profile: Any, now: float | None = None) -> bool:"""Check a peer reservation without creating or migrating shared state."""checked_room_id = _room_id(room_id)checked_profile = _actor_id(target_profile, "target_profile")@@ -1078,7 +1077,7 @@ def probe_peer_room_reservation((checked_room_id, checked_profile, _now(now)), "peer room ownership is temporarily unavailable")-def room_state(db_path: Path | str, *, room_id: Any, include_disbanded: bool = False) -> dict[str, Any]:+def room_state(db_path: DbPath, *, room_id: Any, include_disbanded: bool = False) -> dict[str, Any]:"""Return durable replay and authority state for one room."""room_id = _room_id(room_id)with _transaction(db_path) as conn:@@ -1097,8 +1096,7 @@ def room_state(db_path: Path | str, *, room_id: Any, include_disbanded: bool = Fdef request_room_stop(- db_path: Path | str, *, room_id: Any, cancel_id: Any, expected_gateway_id: Any, expected_epoch: Any-) -> dict[str, Any]:+ db_path: DbPath, *, room_id: Any, cancel_id: Any, expected_gateway_id: Any, expected_epoch: Any) -> dict[str, Any]:"""Append an idempotent fence that supersedes earlier user turns."""cancel_id = _validate_identifier(cancel_id, label="cancel_id", max_chars=MAX_EVENT_ID_CHARS)digest = hashlib.sha256(cancel_id.encode()).hexdigest()[:32]@@ -1127,8 +1125,8 @@ def _append_authority_claim(def claim_authority(- db_path: Path | str, *, room_id: Any, expected_gateway_id: Any, expected_epoch: Any, new_gateway_id: Any,- event_id: Any, now: float | None = None) -> dict[str, Any]:+ db_path: DbPath, *, room_id: Any, expected_gateway_id: Any, expected_epoch: Any, new_gateway_id: Any, event_id: Any,+ now: float | None = None) -> dict[str, Any]:"""Fence a verified authority transfer with a compare-and-swap epoch.Does not decide *when* takeover is safe: a replicated driver calls it only after its@@ -1196,7 +1194,7 @@ def _disband_replay(conn: sqlite3.Connection, room_id: str, room: sqlite3.Row |def disband_room(- db_path: Path | str, *, room_id: Any, expected_gateway_id: Any, expected_epoch: Any, now: float | None = None+ db_path: DbPath, *, room_id: Any, expected_gateway_id: Any, expected_epoch: Any, now: float | None = None) -> dict[str, Any]:"""Tombstone a room id permanently and idempotently."""room_id = _room_id(room_id)@@ -1230,7 +1228,7 @@ def disband_room(def read_events(- db_path: Path | str, *, room_id: Any, since_seq: Any = 0, limit: Any = 100, include_disbanded: bool = False+ db_path: DbPath, *, room_id: Any, since_seq: Any = 0, limit: Any = 100, include_disbanded: bool = False) -> dict[str, Any]:"""Read a monotonic room-log delta after ``since_seq``."""room_id = _room_id(room_id)diff --git a/gateway/hosted_rooms_common.py b/gateway/hosted_rooms_common.pyindex 965cee459f3..537a8789b81 100644--- a/gateway/hosted_rooms_common.py+++ b/gateway/hosted_rooms_common.py@@ -18,6 +18,7 @@ from pathlib import Pathfrom typing import Any, Callable, Iterator, MappingIDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")+DbPath = Path | strdef identifier(@@ -98,7 +99,7 @@ def clock(now: float | None) -> float:return time.time() if now is None else float(now)-def open_sqlite(path: Path | str, *, timeout: float = 10) -> sqlite3.Connection:+def open_sqlite(path: DbPath, *, timeout: float = 10) -> sqlite3.Connection:"""Row-factory connection with foreign keys on; no journal or schema work."""conn = sqlite3.connect(path, timeout=timeout)conn.row_factory = sqlite3.Row@@ -107,7 +108,7 @@ def open_sqlite(path: Path | str, *, timeout: float = 10) -> sqlite3.Connection:def connect(- db_path: Path | str, *, db_label: str, ready: Callable[[sqlite3.Connection], bool],+ db_path: DbPath, *, db_label: str, ready: Callable[[sqlite3.Connection], bool],initialize: Callable[[sqlite3.Connection], None], lock_retries: int = 1) -> sqlite3.Connection:"""Open the shared root store: WAL, foreign keys, then ``initialize`` in one IMMEDIATE txn if not ``ready``.@@ -154,7 +155,7 @@ def table_columns(conn: sqlite3.Connection, table: str) -> frozenset[str]:@contextmanagerdef transaction(- connect: Callable[[Path | str], sqlite3.Connection], db_path: Path | str, *, immediate: bool+ connect: Callable[[DbPath], sqlite3.Connection], db_path: DbPath, *, immediate: bool) -> Iterator[sqlite3.Connection]:"""Open via ``connect``, optionally ``BEGIN IMMEDIATE``, commit on success, always close."""conn = connect(db_path)