The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): repack hosted-room layouts to <=120 cols (AST-neutral)
Tekniumaa6365a0226d
diff --git a/gateway/hosted_room_discussion.py b/gateway/hosted_room_discussion.pyindex af9aaae6971..13b0283d50a 100644--- a/gateway/hosted_room_discussion.py+++ b/gateway/hosted_room_discussion.py@@ -170,8 +170,7 @@ class _ValidatedEvent:payload: Mapping[str, Any]-_identifier = partial(- common.identifier, error=DiscussionValidationError, max_chars=driver.MAX_IDENTIFIER_CHARS)+_identifier = partial(common.identifier, error=DiscussionValidationError, max_chars=driver.MAX_IDENTIFIER_CHARS)_exact_fields = partial(common.exact_fields, error=DiscussionValidationError)_bounded_int = partial(common.bounded_int, error=DiscussionValidationError)@@ -199,8 +198,7 @@ def validate_user_payload(value: Any) -> dict[str, Any]:return {"text": text, "thread_id": _identifier(payload["thread_id"], label="thread_id")}-def _validate_member_target(- value: Any, *, profile: str, known_profiles: set[str], index: int) -> dict[str, Any]:+def _validate_member_target(value: Any, *, profile: str, known_profiles: set[str], index: int) -> dict[str, Any]:if value is None:if profile not in known_profiles:raise DiscussionValidationError(@@ -381,8 +379,7 @@ def _validate_turn_coordinates(payload: Mapping[str, Any], room: DiscussionRoom)def _validate_user_event(- kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom-) -> Mapping[str, Any]:+ kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom) -> Mapping[str, Any]:payload = validate_user_payload(payload)if actor.get("kind") != "user":raise DiscussionValidationError("message.user requires a user actor")@@ -390,8 +387,7 @@ def _validate_user_event(def _validate_member_message(- kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom-) -> Mapping[str, Any]:+ kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom) -> Mapping[str, Any]:_exact_fields(payload, label="message.member payload", required=_MEMBER_MESSAGE_FIELDS)_validate_turn_coordinates(payload, room)text = payload.get("text")@@ -410,8 +406,7 @@ def _validate_member_message(def _validate_terminal_event(- kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom-) -> Mapping[str, Any]:+ kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom) -> Mapping[str, Any]:_exact_fields(payload, label=f"{kind} payload",required=_TERMINAL_COMMON_FIELDS | _TERMINAL_EXTRA_FIELDS[kind],@@ -444,8 +439,7 @@ def _validate_terminal_event(def _validate_gateway_event(- kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom-) -> Mapping[str, Any]:+ kind: str, payload: Mapping[str, Any], actor: Mapping[str, Any], room: DiscussionRoom) -> Mapping[str, Any]:fields, identifier_fields = _GATEWAY_EVENT_FIELDS[kind]_exact_fields(payload, label=f"{kind} payload", required=fields)if kind == "room.activity" and payload.get("status") not in {"settled", "bounded"}:@@ -487,8 +481,7 @@ def _validate_event(raw: Any, *, room: DiscussionRoom, previous_seq: int) -> _Vareturn _ValidatedEvent(raw=raw, seq=seq, event_id=event_id, kind=kind, actor=actor, payload=payload)-def _validated_events(- events: Sequence[Mapping[str, Any]], *, room: DiscussionRoom) -> tuple[_ValidatedEvent, ...]:+def _validated_events(events: Sequence[Mapping[str, Any]], *, room: DiscussionRoom) -> tuple[_ValidatedEvent, ...]:validated: list[_ValidatedEvent] = []previous_seq = 0event_ids: set[str] = set()@@ -581,8 +574,7 @@ def _truncate_utf8_text(value: Any, *, max_bytes: int, suffix: str = "") -> str:def _build_prompt(*, room: DiscussionRoom, member: DiscussionMember, messages: Sequence[_ValidatedEvent],watermark: int, seen_through_seq: int) -> str:- delta = [event for event in messages if watermark < event.seq <= seen_through_seq][- -MAX_DISCUSSION_DELTA_LINES:]+ delta = [event for event in messages if watermark < event.seq <= seen_through_seq][- MAX_DISCUSSION_DELTA_LINES:]peers = ", ".join(f"@{candidate.handle}" for candidate in room.members if candidate.member_id != member.member_id)opening = [@@ -653,8 +645,7 @@ def _make_task_plan(def _pending_discussion(validated: Sequence[_ValidatedEvent]) -> _ValidatedEvent | None:"""Oldest latest-per-thread user message not stopped and not yet completed."""- stopped_through_seq = max(- (event.seq for event in validated if event.kind == "room.stop_requested"), default=0)+ stopped_through_seq = max((event.seq for event in validated if event.kind == "room.stop_requested"), default=0)completed_discussion_ids = {str(event.payload["discussion_event_id"])for event in validated@@ -876,8 +867,7 @@ def _failed_effects(result: Any, **_: Any) -> tuple[dict[str, Any], list[EventPlreturn {"error": error_text, "reason_code": reason_code}, []-def _cancelled_effects(- result: Any, *, newer_same_thread: bool, **_: Any) -> tuple[dict[str, Any], list[EventPlan]]:+def _cancelled_effects(result: Any, *, newer_same_thread: bool, ** _: Any) -> tuple[dict[str, Any], list[EventPlan]]:reason = ("superseded_by_newer_user_event" if newer_same_threadelse _terminal_text(result, field="reason", fallback="member turn cancelled"))@@ -901,8 +891,7 @@ _TERMINAL_EFFECTS = {def plan_publication(room_value: Any, events: Sequence[Mapping[str, Any]], task: DiscussionTaskPlan, *, status: TerminalKind,- result: Any = None, execution_generation: int | None = None, local_profiles: Iterable[str],-) -> PublicationPlan:+ result: Any = None, execution_generation: int | None = None, local_profiles: Iterable[str]) -> PublicationPlan:"""Plan idempotent room effects for one terminal driver task.A newer user event in the same thread supersedes a late result: the taskdiff --git a/gateway/hosted_room_driver.py b/gateway/hosted_room_driver.pyindex 52105d288b6..ca9c6c9e923 100644--- a/gateway/hosted_room_driver.py+++ b/gateway/hosted_room_driver.py@@ -88,8 +88,7 @@ _COMPLETE_STOP_SQL = _task_update(_INDETERMINATE_STALE = "indeterminate task generation changed"_GENERATION_TRANSITIONS = {"resolve": (- "indeterminate", _SETTLE_SET, _INDETERMINATE_STALE, "indeterminate task changed during reconciliation",- ),+ "indeterminate", _SETTLE_SET, _INDETERMINATE_STALE, "indeterminate task changed during reconciliation"),"resolve_cancel": ("indeterminate", _CANCEL_SET, "indeterminate cancellation proof is stale","indeterminate cancellation proof lost its fence"),@@ -181,8 +180,7 @@ def _task_payload(value: Any) -> tuple[dict[str, Any], str, str]:if missing:raise DriverValidationError(f"missing payload fields: {', '.join(sorted(missing))}")target_profile = _identifier(value["target_profile"], label="target_profile")- prompt = text(- value["prompt"], error=DriverValidationError, label="prompt", max_bytes=MAX_PROMPT_BYTES, strip=False)+ prompt = text(value["prompt"], error=DriverValidationError, label="prompt", max_bytes=MAX_PROMPT_BYTES, strip=False)source_event_seq = _bounded_int(value["source_event_seq"], message="source_event_seq must be a positive integer", low=1)normalized = {"target_profile": target_profile, "prompt": prompt, "source_event_seq": source_event_seq}@@ -283,8 +281,7 @@ def _schema_objects_exist(conn: sqlite3.Connection) -> bool:if {row[0] for row in rows} != {"hosted_room_driver_leases", "hosted_room_driver_tasks"}:return Falseindex = conn.execute(- "SELECT 1 FROM sqlite_master WHERE type='index' AND name='idx_hosted_room_driver_tasks_status'"- ).fetchone()+ "SELECT 1 FROM sqlite_master WHERE type='index' AND name='idx_hosted_room_driver_tasks_status'").fetchone()return index is not None@@ -301,8 +298,7 @@ def _migrate_task_status_constraint(conn: sqlite3.Connection) -> None:_create_task_table(conn, "hosted_room_driver_tasks_next")columns = ", ".join(_TASK_COLUMN_ORDER)conn.execute(- f"INSERT INTO hosted_room_driver_tasks_next ({columns}) SELECT {columns} FROM hosted_room_driver_tasks"- )+ f"INSERT INTO hosted_room_driver_tasks_next ({columns}) SELECT {columns} FROM hosted_room_driver_tasks")conn.execute("DROP TABLE hosted_room_driver_tasks")conn.execute("ALTER TABLE hosted_room_driver_tasks_next RENAME TO hosted_room_driver_tasks")conn.execute(_TASK_INDEX_SQL.format(if_not_exists=""))@@ -476,8 +472,7 @@ def _settlement_replay(settlement_id: str, status: str, result_json: str) -> Caldef _cancel_replay(cancel_id: str, status: str = "cancelled") -> Callable[[sqlite3.Row], Any]:"""Replay predicate: same cancel_id already committed in ``status``."""return lambda row: (- _task_from_row(row, idempotent=True) if row["status"] == status and row["cancel_id"] == cancel_id else None- )+ _task_from_row(row, idempotent=True) if row["status"] == status and row["cancel_id"] == cancel_id else None)def _generations_match(row: sqlite3.Row, status: str, execution_generation: int, cancel_generation: int) -> bool:@@ -569,8 +564,7 @@ def acquire_lease("""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")- authority_epoch = _bounded_int(- authority_epoch, message="authority_epoch must be a positive integer", low=1)+ authority_epoch = _bounded_int(authority_epoch, message="authority_epoch must be a positive integer", low=1)process_generation = _identifier(process_generation, label="process_generation")ttl_seconds = _ttl(ttl_seconds)now = _timestamp(clock)@@ -625,8 +619,7 @@ def renew_lease(db_path: Path | str, lease: DriverLease, *, ttl_seconds: Any, cl"""UPDATE hosted_room_driver_leases SET expires_at=?, updated_at=?WHERE room_id=? AND gateway_id=? AND process_generation=?AND lease_generation=? AND released_at IS NULL AND expires_at > ?""",- (expires_at, now, lease.room_id, lease.gateway_id, lease.process_generation, lease.lease_generation, now),- )+ (expires_at, now, lease.room_id, lease.gateway_id, lease.process_generation, lease.lease_generation, now))if updated.rowcount != 1:raise StaleLeaseError("driver lease changed during renewal")return dataclasses.replace(lease, expires_at=expires_at, reclaimed=False)@@ -782,8 +775,7 @@ def resolve_indeterminate_cancellation(now = _timestamp(clock)return _generation_transition(db_path, identity, lease, "resolve_cancel", expected_execution_generation, expected_cancel_generation,- now=now, replay=_cancel_replay(cancel_id), set_params=(expected_cancel_generation + 1, cancel_id, now, now),- )+ now=now, replay=_cancel_replay(cancel_id), set_params=(expected_cancel_generation + 1, cancel_id, now, now))def requeue_indeterminate_task(@@ -945,8 +937,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, retain: int = MAX_RETAINED_TERMINAL_TASKS,-) -> int:+ 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")now = _timestamp(clock)@@ -956,8 +947,7 @@ def prune_published_terminal_tasks(with _transaction(db_path) as conn:publications = conn.execute(- "SELECT 1 FROM sqlite_master WHERE type='table' AND name='hosted_room_policy_publications'"- ).fetchone()+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='hosted_room_policy_publications'").fetchone()if publications is None:return 0rows = conn.execute(diff --git a/gateway/hosted_room_execution_policy.py b/gateway/hosted_room_execution_policy.pyindex ce25dad2e52..f12538b500d 100644--- a/gateway/hosted_room_execution_policy.py+++ b/gateway/hosted_room_execution_policy.py@@ -14,8 +14,7 @@ POLICY_VERSION = 1MAX_POLICY_TOOLSETS = 128MAX_POLICY_ITERATIONS = (1 << 53) - 1_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]*$")-_POLICY_FIELDS = {- "version", "target_profile", "enabled_toolsets", "approval_mode", "max_iterations", "policy_digest"}+_POLICY_FIELDS = {"version", "target_profile", "enabled_toolsets", "approval_mode", "max_iterations", "policy_digest"}class RoomExecutionPolicyError(ValueError):diff --git a/gateway/hosted_room_peer.py b/gateway/hosted_room_peer.pyindex 042640b6fdf..11b7e7a927f 100644--- a/gateway/hosted_room_peer.py+++ b/gateway/hosted_room_peer.py@@ -258,8 +258,7 @@ class GatewayRoomCatalog:def endpoint_mapping(self) -> dict[str, Any]:"""Return the normalized self-advertised endpoint capability."""if self.endpoint_url is not None:- return {- "available": True, "url": self.endpoint_url, "transport_security": self.transport_security}+ return {"available": True, "url": self.endpoint_url, "transport_security": self.transport_security}return {"available": False, "reason": self.endpoint_reason or "not_configured"}@@ -272,8 +271,7 @@ def catalog_mapping(# A Desktop-managed gateway exits with the app: the caller's flag is only an# upper bound, so call sites that still pass ``True`` stay honest.persistent_process = bool(persistent_process and os.getenv("HERMES_DESKTOP") != "1")- profile = (- str(target_profile or "").strip() or (os.getenv("HERMES_PROFILE") or "default").strip() or "default")+ profile = (str(target_profile or "").strip() or (os.getenv("HERMES_PROFILE") or "default").strip() or "default")checked_policy = RoomExecutionPolicy.from_mapping(execution_policy or execution_policy_mapping(target_profile=profile))# A RoomLink run is initiated by another installation. Process-wide YOLO@@ -458,8 +456,7 @@ def issue_room_grant(authority_epoch: int, member_id: str, target_install_id: str, target_profile: str,execution_policy_digest: str | None = None,permissions: Iterable[str] = ("approve", "dispatch", "status", "stop"), issued_at: float | None = None,- ttl_seconds: float = 3600, status_ttl_seconds: float | None = None, status_expires_at: float | None = None,-) -> str:+ ttl_seconds: float = 3600, status_ttl_seconds: float | None = None, status_expires_at: float | None = None) -> str:"""Issue a target-verifiable bearer grant scoped to one room member."""if len(secret) < 32:raise HostedRoomGrantError("room grant secret must be at least 32 bytes")@@ -547,8 +544,7 @@ def decode_room_grant(secret: bytes, token: str, *, permission: str, now: floatreturn payload-def room_grant_needs_dispatch_refresh(- token: str, *, now: float | None = None, leeway_seconds: float = 5 * 60) -> bool:+def room_grant_needs_dispatch_refresh(token: str, *, now: float | None = None, leeway_seconds: float = 5 * 60) -> bool:"""Read only grant timing to schedule target-validated refresh.This deliberately does not establish trust; the target validates thediff --git a/gateway/hosted_room_policy_checkpoint.py b/gateway/hosted_room_policy_checkpoint.pyindex d7c67de2a9b..ec6ba28f1c5 100644--- a/gateway/hosted_room_policy_checkpoint.py+++ b/gateway/hosted_room_policy_checkpoint.py@@ -53,8 +53,7 @@ _SCHEMA_DDL = ()_ROOM_EVENT_COLUMNS = ("room_id, seq, event_id, kind, actor_json, authority_epoch, payload_json, created_at")-_DELETE_ACTIVE_EVENTS_SQL = (- "DELETE FROM hosted_room_policy_events WHERE room_id=? AND discussion_event_id=?")+_DELETE_ACTIVE_EVENTS_SQL = ("DELETE FROM hosted_room_policy_events WHERE room_id=? AND discussion_event_id=?")_TRANSCRIPT_EVENTS_SQL = f"""WITH transcript_events(seq) AS (SELECT seq FROM hosted_room_policy_transcript WHERE room_id=? AND thread_id=?UNION ALL@@ -85,8 +84,7 @@ def _require_room(conn: sqlite3.Connection, room_id: str) -> None:def _settled_message(- conn: sqlite3.Connection, room_id: str, discussion_event_id: str, message_event_id: Any-) -> dict[str, Any] | None:+ conn: sqlite3.Connection, room_id: str, discussion_event_id: str, message_event_id: Any) -> dict[str, Any] | None:"""Return the indexed member message a ``turn.settled`` event committed, if it is in the projection."""rows = conn.execute("SELECT seq, event_json FROM hosted_room_policy_events WHERE room_id=? AND discussion_event_id=?",@@ -116,8 +114,7 @@ class HostedRoomPolicyCheckpoint:@staticmethoddef _store_active_event(- conn: sqlite3.Connection, *, event: Mapping[str, Any], thread_id: str, discussion_event_id: str- ) -> None:+ conn: sqlite3.Connection, *, event: Mapping[str, Any], thread_id: str, discussion_event_id: str) -> None:conn.execute("""INSERT OR IGNORE INTO hosted_room_policy_events(room_id, thread_id, discussion_event_id, seq, event_json@@ -128,8 +125,7 @@ class HostedRoomPolicyCheckpoint:@staticmethoddef _store_transcript_event(- conn: sqlite3.Connection, *, event: Mapping[str, Any], thread_id: str, settled_seq: int | None = None,- ) -> None:+ conn: sqlite3.Connection, *, event: Mapping[str, Any], thread_id: str, settled_seq: int | None = None) -> None:conn.execute("""INSERT INTO hosted_room_policy_transcript(room_id, thread_id, seq, kind, settled_seq@@ -185,8 +181,7 @@ class HostedRoomPolicyCheckpoint:(room_id, discussion_event_id, MAX_ACTIVE_POLICY_EVENTS + 1)).fetchall()if len(active_rows) > MAX_ACTIVE_POLICY_EVENTS:raise RuntimeError(bound_error)- rows = conn.execute(- _TRANSCRIPT_EVENTS_SQL, (room_id, thread_id, room_id, thread_id, room_id)).fetchall()+ rows = conn.execute(_TRANSCRIPT_EVENTS_SQL, (room_id, thread_id, room_id, thread_id, room_id)).fetchall()events_by_seq = {int(event["seq"]): eventfor event in (@@ -227,13 +222,11 @@ class HostedRoomPolicyCheckpoint:(room_id, discussion_event_id)).fetchone()if source is None:return- self._store_active_event(- conn, event=event, thread_id=thread_id, discussion_event_id=discussion_event_id)+ self._store_active_event(conn, event=event, thread_id=thread_id, discussion_event_id=discussion_event_id)if kind not in _TERMINAL_KINDS:returntask_id = str(payload.get("task_id") or "")- execution_generation = (- int(payload.get("execution_generation") or 0) if kind == "turn.deferred" else 0)+ execution_generation = (int(payload.get("execution_generation") or 0) if kind == "turn.deferred" else 0)if task_id:conn.execute("""INSERT OR IGNORE INTO hosted_room_policy_publications(@@ -262,8 +255,7 @@ class HostedRoomPolicyCheckpoint:thread_id = str(payload.get("thread_id") or "")discussion_event_id = str(payload.get("discussion_event_id") or "")conn.execute(_DELETE_ACTIVE_EVENTS_SQL, (room_id, discussion_event_id))- conn.execute(- "DELETE FROM hosted_room_policy_threads WHERE room_id=? AND thread_id=?", (room_id, thread_id))+ conn.execute("DELETE FROM hosted_room_policy_threads WHERE room_id=? AND thread_id=?", (room_id, thread_id))def _apply_stop_requested(self, conn: sqlite3.Connection, event: Mapping[str, Any], payload: Mapping[str, Any]) -> None:@@ -294,12 +286,10 @@ class HostedRoomPolicyCheckpoint:room_id, through_seq, stopped_through_seq, updated_at) VALUES (?, 0, 0, 0)""",(room_id,))- row = conn.execute(- "SELECT through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()+ row = conn.execute("SELECT through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()cursor = int(row["through_seq"])transcript_state = conn.execute(- "SELECT schema_version FROM hosted_room_policy_transcript_state WHERE room_id=?", (room_id,),- ).fetchone()+ "SELECT schema_version FROM hosted_room_policy_transcript_state WHERE room_id=?", (room_id,)).fetchone()if transcript_state is None or int(transcript_state["schema_version"]) < _TRANSCRIPT_SCHEMA_VERSION:self._backfill_transcript(conn, room_id=room_id, through_seq=cursor)conn.execute(@@ -342,8 +332,7 @@ class HostedRoomPolicyCheckpoint:through_seq = self.sync(room_id=room_id, latest_seq=latest_seq)with self._connect() as conn:cursor = conn.execute(- "SELECT stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,),- ).fetchone()+ "SELECT stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()stopped_through_seq = int(cursor["stopped_through_seq"])thread = conn.execute("""SELECT thread_id, discussion_event_id FROM hosted_room_policy_threads@@ -365,12 +354,9 @@ class HostedRoomPolicyCheckpoint:(room_id, thread_id)).fetchall()return PolicySnapshot(through_seq=through_seq, stopped_through_seq=stopped_through_seq, events=tuple(events),- watermarks={- (thread_id, str(row["member_id"])): int(row["seen_through_seq"])- for row in watermark_rows})+ watermarks={(thread_id, str(row["member_id"])): int(row["seen_through_seq"]) for row in watermark_rows})- def publication_exists(- self, *, room_id: str, task_id: str, status: str, execution_generation: int) -> bool:+ def publication_exists(self, *, room_id: str, task_id: str, status: str, execution_generation: int) -> bool:"""Return whether one exact driver outcome is already in the room log."""if status == "deferred":sql = """SELECT 1 FROM hosted_room_policy_publicationsdiff --git a/gateway/hosted_rooms.py b/gateway/hosted_rooms.pyindex 58cfaa8ee8b..15ea6cd74b3 100644--- a/gateway/hosted_rooms.py+++ b/gateway/hosted_rooms.py@@ -50,8 +50,7 @@ CONTROL_EVENT_BYTE_RESERVE = 1024 * 1024_JOURNAL_MODE_LOCK_RETRIES = 8_EVENT_KIND_RE = re.compile(r"^[a-z][a-z0-9_.-]*$")-_CONTROL_EVENT_KINDS = frozenset({- "authority.claimed", "authority.lost", "room.disbanded", "room.stop_requested"})+_CONTROL_EVENT_KINDS = frozenset({"authority.claimed", "authority.lost", "room.disbanded", "room.stop_requested"})_EVENT_KINDS_BY_ACTOR = {"user": frozenset({"message.user"}),"member": frozenset({"message.member"}),@@ -258,10 +257,8 @@ def _system_actor_json(actor_id: str) -> str:def _claim_payload_json(previous_gateway_id: str, new_gateway_id: str, epoch: int) -> str:- return _payload_json({- "previous_gateway_id": previous_gateway_id,- "authority_gateway_id": new_gateway_id,- "authority_epoch": epoch})+ return _payload_json(+ {"previous_gateway_id": previous_gateway_id, "authority_gateway_id": new_gateway_id, "authority_epoch": epoch})def user_event_id(client_event_id: Any) -> str:@@ -446,8 +443,7 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:# permanent: a stale coordinate must never name a different Group Chat.conn.execute(_RETIRE_FROM_ROOMS.format(where="disbanded_at IS NOT NULL"))_migrate_remote_run_schema(conn)- conn.execute(- "CREATE INDEX IF NOT EXISTS idx_hosted_room_events_cursor ON hosted_room_events(room_id, seq)")+ conn.execute("CREATE INDEX IF NOT EXISTS idx_hosted_room_events_cursor ON hosted_room_events(room_id, seq)")if not _schema_is_current(conn):raise HostedRoomError("hosted room schema migration did not complete")@@ -580,8 +576,7 @@ def _insert_event(conn: sqlite3.Connection, room: sqlite3.Row, room_id: str, seq: int, event_id: str, kind: str,actor_json: str, epoch: int, payload_json: str, now: float, *, allow_control: bool = False) -> int:"""Capacity-check then INSERT one event at ``seq``; returns its accounted bytes."""- event_bytes = _prepare_event(- conn, room, event_id, kind, actor_json, payload_json, allow_control=allow_control)+ event_bytes = _prepare_event(conn, room, event_id, kind, actor_json, payload_json, allow_control=allow_control)conn.execute(_INSERT_EVENT, (room_id, seq, event_id, kind, actor_json, epoch, payload_json, now))return event_bytes@@ -595,19 +590,16 @@ def _prepare_event(byte_reserve = CONTROL_EVENT_BYTE_RESERVE if allow_control else 0gateway_byte_limit = MAX_GATEWAY_EVENT_BYTES + byte_reserveif int(room["next_seq"]) - 1 >= MAX_EVENTS_PER_ROOM + count_reserve:- raise HostedRoomError(- "This Group Chat reached its history limit. Start a new Group Chat to continue.")+ raise HostedRoomError("This Group Chat reached its history limit. Start a new Group Chat to continue.")if int(room["event_bytes"]) + additional_bytes > MAX_ROOM_EVENT_BYTES + byte_reserve:- raise HostedRoomError(- "This Group Chat reached its storage limit. Start a new Group Chat to continue.")+ raise HostedRoomError("This Group Chat reached its storage limit. Start a new Group Chat to continue.")gateway_bytes = _gateway_event_bytes(conn)if gateway_bytes + additional_bytes > gateway_byte_limit:_prune_disbanded_rooms_locked(conn, now=None, max_gateway_event_bytes=max(0, gateway_byte_limit - additional_bytes))gateway_bytes = _gateway_event_bytes(conn)if gateway_bytes + additional_bytes > gateway_byte_limit:- raise HostedRoomError(- "Group Chat storage is full on this host. Delete an old Group Chat and try again.")+ raise HostedRoomError("Group Chat storage is full on this host. Delete an old Group Chat and try again.")return additional_bytes@@ -842,16 +834,14 @@ def _read_one(db_path: Path | str, sql: str, params: tuple[Any, ...]) -> sqlite3return 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: Path | str, *, 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: Path | str, *, 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)@@ -881,8 +871,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: Path | str, *, 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)@@ -988,8 +977,7 @@ def create_room(if existing is not None:if existing["disbanded_at"] is not None:raise RoomConflictError("room_id belongs to a disbanded room")- legacy_adoption = (- existing["authority_gateway_id"] == "legacy" and authority_gateway_id != "legacy")+ legacy_adoption = (existing["authority_gateway_id"] == "legacy" and authority_gateway_id != "legacy")members_match = existing["members_json"] == members_json or (legacy_adoptionand _legacy_members_match(existing["members_json"], normalized_members))@@ -1003,8 +991,7 @@ def create_room(raise RoomConflictError("room_id already belongs to a different authority")return _room_from_row(existing, idempotent=True)- active_rooms = int(- conn.execute("SELECT COUNT(*) FROM hosted_rooms WHERE disbanded_at IS NULL").fetchone()[0])+ active_rooms = int(conn.execute("SELECT COUNT(*) FROM hosted_rooms WHERE disbanded_at IS NULL").fetchone()[0])if active_rooms >= MAX_ACTIVE_ROOMS:raise HostedRoomError("This host has too many active Group Chats. Delete one and try again.")conn.execute(@@ -1040,8 +1027,7 @@ def list_rooms(def rename_room(- db_path: Path | str, *, room_id: Any, event_id: Any, name: Any, now: float | None = None-) -> dict[str, Any]:+ db_path: Path | str, *, 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)@@ -1071,8 +1057,7 @@ def rename_room(SET name=?, next_seq=?, event_bytes=event_bytes+?, revision=revision+1, updated_at=?WHERE room_id=?""",(name, seq + 1, event_bytes, now, room_id))- conn.execute(- _INSERT_EVENT, (room_id, seq, event_id, "room.renamed", actor_json, epoch, payload_json, now))+ conn.execute(_INSERT_EVENT, (room_id, seq, event_id, "room.renamed", actor_json, epoch, payload_json, now))updated = conn.execute(_SELECT_ROOM, (room_id,)).fetchone()event = _load_event(conn, room_id, event_id)result = _room_from_row(updated)@@ -1082,8 +1067,7 @@ def rename_room(def append_event(db_path: Path | str, *, 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]:+ 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.Repeating the same ``event_id`` and immutable content returns the original@@ -1288,12 +1272,10 @@ def claim_authority(return state-def _disband_replay(- conn: sqlite3.Connection, room_id: str, room: sqlite3.Row | None) -> dict[str, Any] | None:+def _disband_replay(conn: sqlite3.Connection, room_id: str, room: sqlite3.Row | None) -> dict[str, Any] | None:"""Idempotent replay for a retired or already-disbanded room; None when the room is live."""if room is None:- retired = conn.execute(- "SELECT retired_at FROM hosted_room_retired_ids WHERE room_id=?", (room_id,)).fetchone()+ retired = conn.execute("SELECT retired_at FROM hosted_room_retired_ids WHERE room_id=?", (room_id,)).fetchone()if retired is None:raise RoomNotFoundError("hosted room not found")return {diff --git a/gateway/hosted_rooms_common.py b/gateway/hosted_rooms_common.pyindex a02c771666f..b50a31ffc49 100644--- a/gateway/hosted_rooms_common.py+++ b/gateway/hosted_rooms_common.py@@ -85,8 +85,7 @@ def compact_json(value: Any, *, ensure_ascii: bool = True) -> str:return json.dumps(value, ensure_ascii=ensure_ascii, sort_keys=True, separators=(",", ":"))-def canonical_json(- value: Any, *, error: type[Exception], label: str, max_bytes: int, ensure_ascii: bool) -> str:+def canonical_json(value: Any, *, error: type[Exception], label: str, max_bytes: int, ensure_ascii: bool) -> str:"""``compact_json`` bounded by ``max_bytes`` of UTF-8; unserializable input raises ``error``."""try:encoded = compact_json(value, ensure_ascii=ensure_ascii)